From 93e955a4c7f2f5cfd1f64801b5ebe0bc1566a0f0 Mon Sep 17 00:00:00 2001 From: lotherk Date: Mon, 9 Nov 2026 23:32:49 +0000 Subject: [PATCH] a2a: stream the answer, and a --no-stream path The A2A transport implements send_stream now: SSE events are read as StreamResponse (task, message, statusUpdate, artifactUpdate), artifact and message text goes to the screen as it arrives, intermediate status notes are ignored, and a completed status message is the answer only when no artifact or direct message text came. Failed/canceled/rejected and input/auth-required states fail the turn instead of becoming an answer. One-shot mode already streamed whenever a transport offered it, so the plain send path was unreachable from the CLI. --no-stream asks for it. test_a2a.sh covers both SendMessage and SendStreamingMessage; the new test_a2a_ui.sh drives the UI streaming path through tmux. README, PLUGINS.md, the man page and the site follow. --- Makefile | 1 + README.md | 10 +- TODO.md | 20 ++- docs/PLUGINS.md | 17 +- docs/ROADMAP.md | 10 +- docs/splinter.1 | 4 + plugins/a2a/a2a.c | 404 +++++++++++++++++++++++++++++++++++++++--- src/main.c | 15 +- src/www/index.en.html | 4 +- src/www/index.html | 4 +- src/www/index.pt.html | 4 +- tests/fake_a2a.py | 112 +++++++++--- tests/test_a2a.sh | 52 ++++-- tests/test_a2a_ui.sh | 83 +++++++++ tools/gen_www.py | 6 +- 15 files changed, 652 insertions(+), 94 deletions(-) create mode 100755 tests/test_a2a_ui.sh diff --git a/Makefile b/Makefile index 704d118..d462562 100644 --- a/Makefile +++ b/Makefile @@ -218,6 +218,7 @@ check: $(LIB) $(BIN) $(PLUGIN) $(TESTS) for t in $(TESTS); do echo "== $$t"; ./$$t; done; \ echo "== tests/test_gateway.sh"; sh tests/test_gateway.sh; \ echo "== tests/test_a2a.sh"; sh tests/test_a2a.sh; \ + echo "== tests/test_a2a_ui.sh"; sh tests/test_a2a_ui.sh; \ echo "== tests/test_ui.sh"; sh tests/test_ui.sh; \ echo "all tests passed" diff --git a/README.md b/README.md index a48a908..1ce5430 100644 --- a/README.md +++ b/README.md @@ -116,10 +116,12 @@ SPLINTER_A2A_TOKEN=... \ ``` The client half of Agent2Agent: one `SendMessage` over JSON-RPC 2.0 with a text -part, blocking, and a direct `Message` or a completed `Task` as the answer. The -task and context ids are kept for the session, so the next turn continues the -same A2A context. Text only; streaming, files, push notifications and agent-card -discovery are not built yet. +part, blocking, and a direct `Message` or a completed `Task` as the answer. In +the UI the turn streams: `SendStreamingMessage`, artifact text appearing as it +arrives. The task and context ids are kept for the session, so the next turn +continues the same A2A context. One-shot mode streams by default; `--no-stream` +asks for the blocking send. Text only; files, push notifications, +`GetTask`/`CancelTask` and agent-card discovery are not built yet. ## Configuration diff --git a/TODO.md b/TODO.md index 15b2b21..a2550fa 100644 --- a/TODO.md +++ b/TODO.md @@ -40,16 +40,17 @@ schicken. Braucht Token und Chat. Der Client ist gebaut: `plugins/a2a/a2a.c` sendet `SendMessage` als JSON-RPC 2.0 mit einem Text-Teil, blockierend, und liest eine direkte `Message` oder eine -`Task` in `TASK_STATE_COMPLETED` (Status-Nachricht plus Artefakte). Task- und +`Task` in `TASK_STATE_COMPLETED` (Status-Nachricht plus Artefakte). In der UI +laeuft der Turn ueber `SendStreamingMessage`; Artefakt- und Message-Text +erscheint waehrend des Laufs, Zwischenstatus wird nicht angehaengt. Task- und Context-Id bleiben fuer die Sitzung; ein terminaler Task verliert seine Id, der -Context bleibt. `tests/fake_a2a.py` und `tests/test_a2a.sh` pruefen beide -Ergebnisformen, den Bearer-Token und einen JSON-RPC-Fehler. +Context bleibt. -Offen: `SendStreamingMessage`, Datei- und strukturierte Teile, Push- -Notifications, `GetTask`/`CancelTask`, Agent-Card-Discovery und die -Server-Richtung (andere Agents rufen splinter). +Offen: Datei- und strukturierte Teile, Push-Notifications, +`GetTask`/`CancelTask`, Agent-Card-Discovery und die Server-Richtung (andere +Agents rufen splinter). -Naechster Schritt: Streaming (SSE) und Discovery, danach der Server. +Naechster Schritt: Discovery, danach der Server. ### 4. `~/.local/lib` enthaelt Fremdlast @@ -87,8 +88,9 @@ Naechster Schritt: entscheiden, ob die npm-Reste weg duerfen. Kein Code. (submit/jobs/result, force-Retry, faelliger Job im Scheduler-Tick, Scheduler-Widget). - **A2A-Client**: `plugins/a2a/a2a.c` sendet `SendMessage` (JSON-RPC 2.0, Text, - blockierend) und liest Message oder Task; `tests/test_a2a.sh` prueft Task, - direkte Message, Token und JSON-RPC-Fehler. + blockierend) und in der UI `SendStreamingMessage` (SSE, Artefakt-Text live); + `tests/test_a2a.sh` prueft Task, direkte Message, Token und JSON-RPC-Fehler, + `tests/test_a2a_ui.sh` den Streaming-Pfad. - **Fehler dabei gefunden und behoben**: `delegate_retry` las `id` und `force` in denselben Puffer; `json_str` haengt an, also wurde aus `job-1` mit `force=1` die Id `job-11` (`src/delegate.c`, `tool_delegate_retry`). diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md index 13dccb2..0154c53 100644 --- a/docs/PLUGINS.md +++ b/docs/PLUGINS.md @@ -285,8 +285,15 @@ the curl timeout (default 300 seconds). The task id and context id are remembere for the session, so the next turn stays in the same A2A context; a terminal task loses its id, a context keeps it. -Not implemented yet, and named so nobody assumes otherwise: streaming -(`SendStreamingMessage`), file/structured-data parts, push notifications, -`GetTask`/`CancelTask`, and agent-card discovery. The endpoint is configured -directly. The fake agent in `tests/fake_a2a.py` and `tests/test_a2a.sh` pin the -wire shape, both result forms, the bearer token and a JSON-RPC error. +When the UI is driving the turn (`sp_agent_config.stream` is set), the transport +uses `SendStreamingMessage` instead and hands artifact/message text to the screen +as it arrives. Intermediate status notes are progress and are not appended; a +completed status message is the answer only when no artifact or direct message +text came. One-shot mode streams too unless `--no-stream` asks for the blocking +`SendMessage` path. + +Not implemented yet, and named so nobody assumes otherwise: file/structured-data +parts, push notifications, `GetTask`/`CancelTask`, and agent-card discovery. The +endpoint is configured directly. `tests/fake_a2a.py` and `tests/test_a2a.sh` pin +the blocking wire shape, both result forms, the bearer token and a JSON-RPC +error; `tests/test_a2a_ui.sh` drives the streaming path through tmux. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index cbec0d1..0ade42d 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -3,11 +3,11 @@ Stand: 2026-11-09. Die geprüfte, ausführliche Liste mit Belegen steht in `TODO.md`; hier bleibt die Reihenfolge, was als Nächstes gebaut wird. -1. **A2A: Streaming und Server** — der Client (`plugins/a2a/a2a.c`) kann - `SendMessage` mit Text. Offen sind `SendStreamingMessage`, Datei- und - strukturierte Teile, Discovery, `GetTask`/`CancelTask` und die Server-Seite, - damit die Flotte splinter rufen kann. `swarm` ist nur lokale IPC im selben - Verzeichnis, kein A2A. +1. **A2A: Discovery und Server** — der Client (`plugins/a2a/a2a.c`) kann + `SendMessage` und, in der UI, `SendStreamingMessage` mit Text. Offen sind + Datei- und strukturierte Teile, Push-Notifications, Discovery, + `GetTask`/`CancelTask` und die Server-Seite, damit die Flotte splinter rufen + kann. `swarm` ist nur lokale IPC im selben Verzeichnis, kein A2A. 2. **Echte Gegenstellen** — die Kids-Zustimmung gegen einen echten Telegram-Bot (nicht `fake_telegram.py`), und die Ursache von `claude` Exit 2. diff --git a/docs/splinter.1 b/docs/splinter.1 index aa46270..cee461d 100644 --- a/docs/splinter.1 +++ b/docs/splinter.1 @@ -54,6 +54,10 @@ using Transport: replay one reply per line from .Ar FILE . This needs no network and is how the test suite drives the loop. +.It Fl -no-stream +One-shot mode: wait for the whole reply instead of printing it as it arrives. +A transport that can stream uses its streaming method by default; this asks for +its plain send method. .It Fl -autonomous Run mutating tools without asking. Read-only tools never ask. diff --git a/plugins/a2a/a2a.c b/plugins/a2a/a2a.c index 57440dd..b5fdf95 100644 --- a/plugins/a2a/a2a.c +++ b/plugins/a2a/a2a.c @@ -95,16 +95,17 @@ make_id(char *out, size_t cap, const char *prefix) } static int -build_request(struct a2a_cfg *c, const char *text, struct sp_buf *out) +build_request(struct a2a_cfg *c, const char *method, const char *text, + struct sp_buf *out) { char rid[96], mid[96]; make_id(rid, sizeof(rid), "rpc"); make_id(mid, sizeof(mid), "msg"); if (sp_buf_printf(out, - "{\"jsonrpc\":\"2.0\",\"id\":\"%s\",\"method\":\"SendMessage\"," + "{\"jsonrpc\":\"2.0\",\"id\":\"%s\",\"method\":\"%s\"," "\"params\":{\"message\":{\"messageId\":\"%s\"," - "\"role\":\"ROLE_USER\",", rid, mid) != 0) + "\"role\":\"ROLE_USER\",", rid, method, mid) != 0) return -1; if (c->task_id[0] != '\0' && sp_buf_printf(out, "\"taskId\":\"%s\",", c->task_id) != 0) @@ -302,31 +303,31 @@ dump_request(const char *body, size_t len) fclose(f); } +/* + * Start curl and return the read end. *templ keeps the temp file path; the + * caller unlinks it after waitpid, so curl has certainly read the body. + */ static int -post(struct a2a_cfg *c, const char *body, struct sp_buf *raw, - struct sp_buf *err) +start_post(struct a2a_cfg *c, const char *body, int stream, pid_t *pid, + char *templ, size_t templcap, struct sp_buf *err) { char tmo[32], data[700], auth[sizeof(c->token) + 32]; - char templ[600]; - const char *args[16]; + const char *args[20]; const char *hdrs[2] = { NULL, NULL }; const char *dir; + size_t len = strlen(body); int fd, n = 0; - FILE *f; - pid_t pid = -1; - char chunk[4096]; - size_t got; dir = getenv("TMPDIR"); if (dir == NULL || *dir == '\0') dir = "/var/tmp"; - snprintf(templ, sizeof(templ), "%s/splinter-a2a-XXXXXX", dir); + snprintf(templ, templcap, "%s/splinter-a2a-XXXXXX", dir); fd = mkstemp(templ); if (fd < 0) { sp_buf_printf(err, "a2a: mkstemp: %s", strerror(errno)); return -1; } - if (write(fd, body, strlen(body)) != (ssize_t)strlen(body)) { + if (write(fd, body, len) != (ssize_t)len) { sp_buf_printf(err, "a2a: short write: %s", strerror(errno)); close(fd); unlink(templ); @@ -337,6 +338,8 @@ post(struct a2a_cfg *c, const char *body, struct sp_buf *raw, snprintf(tmo, sizeof(tmo), "%ld", c->timeout); snprintf(data, sizeof(data), "@%s", templ); args[n++] = "-sS"; + if (stream) + args[n++] = "-N"; args[n++] = "-m"; args[n++] = tmo; args[n++] = "-X"; @@ -344,7 +347,8 @@ post(struct a2a_cfg *c, const char *body, struct sp_buf *raw, args[n++] = "-H"; args[n++] = "Content-Type: application/json"; args[n++] = "-H"; - args[n++] = "Accept: application/json"; + args[n++] = stream ? "Accept: text/event-stream" : + "Accept: application/json"; args[n++] = "--data-binary"; args[n++] = data; args[n++] = "-w"; @@ -355,12 +359,28 @@ post(struct a2a_cfg *c, const char *body, struct sp_buf *raw, c->token); hdrs[0] = auth; } - fd = sp_curl_start(args, c->url, hdrs, 0, &pid, err); + fd = sp_curl_start(args, c->url, hdrs, 0, pid, err); memset(auth, 0, sizeof(auth)); if (fd < 0) { unlink(templ); return -1; } + return fd; +} + +static int +post(struct a2a_cfg *c, const char *body, struct sp_buf *raw, + struct sp_buf *err) +{ + char templ[600], chunk[4096]; + pid_t pid = -1; + FILE *f; + size_t got; + int fd, status = 0; + + fd = start_post(c, body, 0, &pid, templ, sizeof(templ), err); + if (fd < 0) + return -1; f = fdopen(fd, "r"); if (f == NULL) { close(fd); @@ -380,20 +400,353 @@ post(struct a2a_cfg *c, const char *body, struct sp_buf *raw, return -1; } fclose(f); - { - int status = 0; - - if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) || - WEXITSTATUS(status) != 0) { - sp_buf_printf(err, "a2a: transfer failed for %s", c->url); - unlink(templ); - return -1; - } + if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) || + WEXITSTATUS(status) != 0) { + sp_buf_printf(err, "a2a: transfer failed for %s", c->url); + unlink(templ); + return -1; } unlink(templ); return 0; } +static void +set_ids(struct a2a_cfg *c, const char *task_id, const char *context_id, + int terminal) +{ + if (context_id != NULL && *context_id != '\0') + snprintf(c->context_id, sizeof(c->context_id), "%s", + context_id); + if (task_id != NULL && *task_id != '\0') { + if (terminal) + c->task_id[0] = '\0'; + else + snprintf(c->task_id, sizeof(c->task_id), "%s", + task_id); + } +} + +/* append one event's text parts and hand the piece to the screen */ +static int +emit_parts(const mcp_json *parts, struct sp_buf *text, int *saw_text, + sp_stream_cb cb, void *cbctx) +{ + struct sp_buf piece; + + if (sp_buf_init(&piece) != 0) + return -1; + if (collect_parts(parts, &piece) && piece.len > 0) { + if (sp_buf_add(text, piece.p, piece.len) != 0) { + sp_buf_free(&piece); + return -1; + } + *saw_text = 1; + if (cb != NULL) + cb(cbctx, SP_STREAM_TEXT, piece.p); + } + sp_buf_free(&piece); + return 0; +} + +static int +is_terminal(const char *state) +{ + return state != NULL && + (strcmp(state, "TASK_STATE_COMPLETED") == 0 || + strcmp(state, "TASK_STATE_FAILED") == 0 || + strcmp(state, "TASK_STATE_CANCELED") == 0 || + strcmp(state, "TASK_STATE_REJECTED") == 0); +} + +/* states that end the turn with an error, not with an answer */ +static int +state_is_error(const char *state) +{ + return state != NULL && + (strcmp(state, "TASK_STATE_FAILED") == 0 || + strcmp(state, "TASK_STATE_CANCELED") == 0 || + strcmp(state, "TASK_STATE_REJECTED") == 0 || + strcmp(state, "TASK_STATE_INPUT_REQUIRED") == 0 || + strcmp(state, "TASK_STATE_AUTH_REQUIRED") == 0); +} + +/* + * One StreamResponse. The answer text can arrive as a direct Message, as + * artifact chunks, or (when neither came) as the message on the final status. + * Intermediate status notes are progress, not the answer, and are ignored. + */ +static int +stream_event(struct a2a_cfg *c, const char *payload, struct sp_buf *text, + int *saw_text, int *finished, sp_stream_cb cb, void *cbctx, + struct sp_buf *err) +{ + mcp_json *v = NULL; + const mcp_json *error, *result, *task, *message, *su, *au, *status; + const char *state; + int rc = -1; + + v = mcp_parse(payload); + if (v == NULL) { + sp_buf_puts(err, "a2a: stream event is not JSON"); + return -1; + } + error = mcp_arg(v, "error"); + if (error != NULL) { + const char *m = mcp_arg_string(error, "message"); + + sp_buf_printf(err, "a2a: %s", m != NULL ? m : "JSON-RPC error"); + goto out; + } + result = mcp_arg(v, "result"); + if (result == NULL) { + sp_buf_puts(err, "a2a: stream event has no result"); + goto out; + } + task = mcp_arg(result, "task"); + message = mcp_arg(result, "message"); + su = mcp_arg(result, "statusUpdate"); + au = mcp_arg(result, "artifactUpdate"); + if (task != NULL) { + const mcp_json *artifacts; + + status = mcp_arg(task, "status"); + state = status != NULL ? mcp_arg_string(status, "state") : + NULL; + set_ids(c, mcp_arg_string(task, "id"), + mcp_arg_string(task, "contextId"), is_terminal(state)); + if (state_is_error(state)) { + sp_buf_printf(err, "a2a: task ended in %s", state); + goto out; + } + artifacts = mcp_arg(task, "artifacts"); + if (artifacts != NULL && artifacts->t == MCP_ARR) { + size_t i, n = mcp_array_len(artifacts); + + for (i = 0; i < n; i++) { + const mcp_json *a = mcp_array_at(artifacts, i); + + if (emit_parts(mcp_arg(a, "parts"), text, + saw_text, cb, cbctx) != 0) + goto oom; + } + } + if (is_terminal(state)) { + if (!*saw_text) { + const mcp_json *sm = status != NULL ? + mcp_arg(status, "message") : NULL; + + if (sm != NULL && + emit_parts(mcp_arg(sm, "parts"), text, + saw_text, cb, cbctx) != 0) + goto oom; + } + *finished = 1; + } + } else if (message != NULL) { + set_ids(c, NULL, mcp_arg_string(message, "contextId"), 0); + if (emit_parts(mcp_arg(message, "parts"), text, saw_text, cb, + cbctx) != 0) + goto oom; + *finished = 1; + } else if (su != NULL) { + status = mcp_arg(su, "status"); + state = status != NULL ? mcp_arg_string(status, "state") : + NULL; + set_ids(c, mcp_arg_string(su, "taskId"), + mcp_arg_string(su, "contextId"), is_terminal(state)); + if (state_is_error(state)) { + sp_buf_printf(err, "a2a: task ended in %s", state); + goto out; + } + if (strcmp(state != NULL ? state : "", + "TASK_STATE_COMPLETED") == 0) { + if (!*saw_text) { + const mcp_json *sm = mcp_arg(status, "message"); + + if (sm != NULL && + emit_parts(mcp_arg(sm, "parts"), text, + saw_text, cb, cbctx) != 0) + goto oom; + } + *finished = 1; + } + } else if (au != NULL) { + set_ids(c, mcp_arg_string(au, "taskId"), + mcp_arg_string(au, "contextId"), 0); + if (emit_parts(mcp_arg(mcp_arg(au, "artifact"), "parts"), + text, saw_text, cb, cbctx) != 0) + goto oom; + } else { + sp_buf_puts(err, "a2a: unknown stream event"); + goto out; + } + rc = 0; + goto out; + +oom: + sp_buf_puts(err, "a2a: out of memory"); +out: + if (v != NULL) + mcp_json_free(v); + return rc; +} + +/* one line of the SSE stream: data, or the numeric HTTP status at the end */ +static int +stream_line(struct a2a_cfg *c, char *line, size_t len, struct sp_buf *text, + int *saw_text, int *finished, int *http, sp_stream_cb cb, void *cbctx, + struct sp_buf *err) +{ + char *p; + + if (len > 0 && line[len - 1] == '\r') + line[--len] = '\0'; + if (len == 0) + return 0; + if (strncmp(line, "data:", 5) == 0) { + p = line + 5; + while (*p == ' ') + p++; + if (strcmp(p, "[DONE]") == 0) + return 0; + return stream_event(c, p, text, saw_text, finished, cb, cbctx, + err); + } + if (line[0] >= '0' && line[0] <= '9') { + char *end; + + *http = (int)strtol(line, &end, 10); + if (*end == '\0') + return 0; + } + return 0; /* event:, id:, comments, status */ +} + +static int +a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, + struct sp_buf *err, sp_stream_cb cb, void *cbctx) +{ + struct a2a_cfg *c = ctx; + struct sp_buf body, text, lbuf; + char templ[600], chunk[4096], *nl, *line; + pid_t pid = -1; + size_t start, len; + ssize_t got; + int fd = -1, http = 0, finished = 0, saw_text = 0; + int rc = -1, status = 0; + + if (c == NULL || conv == NULL || out == NULL) + return -1; + if (c->url[0] == '\0') { + sp_buf_puts(err, "a2a: SPLINTER_A2A_URL is not set"); + return -1; + } + memset(out, 0, sizeof(*out)); + out->status = 200; + memset(&body, 0, sizeof(body)); + memset(&text, 0, sizeof(text)); + memset(&lbuf, 0, sizeof(lbuf)); + if (sp_buf_init(&body) != 0 || sp_buf_init(&text) != 0 || + sp_buf_init(&lbuf) != 0) { + sp_buf_free(&body); + sp_buf_free(&text); + sp_buf_free(&lbuf); + return -1; + } + if (render(conv, c->full, &text) != 0) { + sp_buf_puts(err, "a2a: out of memory"); + goto out; + } + if (text.len == 0) { + sp_buf_puts(err, "a2a: nothing to send"); + goto out; + } + if (build_request(c, "SendStreamingMessage", text.p, &body) != 0) { + sp_buf_puts(err, "a2a: out of memory"); + goto out; + } + sp_buf_clear(&text); + dump_request(body.p, body.len); + fd = start_post(c, body.p, 1, &pid, templ, sizeof(templ), err); + if (fd < 0) + goto out; + while ((got = read(fd, chunk, sizeof(chunk))) > 0) { + if (sp_buf_add(&lbuf, chunk, (size_t)got) != 0) { + sp_buf_puts(err, "a2a: out of memory"); + goto fail; + } + start = 0; + while ((nl = memchr(lbuf.p + start, '\n', + lbuf.len - start)) != NULL) { + *nl = '\0'; + line = lbuf.p + start; + len = (size_t)(nl - line); + if (stream_line(c, line, len, &text, &saw_text, + &finished, &http, cb, cbctx, err) != 0) + goto fail; + start = (size_t)(nl - lbuf.p) + 1; + } + if (start > 0) { + memmove(lbuf.p, lbuf.p + start, lbuf.len - start); + lbuf.len -= start; + lbuf.p[lbuf.len] = '\0'; + } + } + if (got < 0 && errno == EINTR) { + sp_buf_puts(err, "a2a: read interrupted"); + goto fail; + } + if (got < 0) { + sp_buf_printf(err, "a2a: read: %s", strerror(errno)); + goto fail; + } + /* the last line may not end in a newline */ + if (lbuf.len > 0) { + if (stream_line(c, lbuf.p, lbuf.len, &text, &saw_text, + &finished, &http, cb, cbctx, err) != 0) + goto fail; + } + close(fd); + fd = -1; + if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) || + WEXITSTATUS(status) != 0) { + sp_buf_printf(err, "a2a: transfer failed for %s", c->url); + goto out; + } + unlink(templ); + if (http < 200 || http > 299) { + sp_buf_printf(err, "a2a: HTTP %d", http); + goto out; + } + if (!finished) { + sp_buf_puts(err, "a2a: stream ended before a terminal state"); + goto out; + } + if (text.len == 0) { + sp_buf_puts(err, "a2a: empty answer"); + goto out; + } + out->content = strdup(text.p); + if (out->content == NULL) { + sp_buf_puts(err, "a2a: out of memory"); + goto out; + } + rc = 0; + goto out; + +fail: + if (fd >= 0) + close(fd); + (void)kill(pid, SIGKILL); + (void)waitpid(pid, NULL, 0); + unlink(templ); +out: + sp_buf_free(&body); + sp_buf_free(&text); + sp_buf_free(&lbuf); + return rc; +} + static int a2a_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, struct sp_buf *err) @@ -431,7 +784,7 @@ a2a_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, sp_buf_puts(err, "a2a: nothing to send"); goto out; } - if (build_request(c, text.p, &body) != 0) { + if (build_request(c, "SendMessage", text.p, &body) != 0) { sp_buf_puts(err, "a2a: out of memory"); goto out; } @@ -482,6 +835,7 @@ a2a_init(struct sp_host *h) memset(&tr, 0, sizeof(tr)); tr.send = a2a_send; + tr.send_stream = a2a_stream; tr.ctx = &cfg; tr.provider = "a2a"; return sp_host_add_transport(h, "a2a", tr); diff --git a/src/main.c b/src/main.c index d6a224e..f96f754 100644 --- a/src/main.c +++ b/src/main.c @@ -44,6 +44,8 @@ usage(FILE *f) " per line (no network; for tests and demos)\n" " --config PATH read this config file instead of the default\n" " --no-config ignore the config file entirely\n" + " --no-stream one-shot mode: wait for the whole reply\n" + " instead of printing it as it arrives\n" " --init-config write a commented example config and exit\n" " --plugin PATH load a plugin (.so) before the first turn\n" " --transport NAME use a transport a plugin provides (\"cli\")\n" @@ -198,6 +200,7 @@ struct opts { size_t nplugins; int init_config, no_config, list_themes, chat, resume; int daemon, no_stdin, continue_here, interview; + int no_stream; int acklist, ack_id, ack_yes, mcp_port; }; @@ -250,6 +253,8 @@ parse_args(int argc, char **argv, struct opts *o, struct sp_agent_config *cfg) o->init_config = 1; else if (!strcmp(a, "--no-config")) o->no_config = 1; + else if (!strcmp(a, "--no-stream")) + o->no_stream = 1; else if (!strcmp(a, "--config")) VALUE(o->config_path); else if (!strcmp(a, "--transport")) @@ -820,7 +825,7 @@ run_slash_prompt(struct sp_host *host, const char *prompt) /* -p: one turn, the answer on stdout */ static int run_prompt(struct sp_agent *ag, struct sp_agent_config *cfg, const char *prompt, - struct sp_buf *err) + int no_stream, struct sp_buf *err) { struct sp_buf answer; int rc; @@ -832,9 +837,11 @@ run_prompt(struct sp_agent *ag, struct sp_agent_config *cfg, const char *prompt, * that cannot (the cli plugin, an MCP-backed one), setting the callback * made the agent take the non-streaming path while main still assumed the * text had already been printed - the answer vanished and only a newline - * came out. + * came out. --no-stream asks for the blocking path on purpose, which is + * also the only way to exercise a transport's plain send from the CLI. */ - cfg->stream = ag->tr.send_stream != NULL ? stdout_stream : NULL; + cfg->stream = (!no_stream && ag->tr.send_stream != NULL) ? + stdout_stream : NULL; cfg->stream_ctx = NULL; rc = sp_agent_run(ag, prompt, &answer, err); if (rc == 0) { @@ -996,7 +1003,7 @@ main(int argc, char **argv) } else if (o.prompt != NULL && o.prompt[0] == '/' && host != NULL) rc = run_slash_prompt(host, o.prompt); else - rc = run_prompt(&ag, &cfg, o.prompt, &err); + rc = run_prompt(&ag, &cfg, o.prompt, o.no_stream, &err); if (have_mock) sp_mock_free(&mock); diff --git a/src/www/index.en.html b/src/www/index.en.html index 224f786..e6cf697 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.

-

22274 lines of C99/POSIX · +

22635 lines of C99/POSIX · 23 tools · 31 test programs · 16 plugins · 42 palettes · BSD-3-Clause

@@ -106,7 +106,7 @@ hr { border: 0; border-top: 1px solid #1d2126; margin: 3em 0 1.5em 0; } NameWhat it does openaiany OpenAI-compatible endpoint, streaming over SSE cliany program as the model, e.g. claude -p -a2aanother agent over A2A (SendMessage, text) +a2aanother agent over A2A (SendMessage/streaming, text) ringexit ring: 429 or limit → next exit mcpan MCP server as a tool source, with its own schemas lcmcompaction of the conversation diff --git a/src/www/index.html b/src/www/index.html index 6a9fb1d..0e8a30e 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.

-

22274 Zeilen C99/POSIX · +

22635 Zeilen C99/POSIX · 23 Werkzeuge · 31 Test-Programme · 16 Plugins · 42 Farbschemata · BSD-3-Clause

@@ -106,7 +106,7 @@ hr { border: 0; border-top: 1px solid #1d2126; margin: 3em 0 1.5em 0; } NameWas es tut openaijeder OpenAI-kompatible Endpunkt, Streaming ueber SSE clijedes Programm als Modell, etwa claude -p -a2aein anderer Agent ueber A2A (SendMessage, Text) +a2aein anderer Agent ueber A2A (SendMessage/Streaming, Text) ringExit-Ring: 429 oder Limit → naechster Ausgang mcpMCP-Server als Werkzeugquelle, mit den Schemata des Servers lcmKomprimierung der Konversation diff --git a/src/www/index.pt.html b/src/www/index.pt.html index 121d1d5..6a8dd55 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.

-

22274 linhas C99/POSIX · +

22635 linhas C99/POSIX · 23 ferramentas · 31 programas de teste · 16 plugins · 42 paletas · BSD-3-Clause

@@ -87,7 +87,7 @@ skills, memoria e pesquisa na web.

Transportes e plugins

Transporte e um vtable: openai (HTTP/SSE), cli (claude, opencode), a2a -(outro agente via JSON-RPC), mock para teste. Plugins sao .so +(outro agente via JSON-RPC, com streaming), mock para teste. Plugins sao .so carregados com dlopen: lcm, focus, reminder, ring, mcp, cli, a2a, clock, cps, kids, tasks, planner, provider, scheduler, status e tmux.

diff --git a/tests/fake_a2a.py b/tests/fake_a2a.py index 794fcfd..9fdbaa5 100644 --- a/tests/fake_a2a.py +++ b/tests/fake_a2a.py @@ -1,10 +1,33 @@ -# fake A2A agent for tests/test_a2a.sh. -# argv: port, request log. One SendMessage handler, no streaming. +# 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 LOG = sys.argv[2] +def task_obj(state, message=None, artifacts=None): + t = {"id": "task-1", "contextId": "ctx-1", + "status": {"state": state}} + if message is not None: + t["status"]["message"] = {"messageId": "m2", "role": "ROLE_AGENT", + "parts": [{"text": message}]} + if artifacts is not None: + t["artifacts"] = [{"artifactId": "a1", + "parts": [{"text": artifacts}]}] + return t + + +def event(rid, obj): + return "data: " + json.dumps({"jsonrpc": "2.0", "id": rid, + "result": obj}) + "\n\n" + + +def error_event(rid, code, message): + return "data: " + json.dumps({"jsonrpc": "2.0", "id": rid, + "error": {"code": code, + "message": message}}) + "\n\n" + + class H(http.server.BaseHTTPRequestHandler): def log_message(self, *a): pass @@ -15,6 +38,7 @@ class H(http.server.BaseHTTPRequestHandler): with open(LOG, "a") as f: f.write(raw.decode("utf-8") + "\n") req = json.loads(raw) + stream = req.get("method") == "SendStreamingMessage" text = "" try: for p in req["params"]["message"]["parts"]: @@ -22,28 +46,74 @@ class H(http.server.BaseHTTPRequestHandler): except Exception: pass rid = req.get("id") - if "fehler" in text: - body = {"jsonrpc": "2.0", "id": rid, - "error": {"code": -32603, "message": "boom from a2a"}} + ctype = "text/event-stream" if stream else "application/json" + want_auth = "auth" in text + if want_auth and self.headers.get("Authorization") != "Bearer tok": + if stream: + b = error_event(rid, -32000, "unauthorized").encode() + else: + b = json.dumps({"jsonrpc": "2.0", "id": rid, + "error": {"code": -32000, + "message": "unauthorized"}}).encode() + elif "fehler" in text: + if stream: + b = error_event(rid, -32603, "boom from a2a").encode() + else: + b = json.dumps({"jsonrpc": "2.0", "id": rid, + "error": {"code": -32603, + "message": "boom from a2a"}}).encode() elif "direkt" in text: - body = {"jsonrpc": "2.0", "id": rid, "result": {"message": { - "messageId": "m1", "contextId": "ctx-1", - "role": "ROLE_AGENT", - "parts": [{"text": "direkt vom agenten"}]}}} - elif "auth" in text and self.headers.get("Authorization") != "Bearer tok": - body = {"jsonrpc": "2.0", "id": rid, - "error": {"code": -32000, "message": "unauthorized"}} + msg = {"messageId": "m1", "contextId": "ctx-1", + "role": "ROLE_AGENT", + "parts": [{"text": "direkt vom agenten"}]} + if stream: + b = event(rid, {"message": msg}).encode() + else: + b = json.dumps({"jsonrpc": "2.0", "id": rid, + "result": {"message": msg}}).encode() + elif stream and "streamstatus" in text: + b = (event(rid, {"task": task_obj("TASK_STATE_WORKING")}) + + event(rid, {"statusUpdate": { + "taskId": "task-1", "contextId": "ctx-1", + "status": {"state": "TASK_STATE_COMPLETED", + "message": {"messageId": "m3", + "role": "ROLE_AGENT", + "parts": [{"text": "nur status"}]}}}})).encode() + elif stream and "stream" in text: + b = (event(rid, {"task": task_obj("TASK_STATE_WORKING")}) + + event(rid, {"artifactUpdate": { + "taskId": "task-1", "contextId": "ctx-1", + "artifact": {"artifactId": "a2", + "parts": [{"text": "teil eins"}]}}}) + + event(rid, {"artifactUpdate": { + "taskId": "task-1", "contextId": "ctx-1", + "append": True, + "artifact": {"artifactId": "a2", + "parts": [{"text": " teil zwei"}]}}}) + + event(rid, {"statusUpdate": { + "taskId": "task-1", "contextId": "ctx-1", + "status": {"state": "TASK_STATE_COMPLETED", + "message": {"messageId": "m4", + "role": "ROLE_AGENT", + "parts": [{"text": "fertig"}]}}}})).encode() + elif "streamstatus" in text: + b = json.dumps({"jsonrpc": "2.0", "id": rid, "result": { + "task": task_obj("TASK_STATE_COMPLETED", "nur status")}}).encode() + elif "stream" in text: + b = json.dumps({"jsonrpc": "2.0", "id": rid, "result": { + "task": task_obj("TASK_STATE_COMPLETED", None, + "teil eins teil zwei")}}).encode() else: - body = {"jsonrpc": "2.0", "id": rid, "result": {"task": { - "id": "task-1", "contextId": "ctx-1", - "status": {"state": "TASK_STATE_COMPLETED", "message": { - "messageId": "m2", "role": "ROLE_AGENT", - "parts": [{"text": "a2a sagt hallo"}]}}, - "artifacts": [{"artifactId": "a1", - "parts": [{"text": "und tschuess"}]}]}}} - b = json.dumps(body).encode() + task = task_obj("TASK_STATE_COMPLETED", "a2a sagt hallo", + "und tschuess") + if stream: + b = event(rid, {"task": task}).encode() + else: + b = json.dumps({"jsonrpc": "2.0", "id": rid, + "result": {"task": task}}).encode() + self.send_response(200) - self.send_header("Content-Type", "application/json") + self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(b))) self.end_headers() self.wfile.write(b) diff --git a/tests/test_a2a.sh b/tests/test_a2a.sh index 3517490..5fc1ba5 100755 --- a/tests/test_a2a.sh +++ b/tests/test_a2a.sh @@ -1,10 +1,10 @@ #!/bin/sh # splinter -- the A2A client transport, against a fake A2A agent. # -# What it guards: SendMessage as JSON-RPC, the message shape, a Task result -# (status message plus artifact text), a direct Message result, the bearer -# token, and a JSON-RPC error that must fail the turn instead of becoming an -# empty answer. +# What it guards: SendMessage as JSON-RPC (--no-stream), SendStreamingMessage +# with SSE (the default one-shot path), the message shape, a Task result +# (status message plus artifact text), a direct Message, the bearer token, and +# a JSON-RPC error that must fail the turn instead of becoming an empty answer. set -u cd "$(dirname "$0")/.." || exit 1 D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-a2a-XXXXXX") || exit 1 @@ -21,20 +21,25 @@ done fails=0 check() { if "$@"; then :; else echo "FAIL $*"; fails=$((fails + 1)); fi; } -run() { # run , env from the caller +blocking() { # the plain send path + SPLINTER_A2A_URL="http://127.0.0.1:$P/rpc" SPLINTER_A2A_TIMEOUT=20 \ + ./splinter --no-config --plugin plugins/a2a/a2a.so \ + --transport a2a --no-stream -p "$1" +} +streaming() { # the one-shot default: stream when the transport can SPLINTER_A2A_URL="http://127.0.0.1:$P/rpc" SPLINTER_A2A_TIMEOUT=20 \ ./splinter --no-config --plugin plugins/a2a/a2a.so \ --transport a2a -p "$1" } -# a Task: status message and artifact text are both the answer -out=$(run "hallo" 2>&1) +# ---- blocking: a Task, status message and artifact text ---- +out=$(blocking "hallo" 2>&1) echo "$out" | grep -q 'a2a sagt hallo' check test $? -eq 0 echo "$out" | grep -q 'und tschuess' check test $? -eq 0 -# the wire shape +# the wire shape of the blocking call grep -q '"method":"SendMessage"' "$D/req.log" check test $? -eq 0 grep -q '"role":"ROLE_USER"' "$D/req.log" @@ -43,23 +48,46 @@ grep -q '"parts":\[{"text":"hallo"}\]' "$D/req.log" check test $? -eq 0 # a direct Message is an answer, not a task -out=$(run "direkt" 2>&1) +out=$(blocking "direkt" 2>&1) echo "$out" | grep -q 'direkt vom agenten' check test $? -eq 0 # the token goes out as a bearer header, and is required when the agent asks -out=$(SPLINTER_A2A_TOKEN=tok run "auth bitte" 2>&1) +out=$(SPLINTER_A2A_TOKEN=tok blocking "auth bitte" 2>&1) echo "$out" | grep -q 'a2a sagt hallo' check test $? -eq 0 -out=$(run "auth ohne token" 2>&1) +out=$(blocking "auth ohne token" 2>&1) echo "$out" | grep -q 'unauthorized' check test $? -eq 0 # a JSON-RPC error fails the turn with the agent's message -run "fehler" >/dev/null 2>"$D/err" +blocking "fehler" >/dev/null 2>"$D/err" check test $? -ne 0 grep -q 'boom from a2a' "$D/err" check test $? -eq 0 +# ---- streaming: artifact chunks arrive as the answer ---- +out=$(streaming "stream bitte" 2>&1) +echo "$out" | grep -q 'teil eins teil zwei' +check test $? -eq 0 +if echo "$out" | grep -q 'fertig'; then + echo "FAIL the final status note leaked into the streamed answer" + fails=$((fails + 1)) +fi + +# no artifact: the final status message is the answer +out=$(streaming "streamstatus" 2>&1) +echo "$out" | grep -q 'nur status' +check test $? -eq 0 + +# a direct Message also streams +out=$(streaming "direkt" 2>&1) +echo "$out" | grep -q 'direkt vom agenten' +check test $? -eq 0 + +# the wire method, not the blocking one +grep -q '"method":"SendStreamingMessage"' "$D/req.log" +check test $? -eq 0 + if [ "$fails" -eq 0 ]; then echo "test_a2a: ok"; exit 0; fi exit 1 diff --git a/tests/test_a2a_ui.sh b/tests/test_a2a_ui.sh new file mode 100755 index 0000000..ea58a23 --- /dev/null +++ b/tests/test_a2a_ui.sh @@ -0,0 +1,83 @@ +#!/bin/sh +# splinter -- the A2A streaming transport, driven through the curses UI. +# +# The UI is the only path that turns streaming on (src/ui.c sets cfg.stream), +# so this is where SendStreamingMessage is exercised: artifact chunks arrive +# live, the final status note is not appended to them, and a stream whose only +# answer is the final status message still produces text. +set -u +cd "$(dirname "$0")/.." || exit 1 +if ! command -v tmux >/dev/null 2>&1; then + echo "test_a2a_ui: skipped (no tmux)" + exit 0 +fi +D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-a2a-ui-XXXXXX") || exit 1 +unset TMUX TMUX_PANE +export TMUX_TMPDIR="$D" +S=splinter-a2a-ui-$$ +P=$((20000 + ($$ % 20000))) +F= +fails=0 +cleanup() { + tmux kill-server 2>/dev/null + [ -n "$F" ] && kill "$F" 2>/dev/null + rm -rf "$D" +} +trap cleanup EXIT +check() { if "$@"; then :; else echo "FAIL $*"; fails=$((fails + 1)); fi; } +shows() { + for i in $(seq 1 30); do + tmux capture-pane -t $S -p | grep -q -- "$1" && return 0 + sleep 0.5 + done + return 1 +} +done_turn() { + for i in $(seq 1 40); do + tmux capture-pane -t $S -p | grep -q 'working' || return 0 + sleep 0.5 + done + return 1 +} +typed() { tmux send-keys -t $S -l "$1"; } +key() { tmux send-keys -t $S "$@"; } + +mkdir -p "$D/home" +python3 -I tests/fake_a2a.py "$P" "$D/req.log" & +F=$! +for i in $(seq 1 50); do + curl -s -o /dev/null "http://127.0.0.1:$P/x" && break + sleep 0.2 +done +tmux new-session -d -s $S -x 110 -y 30 \ + "HOME=$D/home SPLINTER_LOCALE=en \ + SPLINTER_A2A_URL=http://127.0.0.1:$P/rpc \ + ./splinter --no-config --plugin plugins/a2a/a2a.so \ + --transport a2a --chat 2>/dev/null; echo \$? > $D/rc" +shows 'Enter sends' + +# artifact chunks stream; the completed status note is not appended +typed 'stream bitte'; key Enter +check shows 'teil eins teil zwei' +check done_turn +if tmux capture-pane -t $S -p | grep -q -- 'fertig'; then + echo "FAIL the final status note leaked into the answer" + fails=$((fails + 1)) +fi + +# no artifact: the final status message is the answer +typed 'streamstatus'; key Enter +check shows 'nur status' +check done_turn + +# the wire method, not the blocking one +grep -q '"method":"SendStreamingMessage"' "$D/req.log" +check test $? -eq 0 + +# quit cleanly +key C-u C-d +for i in $(seq 1 20); do [ -s "$D/rc" ] && break; sleep 0.5; done +check test "$(cat "$D/rc" 2>/dev/null)" = 0 + +if [ "$fails" -eq 0 ]; then echo "test_a2a_ui: ok"; exit 0; fi +exit 1 diff --git a/tools/gen_www.py b/tools/gen_www.py index 910f41b..ffc016b 100644 --- a/tools/gen_www.py +++ b/tools/gen_www.py @@ -284,7 +284,7 @@ SECTIONS = { (TRANSPORTS.format(h="Transporte und Plugins", t_name="Name", t_does="Was es tut", d_openai="jeder OpenAI-kompatible Endpunkt, Streaming ueber SSE", d_cli="jedes Programm als Modell, etwa claude -p", - d_a2a="ein anderer Agent ueber A2A (SendMessage, Text)", + d_a2a="ein anderer Agent ueber A2A (SendMessage/Streaming, Text)", d_ring="Exit-Ring: 429 oder Limit → naechster Ausgang", d_mcp="MCP-Server als Werkzeugquelle, mit den Schemata des Servers", d_lcm="Komprimierung der Konversation", @@ -365,7 +365,7 @@ SECTIONS = { (TRANSPORTS.format(h="Transports and plugins", t_name="Name", t_does="What it does", d_openai="any OpenAI-compatible endpoint, streaming over SSE", d_cli="any program as the model, e.g. claude -p", - d_a2a="another agent over A2A (SendMessage, text)", + d_a2a="another agent over A2A (SendMessage/streaming, text)", d_ring="exit ring: 429 or limit → next exit", d_mcp="an MCP server as a tool source, with its own schemas", d_lcm="compaction of the conversation", @@ -516,7 +516,7 @@ entrar na frente com um gate: permitir, negar com motivo, ou nao opinar.

""", skills, memoria e pesquisa na web.

""", """

Transportes e plugins

Transporte e um vtable: openai (HTTP/SSE), cli (claude, opencode), a2a -(outro agente via JSON-RPC), mock para teste. Plugins sao .so +(outro agente via JSON-RPC, com streaming), mock para teste. Plugins sao .so carregados com dlopen: lcm, focus, reminder, ring, mcp, cli, a2a, clock, cps, kids, tasks, planner, provider, scheduler, status e tmux.

""", """

Delegacao: outros modelos, splinter escolhe