diff --git a/README.md b/README.md
index 5ebd63d..198aefd 100644
--- a/README.md
+++ b/README.md
@@ -309,8 +309,10 @@ buttons**; the callback answers the button, removes the buttons and writes the
ack file. The text form `ok An agent harness you own: chat in the terminal, tools with authorization classes, plugins, any model that speaks OpenAI — built by us so we can change it, instead of getting used to how somebody else's client behaves. The bot registers its commands: the menu shows the loaded plugins' commands and the programs in The bot registers its commands: the menu shows the loaded plugins' commands and the programs in Slash commands work there too. Programs in Ein Agent-Harness, das dir gehoert: Chat im Terminal, Werkzeuge mit Autorisierungsklassen, Plugins, jedes Modell das OpenAI spricht — von uns gebaut, damit wir es umbauen koennen, statt uns an das Verhalten eines fremden Clients zu gewoehnen. Der Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in Der Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in Slash-Kommandos funktionieren dort genauso. Programme in Um harness de agente que e seu: chat no terminal, ferramentas com classes de autorizacao, plugins, qualquer modelo que fale OpenAI - escrito por nos para poder mudar-lo, em vez de nos acostumar com o comportamento de um cliente alheio.` block. A long answer
+inline code, fenced blocks, links (also `
` block. A long answer
is split at tag boundaries, with the open tags closed and reopened per
message, and a piece Telegram refuses to parse is sent as plain text instead.
`SPLINTER_TG_MARKDOWN=0` turns the rendering off.
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 478b9d2..20c703d 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -41,6 +41,8 @@ Stream.
`delegate`-Zeile in den Drop-in neben der benutzten Konfiguration, prueft sie
mit einem Test-Turn und registriert sie im laufenden Prozess
(`test_providers`, `test_gateway.sh`, `test_ui.sh`)
+- **Bilder als Foto**: Markdown-Bilder gehen als `sendPhoto` raus (Alt als
+ Caption, Fallback Link), in der Reihenfolge des Textes (`test_gateway.sh`)
- **Markdown als Telegram-HTML**: `src/tgmd.c` rendert fett/kursiv/Code/Links/
Zitate/Tabellen in die Tags von `parse_mode=HTML`, escapt alles andere und
teilt lange Antworten an Tag-Grenzen, mit offenen Tags pro Stueck
diff --git a/src/telegram.c b/src/telegram.c
index 33db16c..605ee91 100644
--- a/src/telegram.c
+++ b/src/telegram.c
@@ -369,7 +369,7 @@ fail:
* one refused message and a chunk boundary is never inside "
".
*/
static int
-send_markdown(const char *token, long chat_id, const char *text,
+send_markdown_text(const char *token, long chat_id, const char *text,
const char *markup, struct sp_buf *err)
{
struct sp_buf html, piece;
@@ -415,6 +415,207 @@ send_markdown(const char *token, long chat_id, const char *text,
return rc;
}
+/* one sendPhoto: Telegram fetches the URL itself, so it has to be public */
+static int
+send_photo(const char *token, long chat_id, const char *url,
+ const char *caption, struct sp_buf *err)
+{
+ struct sp_buf u, body, reply, sink;
+ int rc = 0;
+
+ if (sp_buf_init(&u) != 0 || sp_buf_init(&body) != 0 ||
+ sp_buf_init(&reply) != 0 || sp_buf_init(&sink) != 0)
+ return -1;
+ if (err == NULL)
+ err = &sink;
+ sp_buf_printf(&u, "%s/bot%s/sendPhoto", api_base(), token);
+ sp_buf_printf(&body, "{\"chat_id\":%ld,\"photo\":\"", chat_id);
+ (void)sp_json_escape(&body, url);
+ sp_buf_puts(&body, "\"");
+ if (caption != NULL && *caption != '\0') {
+ char cap[1024];
+
+ snprintf(cap, sizeof(cap), "%.1000s", caption);
+ sp_buf_puts(&body, ",\"caption\":\"");
+ (void)sp_json_escape(&body, cap);
+ sp_buf_puts(&body, "\"");
+ }
+ sp_buf_puts(&body, "}");
+ if (tg_curl(u.p, body.p, &reply, err) != 0)
+ rc = -1;
+ else if (!tg_reply_ok(reply.p)) {
+ sp_buf_printf(err, "telegram: sendPhoto refused: %.200s",
+ reply.p != NULL ? reply.p : "");
+ rc = -1;
+ }
+ sp_buf_free(&u);
+ sp_buf_free(&body);
+ sp_buf_free(&reply);
+ sp_buf_free(&sink);
+ return rc;
+}
+
+static int
+image_url_ok(const char *u, size_t n)
+{
+ return (n > 7 && strncasecmp(u, "http://", 7) == 0) ||
+ (n > 8 && strncasecmp(u, "https://", 8) == 0);
+}
+
+/*
+ * The next  outside a fenced block, an inline code span and a table
+ * row. Images inside code are text, and lifting one out of a table would break
+ * the table, so those stay links in the rendered HTML.
+ */
+static int
+find_image(const char *p, const char **start, const char **end,
+ const char **alt, size_t *altlen, const char **url, size_t *urllen)
+{
+ const char *line = p;
+ int fence = 0;
+
+ while (*line != '\0') {
+ const char *e = strchr(line, '\n');
+ size_t n = e != NULL ? (size_t)(e - line) : strlen(line);
+ size_t i = 0, sp = 0, ticks = 0;
+ int table = 0;
+
+ while (sp < n && (line[sp] == ' ' || line[sp] == '\t') && sp < 4)
+ sp++;
+ while (sp + ticks < n && line[sp + ticks] == '`')
+ ticks++;
+ if (ticks >= 3) {
+ fence = !fence;
+ goto next;
+ }
+ if (fence || (sp < n && line[sp] == '|'))
+ goto next;
+ (void)table;
+ while (i < n) {
+ const char *rb, *rp;
+
+ if (line[i] == '`') {
+ const char *c = memchr(line + i + 1, '`',
+ n - i - 1);
+
+ if (c != NULL) {
+ i = (size_t)(c - line) + 1;
+ continue;
+ }
+ }
+ if (line[i] != '!' || i + 1 >= n || line[i + 1] != '[') {
+ i++;
+ continue;
+ }
+ rb = memchr(line + i + 2, ']', n - i - 2);
+ if (rb == NULL || (size_t)(rb - line) + 1 >= n ||
+ rb[1] != '(') {
+ i++;
+ continue;
+ }
+ rp = memchr(rb + 2, ')', n - (size_t)(rb + 2 - line));
+ if (rp == NULL || rp <= rb + 2 ||
+ !image_url_ok(rb + 2, (size_t)(rp - rb - 2))) {
+ i++;
+ continue;
+ }
+ *start = line + i;
+ *end = rp + 1;
+ *alt = line + i + 2;
+ *altlen = (size_t)(rb - (line + i + 2));
+ *url = rb + 2;
+ *urllen = (size_t)(rp - rb - 2);
+ return 1;
+ }
+next:
+ if (e == NULL)
+ break;
+ line = e + 1;
+ }
+ return 0;
+}
+
+/* anything but whitespace in [p, end)? */
+static int
+has_text(const char *p, const char *end)
+{
+ for (; p < end; p++)
+ if (*p != ' ' && *p != '\t' && *p != '\n' && *p != '\r')
+ return 1;
+ return 0;
+}
+
+/*
+ * An answer with an image is sent in the order it was written: text, photo,
+ * text. Telegram fetches the photo from its URL; when it cannot, the link goes
+ * out as text instead, because a broken image must not swallow the answer.
+ */
+static int
+send_markdown(const char *token, long chat_id, const char *text,
+ const char *markup, struct sp_buf *err)
+{
+ const char *p = text, *img, *end, *alt, *url;
+ size_t altlen, urllen;
+ struct sp_buf part, cap;
+ int rc = 0;
+
+ if (text == NULL || *text == '\0' || !tg_markdown_enabled())
+ return send_markdown_text(token, chat_id, text, markup, err);
+ if (sp_buf_init(&part) != 0 || sp_buf_init(&cap) != 0) {
+ sp_buf_free(&part);
+ sp_buf_free(&cap);
+ return send_markdown_text(token, chat_id, text, markup, err);
+ }
+ while (find_image(p, &img, &end, &alt, &altlen, &url, &urllen)) {
+ if (has_text(p, img)) {
+ sp_buf_clear(&part);
+ if (sp_buf_add(&part, p, (size_t)(img - p)) != 0) {
+ rc = -1;
+ break;
+ }
+ if (send_markdown_text(token, chat_id, part.p, NULL,
+ err) != 0) {
+ rc = -1;
+ break;
+ }
+ }
+ sp_buf_clear(&cap);
+ if (altlen > 0 && sp_buf_add(&cap, alt, altlen) != 0) {
+ rc = -1;
+ break;
+ }
+ sp_buf_clear(&part);
+ if (sp_buf_add(&part, url, urllen) != 0) {
+ rc = -1;
+ break;
+ }
+ if (send_photo(token, chat_id, part.p,
+ cap.p != NULL ? cap.p : "", err) != 0) {
+ /* no photo: send the link as text */
+ sp_buf_clear(err);
+ sp_buf_clear(&part);
+ if (sp_buf_add(&part, img, (size_t)(end - img)) != 0 ||
+ send_markdown_text(token, chat_id, part.p, NULL,
+ err) != 0) {
+ rc = -1;
+ break;
+ }
+ }
+ p = end;
+ }
+ if (rc == 0 && has_text(p, p + strlen(p))) {
+ sp_buf_clear(&part);
+ if (sp_buf_add(&part, p, strlen(p)) != 0)
+ rc = -1;
+ else
+ rc = send_markdown_text(token, chat_id, part.p, markup,
+ err);
+ }
+ sp_buf_free(&part);
+ sp_buf_free(&cap);
+ return rc;
+}
+
static int
send_message(const char *token, long chat_id, const char *text,
struct sp_buf *err)
diff --git a/src/www/index.en.html b/src/www/index.en.html
index a4b2de2..b17aa98 100644
--- a/src/www/index.en.html
+++ b/src/www/index.en.html
@@ -53,7 +53,7 @@ hr { border: 0; border-top: 1px solid #1d2126; margin: 3em 0 1.5em 0; }
splinter_
Gateway: Telegram
splinter --daemon long-polls getUpdates, one turn per message, answers with sendMessage. The token lives in ~/.splinter/telegram.token with mode 0600 and is never passed as an argument — arguments end up in ps. While a turn runs, the chat sees "typing" every four seconds.~/.splinter/commands/; an approval arrives with Yes/No buttons. /interview asks the questions in the chat. /new starts a fresh conversation; /model offers the configured models as buttons, switches the transport and remembers the choice in splinter.conf.d/90-model.conf; /model probe asks the endpoints for /v1/models. /connect asks for name, endpoint, model and key variable, runs one test turn and writes the provider to splinter.conf.d/20-connect.conf. Answers are rendered as Telegram HTML: bold, italic, code and links as tags, tables as columns in a monospace block; a piece Telegram cannot parse goes out as text instead of being lost. Programs in commands/ answer in the chat; in the TUI their output goes to the model.~/.splinter/commands/; an approval arrives with Yes/No buttons. /interview asks the questions in the chat. /new starts a fresh conversation; /model offers the configured models as buttons, switches the transport and remembers the choice in splinter.conf.d/90-model.conf; /model probe asks the endpoints for /v1/models. /connect asks for name, endpoint, model and key variable, runs one test turn and writes the provider to splinter.conf.d/20-connect.conf. Answers are rendered as Telegram HTML: bold, italic, code and links as tags, images as photos (sendPhoto), tables as columns in a monospace block; a piece Telegram cannot parse goes out as text instead of being lost. Programs in commands/ answer in the chat; in the TUI their output goes to the model.~/.splinter/commands/ become /name: they get the rest of the line as an argument, and their output goes to the model as context — not to you as a reply. That is how the model fetches what it cannot see itself.What gets written down
diff --git a/src/www/index.html b/src/www/index.html
index 4558487..6252a08 100644
--- a/src/www/index.html
+++ b/src/www/index.html
@@ -53,7 +53,7 @@ hr { border: 0; border-top: 1px solid #1d2126; margin: 3em 0 1.5em 0; }
splinter_
Gateway: Telegram
splinter --daemon pollt getUpdates, ein Turn pro Nachricht, Antwort per sendMessage. Der Token liegt in ~/.splinter/telegram.token mit Modus 0600 und wird nie als Argument uebergeben — Argumente stehen in ps. Waehrend eines Turns sieht der Chat alle vier Sekunden „typing“.~/.splinter/commands/; eine Zustimmung kommt mit Ja/Nein-Knoepfen. /interview stellt die Fragen im Chat. /new faengt eine frische Konversation an; /model bietet die konfigurierten Modelle als Knoepfe, schaltet den Transport um und merkt die Wahl in splinter.conf.d/90-model.conf; /model probe fragt die Endpoints nach /v1/models. /connect fragt Name, Endpoint, Modell und Key-Variable ab, macht einen Test-Turn und schreibt den Provider nach splinter.conf.d/20-connect.conf. Antworten werden als Telegram-HTML gesetzt: fett, kursiv, Code und Links als Tags, Tabellen als Spalten im Monospace-Block; ein Stueck, das Telegram nicht parst, geht als Text raus statt verloren. Programme in commands/ antworten dort direkt im Chat; im TUI gehen sie ans Modell.~/.splinter/commands/; eine Zustimmung kommt mit Ja/Nein-Knoepfen. /interview stellt die Fragen im Chat. /new faengt eine frische Konversation an; /model bietet die konfigurierten Modelle als Knoepfe, schaltet den Transport um und merkt die Wahl in splinter.conf.d/90-model.conf; /model probe fragt die Endpoints nach /v1/models. /connect fragt Name, Endpoint, Modell und Key-Variable ab, macht einen Test-Turn und schreibt den Provider nach splinter.conf.d/20-connect.conf. Antworten werden als Telegram-HTML gesetzt: fett, kursiv, Code und Links als Tags, Bilder als Foto (sendPhoto), Tabellen als Spalten im Monospace-Block; ein Stueck, das Telegram nicht parst, geht als Text raus statt verloren. Programme in commands/ antworten dort direkt im Chat; im TUI gehen sie ans Modell.~/.splinter/commands/ werden zu /name: sie bekommen den Rest der Zeile als Argument, und ihre Ausgabe geht ans Modell als Kontext — nicht an dich als Antwort. Damit holt sich das Modell, was es selbst nicht sehen kann.Was mitgeschrieben wird
diff --git a/src/www/index.pt.html b/src/www/index.pt.html
index 674bd34..8646951 100644
--- a/src/www/index.pt.html
+++ b/src/www/index.pt.html
@@ -53,7 +53,7 @@ hr { border: 0; border-top: 1px solid #1d2126; margin: 3em 0 1.5em 0; }
splinter_
~/.splinter/commands/; uma aprovacao chega com
botoes Sim/Nao; as respostas viram HTML do Telegram (negrito, codigo, links,
-tabelas em bloco monoespaceado). /new comeca uma conversa nova; /model lista os modelos
+tabelas em bloco monoespaceado, imagens como foto). /new comeca uma conversa nova; /model lista os modelos
configurados em botoes, troca o transporte e guarda a escolha em
splinter.conf.d/90-model.conf; /model probe pergunta
aos endpoints por /v1/models. /connect pergunta nome,
diff --git a/tests/fake_telegram.py b/tests/fake_telegram.py
index 06598bf..3045d75 100644
--- a/tests/fake_telegram.py
+++ b/tests/fake_telegram.py
@@ -78,6 +78,12 @@ class H(http.server.BaseHTTPRequestHandler):
"/editMessageReplyMarkup" in self.path or
"/sendChatAction" in self.path):
return self.reply({"ok": True, "result": True})
+ if "/sendPhoto" in self.path:
+ req = json.loads(raw)
+ with open(sys.argv[3], "a") as f:
+ f.write("photo: %s caption=%s\n" % (
+ req.get("photo", ""), req.get("caption", "")))
+ return self.reply({"ok": True, "result": {"message_id": 101}})
if "/sendMessage" in self.path:
req = json.loads(raw)
text = req.get("text", "")
@@ -136,6 +142,15 @@ class H(http.server.BaseHTTPRequestHandler):
answer = "ok"
chunks = [{"choices": [{"delta": {"content": answer}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
+ elif "codebild" in last_user:
+ # an image inside code is text, not a photo
+ answer = "``\n"
+ chunks = [{"choices": [{"delta": {"content": answer}}]},
+ {"choices": [{"delta": {}, "finish_reason": "stop"}]}]
+ elif "bild" in last_user:
+ answer = "Hier:\n\n\n\nEnde\n"
+ chunks = [{"choices": [{"delta": {"content": answer}}]},
+ {"choices": [{"delta": {}, "finish_reason": "stop"}]}]
elif "markdown" in last_user:
answer = "**fett** und `code`\n"
chunks = [{"choices": [{"delta": {"content": answer}}]},
diff --git a/tests/test_gateway.sh b/tests/test_gateway.sh
index 4fdca8f..d914c02 100755
--- a/tests/test_gateway.sh
+++ b/tests/test_gateway.sh
@@ -129,6 +129,20 @@ run_text "zeig eine tabelle" '' 50 check "a table is drawn in a monospace block" grep -q '' "$D/sent.log" check "a table keeps its columns" grep -q '| a | b |' "$D/sent.log" +# an image in the answer is a photo, not a link, and the text keeps its order +run_text "zeig ein bild" 'Ende' 80 +check "the image is sent as a photo" \ + grep -q '^photo: https://example.org/b.png caption=Ein Bild' "$D/sent.log" +check "the text before the image arrives" grep -q '^Hier:' "$D/sent.log" +check "the text after the image arrives" grep -q 'Ende' "$D/sent.log" +check "no markdown image reaches the chat" \ + sh -c "! grep -q '!\\[Ein Bild\\]' '$D/sent.log'" +run_text "zeig ein codebild" '!\[x\]' 90 +check "an image inside code stays text" \ + grep -q '!\[x\](https://example.org/x.png)' "$D/sent.log" +check "an image inside code is not a photo" \ + sh -c "! grep -q '^photo: https://example.org/x.png' '$D/sent.log'" + # /new starts a fresh conversation and a fresh session file run_text "/new" 'Neue Konversation: sess-' 45 check "the bot says the new session" grep -q '^Neue Konversation: sess-' "$D/sent.log" diff --git a/tools/gen_www.py b/tools/gen_www.py index 183c4fc..cf5b684 100644 --- a/tools/gen_www.py +++ b/tools/gen_www.py @@ -305,7 +305,7 @@ SECTIONS = { "sendMessage. Der Token liegt in " "~/.splinter/telegram.tokenmit Modus 0600 und wird nie als Argument " "uebergeben — Argumente stehen inps. Waehrend eines Turns sieht der " - "Chat alle vier Sekunden „typing“.\nDer Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in
\n~/.splinter/commands/; eine Zustimmung kommt mit Ja/Nein-Knoepfen./interviewstellt die Fragen im Chat./newfaengt eine frische Konversation an;/modelbietet die konfigurierten Modelle als Knoepfe, schaltet den Transport um und merkt die Wahl insplinter.conf.d/90-model.conf;/model probefragt die Endpoints nach/v1/models./connectfragt Name, Endpoint, Modell und Key-Variable ab, macht einen Test-Turn und schreibt den Provider nachsplinter.conf.d/20-connect.conf. Antworten werden als Telegram-HTML gesetzt: fett, kursiv, Code und Links als Tags, Tabellen als Spalten im Monospace-Block; ein Stueck, das Telegram nicht parst, geht als Text raus statt verloren. Programme incommands/antworten dort direkt im Chat; im TUI gehen sie ans Modell.Slash-Kommandos funktionieren " + "Chat alle vier Sekunden „typing“.
\nDer Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in
\n~/.splinter/commands/; eine Zustimmung kommt mit Ja/Nein-Knoepfen./interviewstellt die Fragen im Chat./newfaengt eine frische Konversation an;/modelbietet die konfigurierten Modelle als Knoepfe, schaltet den Transport um und merkt die Wahl insplinter.conf.d/90-model.conf;/model probefragt die Endpoints nach/v1/models./connectfragt Name, Endpoint, Modell und Key-Variable ab, macht einen Test-Turn und schreibt den Provider nachsplinter.conf.d/20-connect.conf. Antworten werden als Telegram-HTML gesetzt: fett, kursiv, Code und Links als Tags, Bilder als Foto (sendPhoto), Tabellen als Spalten im Monospace-Block; ein Stueck, das Telegram nicht parst, geht als Text raus statt verloren. Programme incommands/antworten dort direkt im Chat; im TUI gehen sie ans Modell.Slash-Kommandos funktionieren " "dort genauso. Programme in
\n~/.splinter/commands/werden zu " "/name: sie bekommen den Rest der Zeile als Argument, und ihre Ausgabe " "geht ans Modell als Kontext — nicht an dich als Antwort. Damit holt sich " @@ -385,7 +385,7 @@ SECTIONS = { "sendMessage. The token lives in " "~/.splinter/telegram.tokenwith mode 0600 and is never passed as an " "argument — arguments end up inps. While a turn runs, the chat sees " - ""typing" every four seconds.The bot registers its commands: the menu shows the loaded plugins' commands and the programs in
\n~/.splinter/commands/; an approval arrives with Yes/No buttons./interviewasks the questions in the chat./newstarts a fresh conversation;/modeloffers the configured models as buttons, switches the transport and remembers the choice insplinter.conf.d/90-model.conf;/model probeasks the endpoints for/v1/models./connectasks for name, endpoint, model and key variable, runs one test turn and writes the provider tosplinter.conf.d/20-connect.conf. Answers are rendered as Telegram HTML: bold, italic, code and links as tags, tables as columns in a monospace block; a piece Telegram cannot parse goes out as text instead of being lost. Programs incommands/answer in the chat; in the TUI their output goes to the model.Slash commands work there too. " + ""typing" every four seconds.
\nThe bot registers its commands: the menu shows the loaded plugins' commands and the programs in
\n~/.splinter/commands/; an approval arrives with Yes/No buttons./interviewasks the questions in the chat./newstarts a fresh conversation;/modeloffers the configured models as buttons, switches the transport and remembers the choice insplinter.conf.d/90-model.conf;/model probeasks the endpoints for/v1/models./connectasks for name, endpoint, model and key variable, runs one test turn and writes the provider tosplinter.conf.d/20-connect.conf. Answers are rendered as Telegram HTML: bold, italic, code and links as tags, images as photos (sendPhoto), tables as columns in a monospace block; a piece Telegram cannot parse goes out as text instead of being lost. Programs incommands/answer in the chat; in the TUI their output goes to the model.Slash commands work there too. " "Programs in
""", mesmos slash commands do terminal. O bot registra seus comandos: o menu mostra os comandos dos plugins carregados e os programas em~/.splinter/commands/become/name: they get " "the rest of the line as an argument, and their output goes to the model as " "context — not to you as a reply. That is how the model fetches what it cannot see " @@ -572,7 +572,7 @@ em ordem de nome. Chave desconhecida e erro com numero de linha.~/.splinter/commands/; uma aprovacao chega com botoes Sim/Nao; as respostas viram HTML do Telegram (negrito, codigo, links, -tabelas em bloco monoespaceado)./newcomeca uma conversa nova;/modellista os modelos +tabelas em bloco monoespaceado, imagens como foto)./newcomeca uma conversa nova;/modellista os modelos configurados em botoes, troca o transporte e guarda a escolha emsplinter.conf.d/90-model.conf;/model probepergunta aos endpoints por/v1/models./connectpergunta nome,