From cc9747b1a75ee6de30d057835acd3b14c3fdd469 Mon Sep 17 00:00:00 2001
From: lotherk
Date: Tue, 10 Nov 2026 19:33:38 +0000
Subject: [PATCH] model choice sticks, endpoints are probed, connect is tested,
A2A takes files
/model writes its choice to .d/90-model.conf, so the next start uses
it; picking main deletes the file and the configuration speaks again. With a
plugin transport nothing is written, because that program picks the model.
/model probe asks every endpoint /v1/models and offers what it really serves
as buttons; the callback carries an index, because a GGUF path does not fit
in Telegram's 64 bytes. The TUI gets the same command: the list, or
/model , with the same persistence.
/connect runs one tiny turn against the provider it just saved (30 s) and
says whether endpoint, model and key answer. The message with the buttons
goes out before the wait starts, so the save is visible immediately.
A2A no longer refuses binary parts: file{bytes} and raw with a non-text media
type are written to the session's inbox (0600, 8 MiB cap) and the prompt says
[file at (mime, n bytes)], so a text model can hand the file to
a tool. The client saves what a remote agent sends the same way
(SPLINTER_A2A_INBOX). SubscribeToTask stays refused: the task store has no
live events, and a one-shot replay would pretend to be a subscription.
Markdown gains autolinks and images (as links, since Telegram
has no inline image without sendPhoto).
---
README.md | 32 +++--
TODO.md | 5 +-
docs/CONFIG.md | 10 +-
docs/PLUGINS.md | 16 ++-
docs/ROADMAP.md | 15 ++-
plugins/a2a/a2a.c | 137 +++++++++++++++----
share/locale/de.msg | 10 ++
share/locale/en.msg | 10 ++
share/locale/pt_BR.msg | 10 ++
src/a2aserver.c | 228 ++++++++++++++++++++++++++-----
src/main.c | 10 +-
src/providers.c | 232 ++++++++++++++++++++++++++++++++
src/providers.h | 21 +++
src/telegram.c | 283 ++++++++++++++++++++++++++++++++++++++-
src/tgmd.c | 41 ++++++
src/ui.c | 101 +++++++++++++-
src/ui.h | 3 +-
src/www/index.en.html | 8 +-
src/www/index.html | 7 +-
src/www/index.pt.html | 10 +-
tests/fake_a2a.py | 19 ++-
tests/fake_telegram.py | 26 +++-
tests/test_a2a.sh | 11 ++
tests/test_a2a_server.sh | 26 +++-
tests/test_gateway.sh | 12 +-
tests/test_providers.c | 35 +++++
tests/test_tgmd.c | 4 +
tests/test_ui.sh | 5 +
tools/gen_www.py | 19 ++-
29 files changed, 1220 insertions(+), 126 deletions(-)
diff --git a/README.md b/README.md
index b0b96d7..12fd5ac 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ the screen, a sidebar on one quarter, plugins that can put tools and widgets
into both.
make # libsplinter.so, the binary, the plugins
- make check # every test binary (33), no network, no model
+ make check # every test binary (35), no network, no model
splinter # starts the chat from ~/.config/splinter/config
@@ -140,9 +140,12 @@ the server creates a context and returns it in the task. A
`taskPushNotificationConfig` in the request posts the completed task to a
webhook: loopback is always allowed, other hosts need
`SPLINTER_A2A_PUSH_ALLOW`; the config's token travels as
-`X-A2A-Notification-Token`, its authentication as `Authorization`. URL or
-binary parts, the push-config CRUD methods, `CancelTask` and continuation of an
-interrupted task are refused with a JSON-RPC error rather than half-answered. Beyond loopback the bearer token is required;
+`X-A2A-Notification-Token`, its authentication as `Authorization`. Binary
+`file`/`raw` parts are written into the session's `inbox/` and described to the
+model by path (a text model cannot read a PNG, the agent around it can); URL
+parts are fetched from loopback or a host in `SPLINTER_A2A_URL_ALLOW`.
+`SubscribeToTask` and a binary URL part stay refused with a JSON-RPC error
+rather than half-answered. Beyond loopback the bearer token is required;
there is no TLS, so put it behind ssh or a tunnel.
## Configuration
@@ -306,20 +309,25 @@ buttons**; the callback answers the button, removes the buttons and writes the
ack file. The text form `ok ` / `no ` still works.
The model's markdown is rendered as Telegram HTML: bold, italic, strike,
-inline code, fenced blocks, links and quotes become tags, everything else is
-escaped. Tables are laid out as columns inside a `` block. A long answer
+inline code, fenced blocks, links (also `` and images, which become
+links) and quotes become tags, everything else is escaped. Tables are laid out as columns inside a `` 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.
`/model` lists the models the config names (the main endpoint, every delegate
with a model, every exit) as buttons and points the running transport at the
-one you press; the choice lasts for this session. `/model ` keeps the
-endpoint and takes another model from it. `/connect` adds a provider in four
-answers — name, endpoint, model, key variable (or `-` for none); `ollama` and
-`opencode` stand for their usual endpoint. It writes the line to
-`.d/20-connect.conf`, so the next start has the provider too, and
-offers to use it right away.
+one you press. The choice is written to `.d/90-model.conf`, so the next
+start uses it too; picking `main` deletes that file. `/model ` keeps the
+endpoint and takes another model from it. `/model probe` asks every endpoint
+`/v1/models` and offers what it really serves. The TUI has the same `/model`
+(list, or `/model `), without buttons.
+
+`/connect` adds a provider in four answers — name, endpoint, model, key
+variable (or `-` for none); `ollama` and `opencode` stand for their usual
+endpoint. It writes the line to `.d/20-connect.conf`, so the next start
+has the provider too, runs one tiny turn against it to prove endpoint, model
+and key work, and offers to use it right away.
`/interview` asks the same six questions as `splinter --interview`, one
message per answer; `/skip` skips one and `/cancel` stops. A program in
diff --git a/TODO.md b/TODO.md
index 54323e3..1f946c6 100644
--- a/TODO.md
+++ b/TODO.md
@@ -6,8 +6,9 @@ Erledigtes steht unten, damit die Liste nicht wieder behauptet, etwas sei offen.
## Offen
-Nichts aus der alten Liste. Binaere A2A-Teile bleiben bewusst abgelehnt
-(`ContentTypeNotSupported`); URL-Teile werden nur von erlaubten Hosts geholt.
+Nichts aus der alten Liste. A2A nimmt binaere `file`/`raw`-Teile an und legt
+sie in `inbox/` ab, der Prompt nennt den Pfad; URL-Teile werden nur von
+erlaubten Hosts geholt. `SubscribeToTask` bleibt abgelehnt.
## Erledigt
diff --git a/docs/CONFIG.md b/docs/CONFIG.md
index b7d6745..ec699cd 100644
--- a/docs/CONFIG.md
+++ b/docs/CONFIG.md
@@ -174,9 +174,13 @@ and stand for `http://127.0.0.1:11434/v1/chat/completions` and
`https://opencode.ai/zen/go/v1/chat/completions` (the latter with
`OPENCODE_GO_API_KEY`).
-`/model` does not write anything: it offers the models the config names and
-switches the transport for the rest of the session. Delete nothing to undo it;
-restart.
+`/model` offers the models the config names and switches the transport; the
+choice is written to `.d/90-model.conf` (`endpoint`, `model`,
+`api_key_env`), so the next start has it. Picking `main` deletes that file and
+the configuration speaks again. `/model probe` asks each endpoint `/v1/models`
+and lists what it really serves; `/model ` takes another model from the
+current endpoint. With a plugin `transport` nothing is written — that program
+picks the model.
## Drop-ins
diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md
index 5dc58bb..460c27e 100644
--- a/docs/PLUGINS.md
+++ b/docs/PLUGINS.md
@@ -294,8 +294,9 @@ selected like any other:
It sends `SendMessage` as JSON-RPC 2.0 with one text part, blocking, and reads
either a direct `Message` or a `Task` in `TASK_STATE_COMPLETED`; text parts,
text/plain `raw` parts (base64) and string `data` parts from the status message
-and the artifacts are joined. A `url` or binary part is ignored on the client
-and refused on the server with `ContentTypeNotSupported` (-32005). `SPLINTER_A2A_FULL=1` sends the
+and the artifacts are joined. A binary `file` or `raw` part is saved
+(`SPLINTER_A2A_INBOX`, default `$TMPDIR/splinter-a2a-inbox`) and named in the
+answer by path, so the agent can open it; a `url` part is ignored on the client. `SPLINTER_A2A_FULL=1` sends the
whole transcript instead of the last user turn, and `SPLINTER_A2A_TIMEOUT` sets
the curl timeout (default 300 seconds). The task id and context id are remembered
for the session, so the next turn stays in the same A2A context; a terminal task
@@ -349,8 +350,11 @@ push-config methods (`CreateTaskPushNotificationConfig`, `Get...`, `List...`,
`Delete...`) manage the same configs in memory.
A text/plain `url` part is fetched from loopback or a host in
-`SPLINTER_A2A_URL_ALLOW` (same syntax, 1 MiB cap, no redirects); a binary or
-other media type is refused.
+`SPLINTER_A2A_URL_ALLOW` (same syntax, 1 MiB cap, no redirects). A binary part
+arrives as `file { name, mimeType, bytes }` or `raw` + `mediaType`; it is
+written to the session's `inbox/` (0600, 8 MiB cap) and the prompt says
+`[file at (mime, n bytes)]`, because a text model cannot read a
+PNG but the agent around it can. The same is true for a binary `url` part.
A mutating tool that needs approval pauses the task in
`TASK_STATE_INPUT_REQUIRED`; the assistant call is already in the context, the
@@ -359,7 +363,7 @@ tool has not run. Another `SendMessage` with the same `taskId` and a
`SendStreamingMessage` has nowhere to resume, so it denies mutating tools
instead of pausing.
-Refused with a JSON-RPC error, not half-answered: `SubscribeToTask` and binary
-parts. Beyond loopback
+Refused with a JSON-RPC error, not half-answered: `SubscribeToTask`. Beyond
+loopback
`SPLINTER_A2A_SERVER_TOKEN` is required and checked as
`Authorization: Bearer ...`; there is no TLS.
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index d715197..8772896 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -5,8 +5,9 @@ Stand: 2026-11-10. Die geprüfte, ausführliche Liste mit Belegen steht in
## Offen
-Nichts aus der alten A2A-Liste. Binaere A2A-Teile bleiben bewusst abgelehnt;
-URL-Teile werden nur von erlaubten Hosts geholt.
+Nichts aus der alten A2A-Liste. Binaere A2A-Teile landen in `inbox/` und
+werden dem Modell als Pfad genannt; URL-Teile nur von erlaubten Hosts.
+`SubscribeToTask` bleibt abgelehnt.
## Erledigt
@@ -30,10 +31,12 @@ URL-Teile werden nur von erlaubten Hosts geholt.
- **Tabellen im Chat**: `src/md.c` erkennt Kopf + Trenner, rechnet Spaltenbreiten
und zeichnet ausgerichteten Text (`test_md`, `test_ui.sh`)
- **Modelle wechseln und Provider anlegen**: `/model` liest die konfigurierten
- Modelle (Haupt-Endpoint, Delegates, Exits) und haengt den Transport um;
- `/connect` schreibt eine validierte `delegate`-Zeile in den Drop-in neben der
- benutzten Konfiguration und registriert sie im laufenden Prozess
- (`test_providers`, `test_gateway.sh`)
+ Modelle (Haupt-Endpoint, Delegates, Exits), haengt den Transport um, merkt
+ die Wahl in `90-model.conf` und fragt per `/model probe` die Endpoints nach
+ `/v1/models`; das TUI kann dasselbe. `/connect` schreibt eine validierte
+ `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`)
- **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/plugins/a2a/a2a.c b/plugins/a2a/a2a.c
index 5cdbb85..8a58af7 100644
--- a/plugins/a2a/a2a.c
+++ b/plugins/a2a/a2a.c
@@ -15,9 +15,9 @@
* artifacts are joined. A Task id and context id are remembered for the rest
* of the session, so the next turn continues the same conversation.
*
- * Not implemented, and said out loud: streaming (SendStreamingMessage), file
- * and structured-data parts, push notifications, task cancel/get, and the
- * agent-card discovery step. The endpoint is configured directly:
+ * Not implemented, and said out loud: SubscribeToTask. A binary part from the
+ * other agent is saved and named by path instead of being dropped. The
+ * endpoint is configured directly:
*
* SPLINTER_A2A_URL the JSON-RPC endpoint (required)
* SPLINTER_A2A_TOKEN optional bearer token
@@ -27,11 +27,14 @@
* The transport is selected like any other: --plugin plugins/a2a/a2a.so
* --transport a2a.
*/
+#include
#include
+#include
#include
#include
#include
#include
+#include
#include
#include
#include
@@ -133,9 +136,96 @@ append_piece(struct sp_buf *out, const char *s)
return sp_buf_puts(out, s);
}
+/* A file a remote agent sent us: its bytes go to disk, its path to the model. */
+#define A2A_MAX_PART (8u * 1024u * 1024u)
+
+static void
+safe_name(const char *in, char *out, size_t cap)
+{
+ const char *base = in != NULL ? strrchr(in, '/') : NULL;
+ size_t n = 0;
+
+ if (base != NULL)
+ in = base + 1;
+ for (; in != NULL && *in != '\0' && n + 1 < cap; in++)
+ out[n++] = (isalnum((unsigned char)*in) || *in == '.' ||
+ *in == '-' || *in == '_') ? *in : '_';
+ if (n == 0) {
+ snprintf(out, cap, "part");
+ return;
+ }
+ out[n] = '\0';
+ if (out[0] == '.')
+ out[0] = '_';
+}
+
+static int
+save_part(const char *name, const char *mime, const char *data, size_t n,
+ struct sp_buf *out)
+{
+ const char *env = getenv("SPLINTER_A2A_INBOX");
+ const char *tmp = getenv("TMPDIR");
+ char dir[700], path[900], safe[96];
+ size_t off = 0;
+ int fd;
+ static unsigned long seq;
+
+ if (n > A2A_MAX_PART)
+ return -1;
+ if (env != NULL && *env != '\0')
+ snprintf(dir, sizeof(dir), "%s", env);
+ else
+ snprintf(dir, sizeof(dir), "%s/splinter-a2a-inbox",
+ tmp != NULL && *tmp != '\0' ? tmp : "/tmp");
+ if (mkdir(dir, 0700) != 0 && errno != EEXIST)
+ return -1;
+ safe_name(name, safe, sizeof(safe));
+ snprintf(path, sizeof(path), "%s/%d-%lu-%s", dir, (int)getpid(),
+ ++seq, safe);
+ fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
+ if (fd < 0)
+ return -1;
+ while (off < n) {
+ ssize_t wr = write(fd, data + off, n - off);
+
+ if (wr <= 0) {
+ close(fd);
+ (void)unlink(path);
+ return -1;
+ }
+ off += (size_t)wr;
+ }
+ close(fd);
+ return sp_buf_printf(out, "[file %s at %s (%s, %zu bytes)]", safe,
+ path, mime != NULL && *mime != '\0' ? mime : "binary", n);
+}
+
+/* base64 bytes: text becomes text, anything else a file the agent can open */
+static int
+part_bytes(const char *b64, const char *name, const char *mime,
+ struct sp_buf *out)
+{
+ struct sp_buf dec;
+ int ok = 0;
+
+ if (sp_buf_init(&dec) != 0)
+ return -1;
+ if (sp_b64_decode(b64, strlen(b64), &dec) != 0 || dec.len == 0) {
+ sp_buf_free(&dec);
+ return -1;
+ }
+ if (mime != NULL && *mime != '\0' && strncmp(mime, "text/", 5) != 0) {
+ ok = save_part(name, mime, dec.p, dec.len, out) == 0;
+ } else {
+ ok = append_piece(out, dec.p) == 0;
+ }
+ sp_buf_free(&dec);
+ return ok ? 0 : -1;
+}
+
/*
- * Text, a string in data, or a text/plain raw part. A binary or url part is
- * ignored: the transport has nowhere to put a file, and an answer made only of
+ * Text, a string in data, a base64 raw part or a file. A part that carries no
+ * bytes cannot be turned into words, so it is skipped: an answer made only of
* one becomes "empty answer" rather than a made-up string.
*/
static int
@@ -149,8 +239,9 @@ collect_parts(const mcp_json *parts, struct sp_buf *out)
n = mcp_array_len(parts);
for (i = 0; i < n; i++) {
const mcp_json *p = mcp_array_at(parts, i);
+ const mcp_json *file, *meta;
const char *t = mcp_arg_string(p, "text");
- const char *d, *raw, *mt;
+ const char *d, *raw, *mt, *name = NULL;
if (t != NULL && *t != '\0') {
if (append_piece(out, t) != 0)
@@ -165,27 +256,25 @@ collect_parts(const mcp_json *parts, struct sp_buf *out)
found = 1;
continue;
}
+ mt = mcp_arg_string(p, "mediaType");
+ meta = mcp_arg(p, "metadata");
+ name = meta != NULL ? mcp_arg_string(meta, "filename") : NULL;
+ file = mcp_arg(p, "file");
+ if (file != NULL) {
+ const char *fn = mcp_arg_string(file, "name");
+ const char *fm = mcp_arg_string(file, "mimeType");
+ const char *bytes = mcp_arg_string(file, "bytes");
+
+ if (bytes != NULL && *bytes != '\0' &&
+ part_bytes(bytes, fn, fm, out) == 0)
+ found = 1;
+ continue;
+ }
raw = mcp_arg_string(p, "raw");
if (raw == NULL || *raw == '\0')
continue;
- mt = mcp_arg_string(p, "mediaType");
- if (mt != NULL && *mt != '\0' && strncmp(mt, "text/", 5) != 0)
- continue;
- {
- struct sp_buf dec;
-
- if (sp_buf_init(&dec) != 0)
- return 0;
- if (sp_b64_decode(raw, strlen(raw), &dec) == 0 &&
- dec.len > 0) {
- if (append_piece(out, dec.p) != 0) {
- sp_buf_free(&dec);
- return 0;
- }
- found = 1;
- }
- sp_buf_free(&dec);
- }
+ if (part_bytes(raw, name, mt, out) == 0)
+ found = 1;
}
return found;
}
diff --git a/share/locale/de.msg b/share/locale/de.msg
index ef9dfc5..5a007f1 100644
--- a/share/locale/de.msg
+++ b/share/locale/de.msg
@@ -140,6 +140,13 @@ model.failed = Umschalten fehlgeschlagen: %s
model.switched = Modell: %s (Provider %s, diese Sitzung).
model.no_key = " (kein %s gesetzt)"
+model.saved = Modell: %s (Provider %s). Fuer den naechsten Start gespeichert.
+model.save_failed = Modell: %s (Provider %s). Nicht gespeichert: %s
+model.probe = Endpoints nach Modellen fragen
+model.probe_start = Frage %zu Provider nach ihren Modellen ...
+model.probe_none = Kein Endpoint hat seine Modelle genannt. /model zeigt weiter die konfigurierten.
+model.probe_stale = Die Liste ist nicht mehr da; /model probe noch einmal.
+
model.toast = Schalte um
connect.start = Neuer Provider. /cancel bricht ab.
connect.name = Name? Kleinbuchstaben, Ziffern, - und _ (max 31).
@@ -156,6 +163,9 @@ connect.failed = Speichern fehlgeschlagen: %s
connect.nodir = Kein Konfigurationsverzeichnis zum Schreiben.
connect.line_too_long = Die Provider-Zeile ist zu lang fuer die Konfiguration.
connect.cancel = connect abgebrochen.
+connect.tested = Test bestanden: %s
+connect.test_failed = Der Test schlug fehl: %s (gespeichert ist er trotzdem)
+
connect.use = Jetzt nutzen
connect.later = Spaeter
diff --git a/share/locale/en.msg b/share/locale/en.msg
index dd33128..57cc13d 100644
--- a/share/locale/en.msg
+++ b/share/locale/en.msg
@@ -139,6 +139,13 @@ model.failed = Could not switch: %s
model.switched = Model: %s (provider %s, this session).
model.no_key = " (no %s set)"
+model.saved = Model: %s (provider %s). Saved for the next start.
+model.save_failed = Model: %s (provider %s). Not saved: %s
+model.probe = Ask the endpoints for their models
+model.probe_start = Asking %zu provider(s) for their models...
+model.probe_none = No endpoint listed its models. /model still shows the configured ones.
+model.probe_stale = That list is gone; run /model probe again.
+
model.toast = Switching
connect.start = New provider. /cancel stops.
connect.name = Name? Lower-case letters, digits, - and _ (max 31).
@@ -155,6 +162,9 @@ connect.failed = Could not save: %s
connect.nodir = No configuration directory to write to.
connect.line_too_long = That provider line is too long for the configuration.
connect.cancel = connect cancelled.
+connect.tested = Test passed: %s
+connect.test_failed = The test failed: %s (it is saved anyway)
+
connect.use = Use now
connect.later = Later
diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg
index 154f738..08f7595 100644
--- a/share/locale/pt_BR.msg
+++ b/share/locale/pt_BR.msg
@@ -143,6 +143,13 @@ model.failed = Nao consegui trocar: %s
model.switched = Modelo: %s (provedor %s, esta sessao).
model.no_key = " (%s nao definida)"
+model.saved = Modelo: %s (provedor %s). Salvo para a proxima sessao.
+model.save_failed = Modelo: %s (provedor %s). Nao salvo: %s
+model.probe = Perguntar aos endpoints quais modelos servem
+model.probe_start = Perguntando a %zu provedor(es) pelos modelos...
+model.probe_none = Nenhum endpoint listou seus modelos. /model continua mostrando os configurados.
+model.probe_stale = A lista sumiu; rode /model probe de novo.
+
model.toast = Trocando
connect.start = Novo provedor. /cancel cancela.
connect.name = Nome? Letras minusculas, digitos, - e _ (max 31).
@@ -159,6 +166,9 @@ connect.failed = Nao consegui salvar: %s
connect.nodir = Nenhum diretorio de configuracao para escrever.
connect.line_too_long = A linha do provedor e longa demais para a configuracao.
connect.cancel = connect cancelado.
+connect.tested = Teste passou: %s
+connect.test_failed = O teste falhou: %s (mesmo assim esta salvo)
+
connect.use = Usar agora
connect.later = Depois
diff --git a/src/a2aserver.c b/src/a2aserver.c
index e25c2fb..a2c254f 100644
--- a/src/a2aserver.c
+++ b/src/a2aserver.c
@@ -12,10 +12,10 @@
* POST /a2a GetTask -> the stored task
* GET /.well-known/agent-card.json
*
- * Deliberately not here yet: file and structured-data parts, push
- * notifications, CancelTask, and multi-turn continuation of an interrupted
- * task. Each of those is refused with a JSON-RPC error rather than answered
- * with half a protocol. Streaming is served: SendStreamingMessage writes
+ * Parts: text, string data, base64 raw and file{bytes}. Bytes that are not
+ * text are written into the session's inbox and the prompt says where, so a
+ * text model can hand the file to a tool. Deliberately not here yet:
+ * SubscribeToTask. Streaming is served: SendStreamingMessage writes
* artifactUpdate and statusUpdate events over SSE.
*
* One turn per request, one connection at a time. A contextId is a
@@ -31,6 +31,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -38,6 +39,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -272,12 +274,16 @@ static int url_host_allowed(const char *url);
static int fetch_url_text(const char *url, struct sp_buf *out);
/*
- * A part can be text, a string in data, a text/plain raw part (base64), or a
- * text/plain url from an allowlisted host. A structured object is not guessed
- * at; a URL to anywhere else is refused with ContentTypeNotSupported. Returns
- * 0 when text was collected, 1 when the content cannot be used, -1 on
+ * A part can be text, a string in data, a file (bytes), a raw part (base64) or
+ * a url from an allowlisted host. Text is appended as text; bytes that are not
+ * text are written into the session's inbox and described by path, because a
+ * text-only model cannot read a PNG but the agent around it can. A URL to
+ * anywhere else is refused with ContentTypeNotSupported. Returns 0 when
+ * something was collected, 1 when the content cannot be used, -1 on
* allocation failure.
*/
+#define A2A_MAX_PART (8u * 1024u * 1024u)
+
static int
append_text(struct sp_buf *out, const char *s)
{
@@ -286,8 +292,107 @@ append_text(struct sp_buf *out, const char *s)
return sp_buf_puts(out, s);
}
+/* /inbox, or a temp directory when this run has no session */
static int
-collect_text(const mcp_json *parts, struct sp_buf *out)
+inbox_dir(struct sp_agent *ag, char *buf, size_t len)
+{
+ if (ag != NULL && ag->sess != NULL && ag->sess->dir[0] != '\0')
+ snprintf(buf, len, "%s/inbox", ag->sess->dir);
+ else {
+ const char *tmp = getenv("TMPDIR");
+
+ snprintf(buf, len, "%s/splinter-a2a-inbox",
+ tmp != NULL && *tmp != '\0' ? tmp : "/tmp");
+ }
+ if (mkdir(buf, 0700) != 0 && errno != EEXIST)
+ return -1;
+ return 0;
+}
+
+/* a part's name is a suggestion from a stranger: keep it a plain file name */
+static void
+safe_name(const char *in, char *out, size_t cap)
+{
+ const char *base = in != NULL ? strrchr(in, '/') : NULL;
+ size_t n = 0;
+
+ if (base != NULL)
+ in = base + 1;
+ for (; in != NULL && *in != '\0' && n + 1 < cap; in++)
+ out[n++] = (isalnum((unsigned char)*in) || *in == '.' ||
+ *in == '-' || *in == '_') ? *in : '_';
+ if (n == 0) {
+ snprintf(out, cap, "part");
+ return;
+ }
+ out[n] = '\0';
+ if (out[0] == '.')
+ out[0] = '_';
+}
+
+static int
+attach_part(const char *inbox, const char *name, const char *mime,
+ const char *data, size_t n, struct sp_buf *out)
+{
+ static unsigned long seq;
+ char path[960], safe[96];
+ size_t off = 0;
+ int fd;
+
+ if (inbox == NULL || *inbox == '\0')
+ return 1;
+ safe_name(name, safe, sizeof(safe));
+ snprintf(path, sizeof(path), "%s/%d-%lu-%s", inbox, (int)getpid(),
+ ++seq, safe);
+ fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
+ if (fd < 0)
+ return 1;
+ while (off < n) {
+ ssize_t wr = write(fd, data + off, n - off);
+
+ if (wr <= 0) {
+ close(fd);
+ (void)unlink(path);
+ return -1;
+ }
+ off += (size_t)wr;
+ }
+ close(fd);
+ if (out->len > 0 && sp_buf_puts(out, "\n") != 0)
+ return -1;
+ return sp_buf_printf(out, "[file %s at %s (%s, %zu bytes)]", safe,
+ path, mime != NULL && *mime != '\0' ? mime : "binary", n);
+}
+
+/* base64 bytes: text goes into the prompt, anything else into the inbox */
+static int
+part_bytes(const char *b64, const char *name, const char *mime,
+ const char *inbox, struct sp_buf *out)
+{
+ struct sp_buf dec;
+ int rc = 0;
+
+ if (sp_buf_init(&dec) != 0)
+ return -1;
+ if (sp_b64_decode(b64, strlen(b64), &dec) != 0) {
+ sp_buf_free(&dec);
+ return 1;
+ }
+ if (dec.len > A2A_MAX_PART) {
+ sp_buf_free(&dec);
+ return 1;
+ }
+ if (mime != NULL && *mime != '\0' && strncmp(mime, "text/", 5) != 0) {
+ rc = attach_part(inbox, name, mime, dec.p, dec.len, out);
+ } else if (dec.len > 0) {
+ rc = append_text(out, dec.p) == 0 ? 0 : -1;
+ }
+ sp_buf_free(&dec);
+ return rc;
+}
+
+static int
+collect_text(const mcp_json *parts, const char *inbox, struct sp_buf *out)
{
size_t i, n;
int got = 0;
@@ -297,8 +402,11 @@ collect_text(const mcp_json *parts, struct sp_buf *out)
n = mcp_array_len(parts);
for (i = 0; i < n; i++) {
const mcp_json *p = mcp_array_at(parts, i);
+ const mcp_json *file;
+ const mcp_json *meta;
const char *t = mcp_arg_string(p, "text");
- const char *d, *raw, *mt;
+ const char *d, *raw, *mt, *name = NULL, *bytes;
+ int rc;
if (t != NULL && *t != '\0') {
if (append_text(out, t) != 0)
@@ -313,25 +421,58 @@ collect_text(const mcp_json *parts, struct sp_buf *out)
got = 1;
continue;
}
+ mt = mcp_arg_string(p, "mediaType");
+ meta = mcp_arg(p, "metadata");
+ name = meta != NULL ? mcp_arg_string(meta, "filename") : NULL;
+ /* the A2A FilePart: file { name, mimeType, bytes } */
+ file = mcp_arg(p, "file");
+ if (file != NULL) {
+ const char *fn = mcp_arg_string(file, "name");
+ const char *fm = mcp_arg_string(file, "mimeType");
+
+ bytes = mcp_arg_string(file, "bytes");
+ if (bytes == NULL || *bytes == '\0') {
+ /* file.uri: handled like a url part below */
+ const char *uri = mcp_arg_string(file, "uri");
+
+ if (uri == NULL || *uri == '\0' ||
+ !url_host_allowed(uri))
+ return 1;
+ {
+ struct sp_buf fetched;
+
+ if (sp_buf_init(&fetched) != 0)
+ return -1;
+ if (fetch_url_text(uri, &fetched) != 0) {
+ sp_buf_free(&fetched);
+ return 1;
+ }
+ if (fm != NULL && *fm != '\0' &&
+ strncmp(fm, "text/", 5) != 0)
+ rc = attach_part(inbox, fn, fm,
+ fetched.p, fetched.len,
+ out);
+ else
+ rc = append_text(out,
+ fetched.p) == 0 ? 0 : -1;
+ sp_buf_free(&fetched);
+ if (rc != 0)
+ return rc;
+ got = 1;
+ continue;
+ }
+ }
+ rc = part_bytes(bytes, fn, fm, inbox, out);
+ if (rc != 0)
+ return rc;
+ got = 1;
+ continue;
+ }
raw = mcp_arg_string(p, "raw");
if (raw != NULL && *raw != '\0') {
- struct sp_buf dec;
-
- mt = mcp_arg_string(p, "mediaType");
- if (mt != NULL && *mt != '\0' &&
- strncmp(mt, "text/", 5) != 0)
- return 1;
- if (sp_buf_init(&dec) != 0)
- return -1;
- if (sp_b64_decode(raw, strlen(raw), &dec) != 0) {
- sp_buf_free(&dec);
- return 1;
- }
- if (dec.len > 0 && append_text(out, dec.p) != 0) {
- sp_buf_free(&dec);
- return -1;
- }
- sp_buf_free(&dec);
+ rc = part_bytes(raw, name, mt, inbox, out);
+ if (rc != 0)
+ return rc;
got = 1;
continue;
}
@@ -341,10 +482,6 @@ collect_text(const mcp_json *parts, struct sp_buf *out)
if (url != NULL && *url != '\0') {
struct sp_buf fetched;
- mt = mcp_arg_string(p, "mediaType");
- if (mt != NULL && *mt != '\0' &&
- strncmp(mt, "text/", 5) != 0)
- return 1;
if (!url_host_allowed(url))
return 1;
if (sp_buf_init(&fetched) != 0)
@@ -354,11 +491,16 @@ collect_text(const mcp_json *parts, struct sp_buf *out)
sp_buf_free(&fetched);
return 1;
}
- if (append_text(out, fetched.p) != 0) {
- sp_buf_free(&fetched);
- return -1;
- }
+ if (mt != NULL && *mt != '\0' &&
+ strncmp(mt, "text/", 5) != 0)
+ rc = attach_part(inbox, "download", mt,
+ fetched.p, fetched.len, out);
+ else
+ rc = append_text(out, fetched.p) == 0 ?
+ 0 : -1;
sp_buf_free(&fetched);
+ if (rc != 0)
+ return rc;
got = 1;
continue;
}
@@ -1131,7 +1273,13 @@ handle_stream(int fd, struct sp_agent *ag, const char *id,
}
message = mcp_arg(params, "message");
parts = message != NULL ? mcp_arg(message, "parts") : NULL;
- rc = collect_text(parts, &text);
+ {
+ char inbox[700];
+
+ if (inbox_dir(ag, inbox, sizeof(inbox)) != 0)
+ inbox[0] = '\0';
+ rc = collect_text(parts, inbox, &text);
+ }
if (rc != 0) {
sse_error(&o, rc == 1 ? -32005 : -32603,
rc == 1 ? "unsupported content type" : "out of memory");
@@ -1235,7 +1383,13 @@ handle_rpc(int fd, struct sp_agent *ag, const char *payload)
message = mcp_arg(params, "message");
task_id = message != NULL ? mcp_arg_string(message, "taskId") : NULL;
parts = message != NULL ? mcp_arg(message, "parts") : NULL;
- rc = collect_text(parts, &text);
+ {
+ char inbox[700];
+
+ if (inbox_dir(ag, inbox, sizeof(inbox)) != 0)
+ inbox[0] = '\0';
+ rc = collect_text(parts, inbox, &text);
+ }
if (rc != 0) {
rpc_error(fd, id, rc == 1 ? -32005 : -32603,
rc == 1 ? "unsupported content type" :
diff --git a/src/main.c b/src/main.c
index 788b235..9f863bf 100644
--- a/src/main.c
+++ b/src/main.c
@@ -1042,6 +1042,14 @@ main(int argc, char **argv)
if ((rc = pick_transport(&o, &ag, host, ®, &mock, &have_mock,
&err)) != 0)
return rc;
+ /*
+ * /model shows the run's providers, and a command line is part of the
+ * run: --endpoint/--model without a config file still has a provider.
+ */
+ if (conf.endpoint[0] == '\0' && o.endpoint != NULL)
+ snprintf(conf.endpoint, sizeof(conf.endpoint), "%s", o.endpoint);
+ if (conf.model[0] == '\0' && o.model != NULL)
+ snprintf(conf.model, sizeof(conf.model), "%s", o.model);
if ((rc = setup_conversation(&o, &ag, &cfg, &sess, &err)) != 0)
return rc;
cfg.approval_in = stdin;
@@ -1074,7 +1082,7 @@ main(int argc, char **argv)
char cwd[512];
if (getcwd(cwd, sizeof(cwd)) == NULL) cwd[0] = '\0';
swarm_init(&sw, cwd);
- rc = sp_ui_run(&ag, o.endpoint, o.model, o.theme, host, &sw);
+ rc = sp_ui_run(&ag, o.endpoint, o.model, o.theme, host, &sw, &conf);
swarm_close(&sw);
}
} else if (o.prompt != NULL && o.prompt[0] == '/' && host != NULL)
diff --git a/src/providers.c b/src/providers.c
index c3e3dba..775c961 100644
--- a/src/providers.c
+++ b/src/providers.c
@@ -16,13 +16,18 @@
*/
#include
#include
+#include
+#include
#include
#include
#include
#include
+#include
#include
#include "config.h"
+#include "curl.h"
+#include "mcp.h"
#include "providers.h"
#include "splinter.h"
#include "splinter_plugin.h"
@@ -198,6 +203,233 @@ sp_provider_use(struct sp_agent *ag, const struct sp_config *cfg, size_t idx,
return sp_provider_apply(ag, p.endpoint, p.model, p.key_env, err);
}
+
+/* ------------------------------------------------------- talking to them */
+
+/*
+ * One GET, no body. curl writes to a pipe; the URL and the header go to curl
+ * on stdin/argv respectively, so a token never shows up in ps.
+ */
+static int
+http_get(const char *url, const char *const *headers, struct sp_buf *out,
+ struct sp_buf *err)
+{
+ int fds[2];
+ pid_t child;
+ const char *args[8];
+ int n = 0;
+ char tbuf[16];
+
+ snprintf(tbuf, sizeof(tbuf), "%d", 8);
+ args[n++] = "-sS";
+ args[n++] = "-m";
+ args[n++] = tbuf;
+ args[n] = NULL;
+ fds[0] = sp_curl_start(args, url, headers, 0, &child, err);
+ if (fds[0] < 0)
+ return -1;
+ {
+ struct pollfd pfd;
+ char chunk[4096];
+
+ pfd.fd = fds[0];
+ pfd.events = POLLIN;
+ for (;;) {
+ ssize_t got;
+
+ if (poll(&pfd, 1, 20000) <= 0) {
+ (void)kill(child, SIGKILL);
+ break;
+ }
+ got = read(fds[0], chunk, sizeof(chunk));
+ if (got <= 0)
+ break;
+ if (sp_buf_add(out, chunk, (size_t)got) != 0)
+ break;
+ }
+ }
+ close(fds[0]);
+ {
+ int st = 0;
+
+ (void)waitpid(child, &st, 0);
+ if (!WIFEXITED(st) || WEXITSTATUS(st) != 0) {
+ if (err != NULL)
+ sp_buf_printf(err, "curl failed (%d)",
+ WIFEXITED(st) ? WEXITSTATUS(st) : -1);
+ return -1;
+ }
+ }
+ return 0;
+}
+
+/* /v1/chat/completions -> /v1/models, and anything else gains /models */
+static void
+models_url(const char *endpoint, char *buf, size_t len)
+{
+ char *cut;
+
+ snprintf(buf, len, "%s", endpoint);
+ cut = strstr(buf, "/chat/completions");
+ if (cut != NULL)
+ snprintf(cut, len - (size_t)(cut - buf), "/models");
+ else if (buf[0] != '\0' && buf[strlen(buf) - 1] == '/')
+ snprintf(buf + strlen(buf), len - strlen(buf), "models");
+ else
+ snprintf(buf + strlen(buf), len - strlen(buf), "/models");
+}
+
+int
+sp_provider_served(const struct sp_provider *p, struct sp_buf *ids,
+ struct sp_buf *err)
+{
+ char url[700], hdr[700];
+ const char *hdrs[2] = { NULL, NULL };
+ struct sp_buf body;
+ mcp_json *v;
+ const mcp_json *data, *item;
+ size_t i;
+
+ if (p == NULL || ids == NULL || p->endpoint[0] == '\0')
+ return -1;
+ models_url(p->endpoint, url, sizeof(url));
+ if (p->key_env[0] != '\0' && getenv(p->key_env) != NULL) {
+ snprintf(hdr, sizeof(hdr), "Authorization: Bearer %s",
+ getenv(p->key_env));
+ hdrs[0] = hdr;
+ }
+ if (sp_buf_init(&body) != 0)
+ return -1;
+ if (http_get(url, hdrs, &body, err) != 0) {
+ sp_buf_free(&body);
+ return -1;
+ }
+ v = mcp_parse(body.p);
+ sp_buf_free(&body);
+ if (v == NULL) {
+ if (err != NULL)
+ sp_buf_puts(err, "the endpoint answered no JSON");
+ return -1;
+ }
+ data = mcp_arg(v, "data");
+ for (i = 0; data != NULL && (item = mcp_array_at(data, i)) != NULL;
+ i++) {
+ const char *id = mcp_arg_string(item, "id");
+
+ if (id == NULL)
+ continue;
+ if (ids->len > 0 && sp_buf_puts(ids, "\n") != 0)
+ goto oom;
+ if (sp_buf_puts(ids, id) != 0)
+ goto oom;
+ }
+ mcp_json_free(v);
+ if (ids->len == 0) {
+ if (err != NULL)
+ sp_buf_puts(err, "the endpoint listed no models");
+ return -1;
+ }
+ return 0;
+oom:
+ mcp_json_free(v);
+ if (err != NULL)
+ sp_buf_puts(err, "out of memory");
+ return -1;
+}
+
+int
+sp_provider_test(const struct sp_provider *p, struct sp_buf *answer,
+ struct sp_buf *err)
+{
+ struct sp_registry empty;
+ struct sp_conv conv;
+ struct sp_reply reply;
+ struct sp_transport tr;
+ const char *key = NULL;
+ int rc;
+
+ if (p == NULL || p->endpoint[0] == '\0' || p->model[0] == '\0')
+ return -1;
+ memset(&empty, 0, sizeof(empty));
+ memset(&reply, 0, sizeof(reply));
+ sp_conv_init(&conv);
+ if (sp_conv_push(&conv, "user", NULL,
+ "Reply with the single word ok.") != 0) {
+ sp_conv_free(&conv);
+ return -1;
+ }
+ if (p->key_env[0] != '\0')
+ key = getenv(p->key_env);
+ tr = sp_openai_transport(p->endpoint, p->model, key, &empty, 30);
+ rc = tr.send(tr.ctx, &conv, &reply, err);
+ if (rc == 0) {
+ size_t n = reply.content != NULL ? strlen(reply.content) : 0;
+
+ if (n == 0) {
+ if (err != NULL)
+ sp_buf_puts(err, "the provider answered nothing");
+ rc = -1;
+ } else if (answer != NULL) {
+ (void)sp_buf_add(answer, reply.content,
+ n > 200 ? 200 : n);
+ }
+ }
+ sp_reply_free(&reply);
+ sp_conv_free(&conv);
+ return rc;
+}
+
+int
+sp_provider_save_choice(const struct sp_config *cfg,
+ const struct sp_provider *p, struct sp_buf *err)
+{
+ char dir[700], path[800], tmp[820];
+ FILE *f;
+
+ if (cfg == NULL || p == NULL)
+ return -1;
+ /*
+ * With a plugin transport the model is whatever that program uses;
+ * a config line would look like it worked and would not.
+ */
+ if (cfg->transport[0] != '\0')
+ return 1;
+ /* no config file (--no-config): nothing to write to, not an error */
+ if (sp_provider_dir(dir, sizeof(dir)) != 0)
+ return 1;
+ snprintf(path, sizeof(path), "%s/90-model.conf", dir);
+ if (p->main) {
+ (void)unlink(path);
+ return 0;
+ }
+ if (mkdir(dir, 0700) != 0 && errno != EEXIST)
+ return -1;
+ snprintf(tmp, sizeof(tmp), "%s.tmp", path);
+ f = fopen(tmp, "w");
+ if (f == NULL) {
+ if (err != NULL)
+ sp_buf_printf(err, "cannot write %s: %s", tmp,
+ strerror(errno));
+ return -1;
+ }
+ (void)fchmod(fileno(f), 0600);
+ fprintf(f, "# written by /model -- delete this file to go back to the "
+ "configuration\n");
+ fprintf(f, "endpoint = %s\n", p->endpoint);
+ fprintf(f, "model = %s\n", p->model);
+ /* the key variable too: a keyless provider must not inherit one */
+ fprintf(f, "api_key_env = %s\n",
+ p->key_env[0] != '\0' ? p->key_env : "SPLINTER_API_KEY");
+ if (fclose(f) != 0 || rename(tmp, path) != 0) {
+ if (err != NULL)
+ sp_buf_printf(err, "cannot replace %s: %s", path,
+ strerror(errno));
+ (void)unlink(tmp);
+ return -1;
+ }
+ return 0;
+}
+
int
sp_provider_dir(char *buf, size_t len)
{
diff --git a/src/providers.h b/src/providers.h
index e8a43ce..06b898c 100644
--- a/src/providers.h
+++ b/src/providers.h
@@ -65,6 +65,27 @@ int sp_provider_endpoint_ok(const char *endpoint);
int sp_provider_model_ok(const char *model);
int sp_provider_key_ok(const char *key_env);
+/*
+ * Ask the endpoint which models it really serves (/v1/models). 'ids' gets one
+ * model name per line. A provider that does not answer that route is not
+ * broken -- many do not -- so the caller decides what a failure means.
+ */
+int sp_provider_served(const struct sp_provider *, struct sp_buf *ids,
+ struct sp_buf *err);
+
+/* One tiny turn against the provider: does the endpoint, the model and the key
+ * work? 'answer' gets the first bytes of what came back. */
+int sp_provider_test(const struct sp_provider *, struct sp_buf *answer,
+ struct sp_buf *err);
+
+/*
+ * Remember the choice for the next start: .d/90-model.conf. Picking
+ * "main" removes the file instead, so the config speaks again. Returns 1 when
+ * nothing was written because a plugin transport decides the model anyway.
+ */
+int sp_provider_save_choice(const struct sp_config *,
+ const struct sp_provider *, struct sp_buf *err);
+
/* The config line for one provider, also handy for showing it. */
int sp_provider_line(char *buf, size_t len, const char *id,
const char *endpoint, const char *model, const char *key_env);
diff --git a/src/telegram.c b/src/telegram.c
index 08a1ebb..27236d7 100644
--- a/src/telegram.c
+++ b/src/telegram.c
@@ -823,7 +823,9 @@ tg_model_menu(const char *token, long chat_id, struct sp_config *conf,
(void)sp_json_escape(&mark, p.id);
sp_buf_puts(&mark, "\"}]");
}
- sp_buf_puts(&mark, "]}");
+ sp_buf_puts(&mark, ",[{\"text\":\"");
+ (void)sp_json_escape(&mark, sp_t("model.probe"));
+ sp_buf_puts(&mark, "\",\"callback_data\":\"mprobe\"}]]}");
(void)send_message_markup(token, chat_id, msg.p, mark.p, err);
sp_buf_free(&msg);
sp_buf_free(&mark);
@@ -862,10 +864,27 @@ tg_model_use(const char *token, long chat_id, struct sp_agent *ag,
}
snprintf(tg_model_id, sizeof(tg_model_id), "%s", p.id);
snprintf(tg_model_name, sizeof(tg_model_name), "%s", p.model);
- if (sp_buf_init(&msg) == 0) {
- sp_buf_printf(&msg, sp_t("model.switched"), p.model, p.id);
- (void)send_message(token, chat_id, msg.p, err);
- sp_buf_free(&msg);
+ {
+ struct sp_buf serr;
+ int saved;
+
+ sp_buf_init(&serr);
+ saved = sp_provider_save_choice(conf, &p, &serr);
+ if (sp_buf_init(&msg) == 0) {
+ if (saved == 0)
+ sp_buf_printf(&msg, sp_t("model.saved"),
+ p.model, p.id);
+ else if (saved < 0)
+ sp_buf_printf(&msg, sp_t("model.save_failed"),
+ p.model, p.id, serr.p != NULL ?
+ serr.p : "?");
+ else
+ sp_buf_printf(&msg, sp_t("model.switched"),
+ p.model, p.id);
+ (void)send_message(token, chat_id, msg.p, err);
+ sp_buf_free(&msg);
+ }
+ sp_buf_free(&serr);
}
sp_buf_free(&perr);
}
@@ -904,12 +923,187 @@ tg_model_named(const char *token, long chat_id, struct sp_agent *ag,
return;
}
snprintf(tg_model_name, sizeof(tg_model_name), "%s", name);
+ {
+ struct sp_provider chosen;
+ struct sp_buf serr;
+ int saved;
+
+ memset(&chosen, 0, sizeof(chosen));
+ snprintf(chosen.id, sizeof(chosen.id), "%s", p.id);
+ snprintf(chosen.endpoint, sizeof(chosen.endpoint), "%s",
+ p.endpoint);
+ snprintf(chosen.model, sizeof(chosen.model), "%s", name);
+ snprintf(chosen.key_env, sizeof(chosen.key_env), "%s",
+ p.key_env);
+ sp_buf_init(&serr);
+ saved = sp_provider_save_choice(conf, &chosen, &serr);
+ if (sp_buf_init(&msg) == 0) {
+ if (saved == 0)
+ sp_buf_printf(&msg, sp_t("model.saved"), name,
+ p.id);
+ else if (saved < 0)
+ sp_buf_printf(&msg, sp_t("model.save_failed"),
+ name, p.id, serr.p != NULL ? serr.p : "?");
+ else
+ sp_buf_printf(&msg, sp_t("model.switched"), name,
+ p.id);
+ (void)send_message(token, chat_id, msg.p, err);
+ sp_buf_free(&msg);
+ }
+ sp_buf_free(&serr);
+ }
+ sp_buf_free(&perr);
+}
+
+/*
+ * /model probe: ask every endpoint what it serves (/v1/models) and offer the
+ * answer as buttons. The buttons carry an index into this table, not a model
+ * name: a GGUF path does not fit in Telegram's 64 bytes of callback data, and
+ * the table dies with the process like the buttons do.
+ */
+#define TG_MAX_PICKS 64
+
+struct tg_pick {
+ char provider[64];
+ char endpoint[512];
+ char model[256];
+ char key_env[64];
+};
+
+static struct tg_pick tg_picks[TG_MAX_PICKS];
+static size_t tg_npicks;
+
+static void
+tg_model_pick_menu(const char *token, long chat_id, struct sp_config *conf,
+ struct sp_buf *err)
+{
+ struct sp_buf msg, mark, ids, perr;
+ struct sp_provider p;
+ size_t i, n, total = 0;
+
+ tg_npicks = 0;
+ n = sp_provider_count(conf);
+ if (n == 0) {
+ (void)send_message(token, chat_id, sp_t("model.none"), err);
+ return;
+ }
+ if (sp_buf_init(&msg) == 0)
+ sp_buf_printf(&msg, sp_t("model.probe_start"), n);
+ (void)send_message(token, chat_id, msg.p, err);
+ sp_buf_free(&msg);
+ if (sp_buf_init(&msg) != 0)
+ return;
+ if (sp_buf_init(&mark) != 0) {
+ sp_buf_free(&msg);
+ return;
+ }
+ if (sp_buf_init(&ids) != 0 || sp_buf_init(&perr) != 0) {
+ sp_buf_free(&msg);
+ sp_buf_free(&mark);
+ return;
+ }
+ sp_buf_puts(&mark, "{\"inline_keyboard\":[\n");
+ for (i = 0; i < n; i++) {
+ const char *line;
+
+ if (sp_provider_at(conf, i, &p) != 0)
+ continue;
+ sp_buf_clear(&ids);
+ sp_buf_clear(&perr);
+ if (sp_provider_served(&p, &ids, &perr) != 0) {
+ sp_buf_printf(&msg, "\n%s: %.120s", p.id,
+ perr.p != NULL ? perr.p : "?");
+ continue;
+ }
+ sp_buf_printf(&msg, "\n%s:", p.id);
+ for (line = strtok(ids.p, "\n"); line != NULL;
+ line = strtok(NULL, "\n")) {
+ char label[64];
+
+ if (tg_npicks >= TG_MAX_PICKS)
+ break;
+ snprintf(tg_picks[tg_npicks].provider, sizeof(
+ tg_picks[0].provider), "%s", p.id);
+ snprintf(tg_picks[tg_npicks].endpoint, sizeof(
+ tg_picks[0].endpoint), "%s", p.endpoint);
+ snprintf(tg_picks[tg_npicks].model, sizeof(
+ tg_picks[0].model), "%s", line);
+ snprintf(tg_picks[tg_npicks].key_env, sizeof(
+ tg_picks[0].key_env), "%s", p.key_env);
+ sp_buf_printf(&msg, " %s", line);
+ /* Telegram caps button text at 64 characters */
+ snprintf(label, sizeof(label), "%.20s: %.40s", p.id,
+ line);
+ if (total > 0)
+ sp_buf_puts(&mark, ",");
+ sp_buf_puts(&mark, "[{\"text\":\"");
+ (void)sp_json_escape(&mark, label);
+ sp_buf_printf(&mark, "\",\"callback_data\":\"mm:%zu\""
+ "}]", tg_npicks);
+ tg_npicks++;
+ total++;
+ }
+ }
+ sp_buf_puts(&mark, "]}");
+ sp_buf_free(&ids);
+ sp_buf_free(&perr);
+ if (total == 0)
+ sp_buf_puts(&msg, "\n");
+ if (total == 0)
+ sp_buf_puts(&msg, sp_t("model.probe_none"));
+ (void)send_message_markup(token, chat_id, msg.p, mark.p, err);
+ sp_buf_free(&mark);
+ sp_buf_free(&msg);
+}
+
+static void
+tg_model_pick_use(const char *token, long chat_id, struct sp_agent *ag,
+ struct sp_config *conf, size_t idx, struct sp_buf *err)
+{
+ struct sp_provider p;
+ struct sp_buf msg, perr, serr;
+ int saved;
+
+ if (idx >= tg_npicks || ag == NULL) {
+ (void)send_message(token, chat_id, sp_t("model.probe_stale"),
+ err);
+ return;
+ }
+ memset(&p, 0, sizeof(p));
+ snprintf(p.id, sizeof(p.id), "%s", tg_picks[idx].provider);
+ snprintf(p.endpoint, sizeof(p.endpoint), "%s",
+ tg_picks[idx].endpoint);
+ snprintf(p.model, sizeof(p.model), "%s", tg_picks[idx].model);
+ snprintf(p.key_env, sizeof(p.key_env), "%s", tg_picks[idx].key_env);
+ sp_buf_init(&perr);
+ if (sp_provider_apply(ag, p.endpoint, p.model, p.key_env, &perr) != 0) {
+ if (sp_buf_init(&msg) == 0) {
+ sp_buf_printf(&msg, sp_t("model.failed"),
+ perr.p != NULL ? perr.p : "?");
+ (void)send_message(token, chat_id, msg.p, err);
+ sp_buf_free(&msg);
+ }
+ sp_buf_free(&perr);
+ return;
+ }
+ sp_buf_free(&perr);
+ snprintf(tg_model_id, sizeof(tg_model_id), "%s", p.id);
+ snprintf(tg_model_name, sizeof(tg_model_name), "%s", p.model);
+ sp_buf_init(&serr);
+ saved = sp_provider_save_choice(conf, &p, &serr);
if (sp_buf_init(&msg) == 0) {
- sp_buf_printf(&msg, sp_t("model.switched"), name, p.id);
+ if (saved == 0)
+ sp_buf_printf(&msg, sp_t("model.saved"), p.model, p.id);
+ else if (saved < 0)
+ sp_buf_printf(&msg, sp_t("model.save_failed"), p.model,
+ p.id, serr.p != NULL ? serr.p : "?");
+ else
+ sp_buf_printf(&msg, sp_t("model.switched"), p.model,
+ p.id);
(void)send_message(token, chat_id, msg.p, err);
sp_buf_free(&msg);
}
- sp_buf_free(&perr);
+ sp_buf_free(&serr);
}
/*
@@ -1039,6 +1233,46 @@ tg_connect_end(const char *token, long chat_id, struct sp_agent *ag,
(void)send_message_markup(token, chat_id, msg.p, mark.p, err);
sp_buf_free(&mark);
sp_buf_free(&msg);
+ /*
+ * The test turn can take half a minute on a slow endpoint. The save is
+ * already in the chat by then, so the operator sees what happened
+ * before the wait starts.
+ */
+ {
+ struct sp_provider p;
+ struct sp_buf ans, terr;
+
+ memset(&p, 0, sizeof(p));
+ snprintf(p.id, sizeof(p.id), "%.63s", tg_cc.id);
+ snprintf(p.endpoint, sizeof(p.endpoint), "%.511s",
+ tg_cc.endpoint);
+ snprintf(p.model, sizeof(p.model), "%.255s", tg_cc.model);
+ snprintf(p.key_env, sizeof(p.key_env), "%.63s", tg_cc.key_env);
+ sp_buf_init(&ans);
+ sp_buf_init(&terr);
+ if (sp_buf_init(&msg) == 0) {
+ if (sp_provider_test(&p, &ans, &terr) == 0) {
+ char want[160];
+ char *nl;
+
+ snprintf(want, sizeof(want), "%.150s",
+ ans.p != NULL ? ans.p : "");
+ nl = strchr(want, '\n');
+ if (nl != NULL)
+ *nl = '\0';
+ sp_buf_printf(&msg, sp_t("connect.tested"),
+ want);
+ } else {
+ sp_buf_printf(&msg, sp_t("connect.test_failed"),
+ terr.p != NULL && terr.len > 0 ?
+ terr.p : "?");
+ }
+ (void)send_message(token, chat_id, msg.p, err);
+ sp_buf_free(&msg);
+ }
+ sp_buf_free(&ans);
+ sp_buf_free(&terr);
+ }
out:
(void)ag;
memset(&tg_cc, 0, sizeof(tg_cc));
@@ -1156,6 +1390,35 @@ tg_callback(const char *token, const char *allow, const mcp_json *cq,
}
return 1;
}
+ if (strcmp(data, "mprobe") == 0) {
+ tg_answer_callback(token, cqid, sp_t("model.toast"));
+ if (mid != 0)
+ tg_clear_buttons(token, chat, mid);
+ if (conf != NULL && chat != 0) {
+ struct sp_buf sink;
+
+ if (sp_buf_init(&sink) == 0) {
+ tg_model_pick_menu(token, chat, conf, &sink);
+ sp_buf_free(&sink);
+ }
+ }
+ return 1;
+ }
+ if (strncmp(data, "mm:", 3) == 0) {
+ tg_answer_callback(token, cqid, sp_t("model.toast"));
+ if (mid != 0)
+ tg_clear_buttons(token, chat, mid);
+ if (ag != NULL && conf != NULL && chat != 0) {
+ struct sp_buf sink;
+
+ if (sp_buf_init(&sink) == 0) {
+ tg_model_pick_use(token, chat, ag, conf,
+ (size_t)strtoul(data + 3, NULL, 10), &sink);
+ sp_buf_free(&sink);
+ }
+ }
+ return 1;
+ }
if (strcmp(data, "mlater") == 0) {
tg_answer_callback(token, cqid, sp_t("connect.later"));
if (mid != 0)
@@ -1477,6 +1740,12 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
while (*arg == ' ')
arg++;
+ if (strcmp(arg, "probe") == 0) {
+ tg_model_pick_menu(token, chat_id,
+ conf, err);
+ sp_buf_clear(err);
+ continue;
+ }
if (*arg != '\0' &&
sp_provider_find(conf, arg, &idx))
tg_model_use(token, chat_id, ag,
diff --git a/src/tgmd.c b/src/tgmd.c
index 2045a45..6c50c53 100644
--- a/src/tgmd.c
+++ b/src/tgmd.c
@@ -225,6 +225,47 @@ inline_md(const char *s, size_t n, struct sp_buf *out, int depth)
continue;
}
}
+ if (s[i] == '<') {
+ size_t k = find_char(s, i + 1, n, '>');
+
+ if (k != (size_t)-1 &&
+ url_ok(s + i + 1, k - i - 1) &&
+ memchr(s + i + 1, ' ', k - i - 1) == NULL) {
+ if (esc(out, s + start, i - start) != 0 ||
+ sp_buf_puts(out, "") != 0 ||
+ esc(out, s + i + 1, k - i - 1) != 0 ||
+ sp_buf_puts(out, "") != 0)
+ return -1;
+ i = k + 1;
+ start = i;
+ continue;
+ }
+ }
+ if (s[i] == '!' && i + 1 < n && s[i + 1] == '[') {
+ size_t k = find_char(s, i + 2, n, ']');
+
+ if (k != (size_t)-1 && k + 1 < n && s[k + 1] == '(') {
+ size_t u = find_char(s, k + 2, n, ')');
+
+ if (u != (size_t)-1 &&
+ url_ok(s + k + 2, u - k - 2)) {
+ /* Telegram has no inline image: a link */
+ if (esc(out, s + start, i - start) != 0 ||
+ sp_buf_puts(out, "") != 0 ||
+ inline_md(s + i + 2, k - i - 2, out,
+ depth + 1) != 0 ||
+ sp_buf_puts(out, "") != 0)
+ return -1;
+ i = u + 1;
+ start = i;
+ continue;
+ }
+ }
+ }
if (s[i] == '[') {
size_t k = find_char(s, i + 1, n, ']');
diff --git a/src/ui.c b/src/ui.c
index 52a60b5..f6fac3e 100644
--- a/src/ui.c
+++ b/src/ui.c
@@ -38,6 +38,8 @@
#include "log.h"
#include "cmdscript.h"
#include "splinter_plugin.h"
+#include "config.h"
+#include "providers.h"
#include "md.h"
#include "theme.h"
#include "ui.h"
@@ -79,6 +81,9 @@ struct ui_state {
size_t last_calls;
const char *endpoint;
const char *model;
+ char cur_endpoint[512]; /* owned: /model moves them */
+ char cur_model[256];
+ struct sp_config *conf; /* for /model, may be NULL */
int quit;
struct sp_theme theme;
struct swarm *sw; /* local fleet, may be NULL/SWARM_NONE */
@@ -1777,6 +1782,86 @@ ui_slash(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
add_entry(s, "splinter", outbuf);
return 1;
}
+ /*
+ * /model: the same list the gateway offers, without buttons. No argument
+ * lists them, an id switches provider, any other word is a model on the
+ * current endpoint. The choice is written for the next start, like the
+ * gateway's.
+ */
+ if (strcmp(name, "model") == 0) {
+ struct sp_provider p;
+ struct sp_buf perr, serr;
+ size_t idx = 0, i, n;
+
+ if (s->conf == NULL) {
+ sp_buf_puts(&out, sp_t("model.none"));
+ } else if (args[0] == '\0') {
+ sp_buf_puts(&out, sp_t("model.choose"));
+ n = sp_provider_count(s->conf);
+ for (i = 0; i < n; i++)
+ if (sp_provider_at(s->conf, i, &p) == 0)
+ sp_buf_printf(&out, "\n %s %s%s",
+ p.id, p.model,
+ strcmp(p.model, s->model) == 0 ?
+ " *" : "");
+ } else if (sp_provider_find(s->conf, args, &idx)) {
+ sp_buf_init(&perr);
+ if (sp_provider_use(ag, s->conf, idx, &perr) != 0) {
+ sp_buf_printf(&out, sp_t("model.failed"),
+ perr.p != NULL ? perr.p : "?");
+ } else if (sp_provider_at(s->conf, idx, &p) == 0) {
+ snprintf(s->cur_endpoint,
+ sizeof(s->cur_endpoint), "%s", p.endpoint);
+ snprintf(s->cur_model, sizeof(s->cur_model),
+ "%s", p.model);
+ sp_buf_init(&serr);
+ sp_buf_printf(&out, sp_provider_save_choice(
+ s->conf, &p, &serr) == 0 ?
+ sp_t("model.saved") : sp_t("model.switched"),
+ p.model, p.id);
+ sp_buf_free(&serr);
+ }
+ sp_buf_free(&perr);
+ } else {
+ struct sp_provider chosen;
+ int ok;
+
+ memset(&p, 0, sizeof(p));
+ if (!sp_provider_find(s->conf, s->model, &idx) ||
+ sp_provider_at(s->conf, idx, &p) != 0)
+ (void)sp_provider_at(s->conf, 0, &p);
+ sp_buf_init(&perr);
+ ok = sp_provider_apply(ag, p.endpoint, args, p.key_env,
+ &perr) == 0;
+ if (ok) {
+ memset(&chosen, 0, sizeof(chosen));
+ snprintf(chosen.id, sizeof(chosen.id), "%s",
+ p.id);
+ snprintf(chosen.endpoint,
+ sizeof(chosen.endpoint), "%s", p.endpoint);
+ snprintf(chosen.model, sizeof(chosen.model),
+ "%s", args);
+ snprintf(chosen.key_env, sizeof(chosen.key_env),
+ "%s", p.key_env);
+ snprintf(s->cur_model, sizeof(s->cur_model),
+ "%s", args);
+ sp_buf_init(&serr);
+ sp_buf_printf(&out, sp_provider_save_choice(
+ s->conf, &chosen, &serr) == 0 ?
+ sp_t("model.saved") : sp_t("model.switched"),
+ args, p.id);
+ sp_buf_free(&serr);
+ } else {
+ sp_buf_printf(&out, sp_t("model.failed"),
+ perr.p != NULL ? perr.p : "?");
+ }
+ sp_buf_free(&perr);
+ }
+ snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : "");
+ sp_buf_free(&out);
+ add_entry(s, "splinter", outbuf);
+ return 1;
+ }
if (host != NULL && sp_host_command(host, name, args, &out) == 0) {
snprintf(outbuf, sizeof(outbuf), "%s", out.p != NULL ? out.p : "");
sp_buf_free(&out);
@@ -2257,16 +2342,21 @@ ui_turn(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
static int
ui_start(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
const char *endpoint, const char *model, const char *theme_name,
- struct swarm *sw)
+ struct swarm *sw, struct sp_config *conf)
{
struct sp_buf err;
const char *user = getenv("USER");
memset(s, 0, sizeof(*s));
sp_buf_init(&s->last_think);
- s->endpoint = endpoint;
+ snprintf(s->cur_endpoint, sizeof(s->cur_endpoint), "%s",
+ endpoint != NULL ? endpoint : "");
+ snprintf(s->cur_model, sizeof(s->cur_model), "%s",
+ model != NULL ? model : "");
+ s->endpoint = s->cur_endpoint;
+ s->conf = conf;
s->sw = sw;
- s->model = model;
+ s->model = s->cur_model;
if (user != NULL && *user != '\0')
snprintf(g_who, sizeof(g_who), "%s", user);
if (model != NULL && *model != '\0') {
@@ -2339,12 +2429,13 @@ ui_start(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
int
sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model,
- const char *theme_name, struct sp_host *host, struct swarm *sw)
+ const char *theme_name, struct sp_host *host, struct swarm *sw,
+ struct sp_config *conf)
{
struct ui_state s;
char input[1024], pending[1024];
- if (ui_start(&s, ag, host, endpoint, model, theme_name, sw) != 0)
+ if (ui_start(&s, ag, host, endpoint, model, theme_name, sw, conf) != 0)
return 1;
for (;;) {
draw_history(&s, 0);
diff --git a/src/ui.h b/src/ui.h
index a7c0327..b8e369a 100644
--- a/src/ui.h
+++ b/src/ui.h
@@ -13,7 +13,8 @@
* Returns 0 on a clean quit.
*/
int sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model,
- const char *theme_name, struct sp_host *host, struct swarm *sw);
+ const char *theme_name, struct sp_host *host, struct swarm *sw,
+ struct sp_config *conf);
/*
* UTF-8 -> ASCII for the screen. The vendored curses writes Latin-1 bytes for
diff --git a/src/www/index.en.html b/src/www/index.en.html
index f8bd5f8..ee9853d 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_
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.
-27543 lines of C99/POSIX ·
+
28449 lines of C99/POSIX ·
25 tools · 35 test programs ·
16 plugins · 42 palettes · BSD-3-Clause
@@ -141,7 +141,7 @@ plugin = plugins/reminder/reminder.so
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.
-The bot registers its commands: the menu shows the loaded plugins' commands and the programs in ~/.splinter/commands/; an approval arrives with Yes/No buttons. /interview asks the questions in the chat. /model offers the configured models as buttons and switches the running transport; /connect asks for name, endpoint, model and key variable 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.
+The bot registers its commands: the menu shows the loaded plugins' commands and the programs in ~/.splinter/commands/; an approval arrives with Yes/No buttons. /interview asks the questions in the chat. /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.
Slash commands work there too. Programs in ~/.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
@@ -213,7 +213,9 @@ splinter: A2A server on 127.0.0.1:8099 (token required)
conversation; without one the server makes one and returns it. A
taskPushNotificationConfig posts the completed task to a webhook
(loopback or SPLINTER_A2A_PUSH_ALLOW); push configs can be managed
-with CRUD and text/plain URLs are fetched from allowed hosts. A mutating tool pauses as
+with CRUD and text/plain URLs are fetched from allowed hosts; binary
+file/raw parts land in the inbox/ and the
+model is told the path. A mutating tool pauses as
INPUT_REQUIRED; a follow-up with taskId and
yes/no resumes. Beyond loopback the bearer
token is required.
diff --git a/src/www/index.html b/src/www/index.html
index 0cc3e7c..a53b3d2 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_
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.
-27543 Zeilen C99/POSIX ·
+
28449 Zeilen C99/POSIX ·
25 Werkzeuge · 35 Test-Programme ·
16 Plugins · 42 Farbschemata · BSD-3-Clause
@@ -141,7 +141,7 @@ plugin = plugins/reminder/reminder.so
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“.
-Der Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in ~/.splinter/commands/; eine Zustimmung kommt mit Ja/Nein-Knoepfen. /interview stellt die Fragen im Chat. /model bietet die konfigurierten Modelle als Knoepfe und schaltet den laufenden Transport um; /connect fragt Name, Endpoint, Modell und Key-Variable ab 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.
+Der Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in ~/.splinter/commands/; eine Zustimmung kommt mit Ja/Nein-Knoepfen. /interview stellt die Fragen im Chat. /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.
Slash-Kommandos funktionieren dort genauso. Programme in ~/.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
@@ -215,7 +215,8 @@ Konversation; ohne eines legt der Server eins an und gibt es zurueck. Eine
taskPushNotificationConfig schickt den fertigen Task an einen
Webhook (Loopback oder SPLINTER_A2A_PUSH_ALLOW); Push-Configs
lassen sich per CRUD verwalten, text/plain-URLs werden von erlaubten Hosts
-geholt. Ein mutierendes Werkzeug pausiert als
+geholt; binaere file/raw-Teile landen im
+inbox/ und das Modell bekommt den Pfad. Ein mutierendes Werkzeug pausiert als
INPUT_REQUIRED; ein Folgeaufruf mit taskId und
yes/no setzt fort. Jenseits von
Loopback ist der Bearer-Token Pflicht.
diff --git a/src/www/index.pt.html b/src/www/index.pt.html
index 624505c..cd3a139 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_
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.
-27543 linhas C99/POSIX ·
+
28449 linhas C99/POSIX ·
25 ferramentas · 35 programas de teste ·
16 plugins · 42 paletas · BSD-3-Clause
@@ -111,9 +111,11 @@ mesmos slash commands do terminal. O bot registra seus comandos: o menu mostra o
e os programas em ~/.splinter/commands/; uma aprovacao chega com
botoes Sim/Nao; as respostas viram HTML do Telegram (negrito, codigo, links,
tabelas em bloco monoespaceado). /model lista os modelos
-configurados em botoes e troca o transporte; /connect pergunta
-nome, endpoint, modelo e variavel da chave e grava o provedor em
-splinter.conf.d/20-connect.conf.
+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,
+endpoint, modelo e variavel da chave, faz um turno de teste e grava o provedor
+em splinter.conf.d/20-connect.conf.
O que fica registrado
Cada sessao escreve session.log (eventos legiveis) e
diff --git a/tests/fake_a2a.py b/tests/fake_a2a.py
index 2f64a6d..94c3289 100644
--- a/tests/fake_a2a.py
+++ b/tests/fake_a2a.py
@@ -1,6 +1,6 @@
# fake A2A agent for tests/test_a2a.sh and tests/test_a2a_ui.sh.
# argv: port, request log. SendMessage (JSON) and SendStreamingMessage (SSE).
-import http.server, json, sys
+import base64, http.server, json, sys
LOG = sys.argv[2]
@@ -107,6 +107,23 @@ class H(http.server.BaseHTTPRequestHandler):
else:
b = json.dumps({"jsonrpc": "2.0", "id": rid,
"result": {"message": msg}}).encode()
+ elif "datei" in text:
+ # an answer with a binary part: the client saves it and tells the
+ # model the path
+ task = {"id": "task-1", "contextId": "ctx-1",
+ "status": {"state": "TASK_STATE_COMPLETED",
+ "message": {"messageId": "m6",
+ "role": "ROLE_AGENT",
+ "parts": [
+ {"text": "hier ist die datei"},
+ {"file": {
+ "name": "bild.png",
+ "mimeType": "image/png",
+ "bytes": base64.b64encode(
+ b"PNGDATA").decode()}}]}}}
+ last_task = task
+ body = {"jsonrpc": "2.0", "id": rid, "result": {"task": task}}
+ b = json.dumps(body).encode()
elif "raw" in text:
task = {"id": "task-1", "contextId": "ctx-1",
"status": {"state": "TASK_STATE_COMPLETED",
diff --git a/tests/fake_telegram.py b/tests/fake_telegram.py
index 5abc5c6..06598bf 100644
--- a/tests/fake_telegram.py
+++ b/tests/fake_telegram.py
@@ -52,6 +52,9 @@ class H(http.server.BaseHTTPRequestHandler):
return self.rfile.read(n)
def do_GET(self):
+ if "/models" in self.path:
+ # the OpenAI /v1/models route: /model probe reads this
+ return self.reply({"data": [{"id": "m"}, {"id": "other"}]})
if "/getUpdates" in self.path:
off = int(re.search(r"offset=(-?\d+)", self.path).group(1))
for _ in range(10):
@@ -97,11 +100,19 @@ class H(http.server.BaseHTTPRequestHandler):
if "Neuer Provider" in text:
add_update("testprov")
elif "Endpoint?" in text:
- add_update("ollama")
+ # the fake is its own OpenAI endpoint, so the test turn in
+ # /connect has somewhere to go
+ add_update("http://127.0.0.1:%s/v1/chat/completions"
+ % sys.argv[1])
elif "Welches Modell" in text:
add_update("llama3")
elif "Umgebungsvariable" in text:
add_update("-")
+ # /model probe: the menu of served models arrives, press the first
+ cb = [b.get("callback_data", "") for row in (markup or {}).get(
+ "inline_keyboard", []) for b in row]
+ if any(c.startswith("mm:") for c in cb):
+ add_callback("mm:0")
m = re.match(r"Frage (\d+)/", text)
if m:
add_update("antwort-%s" % m.group(1))
@@ -119,7 +130,13 @@ class H(http.server.BaseHTTPRequestHandler):
if m.get("role") == "user":
last_user = m.get("content") or ""
break
- if "markdown" in last_user:
+ answer = "ok"
+ if "single word ok" in last_user:
+ # /connect's test turn
+ answer = "ok"
+ 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}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
@@ -136,6 +153,11 @@ class H(http.server.BaseHTTPRequestHandler):
chunks = [{"choices": [{"delta": {"tool_calls": [{"index": 0, "id": "c1",
"type": "function", "function": {"name": "write", "arguments": args}}]}}]},
{"choices": [{"delta": {}, "finish_reason": "tool_calls"}]}]
+ if not req.get("stream"):
+ # the non-streaming flavour, e.g. provider tests from /connect
+ return self.reply({"choices": [{"index": 0, "message": {
+ "role": "assistant", "content": answer},
+ "finish_reason": "stop"}]})
b = "".join("data: " + json.dumps(c) + "\n\n" for c in chunks) + "data: [DONE]\n\n"
self.reply(b.encode(), "text/event-stream")
diff --git a/tests/test_a2a.sh b/tests/test_a2a.sh
index bc04c73..94f29ed 100755
--- a/tests/test_a2a.sh
+++ b/tests/test_a2a.sh
@@ -12,6 +12,7 @@ P=$((20000 + ($$ % 20000)))
F=
cleanup() { [ -n "$F" ] && kill "$F" 2>/dev/null; rm -rf "$D"; }
trap cleanup EXIT
+export SPLINTER_A2A_INBOX="$D/inbox"
python3 -I tests/fake_a2a.py "$P" "$D/req.log" &
F=$!
for i in $(seq 1 50); do
@@ -57,6 +58,16 @@ out=$(blocking "direkt" 2>&1)
echo "$out" | grep -q 'direkt vom agenten'
check test $? -eq 0
+# a binary part is not dropped: it is saved and the path is in the answer
+out=$(blocking "schick eine datei" 2>&1)
+echo "$out" | grep -q 'hier ist die datei'
+check test $? -eq 0
+echo "$out" | grep -q '\[file bild.png at'
+check test $? -eq 0
+found=$(ls "$SPLINTER_A2A_INBOX"/*bild.png 2>/dev/null | head -1)
+check test -n "$found"
+check sh -c "printf PNGDATA | cmp - '$found'"
+
# raw (text/plain base64) and string data parts are read
out=$(blocking "raw" 2>&1)
echo "$out" | grep -q 'hallo'
diff --git a/tests/test_a2a_server.sh b/tests/test_a2a_server.sh
index d19d0aa..d8de4bc 100755
--- a/tests/test_a2a_server.sh
+++ b/tests/test_a2a_server.sh
@@ -21,7 +21,7 @@ cleanup() {
}
trap cleanup EXIT
mkdir -p "$D/home"
-printf 'answer hallo von splinter\nanswer hallo von splinter\nanswer hallo von splinter\nanswer hallo von splinter\nanswer hallo von splinter\nanswer hallo von splinter\nanswer hallo von splinter\n' > "$D/model.txt"
+printf 'answer hallo von splinter\n%.0s' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 > "$D/model.txt"
fails=0
check() { if "$@"; then :; else echo "FAIL $*"; fails=$((fails + 1)); fi; }
@@ -112,6 +112,30 @@ resp9=$(post "$P" "{\"jsonrpc\":\"2.0\",\"id\":\"9\",\"method\":\"GetTaskPushNot
echo "$resp9" | grep -q '"code":-32001'
check test $? -eq 0
+# a binary part is accepted: the bytes land in the session's inbox and the
+# model is told the path (a text model cannot read a PNG, the agent can)
+b64=$(printf 'PNGDATA' | python3 -c 'import base64,sys; print(base64.b64encode(sys.stdin.buffer.read()).decode())')
+resp13=$(post "$P" "{\"jsonrpc\":\"2.0\",\"id\":\"13\",\"method\":\"SendMessage\",\"params\":{\"message\":{\"messageId\":\"m13\",\"role\":\"ROLE_USER\",\"parts\":[{\"file\":{\"name\":\"pic.png\",\"mimeType\":\"image/png\",\"bytes\":\"$b64\"}},{\"text\":\"sieh dir das an\"}]}}}")
+echo "$resp13" | grep -q 'TASK_STATE_COMPLETED'
+check test $? -eq 0
+found=$(ls "$D"/home/.splinter/inbox/*pic.png 2>/dev/null | head -1)
+check_that "the binary part lands in the inbox" test -n "$found"
+check_that "the bytes are the bytes" sh -c "printf PNGDATA | cmp - '$found'"
+check_that "the model is told the path" grep -rq 'file pic.png at' "$D/home/.splinter"
+
+# the raw shape (base64 in "raw") is the same thing
+resp14=$(post "$P" "{\"jsonrpc\":\"2.0\",\"id\":\"14\",\"method\":\"SendMessage\",\"params\":{\"message\":{\"messageId\":\"m14\",\"role\":\"ROLE_USER\",\"parts\":[{\"raw\":\"$b64\",\"mediaType\":\"image/png\",\"metadata\":{\"filename\":\"raw.png\"}},{\"text\":\"und das\"}]}}}")
+echo "$resp14" | grep -q 'TASK_STATE_COMPLETED'
+check test $? -eq 0
+found=$(ls "$D"/home/.splinter/inbox/*raw.png 2>/dev/null | head -1)
+check_that "a raw part lands in the inbox" test -n "$found"
+
+# a binary part without a session and without an inbox still must not be lost
+# silently: a text/plain raw part is still text
+resp15=$(post "$P" "{\"jsonrpc\":\"2.0\",\"id\":\"15\",\"method\":\"SendMessage\",\"params\":{\"message\":{\"messageId\":\"m15\",\"role\":\"ROLE_USER\",\"parts\":[{\"raw\":\"$b64\",\"mediaType\":\"text/plain\"}]}}}")
+echo "$resp15" | grep -q 'TASK_STATE_COMPLETED'
+check test $? -eq 0
+
# ListTasks: the stored task, and an empty list for another context
resp7=$(post "$P" '{"jsonrpc":"2.0","id":"7","method":"ListTasks","params":{}}')
echo "$resp7" | grep -q "$id"
diff --git a/tests/test_gateway.sh b/tests/test_gateway.sh
index b85eef8..cfde53e 100755
--- a/tests/test_gateway.sh
+++ b/tests/test_gateway.sh
@@ -140,16 +140,26 @@ check "the button switches the model" \
check "the next turn goes to the new endpoint" \
grep -q '^openai:' "$D/sent.log"
+# /model probe asks the endpoint what it serves and switches to one of them
+run_text "/model probe" 'gespeichert' 55
+check "the probe lists served models" grep -q '"callback_data":"mm:0"' "$D/sent.log"
+check "a probed model is used" grep -q '^Modell: m (Provider main)' "$D/sent.log"
+check "the choice is saved for the next start" \
+ test -f "$D/home/splinter.conf.d/90-model.conf"
+check "the saved choice names the model" \
+ grep -q '^model = m$' "$D/home/splinter.conf.d/90-model.conf"
+
# /connect writes a provider to the config drop-in
run_text "/connect" 'Provider testprov gespeichert' 70
drop="$D/home/splinter.conf.d/20-connect.conf"
check "connect writes the drop-in" test -f "$drop"
check "the line names the provider" grep -q '^delegate = testprov |' "$drop"
check "the line names the endpoint" \
- grep -q 'endpoint=http://127.0.0.1:11434/v1/chat/completions' "$drop"
+ grep -q "endpoint=http://127.0.0.1:$P/v1/chat/completions" "$drop"
check "the line names the model" grep -q 'model=llama3' "$drop"
check "connect offers to use it now" \
grep -q '"callback_data":"model:testprov"' "$D/sent.log"
+check "connect tested the provider" grep -q 'Test bestanden: ok' "$D/sent.log"
# /interview asks the six questions and writes the profile
run_text "/interview" '^Profil geschrieben' 30
diff --git a/tests/test_providers.c b/tests/test_providers.c
index 707bea3..73401ec 100644
--- a/tests/test_providers.c
+++ b/tests/test_providers.c
@@ -178,6 +178,41 @@ main(void)
}
}
+ /* /model writes 90-model.conf; picking main removes it again */
+ {
+ struct sp_provider pick;
+ char mpath[800], mbuf[1024];
+ struct sp_buf merr;
+ FILE *mf;
+
+ memset(&pick, 0, sizeof(pick));
+ snprintf(pick.id, sizeof(pick.id), "ocgo");
+ snprintf(pick.endpoint, sizeof(pick.endpoint),
+ "https://opencode.ai/zen/go/v1/chat/completions");
+ snprintf(pick.model, sizeof(pick.model), "other-model");
+ snprintf(pick.key_env, sizeof(pick.key_env), "OPENCODE_GO_API_KEY");
+ sp_buf_init(&merr);
+ CHECK(sp_provider_save_choice(&back, &pick, &merr) == 0);
+ snprintf(mpath, sizeof(mpath), "%s.d/90-model.conf", mainconf);
+ mf = fopen(mpath, "r");
+ CHECK(mf != NULL);
+ if (mf != NULL) {
+ mbuf[0] = '\0';
+ (void)fread(mbuf, 1, sizeof(mbuf) - 1, mf);
+ mbuf[sizeof(mbuf) - 1] = '\0';
+ fclose(mf);
+ CHECK(strstr(mbuf, "model = other-model") != NULL);
+ CHECK(strstr(mbuf, "endpoint = https://") != NULL);
+ CHECK(strstr(mbuf, "api_key_env = OPENCODE_GO_API_KEY") !=
+ NULL);
+ }
+ memset(&pick, 0, sizeof(pick));
+ pick.main = 1;
+ CHECK(sp_provider_save_choice(&back, &pick, &merr) == 0);
+ CHECK(access(mpath, F_OK) != 0);
+ sp_buf_free(&merr);
+ }
+
CHECK(sp_provider_line(line, sizeof(line), "ocgo", "https://x/v1",
"m", "K") == 0);
CHECK(strstr(line, "delegate = ocgo |") != NULL);
diff --git a/tests/test_tgmd.c b/tests/test_tgmd.c
index d2fa43d..f3ab993 100644
--- a/tests/test_tgmd.c
+++ b/tests/test_tgmd.c
@@ -169,6 +169,10 @@ main(void)
"fett mit kursiv");
check_render("[Titel](https://example.org/a?x=1&y=2)",
"Titel");
+ check_render("",
+ "https://example.org/x");
+ check_render("",
+ "Bild");
/* what must stay text */
check_render("snake_case_name", "snake_case_name");
diff --git a/tests/test_ui.sh b/tests/test_ui.sh
index 9bb936c..f510245 100755
--- a/tests/test_ui.sh
+++ b/tests/test_ui.sh
@@ -91,6 +91,11 @@ typed '!echo hallo-shell'; key Enter
check shows 'hallo-shell'
typed '/xyz'; key Enter
check shows 'unknown command: /xyz'
+typed '/model'; key Enter
+check shows 'main m'
+check shows 'Choose a model'
+typed '/model andere'; key Enter
+check shows 'Model: andere (provider main'
typed 'schreib die datei'; key Enter
check shows 'changes files'
key y
diff --git a/tools/gen_www.py b/tools/gen_www.py
index 5af4806..05c7363 100644
--- a/tools/gen_www.py
+++ b/tools/gen_www.py
@@ -305,7 +305,7 @@ SECTIONS = {
"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“.
\nDer Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in ~/.splinter/commands/; eine Zustimmung kommt mit Ja/Nein-Knoepfen. /interview stellt die Fragen im Chat. /model bietet die konfigurierten Modelle als Knoepfe und schaltet den laufenden Transport um; /connect fragt Name, Endpoint, Modell und Key-Variable ab 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.
\nSlash-Kommandos funktionieren "
+ "Chat alle vier Sekunden „typing“.
\nDer Bot registriert seine Befehle: das Menue zeigt die geladenen Plugin-Befehle und die Programme in ~/.splinter/commands/; eine Zustimmung kommt mit Ja/Nein-Knoepfen. /interview stellt die Fragen im Chat. /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.
\nSlash-Kommandos funktionieren "
"dort genauso. Programme in ~/.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.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.
\nThe bot registers its commands: the menu shows the loaded plugins' commands and the programs in ~/.splinter/commands/; an approval arrives with Yes/No buttons. /interview asks the questions in the chat. /model offers the configured models as buttons and switches the running transport; /connect asks for name, endpoint, model and key variable 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.
\nSlash commands work there too. "
+ ""typing" every four seconds.
\nThe bot registers its commands: the menu shows the loaded plugins' commands and the programs in ~/.splinter/commands/; an approval arrives with Yes/No buttons. /interview asks the questions in the chat. /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.
\nSlash commands work there too. "
"Programs in ~/.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 "
@@ -461,7 +461,8 @@ Konversation; ohne eines legt der Server eins an und gibt es zurueck. Eine
taskPushNotificationConfig schickt den fertigen Task an einen
Webhook (Loopback oder SPLINTER_A2A_PUSH_ALLOW); Push-Configs
lassen sich per CRUD verwalten, text/plain-URLs werden von erlaubten Hosts
-geholt. Ein mutierendes Werkzeug pausiert als
+geholt; binaere file/raw-Teile landen im
+inbox/ und das Modell bekommt den Pfad. Ein mutierendes Werkzeug pausiert als
INPUT_REQUIRED; ein Folgeaufruf mit taskId und
yes/no setzt fort. Jenseits von
Loopback ist der Bearer-Token Pflicht.
""",
@@ -513,7 +514,9 @@ splinter: A2A server on 127.0.0.1:8099 (token required)
conversation; without one the server makes one and returns it. A
taskPushNotificationConfig posts the completed task to a webhook
(loopback or SPLINTER_A2A_PUSH_ALLOW); push configs can be managed
-with CRUD and text/plain URLs are fetched from allowed hosts. A mutating tool pauses as
+with CRUD and text/plain URLs are fetched from allowed hosts; binary
+file/raw parts land in the inbox/ and the
+model is told the path. A mutating tool pauses as
INPUT_REQUIRED; a follow-up with taskId and
yes/no resumes. Beyond loopback the bearer
token is required.""",
@@ -568,9 +571,11 @@ mesmos slash commands do terminal. O bot registra seus comandos: o menu mostra o
e os programas em ~/.splinter/commands/; uma aprovacao chega com
botoes Sim/Nao; as respostas viram HTML do Telegram (negrito, codigo, links,
tabelas em bloco monoespaceado). /model lista os modelos
-configurados em botoes e troca o transporte; /connect pergunta
-nome, endpoint, modelo e variavel da chave e grava o provedor em
-splinter.conf.d/20-connect.conf.""",
+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,
+endpoint, modelo e variavel da chave, faz um turno de teste e grava o provedor
+em splinter.conf.d/20-connect.conf.""",
"""O que fica registrado
Cada sessao escreve session.log (eventos legiveis) e
wire.jsonl (o que foi de fato enviado ao modelo).
""",