gateway: a local file that is not an image goes as a document

sendPhoto and sendDocument are one upload path now: send_upload() takes the
method and the form field, so ![alt](/path/report.md) leaves the chat as a
document with the alt text as caption, in the order of the answer. The photo
branch still checks the bytes (PNG/JPEG/GIF/WebP, 10 MiB), so a text file
cannot ride in as a photo; documents are capped at 50 MiB and have to be a
readable regular file. A missing or unreadable path stays a reference in the
chat.

test_gateway: a local PNG is a photo, a text file is a document, and neither
leaves the markdown in the chat.
This commit is contained in:
lotherk committed 2026-11-11 07:17:28 +00:00
1 parent 07e8b62be9
commit a72df5bb7f
9 files changed
+61 -27

No files matched your search

+5 -4
View File
@@ -312,10 +312,11 @@ The model's markdown is rendered as Telegram HTML: bold, italic, strike,
inline code, fenced blocks, links (also `<https://…>`) and quotes become tags,
everything else is escaped. An image is sent as a photo with the alt text as
caption: `![alt](https://…)` is fetched by Telegram, `![alt](/path/to.png)` (or
`file:///…`) is uploaded from this machine — but only when it really is a
PNG/JPEG/GIF/WebP up to 10 MiB, so the chat cannot be used to post arbitrary
files. If neither works, the reference goes out as text. Images inside code or
a table stay text. Tables are laid out as columns inside a `<pre>` block. A long answer
`file:///…`) is uploaded from this machine. A local file that is not an image
goes out as a document (`sendDocument`, at most 50 MiB). The photo guard still
checks the bytes — PNG/JPEG/GIF/WebP up to 10 MiB — so a text file cannot ride
in as a photo; a missing or unreadable file stays a reference in the chat.
Images inside code or a table stay text. Tables are laid out as columns inside a `<pre>` 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.
+1 -1
View File
@@ -43,7 +43,7 @@ Stream.
(`test_providers`, `test_gateway.sh`, `test_ui.sh`)
- **Bilder als Foto**: Markdown-Bilder gehen als `sendPhoto` raus (Alt als
Caption, Fallback Text), in der Reihenfolge des Textes; lokale Dateien per
Multipart, nur echte Bilder bis 10 MiB (`test_gateway.sh`)
Multipart als Foto (10 MiB) oder Dokument (50 MiB) (`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
+35 -8
View File
@@ -423,10 +423,13 @@ send_markdown_text(const char *token, long chat_id, const char *text,
return rc;
}
/* one sendPhoto with the bytes from this machine: multipart, not a URL */
/*
* One upload from this machine: multipart, not a URL. 'method' is sendPhoto or
* sendDocument; 'field' is the form field the API wants the bytes in.
*/
static int
send_photo_file(const char *token, long chat_id, const char *path,
const char *caption, struct sp_buf *err)
send_upload(const char *token, const char *method, const char *field,
long chat_id, const char *path, const char *caption, struct sp_buf *err)
{
struct sp_buf u, reply, sink;
char idbuf[64], pbuf[1400], cbuf[1100];
@@ -438,9 +441,9 @@ send_photo_file(const char *token, long chat_id, const char *path,
return -1;
if (err == NULL)
err = &sink;
sp_buf_printf(&u, "%s/bot%s/sendPhoto", api_base(), token);
sp_buf_printf(&u, "%s/bot%s/%s", api_base(), token, method);
snprintf(idbuf, sizeof(idbuf), "chat_id=%ld", chat_id);
snprintf(pbuf, sizeof(pbuf), "photo=@%s", path);
snprintf(pbuf, sizeof(pbuf), "%s=@%s", field, path);
args[n++] = "-sS";
args[n++] = "-m";
args[n++] = "120";
@@ -550,6 +553,23 @@ image_file_ok(const char *path)
return 0;
}
/* everything a document may be: a real file, readable, at most 50 MiB */
static int
document_file_ok(const char *path)
{
struct stat st;
FILE *f;
if (path == NULL || stat(path, &st) != 0 || !S_ISREG(st.st_mode) ||
st.st_size <= 0 || st.st_size > 50 * 1024 * 1024)
return 0;
f = fopen(path, "rb");
if (f == NULL)
return 0;
fclose(f);
return 1;
}
/*
* The next ![alt](url-or-path) outside a fenced block, an inline code span and
* a table row. Images inside code are text, and lifting one out of a table
@@ -695,9 +715,16 @@ send_markdown(const char *token, long chat_id, const char *text,
}
snprintf(path, sizeof(path), "%.*s", (int)n,
ref);
sent = image_file_ok(path) &&
send_photo_file(token, chat_id, path, cap_p,
err) == 0;
if (image_file_ok(path))
sent = send_upload(token, "sendPhoto",
"photo", chat_id, path, cap_p,
err) == 0;
else if (document_file_ok(path))
sent = send_upload(token, "sendDocument",
"document", chat_id, path, cap_p,
err) == 0;
else
sent = 0;
} else {
sent = send_photo(token, chat_id, part.p, cap_p,
err) == 0;
+2 -2
View File
@@ -53,7 +53,7 @@ hr { border: 0; border-top: 1px solid #1d2126; margin: 3em 0 1.5em 0; }
<h1>splinter<span>_</span></h1>
<p class="lead">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.</p>
<p class="meta"><b>29083</b> lines of C99/POSIX &middot;
<p class="meta"><b>29110</b> lines of C99/POSIX &middot;
<b>25</b> tools &middot; <b>35</b> test programs &middot;
<b>16</b> plugins &middot; <b>42</b> palettes &middot; BSD-3-Clause</p>
@@ -141,7 +141,7 @@ plugin = plugins/reminder/reminder.so</pre>
<h2>Gateway: Telegram</h2>
<p><code>splinter --daemon</code> long-polls <code>getUpdates</code>, one turn per message, answers with <code>sendMessage</code>. The token lives in <code>~/.splinter/telegram.token</code> with mode 0600 and is never passed as an argument — arguments end up in <code>ps</code>. While a turn runs, the chat sees &quot;typing&quot; every four seconds.</p>
<p>The bot registers its commands: the menu shows the loaded plugins' commands and the programs in <code>~/.splinter/commands/</code>; an approval arrives with Yes/No buttons. <code>/interview</code> asks the questions in the chat. <code>/new</code> starts a fresh conversation; <code>/model</code> offers the configured models as buttons, switches the transport and remembers the choice in <code>splinter.conf.d/90-model.conf</code>; <code>/model probe</code> asks the endpoints for <code>/v1/models</code>. <code>/connect</code> asks for name, endpoint, model and key variable, runs one test turn and writes the provider to <code>splinter.conf.d/20-connect.conf</code>. Answers are rendered as Telegram HTML: bold, italic, code and links as tags, images as photos (<code>sendPhoto</code>, local files too), tables as columns in a monospace block; a piece Telegram cannot parse goes out as text instead of being lost. Programs in <code>commands/</code> answer in the chat; in the TUI their output goes to the model.</p>
<p>The bot registers its commands: the menu shows the loaded plugins' commands and the programs in <code>~/.splinter/commands/</code>; an approval arrives with Yes/No buttons. <code>/interview</code> asks the questions in the chat. <code>/new</code> starts a fresh conversation; <code>/model</code> offers the configured models as buttons, switches the transport and remembers the choice in <code>splinter.conf.d/90-model.conf</code>; <code>/model probe</code> asks the endpoints for <code>/v1/models</code>. <code>/connect</code> asks for name, endpoint, model and key variable, runs one test turn and writes the provider to <code>splinter.conf.d/20-connect.conf</code>. Answers are rendered as Telegram HTML: bold, italic, code and links as tags, images as photos (<code>sendPhoto</code>, local files too), other files as documents, tables as columns in a monospace block; a piece Telegram cannot parse goes out as text instead of being lost. Programs in <code>commands/</code> answer in the chat; in the TUI their output goes to the model.</p>
<p>Slash commands work there too. Programs in <code>~/.splinter/commands/</code> become <code>/name</code>: they get the rest of the line as an argument, and their output goes <em>to the model</em> as context — not to you as a reply. That is how the model fetches what it cannot see itself.</p>
<h2>What gets written down</h2>
+2 -2
View File
@@ -53,7 +53,7 @@ hr { border: 0; border-top: 1px solid #1d2126; margin: 3em 0 1.5em 0; }
<h1>splinter<span>_</span></h1>
<p class="lead">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.</p>
<p class="meta"><b>29083</b> Zeilen C99/POSIX &middot;
<p class="meta"><b>29110</b> Zeilen C99/POSIX &middot;
<b>25</b> Werkzeuge &middot; <b>35</b> Test-Programme &middot;
<b>16</b> Plugins &middot; <b>42</b> Farbschemata &middot; BSD-3-Clause</p>
@@ -141,7 +141,7 @@ plugin = plugins/reminder/reminder.so</pre>
<h2>Gateway: Telegram</h2>
<p><code>splinter --daemon</code> pollt <code>getUpdates</code>, ein Turn pro Nachricht, Antwort per <code>sendMessage</code>. Der Token liegt in <code>~/.splinter/telegram.token</code> mit Modus 0600 und wird nie als Argument uebergeben — Argumente stehen in <code>ps</code>. Waehrend eines Turns sieht der Chat alle vier Sekunden &bdquo;typing&ldquo;.</p>
<p>Der Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in <code>~/.splinter/commands/</code>; eine Zustimmung kommt mit Ja/Nein-Knoepfen. <code>/interview</code> stellt die Fragen im Chat. <code>/new</code> faengt eine frische Konversation an; <code>/model</code> bietet die konfigurierten Modelle als Knoepfe, schaltet den Transport um und merkt die Wahl in <code>splinter.conf.d/90-model.conf</code>; <code>/model probe</code> fragt die Endpoints nach <code>/v1/models</code>. <code>/connect</code> fragt Name, Endpoint, Modell und Key-Variable ab, macht einen Test-Turn und schreibt den Provider nach <code>splinter.conf.d/20-connect.conf</code>. Antworten werden als Telegram-HTML gesetzt: fett, kursiv, Code und Links als Tags, Bilder als Foto (<code>sendPhoto</code>, auch lokale Dateien), Tabellen als Spalten im Monospace-Block; ein Stueck, das Telegram nicht parst, geht als Text raus statt verloren. Programme in <code>commands/</code> antworten dort direkt im Chat; im TUI gehen sie ans Modell.</p>
<p>Der Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in <code>~/.splinter/commands/</code>; eine Zustimmung kommt mit Ja/Nein-Knoepfen. <code>/interview</code> stellt die Fragen im Chat. <code>/new</code> faengt eine frische Konversation an; <code>/model</code> bietet die konfigurierten Modelle als Knoepfe, schaltet den Transport um und merkt die Wahl in <code>splinter.conf.d/90-model.conf</code>; <code>/model probe</code> fragt die Endpoints nach <code>/v1/models</code>. <code>/connect</code> fragt Name, Endpoint, Modell und Key-Variable ab, macht einen Test-Turn und schreibt den Provider nach <code>splinter.conf.d/20-connect.conf</code>. Antworten werden als Telegram-HTML gesetzt: fett, kursiv, Code und Links als Tags, Bilder als Foto (<code>sendPhoto</code>, auch lokale Dateien), andere Dateien als Dokument, Tabellen als Spalten im Monospace-Block; ein Stueck, das Telegram nicht parst, geht als Text raus statt verloren. Programme in <code>commands/</code> antworten dort direkt im Chat; im TUI gehen sie ans Modell.</p>
<p>Slash-Kommandos funktionieren dort genauso. Programme in <code>~/.splinter/commands/</code> werden zu <code>/name</code>: sie bekommen den Rest der Zeile als Argument, und ihre Ausgabe geht <em>ans Modell</em> als Kontext — nicht an dich als Antwort. Damit holt sich das Modell, was es selbst nicht sehen kann.</p>
<h2>Was mitgeschrieben wird</h2>
+2 -2
View File
@@ -53,7 +53,7 @@ hr { border: 0; border-top: 1px solid #1d2126; margin: 3em 0 1.5em 0; }
<h1>splinter<span>_</span></h1>
<p class="lead">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.</p>
<p class="meta"><b>29083</b> linhas C99/POSIX &middot;
<p class="meta"><b>29110</b> linhas C99/POSIX &middot;
<b>25</b> ferramentas &middot; <b>35</b> programas de teste &middot;
<b>16</b> plugins &middot; <b>42</b> paletas &middot; BSD-3-Clause</p>
@@ -110,7 +110,7 @@ em ordem de nome. Chave desconhecida e erro com numero de linha.</p>
mesmos slash commands do terminal. O bot registra seus comandos: o menu mostra os comandos dos plugins carregados
e os programas em <code>~/.splinter/commands/</code>; uma aprovacao chega com
botoes Sim/Nao; as respostas viram HTML do Telegram (negrito, codigo, links,
tabelas em bloco monoespaceado, imagens como foto (inclusive arquivos locais)). <code>/new</code> comeca uma conversa nova; <code>/model</code> lista os modelos
tabelas em bloco monoespaceado, imagens como foto (inclusive arquivos locais), outros arquivos como documento). <code>/new</code> comeca uma conversa nova; <code>/model</code> lista os modelos
configurados em botoes, troca o transporte e guarda a escolha em
<code>splinter.conf.d/90-model.conf</code>; <code>/model probe</code> pergunta
aos endpoints por <code>/v1/models</code>. <code>/connect</code> pergunta nome,
+5 -2
View File
@@ -69,11 +69,14 @@ class H(http.server.BaseHTTPRequestHandler):
def do_POST(self):
raw = self.body()
ctype = self.headers.get("Content-Type", "")
if "/sendPhoto" in self.path and ctype.startswith("multipart/"):
if (("/sendPhoto" in self.path or "/sendDocument" in self.path) and
ctype.startswith("multipart/")):
kind = "photo-file" if "/sendPhoto" in self.path else "document-file"
cap = re.search(rb'name="caption"\r\n\r\n(.*?)\r\n', raw, re.S)
fn = re.search(rb'filename="([^"]*)"', raw)
with open(sys.argv[3], "a") as f:
f.write("photo-file: %s caption=%s\n" % (
f.write("%s: %s caption=%s\n" % (
kind,
fn.group(1).decode() if fn else "",
cap.group(1).decode() if cap else ""))
return self.reply({"ok": True, "result": {"message_id": 102}})
+6 -3
View File
@@ -149,10 +149,13 @@ check "a local image is uploaded" \
grep -q '^photo-file: pic.png caption=Lokal' "$D/sent.log"
check "the local image does not show up as markdown" \
sh -c "! grep -q '!\\[Lokal\\]' '$D/sent.log'"
run_text "zeig kein bild" 'Kein Bild' 110
check "a non-image file is not uploaded" \
run_text "zeig kein bild" 'document-file: notimg.txt' 110
check "a non-image file goes as a document" \
grep -q '^document-file: notimg.txt caption=Kein Bild' "$D/sent.log"
check "it is not sent as a photo" \
sh -c "! grep -q '^photo-file: notimg.txt' '$D/sent.log'"
check "the reference stays text" grep -q '!\[Kein Bild\]' "$D/sent.log"
check "the reference does not stay in the chat" \
sh -c "! grep -q '!\\[Kein Bild\\]' '$D/sent.log'"
# /new starts a fresh conversation and a fresh session file
run_text "/new" 'Neue Konversation: sess-' 45
+3 -3
View File
@@ -305,7 +305,7 @@ SECTIONS = {
"<code>sendMessage</code>. Der Token liegt in "
"<code>~/.splinter/telegram.token</code> mit Modus 0600 und wird nie als Argument "
"uebergeben — Argumente stehen in <code>ps</code>. Waehrend eines Turns sieht der "
"Chat alle vier Sekunden &bdquo;typing&ldquo;.</p>\n<p>Der Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in <code>~/.splinter/commands/</code>; eine Zustimmung kommt mit Ja/Nein-Knoepfen. <code>/interview</code> stellt die Fragen im Chat. <code>/new</code> faengt eine frische Konversation an; <code>/model</code> bietet die konfigurierten Modelle als Knoepfe, schaltet den Transport um und merkt die Wahl in <code>splinter.conf.d/90-model.conf</code>; <code>/model probe</code> fragt die Endpoints nach <code>/v1/models</code>. <code>/connect</code> fragt Name, Endpoint, Modell und Key-Variable ab, macht einen Test-Turn und schreibt den Provider nach <code>splinter.conf.d/20-connect.conf</code>. Antworten werden als Telegram-HTML gesetzt: fett, kursiv, Code und Links als Tags, Bilder als Foto (<code>sendPhoto</code>, auch lokale Dateien), Tabellen als Spalten im Monospace-Block; ein Stueck, das Telegram nicht parst, geht als Text raus statt verloren. Programme in <code>commands/</code> antworten dort direkt im Chat; im TUI gehen sie ans Modell.</p>\n<p>Slash-Kommandos funktionieren "
"Chat alle vier Sekunden &bdquo;typing&ldquo;.</p>\n<p>Der Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in <code>~/.splinter/commands/</code>; eine Zustimmung kommt mit Ja/Nein-Knoepfen. <code>/interview</code> stellt die Fragen im Chat. <code>/new</code> faengt eine frische Konversation an; <code>/model</code> bietet die konfigurierten Modelle als Knoepfe, schaltet den Transport um und merkt die Wahl in <code>splinter.conf.d/90-model.conf</code>; <code>/model probe</code> fragt die Endpoints nach <code>/v1/models</code>. <code>/connect</code> fragt Name, Endpoint, Modell und Key-Variable ab, macht einen Test-Turn und schreibt den Provider nach <code>splinter.conf.d/20-connect.conf</code>. Antworten werden als Telegram-HTML gesetzt: fett, kursiv, Code und Links als Tags, Bilder als Foto (<code>sendPhoto</code>, auch lokale Dateien), andere Dateien als Dokument, Tabellen als Spalten im Monospace-Block; ein Stueck, das Telegram nicht parst, geht als Text raus statt verloren. Programme in <code>commands/</code> antworten dort direkt im Chat; im TUI gehen sie ans Modell.</p>\n<p>Slash-Kommandos funktionieren "
"dort genauso. Programme in <code>~/.splinter/commands/</code> werden zu "
"<code>/name</code>: sie bekommen den Rest der Zeile als Argument, und ihre Ausgabe "
"geht <em>ans Modell</em> als Kontext — nicht an dich als Antwort. Damit holt sich "
@@ -385,7 +385,7 @@ SECTIONS = {
"<code>sendMessage</code>. The token lives in "
"<code>~/.splinter/telegram.token</code> with mode 0600 and is never passed as an "
"argument — arguments end up in <code>ps</code>. While a turn runs, the chat sees "
"&quot;typing&quot; every four seconds.</p>\n<p>The bot registers its commands: the menu shows the loaded plugins' commands and the programs in <code>~/.splinter/commands/</code>; an approval arrives with Yes/No buttons. <code>/interview</code> asks the questions in the chat. <code>/new</code> starts a fresh conversation; <code>/model</code> offers the configured models as buttons, switches the transport and remembers the choice in <code>splinter.conf.d/90-model.conf</code>; <code>/model probe</code> asks the endpoints for <code>/v1/models</code>. <code>/connect</code> asks for name, endpoint, model and key variable, runs one test turn and writes the provider to <code>splinter.conf.d/20-connect.conf</code>. Answers are rendered as Telegram HTML: bold, italic, code and links as tags, images as photos (<code>sendPhoto</code>, local files too), tables as columns in a monospace block; a piece Telegram cannot parse goes out as text instead of being lost. Programs in <code>commands/</code> answer in the chat; in the TUI their output goes to the model.</p>\n<p>Slash commands work there too. "
"&quot;typing&quot; every four seconds.</p>\n<p>The bot registers its commands: the menu shows the loaded plugins' commands and the programs in <code>~/.splinter/commands/</code>; an approval arrives with Yes/No buttons. <code>/interview</code> asks the questions in the chat. <code>/new</code> starts a fresh conversation; <code>/model</code> offers the configured models as buttons, switches the transport and remembers the choice in <code>splinter.conf.d/90-model.conf</code>; <code>/model probe</code> asks the endpoints for <code>/v1/models</code>. <code>/connect</code> asks for name, endpoint, model and key variable, runs one test turn and writes the provider to <code>splinter.conf.d/20-connect.conf</code>. Answers are rendered as Telegram HTML: bold, italic, code and links as tags, images as photos (<code>sendPhoto</code>, local files too), other files as documents, tables as columns in a monospace block; a piece Telegram cannot parse goes out as text instead of being lost. Programs in <code>commands/</code> answer in the chat; in the TUI their output goes to the model.</p>\n<p>Slash commands work there too. "
"Programs in <code>~/.splinter/commands/</code> become <code>/name</code>: they get "
"the rest of the line as an argument, and their output goes <em>to the model</em> 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.</p>""",
mesmos slash commands do terminal. O bot registra seus comandos: o menu mostra os comandos dos plugins carregados
e os programas em <code>~/.splinter/commands/</code>; uma aprovacao chega com
botoes Sim/Nao; as respostas viram HTML do Telegram (negrito, codigo, links,
tabelas em bloco monoespaceado, imagens como foto (inclusive arquivos locais)). <code>/new</code> comeca uma conversa nova; <code>/model</code> lista os modelos
tabelas em bloco monoespaceado, imagens como foto (inclusive arquivos locais), outros arquivos como documento). <code>/new</code> comeca uma conversa nova; <code>/model</code> lista os modelos
configurados em botoes, troca o transporte e guarda a escolha em
<code>splinter.conf.d/90-model.conf</code>; <code>/model probe</code> pergunta
aos endpoints por <code>/v1/models</code>. <code>/connect</code> pergunta nome,