diff --git a/Makefile b/Makefile index 2a8d416..3e19c03 100644 --- a/Makefile +++ b/Makefile @@ -286,8 +286,14 @@ tests/test_lifecycle: tests/test_lifecycle.c $(LIB) tests/plugin_lifecycle.so tests/test_plugin: tests/test_plugin.c $(LIB) $(PLUGIN) $(CC) $(CFLAGS) -o $@ tests/test_plugin.c -L. -lsplinter $(TEST_RPATH) $(LIBS) +# Every test runs under a 64 MB address-space limit: splinter is meant to +# be small, and a test that runs away (a retry loop appending to a buffer +# took 17 GB, 2026-11-18) must die at once instead of swapping the host. +TEST_MEM_KB ?= 65536 + check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) tests/test_junction @set -e; python3 tools/check_i18n.py; \ + ulimit -v $(TEST_MEM_KB); \ export LD_LIBRARY_PATH=.; \ SPLINTER_SESSION_DIR=$$(mktemp -d "$${TMPDIR:-/tmp}/splinter-check-XXXXXX"); \ export SPLINTER_SESSION_DIR; \ diff --git a/include/splinter.h b/include/splinter.h index ec42ba7..f8f9a50 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -131,7 +131,6 @@ int sp_conv_push(struct sp_conv *, const char *role, const char *name, */ int sp_conv_reset(struct sp_conv *, const char *system_prompt); size_t sp_conv_bytes(const struct sp_conv *); -int sp_conv_trim(struct sp_conv *, size_t keep_last); /* ------------------------------------------------------------- transport */ diff --git a/include/splinter_engine.h b/include/splinter_engine.h index 674cc6c..d46a018 100644 --- a/include/splinter_engine.h +++ b/include/splinter_engine.h @@ -187,6 +187,23 @@ int sp_engine_quit(struct sp_engine *); * next submit; closing does it too. */ int sp_engine_wait(struct sp_engine *); +/* + * Work on the engine's agent outside its turn thread. A daemon's Telegram + * turn runs sp_agent_run() on its own thread with the engine's agent: + * sp_engine_turn_begin() before it, sp_engine_turn_end() after; -1 means + * busy (a turn or a session tool owns the agent) and nothing was taken. + * While held, sp_engine_busy() says 1. The _agent_ forms find the engine + * that owns the agent (0 and a no-op for an agent no engine owns). + * sp_engine_hold()/release() is the short form for one tool call: exclusive + * like a turn, refused while one runs, not reported as busy. + */ +int sp_engine_turn_begin(struct sp_engine *); +void sp_engine_turn_end(struct sp_engine *); +int sp_engine_agent_turn_begin(struct sp_agent *); +void sp_engine_agent_turn_end(struct sp_agent *); +int sp_engine_hold(struct sp_engine *); +void sp_engine_release(struct sp_engine *); + /* Ask the model once without the queue: what -p and the slash prompt use. */ int sp_engine_prompt(struct sp_engine *, const char *text, sp_stream_cb, void *stream_ctx, struct sp_buf *answer, struct sp_buf *err); diff --git a/plugins/a2a/a2a.c b/plugins/a2a/a2a.c index a876066..99dcc93 100644 --- a/plugins/a2a/a2a.c +++ b/plugins/a2a/a2a.c @@ -115,11 +115,16 @@ build_request(struct a2a_cfg *c, const char *method, const char *text, "\"params\":{\"message\":{\"messageId\":\"%s\"," "\"role\":\"ROLE_USER\",", rid, method, mid) != 0) return -1; + /* both ids came from the server: escaped, never pasted */ if (c->task_id[0] != '\0' && - sp_buf_printf(out, "\"taskId\":\"%s\",", c->task_id) != 0) + (sp_buf_puts(out, "\"taskId\":\"") != 0 || + sp_json_escape(out, c->task_id) != 0 || + sp_buf_puts(out, "\",") != 0)) return -1; if (c->context_id[0] != '\0' && - sp_buf_printf(out, "\"contextId\":\"%s\",", c->context_id) != 0) + (sp_buf_puts(out, "\"contextId\":\"") != 0 || + sp_json_escape(out, c->context_id) != 0 || + sp_buf_puts(out, "\",") != 0)) return -1; if (sp_buf_puts(out, "\"parts\":[{\"text\":\"") != 0 || sp_json_escape(out, text) != 0 || @@ -202,7 +207,24 @@ save_part(const char *name, const char *mime, const char *data, size_t n, path, mime != NULL && *mime != '\0' ? mime : "binary", n); } -/* base64 bytes: text becomes text, anything else a file the agent can open */ +/* a media type whose bytes are words: text, JSON and the +json family */ +static int +mime_is_text(const char *mime) +{ + if (mime == NULL || *mime == '\0') + return 0; + if (strncasecmp(mime, "text/", 5) == 0) + return 1; + return strncasecmp(mime, "application/json", 16) == 0 || + strstr(mime, "+json") != NULL; +} + +/* + * base64 bytes: text becomes text, anything else a file the agent can open. + * A part without a media type is not assumed to be text: its bytes could be + * anything, and pasted into the conversation they are noise (or cut at the + * first NUL). Should the file not be written, a placeholder says what came. + */ static int part_bytes(const char *b64, const char *name, const char *mime, struct sp_buf *out) @@ -216,10 +238,15 @@ part_bytes(const char *b64, const char *name, const char *mime, 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 { + if (mime_is_text(mime)) { ok = append_piece(out, dec.p) == 0; + } else { + ok = save_part(name, mime, dec.p, dec.len, out) == 0; + if (!ok) + ok = sp_buf_printf(out, "%s[binary part %s, %zu bytes, " + "not saved]", out->len > 0 ? "\n" : "", + mime != NULL && *mime != '\0' ? mime : "without type", + dec.len) == 0; } sp_buf_free(&dec); return ok ? 0 : -1; @@ -864,11 +891,16 @@ out: return rc; } -/* one line of the SSE stream: data, or the numeric HTTP status at the end */ +/* + * One line of the SSE stream: data, or the numeric HTTP status at the end. + * A server that does not stream answers with a plain JSON body instead - a + * JSON-RPC error, typically. Those lines are kept in 'plain' and read once the + * stream is over, so the server's own message is what the user sees. + */ 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) + struct sp_buf *plain, struct sp_buf *err) { char *p; @@ -892,7 +924,15 @@ stream_line(struct a2a_cfg *c, char *line, size_t len, struct sp_buf *text, if (*end == '\0') return 0; } - return 0; /* event:, id:, comments, status */ + if (strncmp(line, "event:", 6) == 0 || strncmp(line, "id:", 3) == 0 || + strncmp(line, "retry:", 6) == 0 || line[0] == ':') + return 0; /* event:, id:, comments */ + if (plain->len < 65536 && (sp_buf_puts(plain, line) != 0 || + sp_buf_puts(plain, "\n") != 0)) { + sp_buf_puts(err, "a2a: out of memory"); + return -1; + } + return 0; } static int @@ -900,8 +940,8 @@ 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; + struct sp_buf body, text, lbuf, plain; + char templ[600] = "", chunk[4096], *nl, *line; pid_t pid = -1; size_t start, len; ssize_t got; @@ -922,11 +962,13 @@ a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, memset(&body, 0, sizeof(body)); memset(&text, 0, sizeof(text)); memset(&lbuf, 0, sizeof(lbuf)); + memset(&plain, 0, sizeof(plain)); if (sp_buf_init(&body) != 0 || sp_buf_init(&text) != 0 || - sp_buf_init(&lbuf) != 0) { + sp_buf_init(&lbuf) != 0 || sp_buf_init(&plain) != 0) { sp_buf_free(&body); sp_buf_free(&text); sp_buf_free(&lbuf); + sp_buf_free(&plain); return -1; } if (render(conv, c->full, &text) != 0) { @@ -944,8 +986,10 @@ a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *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) + if (fd < 0) { + templ[0] = '\0'; /* start_post removed it */ 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"); @@ -958,7 +1002,7 @@ a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, line = lbuf.p + start; len = (size_t)(nl - line); if (stream_line(c, line, len, &text, &saw_text, - &finished, &http, cb, cbctx, err) != 0) + &finished, &http, cb, cbctx, &plain, err) != 0) goto fail; start = (size_t)(nl - lbuf.p) + 1; } @@ -979,7 +1023,7 @@ a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, /* 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) + &finished, &http, cb, cbctx, &plain, err) != 0) goto fail; } close(fd); @@ -989,7 +1033,26 @@ a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, sp_buf_printf(err, "a2a: transfer failed for %s", c->url); goto out; } - unlink(templ); + /* + * Not a stream but one JSON body: a JSON-RPC error (or a plain + * result) the server sent instead. Read it like an event; an error + * member becomes the error. + */ + if (!finished && plain.len > 0 && plain.p[0] == '{') { + struct sp_buf perr; + + if (sp_buf_init(&perr) == 0) { + if (stream_event(c, plain.p, &text, &saw_text, + &finished, cb, cbctx, &perr) != 0 && perr.len > 0) { + sp_buf_puts(err, perr.p); + if (http < 200 || http > 299) + sp_buf_printf(err, " (HTTP %d)", http); + sp_buf_free(&perr); + goto out; + } + sp_buf_free(&perr); + } + } if (http < 200 || http > 299) { sp_buf_printf(err, "a2a: HTTP %d", http); goto out; @@ -1015,11 +1078,14 @@ fail: close(fd); (void)kill(pid, SIGKILL); (void)waitpid(pid, NULL, 0); - unlink(templ); out: + /* the request is the whole conversation: never left behind */ + if (templ[0] != '\0') + (void)unlink(templ); sp_buf_free(&body); sp_buf_free(&text); sp_buf_free(&lbuf); + sp_buf_free(&plain); return rc; } diff --git a/plugins/cache/cache.c b/plugins/cache/cache.c index a919d6c..2bfd646 100644 --- a/plugins/cache/cache.c +++ b/plugins/cache/cache.c @@ -35,6 +35,7 @@ #define CACHE_MS 3000 #define CACHE_PROBE_MS 15000 +#define CACHE_BACKOFF_S 60 /* the longest wait after failed probes */ struct jcache { int valid; @@ -48,8 +49,36 @@ static struct { pthread_mutex_t lock; struct jcache j; char widget[1024]; - char dbg[256]; -} c = { NULL, PTHREAD_MUTEX_INITIALIZER, { 0 }, "", "" }; + char dbg[256]; /* why the last probe failed; under lock */ + int down; /* the last probe failed */ + unsigned fails; /* failed probes in a row */ + time_t next_probe; /* not before this */ +} c = { NULL, PTHREAD_MUTEX_INITIALIZER, { 0 }, "", "", 0, 0, 0 }; + +/* + * A probe that failed: say why, mark the numbers as stale (they are kept, with + * their age, but no longer shown as current) and wait longer before the next + * try - 3, 6, 12 ... up to 60 s. Every probe blocks the widget thread for up + * to 4 s; a junction that is down must not cost that on every tick. + */ +static void +probe_failed(const char *fmt, const char *what) +{ + unsigned delay = CACHE_MS / 1000; + unsigned k; + + pthread_mutex_lock(&c.lock); + snprintf(c.dbg, sizeof(c.dbg), fmt, what); + c.down = 1; + if (c.fails < 16) + c.fails++; + for (k = 1; k < c.fails && delay < CACHE_BACKOFF_S; k++) + delay *= 2; + if (delay > CACHE_BACKOFF_S) + delay = CACHE_BACKOFF_S; + c.next_probe = time(NULL) + (time_t)delay; + pthread_mutex_unlock(&c.lock); +} /* "12.3k" for token counts; a cache line should fit one sidebar row */ static void @@ -147,10 +176,6 @@ get_body(const char *url, const char *header) while (waitpid(pid, &st, 0) < 0 && errno == EINTR) ; sp_buf_free(&err); - if (body.p == NULL) { - sp_buf_free(&body); - return NULL; - } return body.p; } @@ -168,39 +193,42 @@ probe_junction(void) if (url[0] == '\0') return; body = get_body(url, hdr); - if (body == NULL) { - snprintf(c.dbg, sizeof(c.dbg), "no body from %s", url); + if (body == NULL || body[0] == '\0') { + free(body); + probe_failed("no body from %s", url); return; } v = mcp_parse(body); if (v == NULL) { - snprintf(c.dbg, sizeof(c.dbg), "unparseable: %.120s", body); + probe_failed("unparseable: %.120s", body); free(body); return; } cache = mcp_arg(v, "cache"); if (cache == NULL) { - snprintf(c.dbg, sizeof(c.dbg), "no cache object: %.100s", body); + probe_failed("no cache object: %.100s", body); free(body); mcp_json_free(v); return; } free(body); - if (cache != NULL) { - memset(&j, 0, sizeof(j)); - j.valid = 1; - j.ttl_s = (long)mcp_arg_int(cache, "ttl_s", 0); - j.entries = (long)mcp_arg_int(cache, "entries", 0); - j.bytes = (long)mcp_arg_int(cache, "bytes", 0); - j.hits = (long)mcp_arg_int(cache, "hits", 0); - j.misses = (long)mcp_arg_int(cache, "misses", 0); - j.joined = (long)mcp_arg_int(cache, "joined", 0); - j.at = time(NULL); - snprintf(j.url, sizeof(j.url), "%s", url); - pthread_mutex_lock(&c.lock); - c.j = j; - pthread_mutex_unlock(&c.lock); - } + memset(&j, 0, sizeof(j)); + j.valid = 1; + j.ttl_s = (long)mcp_arg_int(cache, "ttl_s", 0); + j.entries = (long)mcp_arg_int(cache, "entries", 0); + j.bytes = (long)mcp_arg_int(cache, "bytes", 0); + j.hits = (long)mcp_arg_int(cache, "hits", 0); + j.misses = (long)mcp_arg_int(cache, "misses", 0); + j.joined = (long)mcp_arg_int(cache, "joined", 0); + j.at = time(NULL); + snprintf(j.url, sizeof(j.url), "%s", url); + pthread_mutex_lock(&c.lock); + c.j = j; + c.down = 0; + c.fails = 0; + c.dbg[0] = '\0'; + c.next_probe = j.at + CACHE_PROBE_MS / 1000; + pthread_mutex_unlock(&c.lock); mcp_json_free(v); } @@ -212,20 +240,20 @@ cache_tick(struct sp_host *h, const char *name, void *ctx) char text[1024], last[24], ses[24], l[24], s[24]; int lpct = 0, spct = 0; time_t now = time(NULL); - int probe = 0; + int probe = 0, down; (void)ctx; c.host = h; sp_host_meter_get(h, &m); pthread_mutex_lock(&c.lock); - j = c.j; - if (!j.valid || now - j.at >= CACHE_PROBE_MS / 1000) + if (now >= c.next_probe) probe = 1; pthread_mutex_unlock(&c.lock); if (probe) probe_junction(); pthread_mutex_lock(&c.lock); j = c.j; + down = c.down; pthread_mutex_unlock(&c.lock); human(m.ctx_used, last, sizeof(last)); @@ -248,7 +276,16 @@ cache_tick(struct sp_host *h, const char *name, void *ctx) "cached %s of %s last\n" "session %s of %s tokens", lpct, spct, l, last, s, ses); - if (j.valid) { + if (j.valid && down) { + size_t off = strlen(text); + + /* the old numbers are not the cache now: say how old they are */ + snprintf(text + off, sizeof(text) - off, + "\njunction %s | stats down\n" + "junction last stats %lds ago", + sp_host_cache_mode(h)[0] != '\0' ? + sp_host_cache_mode(h) : "unknown", (long)(now - j.at)); + } else if (j.valid) { size_t off = strlen(text); char b[24]; @@ -280,7 +317,8 @@ cache_command(struct sp_host *h, const char *args, struct sp_buf *out, char l[24], s[24], b[24]; char curl[600], chdr[600]; const struct sp_config *cfg; - int lpct = 0, spct = 0; + char dbg[sizeof(c.dbg)]; + int lpct = 0, spct = 0, down; (void)args; (void)ctx; @@ -290,6 +328,8 @@ cache_command(struct sp_host *h, const char *args, struct sp_buf *out, sp_host_meter_get(h, &m); pthread_mutex_lock(&c.lock); j = c.j; + down = c.down; + snprintf(dbg, sizeof(dbg), "%s", c.dbg); pthread_mutex_unlock(&c.lock); if (m.ctx_used > 0) lpct = (int)((m.cached * 100 + m.ctx_used / 2) / m.ctx_used); @@ -313,11 +353,14 @@ cache_command(struct sp_host *h, const char *args, struct sp_buf *out, "%ld misses, %s, ttl %ld s, %ld joined\n", j.entries, j.hits, j.misses, b, j.ttl_s, j.joined); sp_buf_printf(out, " junction status: %s\n", j.url); - } else { + if (down) + sp_buf_printf(out, " junction: stale, from %ld s ago; " + "the last probe failed\n", + (long)(time(NULL) - j.at)); + } else sp_buf_puts(out, " junction: no /status cache stats\n"); - if (c.dbg[0] != '\0') - sp_buf_printf(out, " probe: %s\n", c.dbg); - } + if (dbg[0] != '\0') + sp_buf_printf(out, " probe: %s\n", dbg); return 0; } diff --git a/plugins/cps/cps.c b/plugins/cps/cps.c index f97d36d..6635802 100644 --- a/plugins/cps/cps.c +++ b/plugins/cps/cps.c @@ -25,7 +25,6 @@ #include "splinter_plugin.h" #include "i18n.h" -#define SNAP_MAX 256 #define KEEP_TAIL 6 #define SUMMARY_MAX 512 @@ -37,10 +36,12 @@ struct snap_msg { static struct { pthread_mutex_t lock; - size_t n; /* messages in the snapshot, <= SNAP_MAX */ + size_t n; /* messages in the snapshot: all of them */ + size_t cap; /* allocated entries in m */ size_t total; /* messages in the conversation then */ size_t bytes; /* and its size: a stale plan is refused */ - struct snap_msg m[SNAP_MAX]; + size_t budget; /* the budget the plan is made for */ + struct snap_msg *m; int requested; int ready; size_t cut; /* drop [1, cut) */ @@ -53,21 +54,53 @@ static struct { char widget[256]; } cps; -static void -copy_snapshot(const struct sp_conv *conv) +/* one message as sp_conv_bytes() counts it */ +static size_t +msg_bytes(const struct sp_msg *m) { - size_t i, n = conv->n > SNAP_MAX ? SNAP_MAX : conv->n; + return (m->role != NULL ? strlen(m->role) : 0) + + (m->name != NULL ? strlen(m->name) : 0) + + (m->content != NULL ? strlen(m->content) : 0) + + (m->calls != NULL ? strlen(m->calls) : 0) + 16; +} + +/* + * The index covers the whole conversation: a plan made from the first few + * hundred messages cut against a conversation of thousands. + */ +static void +copy_snapshot(const struct sp_conv *conv, size_t budget) +{ + size_t i, n = conv->n; pthread_mutex_lock(&cps.lock); + if (n > cps.cap) { + struct snap_msg *nm; + size_t ncap = cps.cap ? cps.cap : 64; + + while (ncap < n) + ncap *= 2; + nm = realloc(cps.m, ncap * sizeof(*nm)); + if (nm == NULL) { + /* no index, no plan: lcm or the host trim still work */ + cps.requested = 0; + cps.ready = 0; + pthread_mutex_unlock(&cps.lock); + return; + } + cps.m = nm; + cps.cap = ncap; + } cps.n = n; cps.total = conv->n; cps.bytes = sp_conv_bytes(conv); + cps.budget = budget; for (i = 0; i < n; i++) { const struct sp_msg *m = &conv->v[i]; snprintf(cps.m[i].role, sizeof(cps.m[i].role), "%s", m->role != NULL ? m->role : "?"); - cps.m[i].len = m->content != NULL ? strlen(m->content) : 0; + cps.m[i].len = msg_bytes(m); snprintf(cps.m[i].head, sizeof(cps.m[i].head), "%s", m->content != NULL ? m->content : ""); } @@ -89,21 +122,22 @@ cps_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, pthread_mutex_lock(&cps.lock); /* - * The plan fits this conversation only if it is the one it was made for. - * Comparing against cps.n, which stops at SNAP_MAX, meant that past 256 - * messages no plan ever applied - compaction just stopped. + * The plan fits this conversation only if it is the one it was made for: + * same length, same size, same budget. */ if (budget == 0) { pthread_mutex_unlock(&cps.lock); return 0; /* no byte budget: nothing to do */ } - if (cps.ready && cps.total == conv->n && + if (cps.ready && cps.total == conv->n && cps.budget == budget && cps.bytes == sp_conv_bytes(conv) && sp_conv_bytes(conv) > budget) { apply = 1; } else { pthread_mutex_unlock(&cps.lock); - copy_snapshot(conv); + if (sp_conv_bytes(conv) <= budget) + return 0; /* fits: no plan needed */ + copy_snapshot(conv, budget); return 0; /* plan is being prepared */ } @@ -171,20 +205,44 @@ cps_tick(struct sp_host *h, const char *name, void *ctx) cps.requested = 0; for (i = 0; i < cps.n; i++) - total += cps.m[i].len + 16; + total += cps.m[i].len; tail_from = cps.n > KEEP_TAIL ? cps.n - KEEP_TAIL : 1; - cut = tail_from; - if (cut <= 1) - cut = 1; + if (tail_from < 1) + tail_from = 1; + /* + * Cut from the front only as far as the budget needs (room left for the + * summary), never into the verbatim tail, and never so that the first + * kept message is a tool result without its call. + */ + cut = 1; + { + size_t left = total; + + while (cut < tail_from && left + SUMMARY_MAX > cps.budget) { + left -= cps.m[cut].len; + cut++; + } + } + while (cut < cps.n && strcmp(cps.m[cut].role, "tool") == 0) + cut++; snprintf(cps.summary, sizeof(cps.summary), - "[cps] %zu messages cut from the front to stay under budget; " + "[cps] %zu messages cut from the front to fit %zu bytes; " "verbatim tail of %zu messages follows. Oldest cut turn began with: " - "\"%.60s\"", cut - 1, cps.n - cut, + "\"%.60s\"", cut - 1, cps.budget, cps.n - cut, cps.n > 1 ? cps.m[1].head : ""); cps.before = total; - cps.after = 0; + cps.after = cps.n > 0 ? cps.m[0].len : 0; for (i = cut; i < cps.n; i++) - cps.after += cps.m[i].len + 16; + cps.after += cps.m[i].len; + if (cut <= 1 || cut >= cps.n) { + /* nothing to cut that would leave a valid tail */ + cps.ready = 0; + snprintf(line, sizeof(line), sp_td("cps.idle", + "idle (applied %lu, prepared %lu)"), cps.applied, + cps.prepared); + pthread_mutex_unlock(&cps.lock); + return sp_host_widget_text(h, name, line); + } cps.cut = cut; cps.ready = 1; cps.prepared++; diff --git a/plugins/junction/junction.c b/plugins/junction/junction.c index 3bf076b..186ff99 100644 --- a/plugins/junction/junction.c +++ b/plugins/junction/junction.c @@ -95,7 +95,9 @@ static struct { unsigned interval_ms; unsigned models_ms; char status_path[24]; /* the alias that answered last */ - int status_alias; /* index into aliases, -1 unknown */ + char status_cfg[24]; /* status_path from the config */ + int status_alias; /* index into aliases, -1 unknown, + J_ALIASES the configured one */ char widget[1024]; /* the sidebar block, no colon in line 2+ */ char stats[J_STAT_MAX]; /* the X-Junction-* statistics */ @@ -120,6 +122,7 @@ static struct { struct { char name[32]; int ok; } prev[40]; size_t nprev; char route[256]; /* the rule targets, space separated */ + int route_blocked; /* the matching rule blocks the model */ char route_down[160]; /* targets whose probe failed */ unsigned route_up, route_n; struct jep ep[40]; @@ -557,13 +560,20 @@ read_status(const char *body) } } m = mcp_arg(root, "rules"); + j.route_blocked = 0; if (m != NULL) { char blocked[8]; route_for_model(m, j.model, j.route, sizeof(j.route), blocked, sizeof(blocked)); - if (blocked[0] != '\0') - snprintf(j.route, sizeof(j.route), "blocked by a rule"); + /* + * A status, not a target list: j.route is split on spaces as + * target names, so the text must not end up in it. + */ + if (blocked[0] != '\0') { + j.route_blocked = 1; + j.route[0] = '\0'; + } } route_health(); /* @@ -648,10 +658,10 @@ compose_stats(void) sets[1] = &j.h_status; sets[2] = &j.h_mcp; buf[0] = '\0'; - for (s = 0; s < 3; s++) { + for (s = 0; s < 3 && off < sizeof(buf) - 1; s++) { const struct jset *set = sets[s]; - for (i = 0; i < set->n; i++) { + for (i = 0; i < set->n && off < sizeof(buf) - 1; i++) { const char *name = set->v[i].name; char key[40]; size_t kl; @@ -685,8 +695,9 @@ compose_stats(void) off += (size_t)snprintf(buf + off, sizeof(buf) - off, "%s%s=%s", off > 0 ? " " : "", key, set->v[i].value); - if (off >= sizeof(buf)) - break; + /* truncated: clamp, and both loops stop on the guard */ + if (off >= sizeof(buf) - 1) + off = sizeof(buf) - 1; } } snprintf(j.stats, sizeof(j.stats), "%s", buf); @@ -803,9 +814,10 @@ compose(void) } if (first) off = (size_t)snprintf(j.widget, sizeof(j.widget), - "%s\nserving %s\nroute (no rule matched)", + "%s\nserving %s\nroute %s", j.model[0] != '\0' ? j.model : "(model unknown)", - sbuf); + sbuf, j.route_blocked ? "blocked by a rule" : + "(no rule matched)"); if (off < sizeof(j.widget)) snprintf(j.widget + off, sizeof(j.widget) - off, "\n%u/%u up", j.route_up, j.route_n); @@ -923,8 +935,15 @@ probe(void) status_aliases[j.status_alias]); body_ok = probe_status(base, path, &hstatus); } + /* the configured status_path is tried first, and remembered */ + if (!body_ok && j.status_cfg[0] != '\0') { + snprintf(path, sizeof(path), "%s", j.status_cfg); + body_ok = probe_status(base, path, &hstatus); + j.status_alias = body_ok ? J_ALIASES : -1; + } for (i = 0; !body_ok && i < J_ALIASES; i++) { - if (j.status_alias == i) + if (j.status_alias == i || + strcmp(status_aliases[i], j.status_cfg) == 0) continue; snprintf(path, sizeof(path), "%s", status_aliases[i]); body_ok = probe_status(base, path, &hstatus); @@ -1026,7 +1045,7 @@ snapshot_text(struct sp_buf *out) sp_buf_puts(out, " judge next: no headers\n"); } sp_buf_printf(out, " route: %s\n", j.route[0] != '\0' ? j.route : - "(no rule matched)"); + j.route_blocked ? "blocked by a rule" : "(no rule matched)"); sp_buf_printf(out, " route health: %u/%u up%s%s\n", j.route_up, j.route_n, j.route_down[0] != '\0' ? ", down: " : "", j.route_down); @@ -1167,11 +1186,14 @@ resolve_config(struct sp_host *h) if (j.models_ms < 10000) j.models_ms = J_MODELS_MS; v = sp_host_plugin_config(h, "junction", "status_path"); - if (v != NULL && *v == '/') + if (v != NULL && *v == '/') { + snprintf(j.status_cfg, sizeof(j.status_cfg), "%s", v); snprintf(j.status_path, sizeof(j.status_path), "%s", v); - else + } else { + j.status_cfg[0] = '\0'; snprintf(j.status_path, sizeof(j.status_path), "%s", status_aliases[0]); + } } static int diff --git a/plugins/kids/kids.c b/plugins/kids/kids.c index 0459726..ee26b52 100644 --- a/plugins/kids/kids.c +++ b/plugins/kids/kids.c @@ -20,6 +20,7 @@ * - the whitelist matches the tool and its arguments, never the mood. */ #include +#include #include #include #include @@ -260,25 +261,48 @@ whitelisted(const char *tool, const char *args) /* * sh -c '' sh '': the command string is parsed, the argument is not. - * Returns the wait status, like system(3). + * Returns the wait status, like system(3). After 'secs' seconds the command and + * everything it started (its own process group) are killed and *timed_out is + * set: a parent who is not looking does not approve anything, and the child is + * not kept waiting forever either. */ static int -run_with_arg(const char *cmd, const char *arg) +run_with_arg(const char *cmd, const char *arg, unsigned secs, int *timed_out) { - pid_t child; - int status; + pid_t child, r; + int status; + struct timespec start, now, nap = { 0, 50000000L }; + *timed_out = 0; child = fork(); if (child < 0) return -1; if (child == 0) { + (void)setpgid(0, 0); execl("/bin/sh", "sh", "-c", cmd, "sh", arg, (char *)NULL); _exit(127); } - while (waitpid(child, &status, 0) < 0) - if (errno != EINTR) + (void)setpgid(child, child); + (void)clock_gettime(CLOCK_MONOTONIC, &start); + for (;;) { + r = waitpid(child, &status, WNOHANG); + if (r == child) + return status; + if (r < 0 && errno != EINTR) return -1; - return status; + (void)clock_gettime(CLOCK_MONOTONIC, &now); + if ((now.tv_sec - start.tv_sec) * 1000L + + (now.tv_nsec - start.tv_nsec) / 1000000L >= + (long)secs * 1000L) { + *timed_out = 1; + (void)kill(-child, SIGKILL); + (void)kill(child, SIGKILL); + while (waitpid(child, &status, 0) < 0 && errno == EINTR) + ; + return -1; + } + (void)nanosleep(&nap, NULL); + } } /* @@ -289,7 +313,7 @@ static int ask_parent(const char *tool, const char *args, char *reason, size_t reason_len) { char cmd[1024], request[1024]; - int rc; + int rc, timed_out; /* * The general ack mechanism first: a request file plus whichever channels are @@ -327,12 +351,12 @@ ask_parent(const char *tool, const char *args, char *reason, size_t reason_len) snprintf(cmd, sizeof(cmd), "%s \"$1\"", approve_cmd); snprintf(request, sizeof(request), "Anfrage: %s %s", tool, args != NULL ? args : ""); - rc = run_with_arg(cmd, request); - if (rc == 0) + rc = run_with_arg(cmd, request, timeout_s, &timed_out); + if (rc == 0 && !timed_out) return 1; snprintf(reason, reason_len, "ein Erwachsener hat nicht zugestimmt (%s)", - WIFEXITED(rc) && WEXITSTATUS(rc) == 124 ? "Zeit abgelaufen" : - "abgelehnt"); + timed_out || (rc != -1 && WIFEXITED(rc) && WEXITSTATUS(rc) == 124) ? + "Zeit abgelaufen" : "abgelehnt"); return 0; } @@ -423,6 +447,15 @@ kids_gate(struct sp_host *h, const char *tool, int auth, const char *args, char *reason, size_t reason_len) { (void)h; + /* + * The budget comes first: when the day is over every tool is refused, + * reading and the parent's own domain list included. + */ + if (quota_left() == 0) { + snprintf(reason, reason_len, "fuer heute ist Schluss (%ld von %u " + "Minuten)", used_seconds / 60, daily_minutes); + return 0; + } if (strcmp(tool, "websearch") == 0 || strcmp(tool, "webfetch") == 0) { /* * The curated list is the safe ground and works in every mode: a @@ -447,11 +480,6 @@ kids_gate(struct sp_host *h, const char *tool, int auth, const char *args, } else if (auth == SP_AUTH_READ) return 1; - if (quota_left() == 0) { - snprintf(reason, reason_len, "fuer heute ist Schluss (%ld von %u " - "Minuten)", used_seconds / 60, daily_minutes); - return 0; - } load_rules(); if (whitelisted(tool, args)) return 1; diff --git a/plugins/lcm/lcm.c b/plugins/lcm/lcm.c index bc86d5a..6bb7882 100644 --- a/plugins/lcm/lcm.c +++ b/plugins/lcm/lcm.c @@ -46,6 +46,30 @@ is_role(const struct sp_msg *m, const char *role) return m->role != NULL && strcmp(m->role, role) == 0; } +/* + * The engine's own continuation prompts. They arrive as user messages, but they + * are not the question: after /resume the newest user message is "Continue with + * the task ...", and pinning that keeps the keystroke while the task it was + * meant to continue is cut away. Measured: a session resumed after a rate limit + * woke up with the prompt, one tool call and its error, and no task at all. + */ +static int +is_continuation_prompt(const struct sp_msg *m) +{ + static const char *const pfx[] = { + "Continue with the task you were working on", + "Continue working toward this goal", + }; + size_t i; + + if (m->content == NULL) + return 0; + for (i = 0; i < sizeof(pfx) / sizeof(pfx[0]); i++) + if (strncmp(m->content, pfx[i], strlen(pfx[i])) == 0) + return 1; + return 0; +} + /* the first line of a text, at most n bytes, for the marker */ static void first_line(const char *s, char *out, size_t cap, size_t n) @@ -115,6 +139,16 @@ trim_tools(struct sp_conv *conv, size_t first, size_t end, size_t cap) return n; } +/* one message as sp_conv_bytes() counts it */ +static size_t +msg_bytes(const struct sp_msg *m) +{ + return (m->role != NULL ? strlen(m->role) : 0) + + (m->name != NULL ? strlen(m->name) : 0) + + (m->content != NULL ? strlen(m->content) : 0) + + (m->calls != NULL ? strlen(m->calls) : 0) + 16; +} + static int lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, unsigned turn) @@ -124,7 +158,8 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, char preview[PREVIEW + 1]; char summary[512]; size_t n_user = 0, n_asst = 0, n_tool = 0; - size_t pin_at = 0; + size_t drop_bytes = 0, add_bytes; + long pin_at = -1; char *pin_content = NULL, *pin_name = NULL; int trimmed, pinned = 0; const char *oldest; @@ -178,14 +213,20 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, * The newest user message is the task being answered. A long tool loop * can push it out of the verbatim tail; dropping it made the model ask * "what was the question?" and dig it out with recall. Pin it and put - * it back right after the summary. + * it back right after the summary. Only a user message is pinned: with + * none in the cut range nothing is (pin_at stays -1), never the system + * prompt or an assistant turn under the wrong role. A continuation prompt + * is skipped: it is the harness talking, not the task. */ - for (i = conv->n; i > first; i--) - if (is_role(&conv->v[i - 1], "user")) { - pin_at = i - 1; - break; - } - if (pin_at < keep_from && keep_from > first) { + for (i = conv->n; i > first; i--) { + if (!is_role(&conv->v[i - 1], "user")) + continue; + if (is_continuation_prompt(&conv->v[i - 1])) + continue; + pin_at = (long)(i - 1); + break; + } + if (pin_at >= 0 && (size_t)pin_at < keep_from) { pin_content = strdup(conv->v[pin_at].content != NULL ? conv->v[pin_at].content : ""); if (conv->v[pin_at].name != NULL) @@ -193,13 +234,43 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, pinned = pin_content != NULL; } drop = keep_from - first; + + oldest = conv->v[first].content; /* the oldest one that goes */ + for (i = first; i < keep_from; i++) { + drop_bytes += msg_bytes(&conv->v[i]); + if (is_role(&conv->v[i], "user")) + n_user++; + else if (is_role(&conv->v[i], "assistant")) + n_asst++; + else if (is_role(&conv->v[i], "tool")) + n_tool++; + } + if (pinned && n_user > 0) + n_user--; /* the pinned one is kept */ + snprintf(preview, sizeof(preview), "%s", oldest != NULL ? oldest : ""); + snprintf(summary, sizeof(summary), + "[lcm] %zu messages compacted out (user %zu, assistant %zu, tool %zu) " + "to fit %zu bytes; the verbatim tail of %zu messages follows.%s " + "Oldest dropped turn began with: \"%s\"", + drop - (pinned ? 1 : 0), n_user, n_asst, n_tool, + budget, conv->n - keep_from, + pinned ? " The current question was kept." : + (trimmed > 0 ? " Older tool output was cut too (recall still has it)." : + ""), + preview); + add_bytes = strlen("system") + strlen(summary) + 16; + if (pinned) + add_bytes += strlen("user") + strlen(pin_content) + + (pin_name != NULL ? strlen(pin_name) : 0) + 16; /* * A summary and the pinned question are messages too. If the cut would - * remove no more than it adds, the count grows (N -> N+1 was the - * /resume loop) and the context never shrinks. Keep the output trim, - * skip the message rewrite. + * remove no more bytes than it adds, the conversation grows (N -> N+1 + * was the /resume loop) and the context never shrinks. Keep the output + * trim, skip the message rewrite. Bytes, not messages: the budget is in + * bytes, and one huge message is worth cutting even if it is the only + * one that goes. */ - if (drop <= (size_t)1 + (pinned ? 1 : 0)) { + if (drop_bytes <= add_bytes) { free(pin_content); free(pin_name); if (trimmed > 0) { @@ -214,27 +285,6 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, return 0; } - oldest = conv->v[first].content; /* the oldest one that goes */ - for (i = first; i < keep_from; i++) { - if (is_role(&conv->v[i], "user")) - n_user++; - else if (is_role(&conv->v[i], "assistant")) - n_asst++; - else if (is_role(&conv->v[i], "tool")) - n_tool++; - } - snprintf(preview, sizeof(preview), "%s", oldest != NULL ? oldest : ""); - snprintf(summary, sizeof(summary), - "[lcm] %zu messages compacted out (user %zu, assistant %zu, tool %zu) " - "to fit %zu bytes; the verbatim tail of %zu messages follows.%s " - "Oldest dropped turn began with: \"%s\"", - drop - (pinned ? 1 : 0), n_user - (pinned ? 1 : 0), n_asst, n_tool, - budget, conv->n - keep_from, - pinned ? " The current question was kept." : - (trimmed > 0 ? " Older tool output was cut too (recall still has it)." : - ""), - preview); - for (i = first; i < keep_from; i++) { free(conv->v[i].role); free(conv->v[i].name); diff --git a/plugins/mcp/mcp.c b/plugins/mcp/mcp.c index c8c8ae8..3b760c8 100644 --- a/plugins/mcp/mcp.c +++ b/plugins/mcp/mcp.c @@ -89,44 +89,81 @@ struct toolref { }; /* - * Slice the JSON object that follows "inputSchema" out of the raw line. + * Print a parsed JSON value back as text. * - * libmcp parses but does not print, and a tool schema has to be handed back to - * the model exactly as the server wrote it. Brace matching that respects - * strings and escapes is small and has no dependency. + * libmcp parses but does not print. A tool's schema has to be handed to the + * model; it is taken from the tool's own entry in the parsed tools array, so a + * tool without one (or a description that mentions "inputSchema") can never + * hand its neighbour's schema over. Key order is kept; numbers are printed as + * integers when they are integral. */ -static const char * -slice_object(const char *at, size_t *lenp) +static int +json_print(struct sp_buf *b, const mcp_json *v) { - const char *p = strchr(at, '{'); - const char *start; - int depth = 0, instr = 0, escape = 0; + size_t i; - if (p == NULL) - return NULL; - start = p; - for (; *p != '\0'; p++) { - if (escape) { - escape = 0; - continue; - } - if (instr) { - if (*p == '\\') - escape = 1; - else if (*p == '"') - instr = 0; - continue; - } - if (*p == '"') - instr = 1; - else if (*p == '{') - depth++; - else if (*p == '}' && --depth == 0) { - *lenp = (size_t)(p - start + 1); - return start; + switch (v->t) { + case MCP_NULL: + return sp_buf_puts(b, "null"); + case MCP_BOOL: + return sp_buf_puts(b, v->b ? "true" : "false"); + case MCP_NUM: + if (v->n == (double)(long long)v->n && + v->n > -9007199254740992.0 && v->n < 9007199254740992.0) + return sp_buf_printf(b, "%lld", (long long)v->n); + return sp_buf_printf(b, "%.17g", v->n); + case MCP_STR: { + const unsigned char *p = (const unsigned char *) + (v->s != NULL ? v->s : ""); + + if (sp_buf_puts(b, "\"") != 0) + return -1; + for (; *p != '\0'; p++) { + int rc; + + if (*p == '"' || *p == '\\') + rc = sp_buf_printf(b, "\\%c", *p); + else if (*p == '\n') + rc = sp_buf_puts(b, "\\n"); + else if (*p == '\r') + rc = sp_buf_puts(b, "\\r"); + else if (*p == '\t') + rc = sp_buf_puts(b, "\\t"); + else if (*p < 0x20) + rc = sp_buf_printf(b, "\\u%04x", *p); + else + rc = sp_buf_add(b, (const char *)p, 1); + if (rc != 0) + return -1; } + return sp_buf_puts(b, "\""); } - return NULL; + case MCP_ARR: + if (sp_buf_puts(b, "[") != 0) + return -1; + for (i = 0; i < v->count; i++) + if ((i > 0 && sp_buf_puts(b, ",") != 0) || + json_print(b, v->items[i]) != 0) + return -1; + return sp_buf_puts(b, "]"); + case MCP_OBJ: + if (sp_buf_puts(b, "{") != 0) + return -1; + for (i = 0; i < v->count; i++) { + mcp_json key; + + memset(&key, 0, sizeof(key)); + key.t = MCP_STR; + key.s = v->keys[i]; + if ((i > 0 && sp_buf_puts(b, ",") != 0) || + json_print(b, &key) != 0 || + sp_buf_puts(b, ":") != 0 || + json_print(b, v->items[i]) != 0) + return -1; + } + return sp_buf_puts(b, "}"); + } + return -1; } /* ---- stdio transport ---- */ @@ -499,7 +536,7 @@ rpc_locked(size_t which, const char *method, const char *params, struct sp_buf line; char *raw; - if (s->dead) { + if (s->dead || (!s->http && (s->to == NULL || s->from <= 0))) { sp_buf_puts(err, "mcp: server not connected (reconnecting)"); return NULL; } @@ -560,7 +597,8 @@ notify(struct server *s, const char *method) if (s->http) { struct sp_buf err; char body[600], hdr[600], data[640]; - const char *args[20], *hdrs[3]; + const char *args[24], *hdrs[3]; + char sess[200]; struct sp_buf req; pid_t pid; int fd, n = 0; @@ -586,6 +624,11 @@ notify(struct server *s, const char *method) args[n++] = HTTP_TIMEOUT_S; args[n++] = "-X"; args[n++] = "POST"; + args[n++] = "-H"; + args[n++] = "Content-Type: application/json"; + args[n++] = "-H"; + args[n++] = "Accept: application/json, " + "text/event-stream"; args[n++] = "--data-binary"; args[n++] = data; args[n++] = "-D"; @@ -594,6 +637,13 @@ notify(struct server *s, const char *method) n = 0; if (s->header[0] != '\0') hdrs[n++] = s->header; + /* the session initialize handed out */ + if (s->session[0] != '\0') { + snprintf(sess, sizeof(sess), + "Mcp-Session-Id: %s", + s->session); + hdrs[n++] = sess; + } hdrs[n] = NULL; fd = stopping ? -1 : sp_curl_start(args, s->url, hdrs, @@ -614,6 +664,8 @@ notify(struct server *s, const char *method) sp_buf_free(&err); return; } + if (s->to == NULL) + return; fprintf(s->to, "{\"jsonrpc\":\"2.0\",\"method\":\"%s\"}\n", method); fflush(s->to); } @@ -631,13 +683,23 @@ spawn(struct server *s, struct sp_buf *err) sp_buf_puts(err, "mcp: a stdio server needs a cmd"); return -1; } - if (pipe(to) != 0 || pipe(from) != 0) { + if (pipe(to) != 0) { sp_buf_printf(err, "mcp: pipe: %s", strerror(errno)); return -1; } + if (pipe(from) != 0) { + sp_buf_printf(err, "mcp: pipe: %s", strerror(errno)); + close(to[0]); + close(to[1]); + return -1; + } child = fork(); if (child < 0) { sp_buf_printf(err, "mcp: fork: %s", strerror(errno)); + close(to[0]); + close(to[1]); + close(from[0]); + close(from[1]); return -1; } if (child == 0) { @@ -655,6 +717,8 @@ spawn(struct server *s, struct sp_buf *err) s->pid = child; s->to = fdopen(to[1], "w"); s->from = from[0]; + if (s->to == NULL) + close(to[1]); /* teardown() closes the rest */ if (s->to == NULL || sp_buf_init(&s->in) != 0) { sp_buf_puts(err, "mcp: fdopen failed"); return -1; @@ -674,8 +738,18 @@ call_tool(const char *args, struct sp_buf *out, void *ctx) if (sp_buf_init(¶ms) != 0 || sp_buf_init(&err) != 0) return -1; - sp_buf_printf(¶ms, "{\"name\":\"%s\",\"arguments\":%s}", tool->name, - args != NULL && args[0] == '{' ? args : "{}"); + { + mcp_json nm; + + /* the name came from the server: printed back escaped */ + memset(&nm, 0, sizeof(nm)); + nm.t = MCP_STR; + nm.s = (char *)tool->name; + sp_buf_puts(¶ms, "{\"name\":"); + (void)json_print(¶ms, &nm); + sp_buf_printf(¶ms, ",\"arguments\":%s}", + args != NULL && args[0] == '{' ? args : "{}"); + } reply = rpc(tool->srv, "tools/call", params.p, &err); sp_buf_free(¶ms); if (reply == NULL) { @@ -695,15 +769,30 @@ call_tool(const char *args, struct sp_buf *out, void *ctx) return 0; } { - const mcp_json *res = mcp_arg(v, "result"); - const mcp_json *content = res != NULL ? mcp_arg(res, "content") : NULL; - const mcp_json *first = content != NULL ? mcp_array_at(content, 0) : NULL; - const char *text = first != NULL ? - mcp_arg_string(first, "text") : NULL; + const mcp_json *res = mcp_arg(v, "result"); + const mcp_json *content = res != NULL ? + mcp_arg(res, "content") : NULL; + size_t i, ntext = 0; + int is_error = res != NULL && + mcp_arg_bool(res, "isError", 0); - if (text != NULL) - sp_buf_printf(out, "%s", text); - else + /* + * Every text part, not only the first; a tool that failed says + * so in isError, and the observation has to say it too. + */ + if (is_error) + sp_buf_puts(out, "error: "); + for (i = 0; content != NULL && i < mcp_array_len(content); i++) { + const mcp_json *part = mcp_array_at(content, i); + const char *text = part != NULL ? + mcp_arg_string(part, "text") : NULL; + + if (text == NULL) + continue; + sp_buf_printf(out, "%s%s", ntext > 0 ? "\n" : "", text); + ntext++; + } + if (ntext == 0) sp_buf_printf(out, "%s", reply); } mcp_json_free(v); @@ -717,7 +806,6 @@ static int register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err) { char *reply; - const char *schema_at; mcp_json*v; const mcp_json *result, *tools; size_t i; @@ -739,13 +827,10 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err) return 0; } - /* the schemas, in array order, from the raw text */ - schema_at = reply; for (i = 0; ; i++) { const mcp_json *t = mcp_array_at(tools, i); + const mcp_json *schema; const char *name, *desc; - const char *slice; - size_t len = 0; struct toolref *ref; struct sp_tool tool; size_t nlen; @@ -756,11 +841,10 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err) desc = mcp_arg_string(t, "description"); if (name == NULL) continue; - slice = strstr(schema_at, "inputSchema"); - if (slice != NULL) - slice = slice_object(slice, &len); - if (slice != NULL) - schema_at = slice; + /* this tool's own schema, from its own entry */ + schema = mcp_arg(t, "inputSchema"); + if (schema != NULL && schema->t != MCP_OBJ) + schema = NULL; /* the tool's own name, plus "mcp_" and, with several servers, its id */ nlen = strlen(name) + 8 + (prefix ? strlen(s->id) + 1 : 0); @@ -768,10 +852,8 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err) if (ref == NULL) continue; ref->srv = which; - if (prefix) - snprintf(ref->name, nlen, "%s_%s", s->id, name); - else - snprintf(ref->name, nlen, "%s", name); + /* the server knows the tool by its own name, never the prefix */ + snprintf(ref->name, nlen, "%s", name); memset(&tool, 0, sizeof(tool)); { @@ -781,7 +863,11 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err) free(ref); continue; } - snprintf(toolname, nlen + 4, "mcp_%s", ref->name); + if (prefix) + snprintf(toolname, nlen + 4, "mcp_%s_%s", s->id, + name); + else + snprintf(toolname, nlen + 4, "mcp_%s", name); tool.name = toolname; } /* @@ -796,13 +882,14 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err) free(ref); continue; } - if (slice != NULL) { - char *copy = malloc(len + 1); + if (schema != NULL) { + struct sp_buf sb; - if (copy != NULL) { - memcpy(copy, slice, len); - copy[len] = '\0'; - tool.params = copy; + if (sp_buf_init(&sb) == 0) { + if (json_print(&sb, schema) == 0 && sb.p != NULL) + tool.params = sb.p; /* kept, like the copy */ + else + sp_buf_free(&sb); } } if (tool.params == NULL) @@ -878,7 +965,10 @@ handshake(size_t which, struct sp_buf *err) return -1; free(reply); /* the handshake is not finished until the server is told so */ - notify(&sv[which], "notifications/initialized"); + pthread_mutex_lock(&sv[which].lock); + if (!sv[which].dead) + notify(&sv[which], "notifications/initialized"); + pthread_mutex_unlock(&sv[which].lock); return 0; } @@ -901,6 +991,8 @@ teardown(struct server *s) } s->session[0] = '\0'; s->up = 0; + /* until connect_server() has new pipes, a call fails cleanly */ + s->dead = 1; } /* Everything one connect attempt needs: start, handshake, tools (once). */ @@ -909,9 +1001,14 @@ connect_server(size_t i, struct sp_buf *err) { struct server *s = &sv[i]; - s->dead = 0; - if (!s->http && spawn(s, err) != 0) + /* a tool call may be in rpc() now: the pipes change under the lock */ + pthread_mutex_lock(&s->lock); + if (!s->http && spawn(s, err) != 0) { + pthread_mutex_unlock(&s->lock); return -1; + } + s->dead = 0; + pthread_mutex_unlock(&s->lock); if (handshake(i, err) != 0) return -1; if (!s->registered) { @@ -990,6 +1087,7 @@ server_thread(void *arg) ever_up = 1; failed_said = 0; } else { + pthread_mutex_lock(&s->lock); teardown(s); pthread_mutex_unlock(&s->lock); if (!failed_said) { diff --git a/plugins/processes/processes.c b/plugins/processes/processes.c index e8f6672..1e79917 100644 --- a/plugins/processes/processes.c +++ b/plugins/processes/processes.c @@ -235,6 +235,8 @@ find(int id) { int i; + if (id <= 0) + return NULL; /* 0 marks a released slot */ for (i = 0; i < ntasks; i++) if (tasks[i].id == id) return &tasks[i]; @@ -269,6 +271,44 @@ arg_str(const char *args, const char *key, char *buf, size_t len) static struct sp_host *host_ref; +/* + * A slot for a new task, under tasks_lock. The table is small, but a session + * starts more than sixteen tasks: once it is full, the finished task that ended + * first gives its slot (and its output) up. Finished tasks stay listed until + * then. NULL only when every slot is still running. + */ +static struct task * +slot_alloc(void) +{ + struct task *t = NULL; + int i; + + if (ntasks < TASKS_MAX) + return &tasks[ntasks++]; + for (i = 0; i < ntasks; i++) { + if (tasks[i].running) + continue; + if (t == NULL || tasks[i].ended < t->ended || + (tasks[i].ended == t->ended && tasks[i].id < t->id)) + t = &tasks[i]; + } + if (t == NULL) + return NULL; + /* its thread is gone: process_finish() was its last touch */ + sp_buf_free(&t->out); + (void)pthread_mutex_destroy(&t->lock); + return t; +} + +/* a slot that never became a task: invisible, and the first to be reused */ +static void +slot_release(struct task *t) +{ + t->id = 0; + t->running = 0; + t->ended = 0; +} + /* * Tasks someone else owns - a delegate on another host. They get an entry and a * clock, but no thread here: the harness closes them when the call returns. @@ -281,11 +321,10 @@ ops_begin(struct sp_host *h, const char *label, const char *detail) (void)detail; pthread_mutex_lock(&tasks_lock); - if (ntasks == TASKS_MAX) { + if ((t = slot_alloc()) == NULL) { pthread_mutex_unlock(&tasks_lock); return -1; } - t = &tasks[ntasks++]; memset(t, 0, sizeof(*t)); (void)pthread_mutex_init(&t->lock, NULL); t->id = next_id++; @@ -346,11 +385,10 @@ tool_process_start(const char *args, struct sp_buf *out, void *ctx) max_parallel); pthread_mutex_lock(&tasks_lock); - if (ntasks == TASKS_MAX) { + if ((t = slot_alloc()) == NULL) { pthread_mutex_unlock(&tasks_lock); return sp_buf_puts(out, "error: task table full"); } - t = &tasks[ntasks++]; memset(t, 0, sizeof(*t)); t->id = next_id++; (void)pthread_mutex_init(&t->lock, NULL); @@ -359,14 +397,14 @@ tool_process_start(const char *args, struct sp_buf *out, void *ctx) t->started = time(NULL); t->running = 1; if (sp_buf_init(&t->out) != 0) { - ntasks--; + slot_release(t); pthread_mutex_unlock(&tasks_lock); return sp_buf_puts(out, "error: no memory"); } id = t->id; if (pthread_create(&t->th, NULL, process_run, t) != 0) { - t->running = 0; - ntasks--; + sp_buf_free(&t->out); + slot_release(t); pthread_mutex_unlock(&tasks_lock); return sp_buf_puts(out, "error: cannot start thread"); } @@ -392,6 +430,8 @@ tool_process_list(const char *args, struct sp_buf *out, void *ctx) for (i = 0; i < ntasks; i++) { struct task *t = &tasks[i]; + if (t->id == 0) + continue; /* released slot */ any = 1; if (t->running) sp_buf_printf(out, "#%d running %lds %zu B %s\n", t->id, diff --git a/plugins/self/self.c b/plugins/self/self.c index 432ee39..136f8ed 100644 --- a/plugins/self/self.c +++ b/plugins/self/self.c @@ -198,53 +198,82 @@ human_bytes(unsigned long b, char *buf, size_t cap) snprintf(buf, cap, "%lu B", b); } +static int +kid_cmp(const void *a, const void *b) +{ + const struct kid *x = a, *y = b; + + return (x->pid > y->pid) - (x->pid < y->pid); +} + /* - * Who is under this process: one read of every /proc//stat, then include - * anything whose parent is already included until nothing changes. The tree is - * a few levels deep, so a handful of passes is enough. + * Who is under this process: one read of every /proc//stat - all of them, + * a busy machine has thousands and stopping at a fixed count missed our own + * pid - then include anything whose parent is already included until nothing + * changes. Sorted by pid, a parent is a binary search away. */ static void scan_kids(struct sample *s) { DIR *d; - struct kid v[SELF_KIDS_MAX]; - unsigned char in[SELF_KIDS_MAX]; - size_t n = 0, i, pass; - int self = (int)getpid(); + struct kid *v = NULL; + unsigned char *in = NULL; + size_t *parent = NULL; + size_t n = 0, cap = 0, i; + int self = (int)getpid(); d = opendir("/proc"); if (d != NULL) { struct dirent *e; - while ((e = readdir(d)) != NULL && n < SELF_KIDS_MAX) { + while ((e = readdir(d)) != NULL) { char *end; long pid = strtol(e->d_name, &end, 10); if (*end != '\0' || pid <= 0) continue; + if (n == cap) { + size_t ncap = cap ? cap * 2 : 512; + struct kid *nv = realloc(v, ncap * sizeof(*nv)); + + if (nv == NULL) + break; + v = nv; + cap = ncap; + } memset(&v[n], 0, sizeof(v[n])); if (read_stat((int)pid, &v[n]) != 0) continue; - in[n] = pid == self; n++; } closedir(d); } - for (pass = 0; pass < 8; pass++) { + if (n > 0) { + in = calloc(n, sizeof(*in)); + parent = calloc(n, sizeof(*parent)); + if (in == NULL || parent == NULL) + n = 0; + } + if (n > 0) { + qsort(v, n, sizeof(*v), kid_cmp); + for (i = 0; i < n; i++) { + struct kid key, *pp; + + key.pid = v[i].ppid; + pp = bsearch(&key, v, n, sizeof(*v), kid_cmp); + parent[i] = pp != NULL ? (size_t)(pp - v) : n; + in[i] = v[i].pid == self; + } + } + /* each pass adds at least one more generation, so this ends */ + for (;;) { int changed = 0; - for (i = 0; i < n; i++) { - size_t j; - - if (in[i]) - continue; - for (j = 0; j < n; j++) - if (in[j] && v[j].pid == v[i].ppid) { - in[i] = 1; - changed = 1; - break; - } - } + for (i = 0; i < n; i++) + if (!in[i] && parent[i] < n && in[parent[i]]) { + in[i] = 1; + changed = 1; + } if (!changed) break; } @@ -280,6 +309,9 @@ scan_kids(struct sample *s) prev_kids[prev_nkids].ticks = v[i].ticks; prev_nkids++; } + free(v); + free(in); + free(parent); } static void diff --git a/plugins/status/status.c b/plugins/status/status.c index 5065220..5cf9af9 100644 --- a/plugins/status/status.c +++ b/plugins/status/status.c @@ -20,7 +20,8 @@ * * SPLINTER_PRICE_IN=3.0 dollars per million input tokens * SPLINTER_PRICE_OUT=15.0 dollars per million output tokens - * SPLINTER_PRICE_CACHED=0.3 + * SPLINTER_PRICE_CACHED=0.3 per million input tokens served from the + * provider's cache (default: the input price) * * Without them the cost segment says nothing rather than inventing a number. */ @@ -35,6 +36,7 @@ #define BAR_WIDTH 24 static double price_in, price_out, price_cached; +static int have_cached; /* SPLINTER_PRICE_CACHED was set */ static void human(size_t n, char *buf, size_t len) @@ -138,9 +140,20 @@ render_cost(struct sp_host *h, char *buf, size_t len) buf[0] = '\0'; return; } - snprintf(buf, len, "$%.4f", - (double)m->tok_in * price_in / 1e6 + - (double)m->tok_out * price_out / 1e6); + /* + * Cached input tokens are part of tok_in and billed at their own + * price; without one they cost what any input token does. + */ + { + size_t cached = m->cached_total <= m->tok_in ? + m->cached_total : m->tok_in; + double pc = have_cached ? price_cached : price_in; + + snprintf(buf, len, "$%.4f", + (double)(m->tok_in - cached) * price_in / 1e6 + + (double)cached * pc / 1e6 + + (double)m->tok_out * price_out / 1e6); + } } static void @@ -193,9 +206,10 @@ status_init(struct sp_host *h) price_in = strtod(in, NULL); if (out != NULL && *out != '\0') price_out = strtod(out, NULL); - if (cached != NULL && *cached != '\0') + if (cached != NULL && *cached != '\0') { price_cached = strtod(cached, NULL); - (void)price_cached; + have_cached = 1; + } (void)sp_host_add_status(h, &seg_clock); (void)sp_host_add_status(h, &seg_ctx); diff --git a/share/locale/de.msg b/share/locale/de.msg index 3ef4708..4ea4c26 100644 --- a/share/locale/de.msg +++ b/share/locale/de.msg @@ -111,6 +111,7 @@ openai.transfer_failed = openai: Uebertragung fehlgeschlagen fuer %s openai.unparseable = openai: Antwort nicht lesbar (kein Status) openai.stream_failed = openai: Stream fehlgeschlagen fuer %s: %.300s openai.no_sse = openai: Endpoint sendete keine SSE-Daten: %.300s +openai.http_status = openai: HTTP %ld von %s: %.300s openai.stream_no_answer = openai: Stream endete ohne Antwort: %.300s # delegate @@ -126,7 +127,6 @@ tg.cmd.tasks = Plandateien zeigen tg.help = Ich bin splinter. Schreib eine Nachricht fuer einen Turn. /goal setzt das Ziel und startet einen Recap-Turn, /tasks zeigt den Plan. Aenderungen fragen hier mit Ja/Nein oder ok / no . ack.yes = Ja ack.no = Nein -ack.how = Antwort: Knopf unten oder ok %d / no %d tg.cmd.interview = Profil im Chat anlegen tg.interview.start = Erstes Gespraech fuer '%s'. Ich stelle %zu Fragen; /skip ueberspringt eine, /cancel bricht ab. @@ -179,7 +179,7 @@ model.pending = Modellwechsel auf %s nach der laufenden Anfrage ui.cancelling = breche ab ... (Ctrl-C nochmal beendet) model.failed = Umschalten fehlgeschlagen: %s model.switched = Modell: %s (Provider %s, diese Sitzung). -model.no_key = " (kein %s gesetzt)" +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 @@ -263,3 +263,12 @@ status.swarm_value = %s (Id %d) interview.system = Du bist splinter und arbeitest zum ersten Mal mit dieser Person. Interview sie, um sie kennenzulernen: woran sie arbeitet, welche Werkzeuge und Sprachen sie nutzt, wie sie angesprochen werden will, was sie nie will und welche Projekte zaehlen. Stelle eine Frage auf einmal, hoere zu und gehe nach, wo es wichtig ist. Frage nicht nach Codedetails, die du im Repository lesen kannst. Wenn du genug hast, schreibe eine kompakte Zusammenfassung der Person und ihrer Arbeitsweise (ein paar Absaetze oder Punkte) und beende deine Antwort mit der einen Zeile INTERVIEW_COMPLETE. Diese Zusammenfassung wird in ~/.splinter/USER.txt gespeichert und am Anfang jeder spaeteren Sitzung gelesen. interview.saved = Interview in USER.txt gespeichert tg.interview.begin = Interview gestartet. Beantworte die Fragen des Modells; /new beendet das Interview. + +# Kommandos in commands/, fehlendes Profil, die beiden Besetzt-Hinweise +cmd.script.empty = Das Kommando /%s hat nichts ausgegeben. +cmd.script.failed = /%s ist fehlgeschlagen: %s +cmd.script.output = Ausgabe von /%s%s%s: +main.no_profile = splinter: kein Profil fuer '%s' - `splinter --interview` legt eines an +tg.busy = besetzt - ein Turn laeuft +tg.interview.running = das Interview laeuft bereits +ui.agent_busy = ein Turn laeuft; wechsle den Agenten, wenn er fertig ist diff --git a/share/locale/en.msg b/share/locale/en.msg index 2405f0f..9558588 100644 --- a/share/locale/en.msg +++ b/share/locale/en.msg @@ -110,6 +110,7 @@ openai.transfer_failed = openai: transfer failed for %s openai.unparseable = openai: unparseable response (no status) openai.stream_failed = openai: stream failed for %s: %.300s openai.no_sse = openai: endpoint sent no SSE data: %.300s +openai.http_status = openai: HTTP %ld from %s: %.300s openai.stream_no_answer = openai: stream ended with no answer: %.300s # delegate @@ -125,7 +126,6 @@ tg.cmd.tasks = Show the plan tg.help = I am splinter. Send a message for a turn. /goal sets the goal and starts a recap turn, /tasks shows the plan. Changes ask here with Yes/No or ok / no . ack.yes = Yes ack.no = No -ack.how = Answer: button below or ok %d / no %d tg.cmd.interview = create the profile in the chat tg.interview.start = First conversation for '%s'. I ask %zu questions; /skip skips one, /cancel stops. @@ -178,7 +178,7 @@ model.pending = model switch to %s after the current request ui.cancelling = cancelling ... (Ctrl-C again quits) model.failed = Could not switch: %s model.switched = Model: %s (provider %s, this session). -model.no_key = " (no %s set)" +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 @@ -262,3 +262,12 @@ status.swarm_value = %s (id %d) interview.system = You are splinter, about to work with this person for the first time. Interview them to get to know them: what they work on, the tools and languages they reach for, how they want to be spoken to, what they never want, and which projects matter. Ask one question at a time, listen, and go deeper where it matters. Do not ask about code details you can read from the repository. When you have enough, write a compact summary of the person and how they want to work (a few paragraphs or bullets), then end your answer with the single line INTERVIEW_COMPLETE. That summary is saved to ~/.splinter/USER.txt and read at the start of every later session. interview.saved = interview saved to USER.txt tg.interview.begin = Interview started. Answer the model's questions; /new leaves the interview. + +# commands/ programs, a missing profile, and the two busy notices +cmd.script.empty = The command /%s printed nothing. +cmd.script.failed = /%s failed: %s +cmd.script.output = Output of /%s%s%s: +main.no_profile = splinter: no profile for '%s' - `splinter --interview` creates one +tg.busy = busy - a turn is running +tg.interview.running = the interview is already running +ui.agent_busy = a turn is running; switch the agent when it is done diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg index 070fc67..d12b196 100644 --- a/share/locale/pt_BR.msg +++ b/share/locale/pt_BR.msg @@ -114,6 +114,7 @@ openai.transfer_failed = openai: falha na transferencia para %s openai.unparseable = openai: resposta ilegivel (sem status) openai.stream_failed = openai: stream falhou para %s: %.300s openai.no_sse = openai: endpoint nao enviou dados SSE: %.300s +openai.http_status = openai: HTTP %ld de %s: %.300s openai.stream_no_answer = openai: stream terminou sem resposta: %.300s # delegate @@ -129,7 +130,6 @@ tg.cmd.tasks = Mostrar o plano tg.help = Eu sou o splinter. Envie uma mensagem para um turno. /goal define a meta e inicia um turno de recap, /tasks mostra o plano. Mudancas perguntam aqui com Sim/Nao ou ok / no . ack.yes = Sim ack.no = Nao -ack.how = Resposta: botao abaixo ou ok %d / no %d tg.cmd.interview = criar o perfil no chat tg.interview.start = Primeira conversa para '%s'. Sao %zu perguntas; /skip pula uma, /cancel cancela. @@ -182,7 +182,7 @@ model.pending = troca de modelo para %s depois da requisicao atual ui.cancelling = cancelando ... (Ctrl-C de novo encerra) model.failed = Nao consegui trocar: %s model.switched = Modelo: %s (provedor %s, esta sessao). -model.no_key = " (%s nao definida)" +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 @@ -266,3 +266,12 @@ status.swarm_value = %s (id %d) interview.system = Voce e o splinter e vai trabalhar com esta pessoa pela primeira vez. Entreviste-a para conhece-la: no que trabalha, quais ferramentas e linguagens usa, como quer ser tratada, o que nunca quer e quais projetos importam. Faca uma pergunta por vez, escute e aprofunde onde importa. Nao pergunte detalhes de codigo que voce pode ler no repositorio. Quando tiver o suficiente, escreva um resumo compacto da pessoa e de como ela quer trabalhar (alguns paragrafos ou pontos) e termine sua resposta com a linha unica INTERVIEW_COMPLETE. Esse resumo e salvo em ~/.splinter/USER.txt e lido no inicio de cada sessao posterior. interview.saved = entrevista salva em USER.txt tg.interview.begin = Entrevista iniciada. Responda as perguntas do modelo; /new encerra a entrevista. + +# comandos em commands/, perfil ausente, os dois avisos de ocupado +cmd.script.empty = O comando /%s nao imprimiu nada. +cmd.script.failed = /%s falhou: %s +cmd.script.output = Saida de /%s%s%s: +main.no_profile = splinter: sem perfil para '%s' - `splinter --interview` cria um +tg.busy = ocupado - um turno esta em andamento +tg.interview.running = a entrevista ja esta em andamento +ui.agent_busy = um turno esta em andamento; troque de agente quando terminar diff --git a/src/backend/a2aserver.c b/src/backend/a2aserver.c index 2b3cd04..ba1bd47 100644 --- a/src/backend/a2aserver.c +++ b/src/backend/a2aserver.c @@ -226,49 +226,34 @@ read_request(int fd, char *hdr, size_t cap, struct sp_buf *body) return 0; } -/* the id member as it appeared: a string, a number, or null */ +/* + * The request's top-level id as JSON: a string (escaped), a number, or "" + * when there is none, which the replies write as null. + */ static void -json_id(const char *payload, char *out, size_t cap) +json_id(const mcp_json *req, char *out, size_t cap) { - const char *p; + const mcp_json *id = mcp_arg(req, "id"); + struct sp_buf b; out[0] = '\0'; - p = payload != NULL ? strstr(payload, "\"id\"") : NULL; - if (p == NULL) + if (id == NULL) return; - p = strchr(p + 4, ':'); - if (p == NULL) + if (id->t == MCP_NUM) { + if (id->n == (double)(long long)id->n) + snprintf(out, cap, "%lld", (long long)id->n); + else + snprintf(out, cap, "%.17g", id->n); return; - p++; - while (*p == ' ' || *p == '\t') - p++; - if (*p == '"') { - const char *start = p; - size_t n; - - p++; - while (*p != '\0' && *p != '"') { - if (*p == '\\' && p[1] != '\0') - p++; - p++; - } - if (*p == '"') - p++; - n = (size_t)(p - start); - if (n >= cap) - n = cap - 1; - memcpy(out, start, n); - out[n] = '\0'; - } else { - size_t n = 0; - - while (p[n] != '\0' && p[n] != ',' && p[n] != '}' && - !isspace((unsigned char)p[n]) && n + 1 < cap) { - out[n] = p[n]; - n++; - } - out[n] = '\0'; } + if (id->t != MCP_STR || id->s == NULL || sp_buf_init(&b) != 0) + return; + sp_buf_puts(&b, "\""); + sp_json_escape(&b, id->s); + sp_buf_puts(&b, "\""); + if (b.p != NULL && b.len < cap) + snprintf(out, cap, "%s", b.p); + sp_buf_free(&b); } static int url_host_allowed(const char *url); @@ -632,17 +617,29 @@ ctx_get(struct sp_agent *ag, const char *id, int create) } } +/* "":"","contextId":"", both escaped: they are the client's */ +static void +put_ids(struct sp_buf *b, const char *idkey, const char *task, const char *ctx) +{ + sp_buf_printf(b, "\"%s\":\"", idkey); + sp_json_escape(b, task); + sp_buf_puts(b, "\",\"contextId\":\""); + sp_json_escape(b, ctx); + sp_buf_puts(b, "\""); +} + static void task_obj(struct sp_buf *b, const struct a2a_task *t) { int completed = strcmp(t->state, "TASK_STATE_COMPLETED") == 0; - sp_buf_puts(b, "{\"id\":\""); - sp_buf_puts(b, t->id); - sp_buf_printf(b, "\",\"contextId\":\"%s\",\"status\":{\"state\":\"%s\"," - "\"message\":{\"messageId\":\"msg-%s\"," - "\"role\":\"ROLE_AGENT\",\"parts\":[{\"text\":\"", t->context, - t->state[0] != '\0' ? t->state : "TASK_STATE_COMPLETED", t->id); + sp_buf_puts(b, "{"); + put_ids(b, "id", t->id, t->context); + sp_buf_printf(b, ",\"status\":{\"state\":\"%s\"," + "\"message\":{\"messageId\":\"msg-", + t->state[0] != '\0' ? t->state : "TASK_STATE_COMPLETED"); + sp_json_escape(b, t->id); + sp_buf_puts(b, "\",\"role\":\"ROLE_AGENT\",\"parts\":[{\"text\":\""); sp_json_escape(b, t->answer.p); sp_buf_puts(b, "\"}]}}"); if (!completed) { @@ -650,7 +647,7 @@ task_obj(struct sp_buf *b, const struct a2a_task *t) return; } sp_buf_puts(b, ",\"artifacts\":[{\"artifactId\":\"a-"); - sp_buf_puts(b, t->id); + sp_json_escape(b, t->id); sp_buf_puts(b, "\",\"parts\":[{\"text\":\""); sp_json_escape(b, t->answer.p); sp_buf_puts(b, "\"}]}]}"); @@ -685,6 +682,14 @@ host_allowed(const char *url, const char *envname) return 0; p = strstr(url, "://"); host = p + 3; + /* + * userinfo (http://localhost:x@169.254.169.254/) would make the host + * read here differ from the one curl connects to: refuse it, and a + * backslash in the authority, which some parsers take for a '/'. + */ + n = strcspn(host, "/?#"); + if (memchr(host, '@', n) != NULL || memchr(host, '\\', n) != NULL) + return 0; if (*host == '[') { host++; end = strchr(host, ']'); @@ -735,7 +740,8 @@ fetch_url_text(const char *url, struct sp_buf *out) struct sp_buf raw, err; pid_t pid = -1; char chunk[4096], *nl; - size_t got; + ssize_t got; + size_t i; int fd, status = 0; long http; @@ -750,14 +756,14 @@ fetch_url_text(const char *url, struct sp_buf *out) fd = sp_curl_start(args, url, NULL, 1, &pid, &err); if (fd < 0) goto fail; - while ((got = read(fd, chunk, sizeof(chunk))) > 0) { - if (raw.len + got > (1u << 20)) { - close(fd); - (void)kill(pid, SIGKILL); - (void)waitpid(pid, NULL, 0); - goto fail; - } - if (sp_buf_add(&raw, chunk, got) != 0) { + for (;;) { + got = read(fd, chunk, sizeof(chunk)); + if (got < 0 && errno == EINTR) + continue; + if (got == 0) + break; + if (got < 0 || raw.len + (size_t)got > (1u << 20) || + sp_buf_add(&raw, chunk, (size_t)got) != 0) { close(fd); (void)kill(pid, SIGKILL); (void)waitpid(pid, NULL, 0); @@ -768,13 +774,21 @@ fetch_url_text(const char *url, struct sp_buf *out) if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) goto fail; - if (raw.len < 2 || (nl = strrchr(raw.p, '\n')) == NULL) + /* the body may hold NULs: find the status line by length, not strrchr */ + nl = NULL; + for (i = raw.len; i > 0; i--) + if (raw.p[i - 1] == '\n') { + nl = raw.p + i - 1; + break; + } + if (raw.len < 2 || nl == NULL) goto fail; http = strtol(nl + 1, NULL, 10); *nl = '\0'; if (http < 200 || http > 299) goto fail; - sp_buf_puts(out, raw.p); + if (sp_buf_add(out, raw.p, (size_t)(nl - raw.p)) != 0) + goto fail; sp_buf_free(&raw); sp_buf_free(&err); return 0; @@ -1061,9 +1075,14 @@ a2a_deny(void *ctx, const char *name, int auth, const char *args) return 0; /* streaming has nowhere to resume from */ } +/* + * A turn (text != NULL) or the resumption of a paused one (text == NULL, with + * 'decision'): both under the same copy of the configuration, so that a second + * approval inside a resumed task pauses again instead of asking the terminal. + */ static int -run_turn(struct sp_agent *ag, struct sp_conv *conv, const char *text, - int (*approve)(void *, const char *, int, const char *), +turn_with(struct sp_agent *ag, struct sp_conv *conv, const char *text, + int decision, int (*approve)(void *, const char *, int, const char *), struct sp_buf *answer, struct sp_buf *err) { struct sp_agent_config cfg; @@ -1083,24 +1102,30 @@ run_turn(struct sp_agent *ag, struct sp_conv *conv, const char *text, savedconv = ag->conv; ag->cfg = &cfg; ag->conv = conv; - rc = sp_agent_run(ag, text, answer, err); + if (text != NULL) + rc = sp_agent_run(ag, text, answer, err); + else + rc = sp_agent_resume(ag, decision, answer, err); ag->conv = savedconv; ag->cfg = savedcfg; return rc; } +static int +run_turn(struct sp_agent *ag, struct sp_conv *conv, const char *text, + int (*approve)(void *, const char *, int, const char *), + struct sp_buf *answer, struct sp_buf *err) +{ + return turn_with(ag, conv, text != NULL ? text : "", 0, approve, + answer, err); +} + static int resume_turn(struct sp_agent *ag, struct sp_conv *conv, int decision, struct sp_buf *answer, struct sp_buf *err) { - struct sp_conv *saved; - int rc; - - saved = ag->conv; - ag->conv = conv; - rc = sp_agent_resume(ag, decision, answer, err); - ag->conv = saved; - return rc; + g_ir_msg[0] = '\0'; /* the next pause writes its own */ + return turn_with(ag, conv, NULL, decision, a2a_approve, answer, err); } /* yes/ok/ja/sim -> 1, no/nein/nao -> 0, anything else -> -1 */ @@ -1175,8 +1200,9 @@ sse_task(struct sse_out *o, const char *state) if (sp_buf_init(&b) != 0) return; - sp_buf_printf(&b, "{\"task\":{\"id\":\"%s\",\"contextId\":\"%s\"," - "\"status\":{\"state\":\"%s\"}}}", o->task_id, o->context, state); + sp_buf_puts(&b, "{\"task\":{"); + put_ids(&b, "id", o->task_id, o->context); + sp_buf_printf(&b, ",\"status\":{\"state\":\"%s\"}}}", state); sse_write(o, b.p); sp_buf_free(&b); } @@ -1188,9 +1214,10 @@ sse_artifact(struct sse_out *o, const char *text) if (sp_buf_init(&b) != 0) return; - sp_buf_printf(&b, "{\"artifactUpdate\":{\"taskId\":\"%s\"," - "\"contextId\":\"%s\",\"artifact\":{\"artifactId\":\"answer\"," - "\"parts\":[{\"text\":\"", o->task_id, o->context); + sp_buf_puts(&b, "{\"artifactUpdate\":{"); + put_ids(&b, "taskId", o->task_id, o->context); + sp_buf_puts(&b, ",\"artifact\":{\"artifactId\":\"answer\"," + "\"parts\":[{\"text\":\""); sp_json_escape(&b, text); sp_buf_puts(&b, "\"}]},\"append\":true}}"); sse_write(o, b.p); @@ -1205,9 +1232,9 @@ sse_status(struct sse_out *o, const char *state) if (sp_buf_init(&b) != 0) return; - sp_buf_printf(&b, "{\"statusUpdate\":{\"taskId\":\"%s\"," - "\"contextId\":\"%s\",\"status\":{\"state\":\"%s\"}}}", - o->task_id, o->context, state); + sp_buf_puts(&b, "{\"statusUpdate\":{"); + put_ids(&b, "taskId", o->task_id, o->context); + sp_buf_printf(&b, ",\"status\":{\"state\":\"%s\"}}}", state); sse_write(o, b.p); sp_buf_free(&b); } @@ -1219,12 +1246,12 @@ sse_status_full(struct sse_out *o, const char *state, const char *message) if (sp_buf_init(&b) != 0) return; - sp_buf_printf(&b, "{\"statusUpdate\":{\"taskId\":\"%s\"," - "\"contextId\":\"%s\",\"status\":{\"state\":\"%s\"", - o->task_id, o->context, state); + sp_buf_puts(&b, "{\"statusUpdate\":{"); + put_ids(&b, "taskId", o->task_id, o->context); + sp_buf_printf(&b, ",\"status\":{\"state\":\"%s\"", state); if (message != NULL && *message != '\0') { sp_buf_puts(&b, ",\"message\":{\"messageId\":\"msg-"); - sp_buf_puts(&b, o->task_id); + sp_json_escape(&b, o->task_id); sp_buf_puts(&b, "\",\"role\":\"ROLE_AGENT\",\"parts\":" "[{\"text\":\""); sp_json_escape(&b, message); @@ -1348,6 +1375,9 @@ handle_stream(int fd, struct sp_agent *ag, const char *id, snprintf(ctxbuf, sizeof(ctxbuf), "ctx-%d-%u", (int)getpid(), ++g_ctx_seq); ctx = ctxbuf; + } else if (strlen(ctx) >= sizeof(o.context)) { + sse_error(&o, -32602, "contextId too long"); + goto out; } snprintf(o.context, sizeof(o.context), "%s", ctx); if (ag->cfg == NULL) { @@ -1413,8 +1443,8 @@ handle_rpc(int fd, struct sp_agent *ag, const char *payload) struct a2a_push push; int rc; - json_id(payload, id, sizeof(id)); v = mcp_parse(payload); + json_id(v, id, sizeof(id)); if (v == NULL) { rpc_error(fd, id, -32700, "parse error"); return; @@ -1500,6 +1530,7 @@ handle_rpc(int fd, struct sp_agent *ag, const char *payload) ag->pending_from = 0; g_ir_task[0] = '\0'; g_ir_context[0] = '\0'; + g_ir_msg[0] = '\0'; task_update(t, "TASK_STATE_FAILED", &err); rpc_error(fd, id, -32603, err.p != NULL && err.len > 0 ? err.p : @@ -1520,6 +1551,10 @@ handle_rpc(int fd, struct sp_agent *ag, const char *payload) snprintf(ctxbuf, sizeof(ctxbuf), "ctx-%d-%u", (int)getpid(), ++g_ctx_seq); ctx = ctxbuf; + } else if (strlen(ctx) >= sizeof(g_ctx[0].id)) { + /* stored cut short it would join another conversation */ + rpc_error(fd, id, -32602, "contextId too long"); + goto send_out; } cx = ctx_get(ag, ctx, 1); if (cx == NULL) { diff --git a/src/backend/agent.c b/src/backend/agent.c index 93ab14f..95379e9 100644 --- a/src/backend/agent.c +++ b/src/backend/agent.c @@ -261,7 +261,7 @@ run_one_call(struct sp_agent *a, const struct sp_toolcall *call, * no gate has an opinion do the normal rules apply. */ if (a->host != NULL) { - char reason[256]; + char reason[256] = ""; verdict = sp_host_gate(a->host, t->name, (int)t->auth, call->args, reason, sizeof(reason)); @@ -643,12 +643,70 @@ tool_args_valid(const struct sp_reply *r, size_t *bad) return 1; } +/* + * Every tool_call of an assistant message needs its tool result, or each + * later request is refused by the endpoint. A round that ends early (a + * failure between calls) answers the calls it did not get to with an error + * observation; when even that cannot be added, the round is taken back out + * of the conversation instead. 'mark' is the index of the assistant message; + * results are appended in call order, so those present answer the first + * calls. + */ +static void +close_round(struct sp_conv *conv, const struct sp_reply *r, size_t mark) +{ + struct sp_msg tm; + size_t i, answered = 0; + + if (conv == NULL || r == NULL || mark >= conv->n) + return; + for (i = mark + 1; i < conv->n; i++) + if (conv->v[i].role != NULL && + strcmp(conv->v[i].role, "tool") == 0) + answered++; + for (i = answered; i < r->ncalls; i++) { + memset(&tm, 0, sizeof(tm)); + tm.role = "tool"; + tm.name = r->calls[i].name; + tm.call_id = r->calls[i].id; + tm.content = "error: not run, the turn ended before this call"; + if (sp_conv_add(conv, &tm) != 0) + goto rollback; + } + return; +rollback: + while (conv->n > mark) { + struct sp_msg *m = &conv->v[--conv->n]; + + free(m->role); + free(m->name); + free(m->call_id); + free(m->content); + free(m->calls); + memset(m, 0, sizeof(*m)); + } +} + +/* the assistant message that opened the newest tool round, or conv->n */ +static size_t +round_mark(const struct sp_conv *conv) +{ + size_t i; + + for (i = conv->n; i > 0; i--) + if (conv->v[i - 1].role != NULL && + strcmp(conv->v[i - 1].role, "assistant") == 0 && + conv->v[i - 1].calls != NULL) + return i - 1; + return conv->n; +} + static int agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, struct sp_buf *answer, struct sp_buf *err) { struct sp_buf obs; - size_t step, i; + size_t step, i, mark; int rc = -1, limit_tries = 0, bad_tool_tries = 0; if (sp_buf_init(&obs) != 0) { @@ -664,12 +722,26 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, int r = run_one(a, conv, &a->pending.calls[i], 1, decision, &obs, err); - if (r != 0) { - if (r > 0) - sp_buf_puts(err, "agent: approval " - "needed again"); + if (r > 0) { + /* calls before i ran: never run them twice */ + a->pending_from = i; + sp_buf_puts(err, "agent: approval needed again"); goto out; } + if (r != 0) { + /* + * The round cannot be resumed cleanly: answer + * what is left and drop the pending turn, so a + * retry does not run executed calls again. + */ + close_round(conv, &a->pending, + round_mark(conv)); + sp_reply_free(&a->pending); + a->has_pending = 0; + a->pending_from = 0; + goto out; + } + a->pending_from = i + 1; } sp_reply_free(&a->pending); a->has_pending = 0; @@ -870,6 +942,7 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, goto out; } + mark = conv->n; { struct sp_msg am; @@ -900,6 +973,7 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, goto out; } if (r != 0) { + close_round(conv, &reply, mark); sp_reply_free(&reply); goto out; } diff --git a/src/backend/agents.c b/src/backend/agents.c index e544a86..72030f1 100644 --- a/src/backend/agents.c +++ b/src/backend/agents.c @@ -8,6 +8,7 @@ #include #include "agents.h" +#include "log.h" #define MAX_AGENTS 32 @@ -77,9 +78,103 @@ add_def(struct sp_agents *a, const struct sp_agent_def *d) return 0; } +/* is 'name' an entry of the comma list 'list'? */ +static int +in_list(const char *list, const char *name, size_t nlen) +{ + const char *p = list; + + while (*p != '\0') { + const char *e = strchr(p, ','); + size_t n = e != NULL ? (size_t)(e - p) : strlen(p); + + if (n == nlen && strncmp(p, name, n) == 0) + return 1; + if (e == NULL) + break; + p = e + 1; + } + return 0; +} + +/* + * A profile from a project directory comes with whatever repository was + * cloned, so it must not give itself more than the user agreed to: it never + * turns on autonomous mode, and when it replaces a profile (the built-in plan, + * or one of the user's) it keeps that profile's limits: tools no wider, allow + * only what was allowed before, deny everything denied before. + */ +static void +narrow_untrusted(const struct sp_agents *a, struct sp_agent_def *d) +{ + const struct sp_agent_def *o = NULL; + char allow[sizeof(d->allow)]; + const char *p; + size_t i, n = 0; + + if (d->autonomous > 0) { + sp_logf("agents", "%s: autonomous ignored in a project " + "profile; set it in ~/.splinter/agents or the config", + d->source); + d->autonomous = -1; + } + for (i = 0; i < a->n; i++) + if (strcmp(a->v[i].name, d->name) == 0) + o = &a->v[i]; + if (o == NULL) + return; + if (o->autonomous == 0) + d->autonomous = 0; + if (o->max_auth >= 0 && (d->max_auth < 0 || d->max_auth > o->max_auth)) { + sp_logf("agents", "%s: tools no wider than %s allows", + d->source, o->source); + d->max_auth = o->max_auth; + } + /* allow: only names the replaced profile allowed too */ + allow[0] = '\0'; + for (p = d->allow; *p != '\0'; ) { + const char *e = strchr(p, ','); + size_t len = e != NULL ? (size_t)(e - p) : strlen(p); + + if (len > 0 && in_list(o->allow, p, len) && + n + len + 2 < sizeof(allow)) { + if (n > 0) + allow[n++] = ','; + memcpy(allow + n, p, len); + n += len; + allow[n] = '\0'; + } + if (e == NULL) + break; + p = e + 1; + } + if (strcmp(allow, d->allow) != 0) + sp_logf("agents", "%s: allow narrowed to what %s allows", + d->source, o->source); + snprintf(d->allow, sizeof(d->allow), "%s", allow); + /* deny: the old list plus the new one */ + for (p = o->deny; *p != '\0'; ) { + const char *e = strchr(p, ','); + size_t len = e != NULL ? (size_t)(e - p) : strlen(p); + size_t dl = strlen(d->deny); + + if (len > 0 && !in_list(d->deny, p, len) && + dl + len + 2 < sizeof(d->deny)) { + if (dl > 0) + d->deny[dl++] = ','; + memcpy(d->deny + dl, p, len); + d->deny[dl + len] = '\0'; + } + if (e == NULL) + break; + p = e + 1; + } +} + /* one markdown file into a definition; 1 added, 0 skipped */ static int -read_file(struct sp_agents *a, const char *path, const char *name) +read_file(struct sp_agents *a, const char *path, const char *name, + int trusted) { FILE *f = fopen(path, "r"); char line[2048]; @@ -176,11 +271,13 @@ read_file(struct sp_agents *a, const char *path, const char *name) sp_buf_free(&body); if (d.prompt == NULL) return 0; + if (!trusted) + narrow_untrusted(a, &d); return add_def(a, &d) == 0; } static void -read_dir(struct sp_agents *a, const char *dir) +read_dir(struct sp_agents *a, const char *dir, int trusted) { DIR *dp = opendir(dir); struct dirent *e; @@ -213,7 +310,7 @@ read_dir(struct sp_agents *a, const char *dir) name[len] = '\0'; snprintf(path, sizeof(path), "%.700s/%.150s", dir, names[i]); free(names[i]); - (void)read_file(a, path, name); + (void)read_file(a, path, name, trusted); } } @@ -228,7 +325,8 @@ int sp_agents_load(struct sp_agents *a, const char *cwd, const char *home) { struct sp_agent_def b, p; - char dirs[10][700]; + char dirs[17][700]; + int trusted[17]; size_t nd = 0, i; char cur[700]; @@ -264,8 +362,13 @@ sp_agents_load(struct sp_agents *a, const char *cwd, const char *home) add_def(a, &b); add_def(a, &p); - /* the user's, then the project's from far to near: the nearest wins */ + /* + * The user's, then the project's from far to near: the nearest wins. + * Only what lives in the home directory is the user's own; the rest + * came with a checkout and is narrowed (narrow_untrusted). + */ if (home != NULL && *home != '\0') { + trusted[nd] = 1; snprintf(dirs[nd++], sizeof(dirs[0]), "%s/.splinter/agents", home); } if (cwd != NULL && *cwd != '\0') { @@ -285,15 +388,21 @@ sp_agents_load(struct sp_agents *a, const char *cwd, const char *home) *slash = '\0'; } } - for (k = nc; k > 0 && nd + 2 <= 10; k--) { + /* chain[0] is the nearest; 8 levels always fit, far first */ + for (k = nc; k > 0 && nd + 2 <= 17; k--) { + int t = home != NULL && *home != '\0' && + strcmp(chain[k - 1], home) == 0; + + trusted[nd] = t; snprintf(dirs[nd++], sizeof(dirs[0]), "%s/.agents", chain[k - 1]); + trusted[nd] = t; snprintf(dirs[nd++], sizeof(dirs[0]), "%s/.splinter/agents", chain[k - 1]); } } for (i = 0; i < nd; i++) { - read_dir(a, dirs[i]); + read_dir(a, dirs[i], trusted[i]); } /* build and plan stay first; the rest by name */ if (a->n > 2) diff --git a/src/backend/anthropic.c b/src/backend/anthropic.c index b59beaf..52a2570 100644 --- a/src/backend/anthropic.c +++ b/src/backend/anthropic.c @@ -106,6 +106,13 @@ json_emit(struct sp_buf *b, const mcp_json *v) return -1; } +/* the same, for the OpenAI shaping (openai.c), which has no emitter */ +int +sp_json_emit(struct sp_buf *b, const mcp_json *v) +{ + return json_emit(b, v); +} + /* the max output of one step; Anthropic requires the field */ static int max_tokens(void) @@ -635,6 +642,13 @@ struct sp_as_sse { struct as_call calls[AS_MAX_CALLS]; enum as_btype block[AS_MAX_BLOCKS]; size_t nblocks; + /* + * Block index -> call index + 1 (0: not a call). Calls follow text and + * thinking blocks, so the block index of the fifth call can be far + * beyond the fifth slot. + */ + size_t callof[AS_MAX_BLOCKS]; + size_t ncalls; long tokens_in; long tokens_out; long tokens_cached; @@ -810,28 +824,41 @@ sp_as_sse_line(struct sp_as_sse *s, const char *line, struct sp_buf *out, block = mcp_arg(v, "content_block"); bt = block != NULL ? mcp_arg_string(block, "type") : NULL; if (bt != NULL && strcmp(bt, "tool_use") == 0) { - if (index < 0 || index >= AS_MAX_CALLS) { + struct as_call *call; + size_t ci; + + if (index < 0 || index >= AS_MAX_BLOCKS || + (s->callof[index] == 0 && + s->ncalls >= AS_MAX_CALLS)) { sp_buf_puts(err, "anthropic sse: too many tool " "calls"); mcp_json_free(v); return -1; } + if (s->callof[index] == 0) + s->callof[index] = ++s->ncalls; + ci = s->callof[index] - 1; + call = &s->calls[ci]; block_set(s, index, AS_TOOL); - if (sp_buf_init(&s->calls[index].input) != 0) { + free(call->id); + free(call->name); + sp_buf_free(&call->input); + call->id = NULL; + call->name = NULL; + if (sp_buf_init(&call->input) != 0) { mcp_json_free(v); return -1; } - s->calls[index].id = strdup(mcp_arg_string(block, "id") != + call->id = strdup(mcp_arg_string(block, "id") != NULL ? mcp_arg_string(block, "id") : ""); - s->calls[index].name = strdup(mcp_arg_string(block, + call->name = strdup(mcp_arg_string(block, "name") != NULL ? mcp_arg_string(block, "name") : ""); - s->calls[index].saw = 1; - if (s->calls[index].id == NULL || - s->calls[index].name == NULL) { + call->saw = 1; + if (call->id == NULL || call->name == NULL) { mcp_json_free(v); return -1; } - if (sp_buf_puts(out, s->calls[index].name) != 0) { + if (sp_buf_puts(out, call->name) != 0) { mcp_json_free(v); return -1; } @@ -854,8 +881,10 @@ sp_as_sse_line(struct sp_as_sse *s, const char *line, struct sp_buf *out, } if (strcmp(dt, "input_json_delta") == 0) { txt = mcp_arg_string(delta, "partial_json"); - if (txt != NULL && index >= 0 && index < AS_MAX_CALLS && - sp_buf_puts(&s->calls[index].input, txt) != 0) { + if (txt != NULL && index >= 0 && + index < AS_MAX_BLOCKS && s->callof[index] != 0 && + sp_buf_puts(&s->calls[s->callof[index] - 1].input, + txt) != 0) { mcp_json_free(v); return -1; } diff --git a/src/backend/builtin.c b/src/backend/builtin.c index 36ecc9d..5128da1 100644 --- a/src/backend/builtin.c +++ b/src/backend/builtin.c @@ -334,11 +334,14 @@ struct lines { size_t n; }; +static void free_lines(struct lines *); + +/* On failure 'out' is left empty (v NULL, n 0): free_lines() stays safe. */ static int split_lines(const char *text, struct lines *out) { - char *copy, *p; - size_t cap = 16; + const char *p; + size_t cap = 16; out->v = malloc(cap * sizeof(*out->v)); out->n = 0; @@ -346,34 +349,33 @@ split_lines(const char *text, struct lines *out) return -1; if (text == NULL || *text == '\0') return 0; - copy = strdup(text); - if (copy == NULL) { - free(out->v); - return -1; - } - for (p = copy; *p != '\0'; ) { - char *nl = strchr(p, '\n'); + for (p = text; *p != '\0'; ) { + const char *nl = strchr(p, '\n'); + size_t len = nl != NULL ? (size_t)(nl - p) : strlen(p); + char *line; + if (out->n == cap) { char **bigger = realloc(out->v, cap * 2 * sizeof(*bigger)); + if (bigger == NULL) { - free(copy); - free(out->v); + free_lines(out); return -1; } out->v = bigger; cap *= 2; } - out->v[out->n++] = strdup(p); - if (out->v[out->n - 1] == NULL) { - free(copy); + line = malloc(len + 1); + if (line == NULL) { + free_lines(out); return -1; } + memcpy(line, p, len); + line[len] = '\0'; + out->v[out->n++] = line; if (nl == NULL) break; - *strchr(out->v[out->n - 1], '\n') = '\0'; p = nl + 1; } - free(copy); return 0; } diff --git a/src/backend/cmdscript.c b/src/backend/cmdscript.c index e61dfe5..8739a9e 100644 --- a/src/backend/cmdscript.c +++ b/src/backend/cmdscript.c @@ -28,6 +28,7 @@ #include "splinter.h" #include "cmdscript.h" +#include "i18n.h" #define CMD_TIMEOUT_MS 300000 #define CMD_MAX_BYTES (4u << 20) @@ -194,7 +195,8 @@ sp_cmdscript_run(const char *dir, const char *name, const char *args, /* * The entry point UI and gateway share: run /name and hand back the text the * model should see, already framed so it cannot be mistaken for the user's own - * words. + * words. 0 with the text in 'out'; -1 when the program could not run (or ran + * out of time), with the reason in 'err' for the operator. */ int sp_slash_script(const char *dir, const char *name, const char *args, @@ -202,21 +204,31 @@ sp_slash_script(const char *dir, const char *name, const char *args, { struct sp_buf raw, errb; - (void)err; - if (sp_buf_init(&raw) != 0 || sp_buf_init(&errb) != 0) + if (sp_buf_init(&raw) != 0) return -1; + if (sp_buf_init(&errb) != 0) { + sp_buf_free(&raw); + return -1; + } if (sp_cmdscript_run(dir, name, args, &raw, &errb) != 0) { - sp_buf_printf(out, "error: %s", errb.p != NULL ? errb.p : "failed"); + if (err != NULL) + sp_buf_printf(err, sp_td("cmd.script.failed", + "/%s failed: %s"), name, + errb.p != NULL && errb.len > 0 ? errb.p : "?"); sp_buf_free(&raw); sp_buf_free(&errb); - return 0; + return -1; } if (raw.p == NULL || raw.p[0] == '\0') - sp_buf_printf(out, "Der Befehl /%s hat nichts ausgegeben.", name); - else - sp_buf_printf(out, "Ausgabe von /%s%s%s:\n\n%s", name, + sp_buf_printf(out, sp_td("cmd.script.empty", + "The command /%s printed nothing."), name); + else { + sp_buf_printf(out, sp_td("cmd.script.output", + "Output of /%s%s%s:"), name, args != NULL && *args != '\0' ? " " : "", - args != NULL ? args : "", raw.p); + args != NULL ? args : ""); + sp_buf_printf(out, "\n\n%s", raw.p); + } sp_buf_free(&raw); sp_buf_free(&errb); return 0; diff --git a/src/backend/confblock.c b/src/backend/confblock.c index 412d2fc..a2dbda7 100644 --- a/src/backend/confblock.c +++ b/src/backend/confblock.c @@ -281,6 +281,21 @@ clean(struct cb *c, const struct ent *e, const char *s) return 1; } +/* + * A core value becomes one "key = value" line: a newline in it would start a + * second line, a key the block never named. '|' is harmless there (no field + * line), so only line breaks are refused. + */ +static int +clean_line(struct cb *c, const struct ent *e, const char *s) +{ + if (strchr(s, '\n') != NULL || strchr(s, '\r') != NULL) { + fail(c, e->line, "%s must not contain a newline", e->key); + return 0; + } + return 1; +} + static int in_list(const char *const *list, const char *k) { @@ -300,19 +315,24 @@ do_core(struct cb *c, struct ent *e, size_t n) char list[2048]; if (!strcmp(k, "plugins") || !strcmp(k, "skills")) { - for (j = 0; j < e[i].v.n; j++) + for (j = 0; j < e[i].v.n; j++) { + if (!clean_line(c, &e[i], e[i].v.items[j])) + return; emit(c, e[i].line, "%s = %s", k[0] == 'p' ? "plugin" : "skills_dir", e[i].v.items[j]); + } continue; } if (e[i].v.list) { joined(&e[i].v, list, sizeof(list)); + if (!clean_line(c, &e[i], list)) + return; emit(c, e[i].line, "%s = %s", k, list); continue; } s = one(c, &e[i]); - if (s == NULL) + if (s == NULL || !clean_line(c, &e[i], s)) return; if (!strcmp(k, "autonomous") || !strcmp(k, "env_delegates")) emit(c, e[i].line, "%s = %d", k, boolean(s)); diff --git a/src/backend/conv.c b/src/backend/conv.c index 7ef576d..c1c8066 100644 --- a/src/backend/conv.c +++ b/src/backend/conv.c @@ -147,23 +147,3 @@ sp_conv_bytes(const struct sp_conv *c) } return total; } - -int -sp_conv_trim(struct sp_conv *c, size_t keep_last) -{ - size_t drop, i; - - if (c == NULL || keep_last >= c->n) - return 0; - drop = c->n - keep_last; - for (i = 0; i < drop; i++) { - free(c->v[i].role); - free(c->v[i].name); - free(c->v[i].call_id); - free(c->v[i].content); - free(c->v[i].calls); - } - memmove(c->v, c->v + drop, (c->n - drop) * sizeof(*c->v)); - c->n -= drop; - return 0; -} diff --git a/src/backend/delegate.c b/src/backend/delegate.c index c534129..00f7d54 100644 --- a/src/backend/delegate.c +++ b/src/backend/delegate.c @@ -1214,6 +1214,41 @@ parse_reset(const char *e) return t > now ? t : 0; } +/* + * A 429 that is an HTTP status, as the transports write it ("HTTP 429", + * "transport status 429", "Error: 429", "\"code\":429", "429 Too Many"), not + * any "429" in the text: a line number or a count in a child's output tail + * would bench a delegate for an hour. + */ +static int +has_status_429(const char *e) +{ + static const char *const before[] = { + "http ", "http/1.0 ", "http/1.1 ", "http/2 ", "http/2.0 ", + "status ", "status: ", "status=", "status\":", "status\": ", + "code ", "code: ", "code=", "code\":", "code\": ", + "error ", "error: ", NULL + }; + const char *p; + size_t i; + + for (p = strstr(e, "429"); p != NULL; p = strstr(p + 1, "429")) { + if ((p > e && isdigit((unsigned char)p[-1])) || + isdigit((unsigned char)p[3])) + continue; + if (strncasecmp(p + 3, " too many", 9) == 0) + return 1; + for (i = 0; before[i] != NULL; i++) { + size_t n = strlen(before[i]); + + if ((size_t)(p - e) >= n && + strncasecmp(p - n, before[i], n) == 0) + return 1; + } + } + return 0; +} + /* Is this error a limit, and until when? Returns 1 and sets *until. */ int sp_limit_parse(const char *e, long *until) @@ -1223,7 +1258,7 @@ sp_limit_parse(const char *e, long *until) *until = 0; if (e == NULL) return 0; - if (!(strstr(e, "429") != NULL || has_ci(e, "rate limit") || + if (!(has_status_429(e) || has_ci(e, "rate limit") || has_ci(e, "rate_limit") || has_ci(e, "usage limit") || has_ci(e, "weekly limit") || has_ci(e, "daily limit") || has_ci(e, "hit your limit") || has_ci(e, "limit reached") || diff --git a/src/backend/engine.c b/src/backend/engine.c index 19cd053..a491759 100644 --- a/src/backend/engine.c +++ b/src/backend/engine.c @@ -62,6 +62,14 @@ struct engine_cc { char key_env[80]; }; +/* one kind of turn, for /cost */ +struct engine_tally { + unsigned turns; + unsigned long ms; + size_t in, out; + double cost; +}; + struct sp_engine { /* what main handed over; conf is shared, not owned */ struct sp_config *conf; @@ -81,6 +89,14 @@ struct sp_engine { char pend_model[320]; int has_pend_model; pthread_mutex_t model_lock; + /* + * Held by whoever works on the agent outside the turn thread: a + * daemon's Telegram turn for its whole length, an MCP session tool for + * one call. Taken with trylock only; the loser answers "busy". + */ + pthread_mutex_t turn_mx; + int ext_busy; /* a foreign turn holds turn_mx */ + struct sp_engine *next_open; /* the list of open engines */ char theme[48]; char agent_name[48]; char home_id[64]; /* provider before a profile moved it */ @@ -127,12 +143,7 @@ struct sp_engine { size_t turn_out0; /* tokens_out when the turn began */ size_t turn_in0; /* tokens_in when the turn began */ double turn_cost0; /* cost when the turn began */ - struct { - unsigned turns; - unsigned long ms; - size_t in, out; - double cost; - } judged, plain; /* the two kinds, for /cost */ + struct engine_tally judged, plain; /* the two kinds, for /cost */ size_t last_turn_out; /* output tokens it produced */ struct timespec turn_t0; /* @@ -218,20 +229,51 @@ sp_engine_event_free(struct sp_event *ev) } static void snapshot_stats(struct sp_engine *); +static void open_add(struct sp_engine *); +static void open_del(struct sp_engine *); static int capture_interview(struct sp_engine *, struct sp_buf *); /* ------------------------------------------------------------- snapshot */ +/* + * cur_model/cur_endpoint change on the turn thread when a deferred /model is + * applied between requests, while the front end reads them. Writes and the + * front end's reads go through e->lock; never call these with it held. + */ +static void +cur_set(struct sp_engine *e, const char *model, const char *endpoint) +{ + pthread_mutex_lock(&e->lock); + if (model != NULL) + snprintf(e->cur_model, sizeof(e->cur_model), "%s", model); + if (endpoint != NULL) + snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), "%s", + endpoint); + pthread_mutex_unlock(&e->lock); +} + +static void +cur_get(struct sp_engine *e, char *model, size_t mcap, char *endpoint, + size_t ecap) +{ + pthread_mutex_lock(&e->lock); + if (model != NULL && mcap > 0) + snprintf(model, mcap, "%s", e->cur_model); + if (endpoint != NULL && ecap > 0) + snprintf(endpoint, ecap, "%s", e->cur_endpoint); + pthread_mutex_unlock(&e->lock); +} + int sp_engine_state(struct sp_engine *e, struct sp_engine_state *st) { if (e == NULL || st == NULL) return -1; memset(st, 0, sizeof(*st)); + cur_get(e, st->model, sizeof(st->model), st->endpoint, + sizeof(st->endpoint)); if (e->host != NULL) - sp_host_set_model(e->host, e->cur_model); - snprintf(st->model, sizeof(st->model), "%s", e->cur_model); - snprintf(st->endpoint, sizeof(st->endpoint), "%s", e->cur_endpoint); + sp_host_set_model(e->host, st->model); snprintf(st->agent, sizeof(st->agent), "%s", e->agent_name); snprintf(st->session, sizeof(st->session), "%s", e->sess.id); snprintf(st->dir, sizeof(st->dir), "%s", e->sess.dir); @@ -252,7 +294,7 @@ sp_engine_state(struct sp_engine *e, struct sp_engine_state *st) st->last_ms = e->last_ms; st->last_steps = e->last_steps; st->last_calls = e->last_calls; - st->busy = e->running; + st->busy = e->running || e->ext_busy; st->quit = e->quit; st->waiting = e->approve_pending; st->agents_n = (int)e->agents.n; @@ -304,9 +346,12 @@ sp_engine_state_dir(struct sp_engine *e) { return e->sess.dir; } size_t sp_engine_models(struct sp_engine *e, struct sp_model_choice *v, size_t max) { + char model[256]; + if (e == NULL) return 0; - return sp_provider_choices(e->conf, e->cur_model, v, max); + cur_get(e, model, sizeof(model), NULL, 0); + return sp_provider_choices(e->conf, model, v, max); } /* @@ -324,9 +369,12 @@ sp_engine_served_models(struct sp_engine *e, struct sp_model_choice *v, const char *act; char *m, *save = NULL; size_t i, n = 0, np; + char cmodel[256], cendpoint[512]; - if (e == NULL || e->conf == NULL || v == NULL || max == 0 || - e->cur_endpoint[0] == '\0') + if (e == NULL || e->conf == NULL || v == NULL || max == 0) + return 0; + cur_get(e, cmodel, sizeof(cmodel), cendpoint, sizeof(cendpoint)); + if (cendpoint[0] == '\0') return 0; memset(&p, 0, sizeof(p)); act = sp_usage_active(); @@ -338,7 +386,7 @@ sp_engine_served_models(struct sp_engine *e, struct sp_model_choice *v, continue; if ((act != NULL && *act != '\0' && strcmp(q.id, act) == 0) || - strcmp(q.endpoint, e->cur_endpoint) == 0) { + strcmp(q.endpoint, cendpoint) == 0) { p = q; break; } @@ -348,8 +396,8 @@ sp_engine_served_models(struct sp_engine *e, struct sp_model_choice *v, snprintf(p.id, sizeof(p.id), "%s", act != NULL && *act != '\0' ? act : "main"); snprintf(p.kind, sizeof(p.kind), "%s", e->conf->kind); - snprintf(p.endpoint, sizeof(p.endpoint), "%s", e->cur_endpoint); - snprintf(p.model, sizeof(p.model), "%s", e->cur_model); + snprintf(p.endpoint, sizeof(p.endpoint), "%s", cendpoint); + snprintf(p.model, sizeof(p.model), "%s", cmodel); snprintf(p.key_env, sizeof(p.key_env), "%s", e->conf->key_env); } if (p.endpoint[0] == '\0' || strcmp(p.kind, "cli") == 0) @@ -369,7 +417,7 @@ sp_engine_served_models(struct sp_engine *e, struct sp_model_choice *v, sp_provider_label(p.id), m); snprintf(v[n].label, sizeof(v[n].label), "%s/%s", sp_provider_label(p.id), m); - v[n].current = strcmp(m, e->cur_model) == 0; + v[n].current = strcmp(m, cmodel) == 0; n++; } } @@ -540,6 +588,22 @@ sp_engine_agent_name(struct sp_engine *e, int idx) * Kept in the engine, not in a front end: the transcript row, the approval * question and a GUI's call list must all name the same call the same way. */ +/* Append s, clamped: the result never points past the terminator. */ +static size_t +pretty_put(char *out, size_t cap, size_t n, const char *s) +{ + int w; + + if (n + 1 >= cap) + return n; + w = snprintf(out + n, cap - n, "%s", s); + if (w < 0) + return n; + if ((size_t)w >= cap - n) + return cap - 1; + return n + (size_t)w; +} + static void pretty_args(const char *json, char *out, size_t cap) { @@ -547,6 +611,8 @@ pretty_args(const char *json, char *out, size_t cap) size_t n = 0; int first = 1; + if (cap == 0) + return; out[0] = '\0'; while (*p == ' ') p++; @@ -572,9 +638,10 @@ pretty_args(const char *json, char *out, size_t cap) while (*p == ' ' || *p == ':') p++; if (!first) - n += (size_t)snprintf(out + n, cap - n, " "); + n = pretty_put(out, cap, n, " "); first = 0; - n += (size_t)snprintf(out + n, cap - n, "%s: ", key); + n = pretty_put(out, cap, n, key); + n = pretty_put(out, cap, n, ": "); if (*p == '"') { p++; while (*p != '\0' && *p != '"' && n + 4 < cap) { @@ -1083,15 +1150,55 @@ engine_compact(void *ctx, size_t before, size_t after, size_t mb, size_t ma) /* ----------------------------------------------------------------- turns */ +/* + * Book one run of the agent into the judged/plain totals. A leftover steer + * starts another run in the same worker and moves the baselines, so each run + * is booked when it ends, not once for the whole worker. Returns the run's + * output tokens. Called on the turn thread, which owns ag.stats. + */ +static size_t +account_run(struct sp_engine *e, const struct timespec *t0) +{ + struct timespec now; + unsigned long ms; + size_t tin, tout; + double c; + struct engine_tally *k; + + clock_gettime(CLOCK_MONOTONIC, &now); + ms = (unsigned long)((now.tv_sec - t0->tv_sec) * 1000 + + (now.tv_nsec - t0->tv_nsec) / 1000000); + pthread_mutex_lock(&e->lock); + tin = e->ag.stats.tokens_in >= e->turn_in0 ? + e->ag.stats.tokens_in - e->turn_in0 : 0; + tout = e->ag.stats.tokens_out >= e->turn_out0 ? + e->ag.stats.tokens_out - e->turn_out0 : 0; + c = e->ag.stats.cost >= e->turn_cost0 ? + e->ag.stats.cost - e->turn_cost0 : 0; + k = strstr(e->cur_model, "judged") != NULL ? &e->judged : &e->plain; + k->turns++; + k->ms += ms; + k->in += tin; + k->out += tout; + k->cost += c; + pthread_mutex_unlock(&e->lock); + return tout; +} + static void * turn_thread(void *arg) { struct sp_engine *e = arg; char *text = e->turn_text; + size_t steps0, calls0, out_sum = 0; + /* the sidebar's "last turn" is the whole worker, steers included */ + steps0 = e->ag.stats.steps; + calls0 = e->ag.stats.tool_calls; for (;;) { - int rc; - char *next = NULL; + int rc; + char *next = NULL; + struct timespec run_t0; e->ag.cfg = &e->turn_cfg; sp_openai_set_cancel(&e->cancel); @@ -1113,7 +1220,10 @@ turn_thread(void *arg) e->turn_in0 = e->ag.stats.tokens_in; e->turn_cost0 = e->ag.stats.cost; pthread_mutex_unlock(&e->lock); + clock_gettime(CLOCK_MONOTONIC, &run_t0); rc = sp_agent_run(&e->ag, text, &e->answer, &e->err); + /* booked on the model that ran, before a pending /model moves it */ + out_sum += account_run(e, &run_t0); if (e->have_swarm) swarm_report_busy(&e->swarm, 0); sp_openai_set_cancel(NULL); @@ -1205,32 +1315,11 @@ turn_thread(void *arg) (now.tv_nsec - e->turn_t0.tv_nsec) / 1000000); pthread_mutex_lock(&e->lock); e->last_ms = ms; - e->last_turn_out = e->ag.stats.tokens_out >= e->turn_out0 ? - e->ag.stats.tokens_out - e->turn_out0 : 0; - { - struct sp_engine *ce = e; - int is_judged = strstr(ce->cur_model, "judged") != NULL; - size_t tin = ce->ag.stats.tokens_in >= ce->turn_in0 ? - ce->ag.stats.tokens_in - ce->turn_in0 : 0; - double c = ce->ag.stats.cost >= ce->turn_cost0 ? - ce->ag.stats.cost - ce->turn_cost0 : 0; - - if (is_judged) { - ce->judged.turns++; - ce->judged.ms += (unsigned long)ms; - ce->judged.in += tin; - ce->judged.out += ce->last_turn_out; - ce->judged.cost += c; - } else { - ce->plain.turns++; - ce->plain.ms += (unsigned long)ms; - ce->plain.in += tin; - ce->plain.out += ce->last_turn_out; - ce->plain.cost += c; - } - } - e->last_steps = e->ag.stats.steps; - e->last_calls = e->ag.stats.tool_calls; + e->last_turn_out = out_sum; + e->last_steps = e->ag.stats.steps >= steps0 ? + e->ag.stats.steps - steps0 : 0; + e->last_calls = e->ag.stats.tool_calls >= calls0 ? + e->ag.stats.tool_calls - calls0 : 0; pthread_mutex_unlock(&e->lock); } /* @@ -1247,11 +1336,30 @@ turn_thread(void *arg) return NULL; } +static int engine_submit(struct sp_engine *, const char *); + +/* + * A turn starts only while nobody else works on the agent: turn_mx is held + * while the turn is marked running, so a foreign turn either sees it running + * or keeps it from starting. + */ int sp_engine_submit(struct sp_engine *e, const char *text) { + int rc; + if (e == NULL || text == NULL || *text == '\0') return -1; + if (pthread_mutex_trylock(&e->turn_mx) != 0) + return -1; + rc = engine_submit(e, text); + pthread_mutex_unlock(&e->turn_mx); + return rc; +} + +static int +engine_submit(struct sp_engine *e, const char *text) +{ pthread_mutex_lock(&e->lock); if (e->running) { pthread_mutex_unlock(&e->lock); @@ -1347,11 +1455,121 @@ sp_engine_busy(struct sp_engine *e) if (e == NULL) return 0; pthread_mutex_lock(&e->lock); - busy = e->running; + busy = e->running || e->ext_busy; pthread_mutex_unlock(&e->lock); return busy; } +/* ---------------------------------------------- turns outside the engine */ + +/* + * The open engines, so a caller that only has the agent (the Telegram loop) + * can find the engine that owns it. + */ +static pthread_mutex_t open_mx = PTHREAD_MUTEX_INITIALIZER; +static struct sp_engine *open_list; + +static void +open_add(struct sp_engine *e) +{ + pthread_mutex_lock(&open_mx); + e->next_open = open_list; + open_list = e; + pthread_mutex_unlock(&open_mx); +} + +static void +open_del(struct sp_engine *e) +{ + struct sp_engine **pp; + + pthread_mutex_lock(&open_mx); + for (pp = &open_list; *pp != NULL; pp = &(*pp)->next_open) + if (*pp == e) { + *pp = e->next_open; + break; + } + pthread_mutex_unlock(&open_mx); +} + +static struct sp_engine * +engine_of_agent(struct sp_agent *ag) +{ + struct sp_engine *e; + + pthread_mutex_lock(&open_mx); + for (e = open_list; e != NULL; e = e->next_open) + if (&e->ag == ag) + break; + pthread_mutex_unlock(&open_mx); + return e; +} + +int +sp_engine_hold(struct sp_engine *e) +{ + if (e == NULL) + return -1; + if (pthread_mutex_trylock(&e->turn_mx) != 0) + return -1; + pthread_mutex_lock(&e->lock); + if (e->running) { + pthread_mutex_unlock(&e->lock); + pthread_mutex_unlock(&e->turn_mx); + return -1; + } + pthread_mutex_unlock(&e->lock); + return 0; +} + +void +sp_engine_release(struct sp_engine *e) +{ + if (e != NULL) + pthread_mutex_unlock(&e->turn_mx); +} + +int +sp_engine_turn_begin(struct sp_engine *e) +{ + if (sp_engine_hold(e) != 0) + return -1; + pthread_mutex_lock(&e->lock); + e->ext_busy = 1; + pthread_mutex_unlock(&e->lock); + return 0; +} + +void +sp_engine_turn_end(struct sp_engine *e) +{ + if (e == NULL) + return; + pthread_mutex_lock(&e->lock); + e->ext_busy = 0; + pthread_mutex_unlock(&e->lock); + pthread_mutex_unlock(&e->turn_mx); +} + +int +sp_engine_agent_turn_begin(struct sp_agent *ag) +{ + struct sp_engine *e = engine_of_agent(ag); + + if (e == NULL) + return 0; /* not an engine's agent: nothing to share */ + return sp_engine_turn_begin(e); +} + +void +sp_engine_agent_turn_end(struct sp_agent *ag) +{ + struct sp_engine *e = engine_of_agent(ag); + + if (e != NULL) + sp_engine_turn_end(e); +} + int sp_engine_wait(struct sp_engine *e) { @@ -1523,11 +1741,8 @@ agent_switch(struct sp_engine *e, int idx, int announce) ch.model[0] != '\0' ? ch.model : ch.d->model, ch.d->key_env, &perr) == 0) { sp_usage_set_active(ch.d->id); - snprintf(e->cur_model, sizeof(e->cur_model), - "%s", ch.model[0] != '\0' ? ch.model : - ch.d->model); - snprintf(e->cur_endpoint, - sizeof(e->cur_endpoint), "%s", + cur_set(e, ch.model[0] != '\0' ? + ch.model : ch.d->model, ch.d->endpoint); } sp_buf_free(&perr); @@ -1551,6 +1766,14 @@ sp_engine_agent_switch(struct sp_engine *e, int idx) { if (e == NULL) return -1; + /* + * The profile swaps the agent's policy, prompt and transport, which + * the turn thread is using: Tab during a turn is refused, like /agent. + */ + if (sp_engine_busy(e)) { + ev_push(e, SP_EV_ENTRY, 0, "splinter", sp_t("ui.command_busy")); + return -1; + } return agent_switch(e, idx, 1); } @@ -1880,10 +2103,8 @@ cmd_model_apply(struct sp_engine *e, const char *args, struct sp_buf *out, perr.p != NULL ? perr.p : "?"); } else { sp_usage_set_active(ch.d->id); - snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), - "%s", ch.d->endpoint); - snprintf(e->cur_model, sizeof(e->cur_model), "%s", - ch.model[0] != '\0' ? ch.model : ch.d->model); + cur_set(e, ch.model[0] != '\0' ? ch.model : + ch.d->model, ch.d->endpoint); session_model_note(e, poolname, out, e->cur_model, sp_provider_label(ch.d->id)); @@ -1899,10 +2120,7 @@ cmd_model_apply(struct sp_engine *e, const char *args, struct sp_buf *out, } else if (sp_provider_at(e->conf, idx, &p) == 0) { char sel[320]; - snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), "%s", - p.endpoint); - snprintf(e->cur_model, sizeof(e->cur_model), "%s", - p.model); + cur_set(e, p.model, p.endpoint); snprintf(sel, sizeof(sel), "%s/%s", sp_provider_label(p.id), p.model); session_model_note(e, sel, out, p.model, @@ -1927,10 +2145,7 @@ cmd_model_apply(struct sp_engine *e, const char *args, struct sp_buf *out, perr.p != NULL ? perr.p : "?"); } else { sp_usage_set_active(ch.d->id); - snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), - "%s", ch.d->endpoint); - snprintf(e->cur_model, sizeof(e->cur_model), "%s", - model); + cur_set(e, model, ch.d->endpoint); snprintf(sel, sizeof(sel), "%s/%s", sp_provider_label(ch.d->id), model); session_model_note(e, sel, out, e->cur_model, @@ -1958,8 +2173,7 @@ cmd_model_apply(struct sp_engine *e, const char *args, struct sp_buf *out, ok = sp_provider_apply(&e->ag, p.kind, p.endpoint, args, p.key_env, &perr) == 0; if (ok) { - snprintf(e->cur_model, - sizeof(e->cur_model), "%s", args); + cur_set(e, args, NULL); snprintf(sel, sizeof(sel), "%s/%s", sp_provider_label(p.id), args); session_model_note(e, sel, out, args, @@ -2162,7 +2376,7 @@ cmd_status(struct sp_engine *e, struct sp_buf *out) size_t comp = 0, failed = 0; unsigned turns = 0; time_t now = time(NULL); - char tbuf[64]; + char tbuf[64], model[256], endpoint[512]; struct tm tm; (void)localtime_r(&now, &tm); @@ -2173,10 +2387,11 @@ cmd_status(struct sp_engine *e, struct sp_buf *out) sp_buf_puts(out, "\n"); sp_buf_printf(out, " %-8s %s\n", sp_t("status.session"), e->sess.id); sp_buf_printf(out, " %-8s %s\n", sp_t("status.dir"), e->sess.dir); + cur_get(e, model, sizeof(model), endpoint, sizeof(endpoint)); sp_buf_printf(out, " %-8s %s\n", sp_t("status.model"), - e->cur_model[0] != '\0' ? e->cur_model : "-"); + model[0] != '\0' ? model : "-"); sp_buf_printf(out, " %-8s %s\n", sp_t("status.endpoint"), - e->cur_endpoint[0] != '\0' ? e->cur_endpoint : "-"); + endpoint[0] != '\0' ? endpoint : "-"); sp_buf_printf(out, " %-8s %s\n", sp_t("status.theme"), e->theme); sp_buf_printf(out, " %-8s %s\n", sp_t("status.agent"), e->agent_name); sp_buf_printf(out, " %-8s ", sp_t("status.last")); @@ -2307,8 +2522,18 @@ cmd_agents(struct sp_engine *e, struct sp_buf *out) static void cmd_cost(struct sp_engine *e, struct sp_buf *out) { - struct sp_agent_stats st = e->snapshot; + struct sp_agent_stats st; unsigned cachepct = 0; + char model[256]; + struct engine_tally judged, plain; + + /* the turn thread updates all of these under the lock */ + pthread_mutex_lock(&e->lock); + st = e->snapshot; + judged = e->judged; + plain = e->plain; + snprintf(model, sizeof(model), "%s", e->cur_model); + pthread_mutex_unlock(&e->lock); if (st.last_in > 0 && st.last_cached > 0) cachepct = (unsigned)(100.0 * (double)st.last_cached / @@ -2317,37 +2542,37 @@ cmd_cost(struct sp_engine *e, struct sp_buf *out) "last ctx %u%% cached\n", st.cost, st.tokens_in, st.tokens_out, cachepct); sp_buf_printf(out, "average: $%.5f/turn, %zu ms/turn, %zu calls\n", - e->judged.turns + e->plain.turns > 0 ? - st.cost / (double)(e->judged.turns + e->plain.turns) : 0.0, - e->judged.turns + e->plain.turns > 0 ? - (e->judged.ms + e->plain.ms) / (e->judged.turns + e->plain.turns) : 0, + judged.turns + plain.turns > 0 ? + st.cost / (double)(judged.turns + plain.turns) : 0.0, + judged.turns + plain.turns > 0 ? + (judged.ms + plain.ms) / (judged.turns + plain.turns) : 0, st.tool_calls); - if (e->judged.turns > 0 || e->plain.turns > 0) { + if (judged.turns > 0 || plain.turns > 0) { sp_buf_printf(out, "judged: %u turns, %.0f ms/turn, " - "%.0f tok/turn, $%.5f/turn\n", e->judged.turns, - e->judged.turns ? (double)e->judged.ms / e->judged.turns : 0, - e->judged.turns ? (double)(e->judged.in + e->judged.out) / - e->judged.turns : 0, - e->judged.turns ? e->judged.cost / e->judged.turns : 0); + "%.0f tok/turn, $%.5f/turn\n", judged.turns, + judged.turns ? (double)judged.ms / judged.turns : 0, + judged.turns ? (double)(judged.in + judged.out) / + judged.turns : 0, + judged.turns ? judged.cost / judged.turns : 0); sp_buf_printf(out, "plain: %u turns, %.0f ms/turn, " - "%.0f tok/turn, $%.5f/turn\n", e->plain.turns, - e->plain.turns ? (double)e->plain.ms / e->plain.turns : 0, - e->plain.turns ? (double)(e->plain.in + e->plain.out) / - e->plain.turns : 0, - e->plain.turns ? e->plain.cost / e->plain.turns : 0); - if (e->judged.turns > 0 && e->plain.turns > 0) + "%.0f tok/turn, $%.5f/turn\n", plain.turns, + plain.turns ? (double)plain.ms / plain.turns : 0, + plain.turns ? (double)(plain.in + plain.out) / + plain.turns : 0, + plain.turns ? plain.cost / plain.turns : 0); + if (judged.turns > 0 && plain.turns > 0) sp_buf_printf(out, "delta: %+.0f ms, %+.0f tok, " "%+.5f $/turn (judged - plain)\n", - (double)e->judged.ms / e->judged.turns - - (double)e->plain.ms / e->plain.turns, - (double)(e->judged.in + e->judged.out) / - e->judged.turns - - (double)(e->plain.in + e->plain.out) / - e->plain.turns, - (e->judged.cost / e->judged.turns) - - (e->plain.cost / e->plain.turns)); + (double)judged.ms / judged.turns - + (double)plain.ms / plain.turns, + (double)(judged.in + judged.out) / + judged.turns - + (double)(plain.in + plain.out) / + plain.turns, + (judged.cost / judged.turns) - + (plain.cost / plain.turns)); } - if (strstr(e->cur_model, "judged") != NULL) + if (strstr(model, "judged") != NULL) sp_buf_puts(out, "note: judge calls happen upstream; the " "provider's usage carries only the final answer, so they " "are not in $ or tokens above - only latency and the " @@ -2708,12 +2933,17 @@ sp_engine_input(struct sp_engine *e, const char *line, struct sp_buf *out) if (sp_buf_init(&cerr) != 0) return SP_INPUT_HANDLED; if (sp_cmdscript_dir(e->sess.dir, cdir, sizeof(cdir)) == 0 && - sp_cmdscript_exists(cdir, name) && - sp_slash_script(cdir, name, args, out, &cerr) == 0 && - out->p != NULL) { - ev_push(e, SP_EV_ENTRY, 0, "shell", out->p); + sp_cmdscript_exists(cdir, name)) { + if (sp_slash_script(cdir, name, args, out, &cerr) == 0 && + out->p != NULL) { + ev_push(e, SP_EV_ENTRY, 0, "shell", out->p); + sp_buf_free(&cerr); + return SP_INPUT_SUBMIT; + } + sp_buf_clear(out); + sp_buf_puts(out, cerr.p != NULL ? cerr.p : "?"); sp_buf_free(&cerr); - return SP_INPUT_SUBMIT; + return SP_INPUT_HANDLED; } sp_buf_free(&cerr); } @@ -2986,7 +3216,9 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o, } pthread_mutex_init(&e->lock, NULL); pthread_mutex_init(&e->model_lock, NULL); + pthread_mutex_init(&e->turn_mx, NULL); pthread_cond_init(&e->cond, NULL); + open_add(e); sp_buf_init(&e->answer); sp_buf_init(&e->err); sp_buf_init(&e->live); @@ -3188,6 +3420,7 @@ sp_engine_close(struct sp_engine *e) { if (e == NULL) return; + open_del(e); if (sp_engine_busy(e)) (void)sp_engine_cancel(e); engine_join(e); @@ -3215,6 +3448,7 @@ sp_engine_close(struct sp_engine *e) free(e->q); pthread_cond_destroy(&e->cond); pthread_mutex_destroy(&e->model_lock); + pthread_mutex_destroy(&e->turn_mx); pthread_mutex_destroy(&e->lock); free(e); } diff --git a/src/backend/http.c b/src/backend/http.c index c3fc49c..792c8a8 100644 --- a/src/backend/http.c +++ b/src/backend/http.c @@ -45,7 +45,8 @@ sp_http_header_value(const char *hdr, const char *name) return NULL; while ((p = strstr(p, "\r\n")) != NULL) { p += 2; - if (*p == '\0') + /* the blank line ends the headers; what follows is body */ + if (*p == '\0' || (p[0] == '\r' && p[1] == '\n')) break; if (strncasecmp(p, name, n) == 0 && p[n] == ':') { const char *v = p + n + 1; @@ -78,15 +79,22 @@ void sp_http_reply(int fd, int code, const char *reason, const char *type, const char *body) { - char hdr[512]; + sp_http_reply_ex(fd, code, reason, type, NULL, body); +} + +void +sp_http_reply_ex(int fd, int code, const char *reason, const char *type, + const char *extra, const char *body) +{ + char hdr[1024]; int n; n = snprintf(hdr, sizeof(hdr), "HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\n" - "Connection: close\r\n\r\n", code, reason, + "%sConnection: close\r\n\r\n", code, reason, type != NULL ? type : "application/json", - strlen(body != NULL ? body : "")); - if (n > 0) + strlen(body != NULL ? body : ""), extra != NULL ? extra : ""); + if (n > 0 && (size_t)n < sizeof(hdr)) (void)sp_http_write_all(fd, hdr, (size_t)n); (void)sp_http_write_all(fd, body != NULL ? body : "", strlen(body != NULL ? body : "")); @@ -187,8 +195,22 @@ read_chunked(struct http_src *src, struct sp_buf *body, size_t body_max) return -1; if (src_exact(src, (size_t)n, body) != 0) return -1; - /* the CRLF that closes the chunk */ - if (src_read(src, tail, 2) != 2 || tail[1] != '\n') + /* the CRLF that closes the chunk; a read may return 1 byte */ + { + size_t have = 0; + + while (have < sizeof(tail)) { + ssize_t got = src_read(src, tail + have, + sizeof(tail) - have); + + if (got < 0 && errno == EINTR) + continue; + if (got <= 0) + return -1; + have += (size_t)got; + } + } + if (tail[1] != '\n') return -1; } /* trailer section: header lines up to the empty one */ diff --git a/src/backend/http.h b/src/backend/http.h index 70aa2cc..2bdf36f 100644 --- a/src/backend/http.h +++ b/src/backend/http.h @@ -26,6 +26,9 @@ int sp_http_bearer_is(const char *auth, const char *token); /* one complete reply; type is the Content-Type, body is NUL-terminated */ void sp_http_reply(int fd, int code, const char *reason, const char *type, const char *body); +/* the same, with extra header lines (each ending in CRLF) or NULL */ +void sp_http_reply_ex(int fd, int code, const char *reason, + const char *type, const char *extra, const char *body); /* * Start an event stream: status 200, text/event-stream, no Content-Length, * then the caller writes frames and closes the socket. diff --git a/src/backend/i18n.c b/src/backend/i18n.c index b6e195d..6d92605 100644 --- a/src/backend/i18n.c +++ b/src/backend/i18n.c @@ -103,6 +103,81 @@ detect_language(const char *override_lang) } } +/* + * The printf conversions in 's' as a short signature ("s|zu|*d|"), so that a + * catalogue entry can be checked against the text it replaces: catalogue + * strings end up as format strings, and one with other conversions than the + * caller passes arguments for is undefined behaviour. -1 for %n, which no + * message ever needs, or a signature that does not fit. + */ +static int +fmt_sig(const char *s, char *sig, size_t cap) +{ + size_t n = 0; + + if (cap == 0) + return -1; + sig[0] = '\0'; + while ((s = strchr(s, '%')) != NULL) { + char one[16]; + size_t k = 0; + + s++; + if (*s == '%') { + s++; + continue; + } + while (*s != '\0' && strchr("-+ #0'", *s) != NULL) + s++; + if (*s == '*') { + one[k++] = '*'; + s++; + } else + while (isdigit((unsigned char)*s)) + s++; + if (*s == '$') + return -1; /* positional: not checked, refused */ + if (*s == '.') { + s++; + if (*s == '*') { + one[k++] = '*'; + s++; + } else + while (isdigit((unsigned char)*s)) + s++; + } + while (*s != '\0' && strchr("hljztLq", *s) != NULL && k < 8) + one[k++] = *s++; + if (*s == '\0') + break; /* a lone '%' at the end prints nothing */ + if (*s == 'n') + return -1; + one[k++] = *s++; + one[k++] = '|'; + if (n + k + 1 > cap) + return -1; + memcpy(sig + n, one, k); + n += k; + sig[n] = '\0'; + } + return 0; +} + +/* may 'text' stand in for 'ref'? Same conversions, never %n */ +static int +fmt_compatible(const char *text, const char *ref) +{ + char a[128], b[128]; + + if (fmt_sig(text, a, sizeof(a)) != 0) + return 0; + if (ref == NULL) + return 1; + if (fmt_sig(ref, b, sizeof(b)) != 0) + return 0; + return strcmp(a, b) == 0; +} + static size_t parse_stream(FILE *f, struct entry *cat, size_t max) { @@ -122,8 +197,8 @@ parse_stream(FILE *f, struct entry *cat, size_t max) *eq = '\0'; val = trim(eq + 1); key = trim(key); - if (*key == '\0') - continue; + if (*key == '\0' || !fmt_compatible(val, NULL)) + continue; /* %n: never a message */ snprintf(cat[n].key, sizeof(cat[n].key), "%s", key); snprintf(cat[n].text, sizeof(cat[n].text), "%s", val); n++; @@ -227,14 +302,17 @@ sp_t(const char *key) { const char *v; + const char *en; + if (key == NULL) return ""; v = lookup(main_cat, main_n, key); - if (v != NULL) - return v; - v = lookup(fallback, fallback_n, key); - if (v != NULL) + en = lookup(fallback, fallback_n, key); + /* a translation that takes other arguments than English is not used */ + if (v != NULL && (en == NULL || fmt_compatible(v, en))) return v; + if (en != NULL) + return en; return key; /* untranslated keys are visible */ } @@ -269,11 +347,12 @@ sp_td(const char *key, const char *dflt) if (key == NULL) return dflt != NULL ? dflt : ""; + /* the caller's default says which arguments follow: nothing else fits */ v = lookup(main_cat, main_n, key); - if (v != NULL) + if (v != NULL && fmt_compatible(v, dflt)) return v; v = lookup(fallback, fallback_n, key); - if (v != NULL) + if (v != NULL && fmt_compatible(v, dflt)) return v; return dflt != NULL ? dflt : key; } @@ -286,9 +365,10 @@ sp_i18n_init(const char *override_lang) detect_language(override_lang); /* - * Where catalogues may live. The executable's own directory comes first, - * so `splinter` works from any working directory; then the explicit - * override, then the source tree, then an installed prefix. + * Where catalogues may live: the explicit override, then next to the + * executable (the source tree, or /bin -> /share), then + * an installed prefix. Never the working directory: catalogue strings + * are format strings, and any repository could ship a share/locale. */ { const char *env = getenv("SPLINTER_LOCALE_DIR"); @@ -300,7 +380,7 @@ sp_i18n_init(const char *override_lang) char exe[512]; ssize_t n = readlink("/proc/self/exe", exe, sizeof(exe) - 1); - if (n > 0) { + if (n > 0 && exe[0] == '/') { char dir[600]; char *slash; @@ -310,10 +390,15 @@ sp_i18n_init(const char *override_lang) *slash = '\0'; snprintf(dir, sizeof(dir), "%s/share/locale", exe); sp_i18n_add_dir(dir); + snprintf(dir, sizeof(dir), + "%s/../share/splinter/locale", exe); + sp_i18n_add_dir(dir); + snprintf(dir, sizeof(dir), "%s/../share/locale", + exe); + sp_i18n_add_dir(dir); } } } - sp_i18n_add_dir("share/locale"); sp_i18n_add_dir("/usr/local/share/splinter/locale"); if (sp_buf_init(&err) != 0) diff --git a/src/backend/interview.c b/src/backend/interview.c index b564a35..33beb3e 100644 --- a/src/backend/interview.c +++ b/src/backend/interview.c @@ -133,9 +133,16 @@ sp_interview_capture(const char *session_dir, const char *answer, char *clean, f = fopen(tmp, "w"); if (f == NULL) return 0; - if (fprintf(f, "%s\n", clean) < 0 || fclose(f) != 0) { - (void)unlink(tmp); - return 0; + { + int bad = fprintf(f, "%s\n", clean) < 0; + + /* always closed, even when the write failed */ + if (fclose(f) != 0) + bad = 1; + if (bad) { + (void)unlink(tmp); + return 0; + } } (void)chmod(tmp, 0600); if (rename(tmp, path) != 0) { diff --git a/src/backend/mcpserver.c b/src/backend/mcpserver.c index 5dd604f..2e0764f 100644 --- a/src/backend/mcpserver.c +++ b/src/backend/mcpserver.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -73,6 +74,51 @@ on_signal(int sig) mcp_stop = 1; } +void +sp_mcp_stop(void) +{ + mcp_stop = 1; +} + +int +sp_mcp_stopping(void) +{ + return mcp_stop != 0; +} + +/* + * Wait until fd is readable, in short slices so a stop request is seen + * within a quarter second. 1: readable, 0: stopped or timed out (ms <= 0 + * waits for ever), -1: error. + */ +#define MCP_SLICE_MS 250 + +static int +wait_readable(int fd, long ms) +{ + long waited = 0; + + while (!mcp_stop) { + struct pollfd pfd; + int r; + + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + r = poll(&pfd, 1, MCP_SLICE_MS); + if (r > 0) + return 1; + if (r < 0 && errno != EINTR) + return -1; + if (r == 0) { + waited += MCP_SLICE_MS; + if (ms > 0 && waited >= ms) + return 0; + } + } + return 0; +} + /* The object that follows "arguments" in the raw line, braces balanced. */ static const char * slice_object(const char *at, size_t *lenp) @@ -355,7 +401,12 @@ serve_conn(int fd, const struct srv *s, int allow_mutate, const char *token) int authed = token == NULL; for (;;) { - ssize_t got = read(fd, line + used, sizeof(line) - used - 1); + ssize_t got; + + /* five quiet minutes close the connection, so does a stop */ + if (wait_readable(fd, 300 * 1000L) != 1) + return; + got = read(fd, line + used, sizeof(line) - used - 1); if (got <= 0) { if (got < 0 && errno == EINTR) @@ -461,8 +512,14 @@ sp_mcp_serve(struct sp_engine **eng, const struct sp_engine_opts *opts, token != NULL ? "token required" : "loopback, no token"); while (!mcp_stop) { - int c = accept(s, NULL, NULL); + int c, w; + w = wait_readable(s, 0); + if (w < 0) + break; + if (w == 0) + continue; /* stopping: the loop test ends it */ + c = accept(s, NULL, NULL); if (c < 0) { if (errno == EINTR) continue; diff --git a/src/backend/mcpserver.h b/src/backend/mcpserver.h index 4906c25..14df635 100644 --- a/src/backend/mcpserver.h +++ b/src/backend/mcpserver.h @@ -21,4 +21,12 @@ int sp_mcp_serve(struct sp_engine **eng, const struct sp_engine_opts *opts, const struct sp_registry *, const char *ip, int port, int allow_mutate, int own_signals, struct sp_buf *err); +/* + * Ask a running sp_mcp_serve() to return: it stops accepting, closes the + * connection it serves and cancels a splinter_say turn, within a quarter + * second or so. For a server on its own thread, before joining it. + */ +void sp_mcp_stop(void); +int sp_mcp_stopping(void); + #endif /* SPLINTER_MCPSERVER_H */ diff --git a/src/backend/mcpsession.c b/src/backend/mcpsession.c index b45d59e..94bf6d9 100644 --- a/src/backend/mcpsession.c +++ b/src/backend/mcpsession.c @@ -39,6 +39,7 @@ #include "splinter.h" #include "splinter_engine.h" #include "mcp.h" +#include "mcpserver.h" #include "mcpsession.h" static struct sp_engine **session_eng; @@ -46,7 +47,9 @@ static const struct sp_engine_opts *session_opts; #define SAY_TIMEOUT_S 3600 #define SAY_ANSWER_MAX (256 * 1024) +#define SAY_TEXT_MAX 8192 #define HIST_TEXT_MAX 600 +#define BUSY_MSG "error: busy - a turn is running; wait or cancel it" void sp_mcpsession_bind(struct sp_engine **eng, const struct sp_engine_opts *opts) @@ -312,6 +315,11 @@ tool_history(const char *args, struct sp_buf *out) sp_buf_puts(out, "no conversation"); return 0; } + /* a running turn (the engine's or the daemon's) is writing to it */ + if (sp_engine_hold(*session_eng) != 0) { + sp_buf_puts(out, BUSY_MSG); + return 0; + } from = conv->n > (size_t)limit ? conv->n - (size_t)limit : 0; for (i = from; i < conv->n; i++) { const struct sp_msg *m = &conv->v[i]; @@ -325,6 +333,7 @@ tool_history(const char *args, struct sp_buf *out) snprintf(text, sizeof(text), "%s", m->content); sp_buf_printf(out, "[%s] %s\n", m->role, text); } + sp_engine_release(*session_eng); return 0; } @@ -362,32 +371,42 @@ static int tool_say(const char *args, struct sp_buf *out) { struct sp_engine *e = *session_eng; - char text[8192], answer[SAY_ANSWER_MAX]; + char *text, *answer; char nm[64] = "", ar[512] = ""; size_t steps = 0, calls = 0; int known = 0, auth = SP_AUTH_READ; time_t deadline; - arg_string(args, "text", text, sizeof(text)); + /* an MCP thread's stack is small: the buffers live on the heap */ + text = malloc(SAY_TEXT_MAX); + answer = malloc(SAY_ANSWER_MAX); + if (text == NULL || answer == NULL) { + free(text); + free(answer); + sp_buf_puts(out, "error: out of memory"); + return 0; + } + answer[0] = '\0'; + arg_string(args, "text", text, SAY_TEXT_MAX); if (text[0] == '\0') { sp_buf_puts(out, "error: 'text' is required"); - return 0; + goto done; } if (sp_engine_busy(e)) { sp_buf_puts(out, "error: a turn is already running " "(splinter_steer or splinter_cancel)"); - return 0; + goto done; } - answer[0] = '\0'; + /* refused atomically when a daemon turn took the agent meanwhile */ if (sp_engine_submit(e, text) != 0) { - sp_buf_puts(out, "error: cannot start the turn"); - return 0; + sp_buf_puts(out, BUSY_MSG); + goto done; } deadline = time(NULL) + SAY_TIMEOUT_S; for (;;) { struct sp_engine_state st; - collect(e, answer, sizeof(answer), &known, &steps, &calls); + collect(e, answer, SAY_ANSWER_MAX, &known, &steps, &calls); if (!sp_engine_busy(e)) break; if (sp_engine_state(e, &st) == 0 && st.waiting && @@ -398,13 +417,21 @@ tool_say(const char *args, struct sp_buf *out) "{\"allow\":false}\n", nm, ar, auth == SP_AUTH_DESTRUCTIVE ? "destructive" : auth == SP_AUTH_MUTATE ? "mutate" : "read"); - return 0; + goto done; + } + if (sp_mcp_stopping()) { + /* the server is shutting down: do not hold it up */ + (void)sp_engine_cancel(e); + (void)sp_engine_wait(e); + sp_buf_puts(out, "error: the server is stopping; the " + "turn was cancelled"); + goto done; } if (time(NULL) > deadline) { (void)sp_engine_cancel(e); sp_buf_puts(out, "error: the turn did not finish in " "time and was cancelled"); - return 0; + goto done; } { struct timespec ts = { 0, 50 * 1000 * 1000L }; @@ -418,6 +445,9 @@ tool_say(const char *args, struct sp_buf *out) answer[0] != '\0' ? answer : "(empty answer)", steps, calls); else sp_buf_puts(out, "error: the turn ended without an answer\n"); +done: + free(text); + free(answer); return 0; } @@ -470,14 +500,17 @@ tool_model(const char *args, struct sp_buf *out) "(splinter_models lists the selectors)"); return 0; } - if (sp_engine_busy(*session_eng)) { - sp_buf_puts(out, "error: a turn is running; wait or cancel it"); - return 0; - } snprintf(line, sizeof(line), "/model %s", sel); if (sp_buf_init(&reply) != 0) return -1; + /* held, not just checked: a daemon turn must not start under it */ + if (sp_engine_hold(*session_eng) != 0) { + sp_buf_free(&reply); + sp_buf_puts(out, BUSY_MSG); + return 0; + } kind = sp_engine_input(*session_eng, line, &reply); + sp_engine_release(*session_eng); if (kind != SP_INPUT_HANDLED) { sp_buf_puts(out, "error: /model started a turn?"); sp_buf_free(&reply); @@ -499,21 +532,25 @@ tool_agent(const char *args, struct sp_buf *out) sp_buf_puts(out, "error: 'agent' is required"); return 0; } - if (sp_engine_busy(*session_eng)) { - sp_buf_puts(out, "error: a turn is running; wait or cancel it"); + if (sp_engine_hold(*session_eng) != 0) { + sp_buf_puts(out, BUSY_MSG); return 0; } n = sp_engine_agents(*session_eng); cur = sp_engine_agent_cur(*session_eng); for (i = 0; i < n; i++) if (strcmp(sp_engine_agent_name(*session_eng, i), name) == 0) { - if (sp_engine_agent_switch(*session_eng, i) != 0) { + int rc = sp_engine_agent_switch(*session_eng, i); + + sp_engine_release(*session_eng); + if (rc != 0) { sp_buf_puts(out, "error: cannot switch the agent"); return 0; } sp_buf_printf(out, "agent: %s\n", name); return 0; } + sp_engine_release(*session_eng); sp_buf_printf(out, "error: no agent '%s' (active is %s)\n", name, cur >= 0 ? sp_engine_agent_name(*session_eng, cur) : "?"); return 0; diff --git a/src/backend/openai.c b/src/backend/openai.c index fd0b5ed..54105f6 100644 --- a/src/backend/openai.c +++ b/src/backend/openai.c @@ -32,6 +32,100 @@ put_field(struct sp_buf *b, const char *key, const char *value) return 0; } +/* anthropic.c: a parsed value back to JSON text */ +int sp_json_emit(struct sp_buf *, const mcp_json *); + +/* + * The stored calls of an assistant turn, in OpenAI's shape. The conversation + * keeps whatever the provider sent: after a /model switch from Anthropic that + * is [{"id","name","input":{...}}], and OpenAI refuses it with a 400. Calls + * already in OpenAI's shape go out verbatim; anything else is converted to + * {"id","type":"function","function":{"name","arguments":""}}. + * Nothing is written when no usable call remains. + */ +static int +put_calls(struct sp_buf *out, const char *calls) +{ + mcp_json *v; + struct sp_buf conv, args; + size_t i, nout = 0; + int native = 1, rc = -1; + + v = mcp_parse(calls); + if (v == NULL || v->t != MCP_ARR || v->count == 0) { + mcp_json_free(v); + return 0; /* unusable history is left out */ + } + for (i = 0; i < v->count; i++) { + const mcp_json *fn = mcp_arg(v->items[i], "function"); + + if (fn == NULL || fn->t != MCP_OBJ || + mcp_arg_string(fn, "name") == NULL || + mcp_arg_string(fn, "arguments") == NULL) + native = 0; + } + if (native) { + mcp_json_free(v); + return sp_buf_printf(out, ",\"tool_calls\":%s", calls); + } + if (sp_buf_init(&conv) != 0) { + mcp_json_free(v); + return -1; + } + if (sp_buf_init(&args) != 0) { + sp_buf_free(&conv); + mcp_json_free(v); + return -1; + } + for (i = 0; i < v->count; i++) { + const mcp_json *c = v->items[i]; + const mcp_json *fn = mcp_arg(c, "function"); + const mcp_json *input = mcp_arg(c, "input"); + const char *id = mcp_arg_string(c, "id"); + const char *name = fn != NULL ? mcp_arg_string(fn, "name") : + mcp_arg_string(c, "name"); + const char *a = fn != NULL ? + mcp_arg_string(fn, "arguments") : NULL; + char idbuf[32]; + + if (name == NULL || name[0] == '\0') + continue; + sp_buf_clear(&args); + if (a != NULL) { + if (sp_buf_puts(&args, a) != 0) + goto out; + } else if (input != NULL) { + if (sp_json_emit(&args, input) != 0) + goto out; + } else if (sp_buf_puts(&args, "{}") != 0) + goto out; + if (id == NULL || id[0] == '\0') { + snprintf(idbuf, sizeof(idbuf), "call-%zu", i); + id = idbuf; + } + if (sp_buf_puts(&conv, nout > 0 ? "," : "") != 0 || + sp_buf_puts(&conv, "{") != 0 || + put_field(&conv, "id", id) != 0 || + sp_buf_puts(&conv, ",\"type\":\"function\"," + "\"function\":{") != 0 || + put_field(&conv, "name", name) != 0 || + sp_buf_puts(&conv, ",") != 0 || + put_field(&conv, "arguments", args.p != NULL ? args.p : + "{}") != 0 || + sp_buf_puts(&conv, "}}") != 0) + goto out; + nout++; + } + rc = 0; + if (nout > 0) + rc = sp_buf_printf(out, ",\"tool_calls\":[%s]", conv.p); +out: + sp_buf_free(&args); + sp_buf_free(&conv); + mcp_json_free(v); + return rc; +} + static int gen_fields(struct sp_buf *out, const struct sp_gen_opts *g) { @@ -93,17 +187,26 @@ sp_openai_request_opts(const struct sp_conv *conv, const char *model, return -1; } if (m->calls != NULL && *m->calls != '\0') { - if (sp_buf_printf(out, ",\"tool_calls\":%s", m->calls) != 0) + if (put_calls(out, m->calls) != 0) return -1; } if (sp_buf_puts(out, "}") != 0) return -1; } - /* tools: name, description and an open parameter object */ - if (sp_buf_puts(out, "],\"tools\":[") != 0) + /* + * tools: name, description and an open parameter object. An empty + * "tools":[] is refused by OpenAI itself (400), so no tools means no + * field. + */ + if (sp_buf_puts(out, "]") != 0) + return -1; + ntv = 0; + tv = reg != NULL ? sp_registry_tools(reg, &ntv) : NULL; + if (tv == NULL || ntv == 0) + return sp_buf_puts(out, "}"); + if (sp_buf_puts(out, ",\"tools\":[") != 0) return -1; - tv = sp_registry_tools(reg, &ntv); for (i = 0; i < ntv; i++) { const struct sp_tool *t = &tv[i]; @@ -145,14 +248,33 @@ sp_openai_request(const struct sp_conv *conv, const char *model, static char * raw_calls(const char *json, const char *key) { - const char *p = strstr(json, key); - const char *start; + const char *p = json; + const char *start = NULL; int depth = 0, in_str = 0, esc = 0; - size_t len; + size_t len, klen = strlen(key); - if (p == NULL) - return NULL; - start = strchr(p + strlen(key), '['); + /* + * The key, not the first occurrence of its text: "finish_reason": + * "tool_calls" carries the same quoted word as a value. A key is + * followed by optional blanks and a colon, then the array. + */ + while ((p = strstr(p, key)) != NULL) { + const char *q = p + klen; + + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') + q++; + if (*q == ':') { + q++; + while (*q == ' ' || *q == '\t' || *q == '\n' || + *q == '\r') + q++; + if (*q == '[') { + start = q; + break; + } + } + p += klen; + } if (start == NULL) return NULL; for (p = start; *p != '\0'; p++) { diff --git a/src/backend/openai_server.c b/src/backend/openai_server.c index a404eab..3de7eab 100644 --- a/src/backend/openai_server.c +++ b/src/backend/openai_server.c @@ -28,7 +28,9 @@ * Splinter is a stateless gateway here: the conversation travels in every * request, exactly as the OpenAI protocol says. Local gw_ calls are executed * inside one request; a model reply that mixes local and caller calls runs - * the local ones and asks again (the caller calls come on a later step). + * the local ones, returns the caller's calls at once in tool_calls, and puts + * the local observations in the content (the model does not see them as tool + * results, since the caller's results are still owed). * * Security: binding beyond loopback requires SPLINTER_GATEWAY_TOKEN, and the * token is checked on every request. Mutating and destructive local tools run @@ -801,6 +803,7 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body) struct sp_gen_opts gen; long created = (long)time(NULL); long tokens_in = 0, tokens_out = 0; + long up_status = 0, up_retry = 0; int stream, want_usage = 0, headers_sent = 0; unsigned long seq = ++g_seq; char id[80]; @@ -890,7 +893,25 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body) else rc = tr.send(tr.ctx, &conv, &rep, &uerr); sp_transport_dispose(&tr); + /* + * A transport may answer rc 0 with a non-2xx status + * and the error body in content: that is the + * upstream's error, not an assistant answer. The + * caller gets the same status (and Retry-After), so + * its own backoff works through the gateway. + */ + if (rc == 0 && rep.status != 0 && + (rep.status < 200 || rep.status > 299)) { + sp_buf_printf(&uerr, "%sHTTP %ld: %.500s", + uerr.len > 0 ? "; " : "", rep.status, + rep.content != NULL ? rep.content : ""); + rc = -1; + } if (rc != 0) { + if (rep.status >= 400 && rep.status <= 599) { + up_status = rep.status; + up_retry = rep.retry_after_s; + } sp_buf_printf(&err, "upstream: %s", uerr.p != NULL && uerr.len > 0 ? uerr.p : "no answer"); @@ -1106,8 +1127,21 @@ upstream_bad: } else { error_json(&payload, err.p != NULL ? err.p : "upstream failed"); - sp_http_reply(fd, 502, "Bad Gateway", "application/json", - payload.p); + if (up_status != 0) { + char extra[64]; + + extra[0] = '\0'; + if (up_retry > 0) + snprintf(extra, sizeof(extra), + "Retry-After: %ld\r\n", up_retry); + sp_http_reply_ex(fd, (int)up_status, + up_status == 429 ? "Too Many Requests" : + up_status < 500 ? "Upstream Error" : + "Upstream Failure", "application/json", + extra[0] != '\0' ? extra : NULL, payload.p); + } else + sp_http_reply(fd, 502, "Bad Gateway", + "application/json", payload.p); } out: sp_buf_free(&payload); diff --git a/src/backend/plugin.c b/src/backend/plugin.c index 542704c..1252159 100644 --- a/src/backend/plugin.c +++ b/src/backend/plugin.c @@ -376,11 +376,6 @@ sp_host_gate(struct sp_host *h, const char *tool, int auth, const char *args, return -1; } -/* - * Run every compactor in registration order. A compactor that fails does not - * stop the others and does not abort the turn: the failure is counted and the - * loop carries on with whatever the conversation looks like now. - */ int sp_host_add_transport(struct sp_host *h, const char *name, struct sp_transport tr) @@ -460,6 +455,11 @@ sp_host_command_help(struct sp_host *h, struct sp_buf *out) return h->ncommands; } +/* + * Run every compactor in registration order. A compactor that fails does not + * stop the others and does not abort the turn: the failure is counted and the + * loop carries on with whatever the conversation looks like now. + */ int sp_host_compact(struct sp_host *h, struct sp_conv *conv, size_t budget) { @@ -714,12 +714,6 @@ sp_host_widget_snapshot(struct sp_host *h, char *buf, size_t len) return used; } -struct sp_plugin_handle { - void *dl; - const struct sp_plugin *p; - char path[512]; -}; - /* how far each table was filled before a plugin's init() ran */ struct host_mark { size_t tools, widgets, compact, gate, status; @@ -778,7 +772,7 @@ rollback(struct sp_host *h, const struct host_mark *m) int sp_plugin_load(struct sp_host *h, const char *path, struct sp_buf *err) { - struct sp_plugin_handle *hd; + void *hd; const struct sp_plugin *(*describe)(void); if (h == NULL || path == NULL) diff --git a/src/backend/prompt.c b/src/backend/prompt.c index fcc2cc0..e68b608 100644 --- a/src/backend/prompt.c +++ b/src/backend/prompt.c @@ -44,6 +44,22 @@ "Answer briefly: the result first, where the files are, then the next step. Use " \ "the language the user writes in.\n" +/* Append at most what fits; snprintf returns the untruncated length. */ +static size_t +put(char *out, size_t cap, size_t used, const char *a, const char *b) +{ + int n; + + if (used + 1 >= cap) + return used; + n = snprintf(out + used, cap - used, "%s%s", a, b != NULL ? b : ""); + if (n < 0) + return used; + if ((size_t)n >= cap - used) + return cap - 1; + return used + (size_t)n; +} + static void expand_into(const char *tmpl, char *out, size_t cap, const char *model) { @@ -52,25 +68,28 @@ expand_into(const char *tmpl, char *out, size_t cap, const char *model) struct utsname un; const char *home = getenv("HOME"); char cwd[512]; + char os[300]; + if (cap == 0) + return; (void)uname(&un); + snprintf(os, sizeof(os), "%s %s", un.sysname, un.release); if (getcwd(cwd, sizeof(cwd)) == NULL) snprintf(cwd, sizeof(cwd), "?"); while (*src != '\0' && used + 1 < cap) { if (strncmp(src, "{{os}}", 6) == 0) { - used += (size_t)snprintf(out + used, cap - used, "%s %s", - un.sysname, un.release); + used = put(out, cap, used, os, NULL); src += 6; } else if (strncmp(src, "{{home}}", 8) == 0) { - used += (size_t)snprintf(out + used, cap - used, "%s", - home != NULL ? home : "?"); + used = put(out, cap, used, home != NULL ? home : "?", + NULL); src += 8; } else if (strncmp(src, "{{cwd}}", 7) == 0) { - used += (size_t)snprintf(out + used, cap - used, "%s", cwd); + used = put(out, cap, used, cwd, NULL); src += 7; } else if (strncmp(src, "{{model}}", 9) == 0) { - used += (size_t)snprintf(out + used, cap - used, "%s", - model != NULL ? model : "?"); + used = put(out, cap, used, model != NULL ? model : "?", + NULL); src += 9; } else out[used++] = *src++; diff --git a/src/backend/providers.c b/src/backend/providers.c index e6ca0d5..cf351ad 100644 --- a/src/backend/providers.c +++ b/src/backend/providers.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -96,6 +97,7 @@ delegates: snprintf(out->endpoint, sizeof(out->endpoint), "%s", d->endpoint); snprintf(out->model, sizeof(out->model), "%s", d->model); snprintf(out->key_env, sizeof(out->key_env), "%s", d->key_env); + snprintf(out->key, sizeof(out->key), "%s", d->key); snprintf(out->about, sizeof(out->about), "%s", d->about); out->ctx = d->ctx; return 0; @@ -219,13 +221,17 @@ sp_provider_identify(struct sp_transport *tr, const char *endpoint, { /* * The fingerprint outlives this call, and a ring holds several - * transports at once, so it cannot be one static buffer: each identity - * gets its own slot (a hash, never the secret). + * transports at once, so it cannot be one static buffer. Each distinct + * key gets one slot for the life of the process (a hash, never the + * secret): the same key reuses its slot, a new one grows the table. + * A fixed ring overwrote slots that live transports still pointed at. + * The table only grows with distinct keys, which the config bounds. */ - static char pool[16][32]; - static size_t slot; + static char **pool; + static size_t npool, cappool; const char *prov = "openai-compat"; - char *kfp; + char kfp[32]; + size_t i; if (tr == NULL) return; @@ -239,10 +245,28 @@ sp_provider_identify(struct sp_transport *tr, const char *endpoint, prov = "anthropic"; tr->provider = prov; tr->key_id = NULL; - if (secret != NULL && *secret != '\0') { - kfp = pool[slot++ % 16]; - if (sp_key_fingerprint(secret, kfp, 32) != NULL) - tr->key_id = kfp; + if (secret != NULL && *secret != '\0' && + sp_key_fingerprint(secret, kfp, sizeof(kfp)) != NULL) { + for (i = 0; i < npool; i++) + if (strcmp(pool[i], kfp) == 0) + break; + if (i == npool) { + /* the strings never move; only the index does */ + if (npool == cappool) { + size_t nc = cappool > 0 ? cappool * 2 : 16; + char **np = realloc(pool, nc * sizeof(*pool)); + + if (np != NULL) { + pool = np; + cappool = nc; + } + } + if (npool < cappool && + (pool[npool] = strdup(kfp)) != NULL) + npool++; + } + if (i < npool) + tr->key_id = pool[i]; } if (tr->key_id == NULL && strcmp(prov, "ollama") == 0) tr->key_id = "local"; @@ -251,6 +275,20 @@ sp_provider_identify(struct sp_transport *tr, const char *endpoint, int sp_provider_apply(struct sp_agent *ag, const char *kind, const char *endpoint, const char *model, const char *key_env, struct sp_buf *err) +{ + return sp_provider_apply_key(ag, kind, endpoint, model, key_env, NULL, + err); +} + +/* + * A literal key (an auto-detected Ollama delegate carries its token in + * d->key, with no key_env) wins over key_env: reading only the environment + * sent such a provider without a key, and it answered 401. + */ +int +sp_provider_apply_key(struct sp_agent *ag, const char *kind, + const char *endpoint, const char *model, const char *key_env, + const char *literal, struct sp_buf *err) { const char *key = NULL; @@ -262,7 +300,9 @@ sp_provider_apply(struct sp_agent *ag, const char *kind, const char *endpoint, sp_buf_puts(err, "no endpoint or model"); return -1; } - if (key_env != NULL && *key_env != '\0') + if (literal != NULL && *literal != '\0') + key = literal; + else if (key_env != NULL && *key_env != '\0') key = getenv(key_env); if (kind != NULL && strcmp(kind, "anthropic") == 0) { sp_transport_dispose(&ag->tr); @@ -288,8 +328,8 @@ sp_provider_use(struct sp_agent *ag, const struct sp_config *cfg, size_t idx, sp_buf_puts(err, "no such provider"); return -1; } - if (sp_provider_apply(ag, p.kind, p.endpoint, p.model, p.key_env, - err) != 0) + if (sp_provider_apply_key(ag, p.kind, p.endpoint, p.model, p.key_env, + p.key, err) != 0) return -1; sp_usage_set_active(p.main ? "main" : p.id); return 0; @@ -486,6 +526,30 @@ window_pct(const mcp_json *v, const char *name, char *out, size_t cap) return 0; } + +/* + * Append to a fixed buffer. snprintf returns what it wanted to write, so a + * plain n += snprintf(...) walks past cap on a long answer and the next call + * writes out of bounds; this keeps n inside the buffer. + */ +static size_t +catf(char *out, size_t cap, size_t n, const char *fmt, ...) +{ + va_list ap; + int w; + + if (cap == 0 || n >= cap - 1) + return n; + va_start(ap, fmt); + w = vsnprintf(out + n, cap - n, fmt, ap); + va_end(ap); + if (w < 0) + return n; + if ((size_t)w >= cap - n) + return cap - 1; + return n + (size_t)w; +} + int sp_provider_remote_usage(const struct sp_provider *p, char *out, size_t cap) { @@ -553,18 +617,18 @@ sp_provider_remote_usage(const struct sp_provider *p, char *out, size_t cap) double buy = mcp_arg_num(pur, "balance_usd", -1.0); if (ses != NULL) - n += (size_t)snprintf(out + n, cap - n, "session %.0f%% left", + n = catf(out, cap, n, "session %.0f%% left", mcp_arg_num(ses, "remaining_percent", 0)); if (wk != NULL) - n += (size_t)snprintf(out + n, cap - n, "%sweekly %.0f%% left", + n = catf(out, cap, n, "%sweekly %.0f%% left", n ? ", " : "", mcp_arg_num(wk, "remaining_percent", 0)); if (bal >= 0) - n += (size_t)snprintf(out + n, cap - n, "%s$%.2f%s left", + n = catf(out, cap, n, "%s$%.2f%s left", n ? ", " : "", bal, all >= 0 ? "" : ""); if (bal >= 0 && all >= 0) - n += (size_t)snprintf(out + n, cap - n, " of $%.0f", all); + n = catf(out, cap, n, " of $%.0f", all); if (buy > 0) - n += (size_t)snprintf(out + n, cap - n, "%s$%.2f bought", + n = catf(out, cap, n, "%s$%.2f bought", n ? ", " : "", buy); } else { static const char *const names[] = { "rolling", "weekly", @@ -577,7 +641,7 @@ sp_provider_remote_usage(const struct sp_provider *p, char *out, size_t cap) if (window_pct(wrap != NULL ? wrap : v, names[k], line, sizeof(line)) && n < cap) - n += (size_t)snprintf(out + n, cap - n, "%s%s", + n = catf(out, cap, n, "%s%s", n ? ", " : "", line); } mcp_json_free(v); @@ -609,14 +673,32 @@ sp_provider_test(const struct sp_provider *p, struct sp_buf *answer, sp_conv_free(&conv); return -1; } - if (p->key_env[0] != '\0') + if (p->key[0] != '\0') + key = p->key; + else if (p->key_env[0] != '\0') key = getenv(p->key_env); if (p->kind[0] != '\0' && strcmp(p->kind, "anthropic") == 0) tr = sp_anthropic_transport(p->endpoint, p->model, key, &empty, 30); else tr = sp_openai_transport(p->endpoint, p->model, key, &empty, 30); + if (tr.send == NULL) { + if (err != NULL) + sp_buf_puts(err, "cannot build the transport"); + sp_transport_dispose(&tr); + sp_conv_free(&conv); + return -1; + } rc = tr.send(tr.ctx, &conv, &reply, err); + sp_transport_dispose(&tr); + /* an error page with status 429 is not "the provider answered" */ + if (rc == 0 && reply.status != 0 && + (reply.status < 200 || reply.status > 299)) { + if (err != NULL) + sp_buf_printf(err, "HTTP %ld: %.200s", reply.status, + reply.content != NULL ? reply.content : ""); + rc = -1; + } if (rc == 0) { size_t n = reply.content != NULL ? strlen(reply.content) : 0; @@ -1213,8 +1295,8 @@ sp_provider_failover(struct sp_agent *ag, const struct sp_config *cfg) return 0; if (sp_buf_init(&err) != 0) return 0; - rc = sp_provider_apply(ag, d->kind, d->endpoint, d->model, - d->key_env, &err); + rc = sp_provider_apply_key(ag, d->kind, d->endpoint, d->model, + d->key_env, d->key, &err); sp_buf_free(&err); if (rc != 0) return 0; diff --git a/src/backend/providers.h b/src/backend/providers.h index 7e1acd4..f47945e 100644 --- a/src/backend/providers.h +++ b/src/backend/providers.h @@ -23,6 +23,7 @@ struct sp_provider { char endpoint[512]; char model[256]; char key_env[64]; + char key[256]; /* a literal key (d->key), wins over key_env */ char about[128]; unsigned long ctx; /* context window, 0 = unknown */ int main; /* the endpoint/model the run started with */ @@ -69,6 +70,10 @@ int sp_provider_use(struct sp_agent *, const struct sp_config *, size_t, int sp_provider_apply(struct sp_agent *, const char *kind, const char *endpoint, const char *model, const char *key_env, struct sp_buf *err); +/* the same with a literal key, used instead of key_env when not empty */ +int sp_provider_apply_key(struct sp_agent *, const char *kind, + const char *endpoint, const char *model, const char *key_env, + const char *key, struct sp_buf *err); /* The drop-in directory next to the config file (…/splinter.conf.d). */ int sp_provider_dir(char *, size_t); diff --git a/src/backend/session.c b/src/backend/session.c index 7042241..6d55aa2 100644 --- a/src/backend/session.c +++ b/src/backend/session.c @@ -503,10 +503,11 @@ int sp_session_load(const struct sp_session_info *info, struct sp_conv *conv, size_t *loaded, struct sp_buf *err) { - struct sp_buf raw; - char path[640], line[8192]; + char path[640]; + char *line = NULL; + size_t linecap = 0, n = 0; + ssize_t len; FILE *f; - size_t n = 0; (void)err; if (loaded != NULL) @@ -515,16 +516,18 @@ sp_session_load(const struct sp_session_info *info, struct sp_conv *conv, f = fopen(path, "r"); if (f == NULL) return 0; /* nothing to resume from */ - if (sp_buf_init(&raw) != 0) { - fclose(f); - return -1; - } - while (fgets(line, sizeof(line), f) != NULL) { + /* whole lines, however long: a fixed buffer split big records */ + while ((len = getline(&line, &linecap, f)) > 0) { mcp_json *v; const char *role, *text; - if (line[0] != '{') - continue; /* a torn tail is not a record */ + /* + * A record is a complete, newline-terminated JSON object. An + * unterminated last line is the torn tail of a crash: skipped, + * not repaired and not an error. + */ + if (line[len - 1] != '\n' || line[0] != '{') + continue; v = mcp_parse(line); if (v == NULL) continue; @@ -537,8 +540,8 @@ sp_session_load(const struct sp_session_info *info, struct sp_conv *conv, } mcp_json_free(v); } + free(line); fclose(f); - sp_buf_free(&raw); if (loaded != NULL) *loaded = n; return 0; @@ -745,7 +748,7 @@ sp_session_folder_history(const char *dir, const char *cwd, unsigned limit, char *p = strstr(last, "\"text\":\""); if (p != NULL) { - char *v = p + 9; + char *v = p + 8; size_t k = 0; while (*v != '\0' && *v != '"' && k + 1 < sizeof(last)) @@ -929,6 +932,10 @@ sp_session_delete(const char *dir, const char *id, struct sp_buf *err) (void)unlink(side); snprintf(side, sizeof(side), "%s/%s.agent", dir, id); (void)unlink(side); + snprintf(side, sizeof(side), "%s/%s.model", dir, id); + (void)unlink(side); + snprintf(side, sizeof(side), "%s/%s.model.tmp", dir, id); + (void)unlink(side); /* logs are a convenience, not the record: a leftover must not fail this */ snprintf(logdir, sizeof(logdir), "%s/logs/%s", dir, id); (void)rm_tree(logdir); diff --git a/src/backend/skills.c b/src/backend/skills.c index cce3009..5ea4f4e 100644 --- a/src/backend/skills.c +++ b/src/backend/skills.c @@ -21,6 +21,7 @@ */ #include #include +#include #include #include #include @@ -43,6 +44,11 @@ struct skill { static struct skill skills[SKILL_MAX]; static size_t nskills; static const struct sp_config *skills_cfg; +/* + * skills[] is rescanned on every call, and tools run from more than one thread + * (delegates, the gateway): one scan-and-read at a time. + */ +static pthread_mutex_t skills_lock = PTHREAD_MUTEX_INITIALIZER; static void lower(char *dst, size_t cap, const char *src) @@ -197,7 +203,7 @@ scan_all(const char *session_dir) /* ---- tools ---- */ static int -tool_skill_search(const char *args, struct sp_buf *out, void *ctx) +skill_search_locked(const char *args, struct sp_buf *out, void *ctx) { struct sp_buf keep; mcp_json *v; @@ -254,7 +260,7 @@ tool_skill_search(const char *args, struct sp_buf *out, void *ctx) } static int -tool_skill_load(const char *args, struct sp_buf *out, void *ctx) +skill_load_locked(const char *args, struct sp_buf *out, void *ctx) { struct sp_buf keep; mcp_json *v; @@ -319,6 +325,28 @@ tool_skill_load(const char *args, struct sp_buf *out, void *ctx) return 0; } +static int +tool_skill_search(const char *args, struct sp_buf *out, void *ctx) +{ + int rc; + + pthread_mutex_lock(&skills_lock); + rc = skill_search_locked(args, out, ctx); + pthread_mutex_unlock(&skills_lock); + return rc; +} + +static int +tool_skill_load(const char *args, struct sp_buf *out, void *ctx) +{ + int rc; + + pthread_mutex_lock(&skills_lock); + rc = skill_load_locked(args, out, ctx); + pthread_mutex_unlock(&skills_lock); + return rc; +} + int sp_skills_register(struct sp_registry *r, const struct sp_config *cfg) { diff --git a/src/backend/sse.c b/src/backend/sse.c index 8e28ea8..fbfbe59 100644 --- a/src/backend/sse.c +++ b/src/backend/sse.c @@ -198,17 +198,34 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out, /* * Some proxies pretty-print the JSON over several data: lines. Try * the object so far first; only when it is incomplete keep growing it. + * + * A line that is a complete object by itself is a new event, not a + * continuation: the pending fragment was a broken line, and gluing + * every later event onto it lost the rest of the stream. */ + v = NULL; if (s->pending.len > 0) { - if (sp_buf_puts(&s->pending, "\n") != 0 || - sp_buf_puts(&s->pending, payload) != 0) { - sp_buf_puts(err, "sse: out of memory"); - return -1; + if (*payload == '{') { + v = mcp_parse(payload); + if (v != NULL && v->t != MCP_OBJ) { + mcp_json_free(v); + v = NULL; + } + } + if (v != NULL) + sp_buf_clear(&s->pending); + else { + if (sp_buf_puts(&s->pending, "\n") != 0 || + sp_buf_puts(&s->pending, payload) != 0) { + sp_buf_puts(err, "sse: out of memory"); + return -1; + } + payload = s->pending.p; } - payload = s->pending.p; } - v = mcp_parse(payload); + if (v == NULL) + v = mcp_parse(payload); if (v == NULL) { /* * Proxies send text keepalives as `data: ping` or `data: [PING]`. @@ -435,8 +452,12 @@ sp_sse_finish(struct sp_sse *s, struct sp_reply *out, struct sp_buf *err) return -1; out->ncalls = s->ncalls; for (i = 0; i < s->ncalls; i++) { + char idbuf[32]; + + /* one id per call: two "call-0" make the results ambiguous */ + snprintf(idbuf, sizeof(idbuf), "call-%zu", i); out->calls[i].id = strdup(s->calls[i].id != NULL ? - s->calls[i].id : "call-0"); + s->calls[i].id : idbuf); out->calls[i].name = strdup(s->calls[i].name != NULL ? s->calls[i].name : ""); out->calls[i].args = strdup(s->calls[i].args.p != NULL ? diff --git a/src/backend/swarm.c b/src/backend/swarm.c index 37362aa..06e6171 100644 --- a/src/backend/swarm.c +++ b/src/backend/swarm.c @@ -4,6 +4,9 @@ * Copyright (c) 2026 Konrad Lother * SPDX-License-Identifier: BSD-3-Clause */ +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE 1 /* struct ucred for SO_PEERCRED */ +#endif #include #include #include @@ -17,6 +20,7 @@ #include #include "swarm.h" +#include "mcp.h" static void set_nb(int fd) @@ -33,41 +37,44 @@ send_line(int fd, const char *s) return write(fd, s, n) == (ssize_t)n && write(fd, "\n", 1) == 1 ? 0 : -1; } -static int -json_get_int(const char *s, const char *key, int def) +/* the message's type ("t") and the parsed object, or NULL for a bad line */ +static mcp_json * +msg_parse(const char *line, const char **type) { - char pat[64]; - const char *p; - snprintf(pat, sizeof(pat), "\"%s\"", key); - p = strstr(s, pat); - if (!p) return def; - p = strchr(p, ':'); - if (!p) return def; - return (int)strtol(p + 1, NULL, 10); + mcp_json *v = mcp_parse(line); + + *type = v != NULL ? mcp_arg_string(v, "t") : NULL; + if (*type == NULL) { + mcp_json_free(v); + return NULL; + } + return v; } -static const char * -json_get_str(const char *s, const char *key, char *buf, size_t cap) +/* + * The socket lives in the working directory, which may be shared: whoever is + * at the other end has to be this user, on both sides. + */ +static int +same_user(int fd) { - char pat[64]; - const char *p, *q; - size_t n; - buf[0] = '\0'; - snprintf(pat, sizeof(pat), "\"%s\"", key); - p = strstr(s, pat); - if (!p) return buf; - p = strchr(p, ':'); - if (!p) return buf; - p = strchr(p, '"'); - if (!p) return buf; - p++; - q = strchr(p, '"'); - if (!q) return buf; - n = (size_t)(q - p); - if (n >= cap) n = cap - 1; - memcpy(buf, p, n); - buf[n] = '\0'; - return buf; +#if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \ + defined(__DragonFly__) || defined(__APPLE__) + uid_t uid; + gid_t gid; + + return getpeereid(fd, &uid, &gid) == 0 && uid == getuid(); +#elif defined(SO_PEERCRED) + struct ucred cred; + socklen_t len = sizeof(cred); + + if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0) + return 0; + return cred.uid == getuid(); +#else + (void)fd; + return 0; /* no way to check the peer: refuse, never trust */ +#endif } static void @@ -90,11 +97,17 @@ try_become_master(struct swarm *s) memset(&a, 0, sizeof(a)); a.sun_family = AF_UNIX; snprintf(a.sun_path, sizeof(a.sun_path), "%.107s", s->path); - if (bind(fd, (struct sockaddr *)&a, sizeof(a)) != 0) { - close(fd); - return -1; + { + /* created 0600, not chmod'ed after: no window for a connect */ + mode_t old = umask(077); + int rc = bind(fd, (struct sockaddr *)&a, sizeof(a)); + + (void)umask(old); + if (rc != 0) { + close(fd); + return -1; + } } - (void)chmod(s->path, 0600); if (listen(fd, 8) != 0) { close(fd); unlink(s->path); return -1; } set_nb(fd); s->listen_fd = fd; @@ -120,6 +133,10 @@ try_connect_master(struct swarm *s) close(fd); return -1; } + if (!same_user(fd)) { + close(fd); + return -2; /* someone else's master: not ours to join */ + } set_nb(fd); snprintf(msg, sizeof(msg), "{\"t\":\"hello\",\"pid\":%d}", (int)getpid()); send_line(fd, msg); @@ -143,8 +160,14 @@ swarm_init(struct swarm *s, const char *cwd) if (try_become_master(s) == 0) return 0; /* stale socket? try connect; if connect fails, remove and retry bind */ - if (try_connect_master(s) == 0) + switch (try_connect_master(s)) { + case 0: return 0; + case -2: + return -1; /* another user's socket: neither join nor remove */ + default: + break; + } unlink(s->path); if (try_become_master(s) == 0) return 0; @@ -171,6 +194,10 @@ master_accept(struct swarm *s) if (s->listen_fd < 0) return; fd = accept(s->listen_fd, NULL, NULL); if (fd < 0) return; + if (!same_user(fd)) { + close(fd); + return; + } set_nb(fd); /* find free id, 0 is master */ for (id = 1; id < 1000; id++) { @@ -201,39 +228,49 @@ master_accept(struct swarm *s) static void master_handle_line(struct swarm *s, struct swarm_peer *p, const char *line) { + const char *t; + mcp_json *v = msg_parse(line, &t); + (void)s; - if (strstr(line, "\"hello\"")) { - p->pid = json_get_int(line, "pid", 0); - } else if (strstr(line, "\"status\"")) { - p->busy = json_get_int(line, "busy", p->busy); - } else if (strstr(line, "\"pong\"")) { + if (v == NULL) + return; + if (strcmp(t, "hello") == 0) { + p->pid = mcp_arg_int(v, "pid", 0); + } else if (strcmp(t, "status") == 0) { + p->busy = mcp_arg_int(v, "busy", p->busy); + } else if (strcmp(t, "pong") == 0) { p->alive = 1; } + mcp_json_free(v); } static void slave_handle_line(struct swarm *s, const char *line) { - char text[3800]; - if (strstr(line, "\"welcome\"")) { - s->id = json_get_int(line, "id", s->id); + const char *t, *text; + mcp_json *v = msg_parse(line, &t); + + if (v == NULL) + return; + if (strcmp(t, "welcome") == 0) { + s->id = mcp_arg_int(v, "id", s->id); s->locked = 1; - } else if (strstr(line, "\"exec\"")) { - json_get_str(line, "text", text, sizeof(text)); - if (text[0]) { + } else if (strcmp(t, "exec") == 0) { + text = mcp_arg_string(v, "text"); + if (text != NULL && text[0] != '\0') { snprintf(s->inbox, sizeof(s->inbox), "%s", text); s->has_inbox = 1; s->inbox_remote = 1; } - } else if (strstr(line, "\"unlock\"")) { + } else if (strcmp(t, "unlock") == 0) { s->locked = 0; - } else if (strstr(line, "\"lock\"")) { + } else if (strcmp(t, "lock") == 0) { s->locked = 1; - } else if (strstr(line, "\"ping\"")) { + } else if (strcmp(t, "ping") == 0) { send_line(s->master_fd, "{\"t\":\"pong\"}"); - } else if (strstr(line, "\"result\"") || strstr(line, "\"event\"")) { - /* master receives results in its own inbox/handling path as needed */ } + /* "result" and "event" are not handled by a slave */ + mcp_json_free(v); } static void diff --git a/src/backend/telegram.c b/src/backend/telegram.c index c1aa0df..f9d361e 100644 --- a/src/backend/telegram.c +++ b/src/backend/telegram.c @@ -35,6 +35,7 @@ #include "ack.h" #include "curl.h" #include "splinter.h" +#include "splinter_engine.h" #include "i18n.h" #include "mcp.h" #include "log.h" @@ -441,19 +442,35 @@ send_upload(const char *token, const char *method, const char *field, return -1; if (err == NULL) err = &sink; + /* + * curl -F reads ';type=', ';filename=', quotes and commas inside the + * value after '@': a path with any of them would name other files or + * headers. Text fields go as --form-string, which takes '<' and '@' + * literally. + */ + if (path == NULL || strcmp(path, "-") == 0 || + strpbrk(path, ";,\"\\\r\n") != NULL || + strlen(path) + strlen(field) + 2 >= sizeof(pbuf)) { + sp_buf_printf(err, "telegram: refusing to upload '%.200s'", + path != NULL ? path : ""); + sp_buf_free(&u); + sp_buf_free(&reply); + sp_buf_free(&sink); + return -1; + } sp_buf_printf(&u, "%s/bot%s/%s", api_base(), token, method); snprintf(idbuf, sizeof(idbuf), "chat_id=%ld", chat_id); snprintf(pbuf, sizeof(pbuf), "%s=@%s", field, path); args[n++] = "-sS"; args[n++] = "-m"; args[n++] = "120"; - args[n++] = "-F"; + args[n++] = "--form-string"; args[n++] = idbuf; args[n++] = "-F"; args[n++] = pbuf; if (caption != NULL && *caption != '\0') { snprintf(cbuf, sizeof(cbuf), "caption=%.1000s", caption); - args[n++] = "-F"; + args[n++] = "--form-string"; args[n++] = cbuf; } args[n] = NULL; @@ -1016,8 +1033,8 @@ tg_interview_begin(const char *token, long chat_id, struct sp_agent *ag, struct sp_buf msg, answer; if (tg_iv_active) { - (void)send_message(token, chat_id, - "the interview is already running", err); + (void)send_message(token, chat_id, sp_td("tg.interview.running", + "the interview is already running"), err); return; } tg_iv_orig = ag->cfg; @@ -1044,7 +1061,7 @@ tg_interview_begin(const char *token, long chat_id, struct sp_agent *ag, if (answer.p != NULL && sp_interview_capture( ag->sess != NULL ? ag->sess->dir : NULL, answer.p, clean, sizeof(clean))) { - snprintf(note, sizeof(note), sp_td("interview.saved", + snprintf(note, sizeof(note), "%s", sp_td("interview.saved", "interview saved to USER.txt")); (void)send_markdown(token, chat_id, clean, NULL, err); (void)send_message(token, chat_id, note, err); @@ -1219,6 +1236,7 @@ tg_model_named(const char *token, long chat_id, struct sp_agent *ag, struct tg_pick { char provider[64]; + char kind[16]; /* the wire shape: openai, anthropic, cli */ char endpoint[512]; char model[256]; char key_env[64]; @@ -1278,6 +1296,8 @@ tg_model_pick_menu(const char *token, long chat_id, struct sp_config *conf, break; snprintf(tg_picks[tg_npicks].provider, sizeof( tg_picks[0].provider), "%s", p.id); + snprintf(tg_picks[tg_npicks].kind, sizeof( + tg_picks[0].kind), "%s", p.kind); snprintf(tg_picks[tg_npicks].endpoint, sizeof( tg_picks[0].endpoint), "%s", p.endpoint); snprintf(tg_picks[tg_npicks].model, sizeof( @@ -1325,6 +1345,7 @@ tg_model_pick_use(const char *token, long chat_id, struct sp_agent *ag, } memset(&p, 0, sizeof(p)); snprintf(p.id, sizeof(p.id), "%s", tg_picks[idx].provider); + snprintf(p.kind, sizeof(p.kind), "%s", tg_picks[idx].kind); snprintf(p.endpoint, sizeof(p.endpoint), "%s", tg_picks[idx].endpoint); snprintf(p.model, sizeof(p.model), "%s", tg_picks[idx].model); @@ -1625,6 +1646,12 @@ tg_new_conversation(const char *token, long chat_id, struct sp_agent *ag, return; } sp_buf_free(&serr); + /* /new also leaves an interview: the normal prompt comes back */ + if (tg_iv_active) { + if (tg_iv_orig != NULL) + ag->cfg = tg_iv_orig; + tg_iv_active = 0; + } if (sp_conv_reset(ag->conv, ag->cfg->system_prompt) != 0) { (void)send_message(token, chat_id, sp_t("err.oom"), err); return; @@ -2152,7 +2179,25 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token, tg_cur.token = token; tg_cur.chat_id = chat_id; tg_cur.allow = allow; - if (sp_agent_run(ag, text, &answer, &aerr) != 0) { + if (sp_engine_agent_turn_begin(ag) != 0) { + (void)send_message(token, chat_id, + sp_td("tg.busy", "busy - a turn is running"), + err); + if (typing_on) { + tstop = 1; + (void)pthread_join(tty, NULL); + } + sp_buf_clear(err); + continue; + } + { + int trc = sp_agent_run(ag, text, &answer, &aerr); + + sp_engine_agent_turn_end(ag); + if (trc == 0) + goto tg_turn_ok; + } + { (void)send_message(token, chat_id, aerr.p != NULL ? aerr.p : "turn failed", err); @@ -2163,6 +2208,7 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token, sp_buf_clear(err); continue; } +tg_turn_ok: if (typing_on) { tstop = 1; (void)pthread_join(tty, NULL); @@ -2173,8 +2219,8 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token, if (sp_interview_capture( ag->sess != NULL ? ag->sess->dir : NULL, answer.p, clean, sizeof(clean))) { - snprintf(note, sizeof(note), sp_td( - "interview.saved", + snprintf(note, sizeof(note), "%s", + sp_td("interview.saved", "interview saved to USER.txt")); (void)send_markdown(token, chat_id, clean, NULL, err); diff --git a/src/backend/tgmd.c b/src/backend/tgmd.c index 6c50c53..41c157a 100644 --- a/src/backend/tgmd.c +++ b/src/backend/tgmd.c @@ -673,45 +673,64 @@ tag_at(const char *s, size_t len, size_t pos, size_t *end, char *name, static int push_open(struct sp_tgmd_cursor *c, const char *lit, size_t litlen, - const char *name) + const char *name, int dropped) { struct sp_tgmd_open *o; - char *copy; + char *copy = NULL; if (c->nopen >= TGMD_MAX_OPEN) return 0; - copy = malloc(litlen + 1); - if (copy == NULL) - return -1; - memcpy(copy, lit, litlen); - copy[litlen] = '\0'; + if (!dropped) { + copy = malloc(litlen + 1); + if (copy == NULL) + return -1; + memcpy(copy, lit, litlen); + copy[litlen] = '\0'; + } o = &c->open[c->nopen++]; snprintf(o->name, sizeof(o->name), "%s", name); o->lit = copy; - o->litlen = litlen; + o->litlen = dropped ? 0 : litlen; + o->dropped = dropped; return 0; } -static void +/* Returns 1 when the matching opening tag was dropped (so is the close). */ +static int pop_open(struct sp_tgmd_cursor *c, const char *name) { - size_t i, j; + size_t i, j; + int dropped; if (c->nopen == 0) - return; + return 0; if (strcmp(c->open[c->nopen - 1].name, name) == 0) { + dropped = c->open[c->nopen - 1].dropped; free(c->open[--c->nopen].lit); - return; + return dropped; } /* the renderer nests, so this is only a guard against odd input */ for (i = c->nopen; i-- > 0; ) { if (strcmp(c->open[i].name, name) != 0) continue; + dropped = c->open[i].dropped; for (j = i; j < c->nopen; j++) free(c->open[j].lit); c->nopen = i; - return; + return dropped; } + return 0; +} + +/* Bytes the still-open tags cost at the start of every piece. */ +static size_t +open_cost(const struct sp_tgmd_cursor *c) +{ + size_t i, n = 0; + + for (i = 0; i < c->nopen; i++) + n += c->open[i].litlen; + return n; } /* Never cut a UTF-8 character or an entity in half: both become mojibake. */ @@ -744,7 +763,8 @@ sp_tgmd_next(struct sp_tgmd_cursor *c, size_t limit, struct sp_buf *out) return 0; sp_buf_clear(out); for (i = 0; i < c->nopen; i++) - if (sp_buf_add(out, c->open[i].lit, c->open[i].litlen) != 0) + if (!c->open[i].dropped && sp_buf_add(out, c->open[i].lit, + c->open[i].litlen) != 0) return -1; prefix = out->len; while (c->pos < c->len) { @@ -756,13 +776,25 @@ sp_tgmd_next(struct sp_tgmd_cursor *c, size_t limit, struct sp_buf *out) &closing)) { size_t len = end - c->pos; - if (out->len + len > limit && out->len > prefix) + int drop = 0; + + /* + * An opening tag is repeated at the start of every + * later piece; one that eats more than half the budget + * (a link with a huge URL) would leave no room for text + * and the loop would never advance. Send its content + * as plain text instead. + */ + if (!closing && open_cost(c) + len > limit / 2) + drop = 1; + if (!drop && out->len + len > limit && out->len > prefix) break; if (closing) - pop_open(c, name); - else if (push_open(c, c->html + c->pos, len, name) != 0) + drop = pop_open(c, name); + else if (push_open(c, c->html + c->pos, len, name, + drop) != 0) return -1; - if (sp_buf_add(out, c->html + c->pos, len) != 0) + if (!drop && sp_buf_add(out, c->html + c->pos, len) != 0) return -1; c->pos = end; continue; @@ -795,7 +827,8 @@ sp_tgmd_next(struct sp_tgmd_cursor *c, size_t limit, struct sp_buf *out) } if (c->pos >= c->len) { for (i = c->nopen; i-- > 0; ) - if (sp_buf_printf(out, "", c->open[i].name) != 0) + if (!c->open[i].dropped && + sp_buf_printf(out, "", c->open[i].name) != 0) return -1; for (i = 0; i < c->nopen; i++) free(c->open[i].lit); @@ -803,7 +836,8 @@ sp_tgmd_next(struct sp_tgmd_cursor *c, size_t limit, struct sp_buf *out) return 1; } for (i = c->nopen; i-- > 0; ) - if (sp_buf_printf(out, "", c->open[i].name) != 0) + if (!c->open[i].dropped && + sp_buf_printf(out, "", c->open[i].name) != 0) return -1; return 1; } diff --git a/src/backend/tgmd.h b/src/backend/tgmd.h index 1135165..d276e2b 100644 --- a/src/backend/tgmd.h +++ b/src/backend/tgmd.h @@ -31,6 +31,7 @@ struct sp_tgmd_cursor { char name[12]; char *lit; /* the opening tag, as written */ size_t litlen; + int dropped; /* too long to repeat: neither tag sent */ } open[16]; size_t nopen; }; diff --git a/src/backend/transport.c b/src/backend/transport.c index e520664..e2e7321 100644 --- a/src/backend/transport.c +++ b/src/backend/transport.c @@ -203,24 +203,28 @@ mock_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, else sp_buf_puts(&m->last_request, "user \n"); + /* + * The queued body is taken, not copied: sp_mock_free only frees what + * is still queued (head..len), so a copy leaked every consumed reply. + */ out->status = m->queue[m->head].status; - if (out->status < 200 || out->status > 299) { - out->content = strdup(m->queue[m->head].content); - m->head++; - return out->content != NULL ? 0 : -1; - } { - char *body = strdup(m->queue[m->head].content); + char *body = m->queue[m->head].content; + int rc; + free(m->queue[m->head].calls); + m->queue[m->head].calls = NULL; + m->queue[m->head].content = NULL; m->head++; if (body == NULL) return -1; - { - int rc = parse_line(body, out, err); - - free(body); - return rc; + if (out->status < 200 || out->status > 299) { + out->content = body; + return 0; } + rc = parse_line(body, out, err); + free(body); + return rc; } } diff --git a/src/backend/transport_anthropic.c b/src/backend/transport_anthropic.c index 128ccf6..41b7f2a 100644 --- a/src/backend/transport_anthropic.c +++ b/src/backend/transport_anthropic.c @@ -216,14 +216,11 @@ as_curl(const struct as_ctx *c, const char *body_path, int stream, args[n++] = "Content-Type: application/json"; args[n++] = "--data-binary"; args[n++] = data; + /* the status and Retry-After come from this file, not from the body */ if (hdr_path != NULL && *hdr_path != '\0') { args[n++] = "-D"; args[n++] = hdr_path; } - if (!stream) { - args[n++] = "-w"; - args[n++] = "\n%{http_code}"; - } args[n] = NULL; hdrs[nh++] = "Accept: application/json, text/event-stream"; @@ -372,7 +369,7 @@ as_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, sp_log_wire(sp_log_dir(), "response", raw.p != NULL ? raw.p : "", raw.len); if (status == 0) { - /* no -w in a streamed request: the code is in the body */ + /* the -D header file is missing or curl never got an answer */ sp_buf_puts(err, "anthropic: unparseable response (no status)"); finish_request(path, hdr_path); goto out; @@ -414,7 +411,7 @@ as_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, char path[512], hdr_path[540]; FILE *p; pid_t child = -1; - int rc = -1, saw_data = 0; + int rc = -1, saw_data = 0, curl_failed = 0; long status = 0, retry_after = 0; if (c == NULL) @@ -531,9 +528,11 @@ as_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, } fclose(p); { - int st; + int st = 0; - (void)waitpid(child, &st, 0); + if (waitpid(child, &st, 0) < 0 || !WIFEXITED(st) || + WEXITSTATUS(st) != 0) + curl_failed = 1; } (void)parse_status_file(hdr_path, &status, &retry_after); parse_served_by(hdr_path, out->served_by, sizeof(out->served_by)); @@ -546,11 +545,25 @@ as_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, sp_buf_printf(err, "anthropic: HTTP %ld", status); goto out; } + /* + * curl died (timeout, reset): what arrived is a fragment, and a + * fragment must not pass for the whole answer. + */ + if (curl_failed) { + sp_buf_printf(err, "anthropic: stream failed for %s: %.300s", + c->url, tail.p != NULL ? tail.p : ""); + goto out; + } if (!saw_data) { sp_buf_printf(err, "anthropic: endpoint sent no SSE data: %.300s", tail.p != NULL ? tail.p : "(empty)"); goto out; } + if (!sp_as_sse_done(sse)) { + sp_buf_printf(err, "anthropic: stream ended before " + "message_stop: %.300s", tail.p != NULL ? tail.p : ""); + goto out; + } if (sp_as_sse_finish(sse, out, err) != 0) goto out; /* a step that only called tools said nothing: no empty record */ diff --git a/src/backend/transport_openai.c b/src/backend/transport_openai.c index 692db97..799f2dd 100644 --- a/src/backend/transport_openai.c +++ b/src/backend/transport_openai.c @@ -10,8 +10,9 @@ * command line, so no quoting can corrupt a prompt; * - the API key travels as a header built from the environment, and the * command string that carries it is never logged by this code; - * - the HTTP status comes from curl's own -w output, so a 429 is a 429 and - * not an empty success. + * - the HTTP status comes from curl's own -w output (a plain request) or + * from the -D header file (a stream), so a 429 is a 429 and not an empty + * success; Retry-After comes from the header file in both cases. */ #include #include @@ -335,6 +336,36 @@ parse_retry_after_file(const char *path) return ra > 0 ? ra : 0; } +/* + * The status of the last response in a -D header file. curl writes every + * response it saw (a "100 Continue", a proxy's CONNECT) one after another; + * the last status line is the one that carried the body. + */ +static long +parse_status_file(const char *path) +{ + FILE *f; + char line[512]; + long st = 0; + + if (path == NULL || *path == '\0') + return 0; + f = fopen(path, "r"); + if (f == NULL) + return 0; + while (fgets(line, sizeof(line), f)) { + char *sp; + + if (strncmp(line, "HTTP/", 5) != 0) + continue; + sp = strchr(line, ' '); + if (sp != NULL) + st = strtol(sp + 1, NULL, 10); + } + fclose(f); + return st; +} + static int openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, struct sp_buf *err) @@ -390,6 +421,7 @@ openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, p = openai_curl(c, path, 0, &child, err, hdr_path[0]?hdr_path:NULL); if (p == NULL) { unlink(path); + if (hdr_path[0]) unlink(hdr_path); goto out; } if (read_all_cancel(p, &raw, g_cancel, child) != 0) { @@ -475,16 +507,25 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, ssize_t w; size_t n; int saw_data = 0; + long hstatus = 0; + hdr_path[0] = '\0'; if (c == NULL) return -1; + memset(&body, 0, sizeof(body)); + memset(&cmd, 0, sizeof(cmd)); + memset(&tail, 0, sizeof(tail)); + memset(&delta, 0, sizeof(delta)); + sse = NULL; if (sp_buf_init(&body) != 0 || sp_buf_init(&cmd) != 0 || - sp_buf_init(&tail) != 0 || sp_buf_init(&delta) != 0) - return -1; + sp_buf_init(&tail) != 0 || sp_buf_init(&delta) != 0) { + sp_buf_puts(err, sp_td("openai.oom", "openai: out of memory")); + goto out; + } sse = sp_sse_new(); if (sse == NULL) { sp_buf_puts(err, sp_td("openai.oom", "openai: out of memory")); - return -1; + goto out; } if (sp_openai_request_opts(conv, c->model, c->reg, 1, c->have_gen ? &c->gen : NULL, &body) != 0) { @@ -494,7 +535,6 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, } temp_template(path, sizeof(path), "sse"); - hdr_path[0] = '\0'; { int hfd; @@ -676,16 +716,35 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, int st; fclose(p); + /* + * curl writes the status into the -D file, not into the + * stream: without reading it a 429 looked like an endpoint + * that sent no SSE data, with no status for the backoff. + */ if (waitpid(child, &st, 0) < 0 || !WIFEXITED(st) || WEXITSTATUS(st) != 0) { + hstatus = parse_status_file(hdr_path); + if (hstatus != 0 && (hstatus < 200 || hstatus > 299)) + out->status = hstatus; sp_buf_printf(err, sp_td("openai.stream_failed", "openai: stream failed for %s: %.300s"), c->url, tail.p != NULL ? tail.p : ""); unlink(path); goto out; } + hstatus = parse_status_file(hdr_path); + if (hdr_path[0] != '\0') + out->retry_after_s = parse_retry_after_file(hdr_path); } unlink(path); + if (hstatus != 0 && (hstatus < 200 || hstatus > 299)) { + out->status = hstatus; + sp_buf_printf(err, sp_td("openai.http_status", + "openai: HTTP %ld from %s: %.300s"), hstatus, c->url, + tail.p != NULL && tail.len > 0 ? tail.p : "(empty)"); + goto out; + } + if (!saw_data) { sp_buf_printf(err, sp_td("openai.no_sse", "openai: endpoint sent no SSE data: %.300s"), tail.p != NULL ? tail.p : "(empty)"); @@ -693,6 +752,8 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, } if (sp_sse_finish(sse, out, err) != 0) goto out; + if (hstatus != 0) + out->status = hstatus; /* a step that only called tools said nothing: no empty record */ if (out->content != NULL && out->content[0] != '\0') sp_logf("reply", "%s", out->content); @@ -710,7 +771,8 @@ out: parse_judge_headers(hdr_path, out); unlink(hdr_path); } - sp_sse_free(sse); + if (sse != NULL) + sp_sse_free(sse); sp_buf_free(&body); sp_buf_free(&cmd); sp_buf_free(&tail); diff --git a/src/frontend/curses.c b/src/frontend/curses.c index 1712ad3..06b3363 100644 --- a/src/frontend/curses.c +++ b/src/frontend/curses.c @@ -48,6 +48,7 @@ #include #include #include +#include #include #include @@ -1663,9 +1664,20 @@ layout(void) if (in_h < 1) in_h = 1; ui_input_h = in_h; + /* + * A terminal of a few rows still gets every window, overlapping if it + * must: a window cut below the screen is NULL and every draw would + * dereference it. + */ + if (rows < 1) + rows = 1; + if (cols < 1) + cols = 1; chat_rows = rows - 1 - in_h; - if (chat_rows < 2) - chat_rows = 2; + if (chat_rows < 1) + chat_rows = 1; + if (chat_rows > rows) + chat_rows = rows; { int side_w = cols / 4; int chat_w = cols - side_w - 1; @@ -1685,6 +1697,8 @@ layout(void) */ ui_gap = side_w > 0 ? newwin(chat_rows, 1, 0, chat_w) : NULL; } + if (ui_hist == NULL) + ui_hist = newwin(1, cols, 0, 0); wbkgd(ui_hist, COLOR_PAIR(PAIR_MAIN)); if (ui_side != NULL) wbkgd(ui_side, COLOR_PAIR(PAIR_SIDE)); @@ -1693,9 +1707,16 @@ layout(void) werase(ui_gap); } /* the meter line sits above the input, like a status bar */ - ui_status = newwin(1, cols, chat_rows, 0); + ui_status = newwin(1, cols, chat_rows < rows ? chat_rows : rows - 1, 0); + if (ui_status == NULL) + ui_status = newwin(1, cols, 0, 0); wbkgd(ui_status, COLOR_PAIR(PAIR_STATUS)); - ui_input = newwin(in_h, cols, chat_rows + 1, 0); + if (in_h > rows) + in_h = rows; + ui_input = newwin(in_h, cols, chat_rows + 1 + in_h <= rows ? + chat_rows + 1 : rows - in_h, 0); + if (ui_input == NULL) + ui_input = newwin(1, cols, 0, 0); wbkgd(ui_input, COLOR_PAIR(PAIR_INPUT)); keypad(ui_input, TRUE); /* a one-line window that may scroll is a screen that jumps */ @@ -1737,12 +1758,255 @@ redraw(struct ui_state *s, const struct ui_backend *be) doupdate(); } -/* xterm's modifyOtherKeys: makes Shift+Enter a distinct sequence */ +/* + * Terminal modes beyond what curses sets up: xterm's modifyOtherKeys at + * level 1 (Shift+Enter becomes a distinct sequence; Ctrl-C, Ctrl-D and + * Ctrl-L stay plain control bytes, which level 2 did not) and SGR mouse + * reporting for the wheel. The vendored curses has no mouse support, so the + * reports are decoded by ui_getkey() below. + */ +#define TERM_MODES_ON "\033[>4;1m\033[?1000h\033[?1006h" +#define TERM_MODES_OFF "\033[?1006l\033[?1000l\033[>4;0m" + +static volatile sig_atomic_t term_modes_set; + static void -modify_keys(int on) +write_all(const char *p, size_t n) { - fputs(on ? "\033[>4;2m" : "\033[>4;0m", stdout); + ssize_t w; + + while (n > 0) { + w = write(STDOUT_FILENO, p, n); + if (w < 0) { + if (errno == EINTR) + continue; + return; + } + p += w; + n -= (size_t)w; + } +} + +static void +term_modes(int on) +{ + if (!on && !term_modes_set) + return; + /* what curses still buffers goes first, then our bytes */ fflush(stdout); + if (on) + write_all(TERM_MODES_ON, sizeof(TERM_MODES_ON) - 1); + else + write_all(TERM_MODES_OFF, sizeof(TERM_MODES_OFF) - 1); + term_modes_set = on; +} + +static void +term_modes_atexit(void) +{ + term_modes(0); +} + +static void term_signals(void); + +/* + * Keys the decoder hands back besides the curses ones. They are above every + * KEY_* value; a loop that does not know one ignores it. + */ +#define UK_NONE 0x2000 /* a sequence that was read and dropped */ +#define UK_NEWLINE 0x2001 /* Shift/Alt/Ctrl+Enter: a line break */ +#define UK_WHEEL_UP 0x2002 +#define UK_WHEEL_DOWN 0x2003 +#define WHEEL_STEP 3 + +/* a key reported with an xterm modifier (1 + shift|alt<<1|ctrl<<2) */ +static int +key_unmodify(long code, long mod) +{ + int bits = mod > 1 ? (int)(mod - 1) : 0; + int shift = bits & 1, alt = bits & 2, ctrl = bits & 4; + + if (code == 13 || code == 10) + return bits != 0 ? UK_NEWLINE : '\r'; + if (code == 9) + return bits == 0 ? '\t' : (bits == 1 ? KEY_BTAB : UK_NONE); + if (code == 127 || code == 8) + return alt ? UK_NONE : 127; + if (code == 27) + return 27; + if (alt) + return UK_NONE; + if (ctrl) { + if (code >= 'a' && code <= 'z') + return (int)(code - 'a' + 1); + if (code >= '@' && code <= '_') + return (int)(code & 0x1f); + return UK_NONE; + } + (void)shift; + if (code >= 32 && code < 127) + return (int)code; + return UK_NONE; +} + +/* the leading number of each ';'-separated field ("27;5;99", "<64;3;9") */ +static int +csi_params(const char *p, long *v, int max) +{ + int n = 0; + + if (*p == '<' || *p == '?' || *p == '>') + p++; + while (n < max) { + long x = 0; + + while (*p >= '0' && *p <= '9') { + if (x < 100000) + x = x * 10 + (*p - '0'); + p++; + } + v[n++] = x; + while (*p != '\0' && *p != ';') + p++; + if (*p != ';') + break; + p++; + } + return n; +} + +static int +mouse_button(long b, int press) +{ + /* shift, alt and ctrl ride along in bits 2..4 */ + b &= ~28L; + if (!press) + return UK_NONE; + if (b == 64) + return UK_WHEEL_UP; + if (b == 65) + return UK_WHEEL_DOWN; + return UK_NONE; +} + +/* the rest of a CSI sequence: parameters up to the final byte */ +static int +read_csi(WINDOW *w, char *seq, size_t cap, size_t n) +{ + int c, k; + + for (k = 0; k < 64; k++) { + c = wgetch(w); + if (c == ERR || c < 0 || c > 0xff) + return 0; + if (c >= 0x40 && c <= 0x7e) + return c; + if (n + 1 < cap) + seq[n++] = (char)c; + seq[n] = '\0'; + } + return 0; +} + +/* an X10 mouse report: three raw bytes after ESC [ M */ +static int +read_x10(WINDOW *w) +{ + int b = wgetch(w); + + (void)wgetch(w); + (void)wgetch(w); + if (b == ERR) + return UK_NONE; + return mouse_button((long)b - 32, 1); +} + +static int +decode_csi(WINDOW *w, const char *lead) +{ + char seq[40]; + long v[4]; + int fin, np; + + snprintf(seq, sizeof(seq), "%s", lead); + fin = read_csi(w, seq, sizeof(seq), strlen(seq)); + if (fin == 0) + return UK_NONE; + if (seq[0] == '<') { + if (fin != 'M' && fin != 'm') + return UK_NONE; + np = csi_params(seq, v, 4); + return np >= 1 ? mouse_button(v[0], fin == 'M') : UK_NONE; + } + if (fin == 'M' && seq[0] == '\0') + return read_x10(w); + if (seq[0] == '?' || seq[0] == '>') + return UK_NONE; + np = csi_params(seq, v, 4); + if (fin == '~') { + if (np == 3 && v[0] == 27) + return key_unmodify(v[2], v[1]); + if (np == 2 && v[0] == 13 && v[1] >= 2) + return UK_NEWLINE; + return UK_NONE; + } + if (fin == 'u' && seq[0] != '\0') + return key_unmodify(v[0], np >= 2 ? v[1] : 1); + return UK_NONE; +} + +/* + * One key from a window, with every escape sequence curses did not know + * decoded here: modifyOtherKeys (CSI 27;mod;code ~), the CSI u form, the + * SGR mouse wheel. A sequence that means nothing to us is read to its end + * and dropped; none of its bytes reaches a prompt. A lone ESC stays 27. + * restore_ms is the timeout the caller had set on the window. + */ +static int +ui_getkey(WINDOW *w, int restore_ms) +{ + int c, c2, r; + + c = wgetch(w); + if (c != 27 && c != KEY_MOUSE) + return c; + wtimeout(w, 60); + if (c == KEY_MOUSE) { + /* a terminfo kmous of "\E[<" or "\E[M" got there first */ + c2 = wgetch(w); + if (c2 == '<' || (c2 >= '0' && c2 <= '9')) { + char lead[3]; + + lead[0] = '<'; + lead[1] = c2 == '<' ? '\0' : (char)c2; + lead[2] = '\0'; + r = decode_csi(w, lead); + } else if (c2 == ERR) { + r = UK_NONE; + } else { + (void)wgetch(w); + (void)wgetch(w); + r = mouse_button((long)c2 - 32, 1); + } + } else { + c2 = wgetch(w); + if (c2 == ERR) + r = 27; + else if (c2 == '\r' || c2 == '\n') + r = UK_NEWLINE; /* Alt+Enter */ + else if (c2 == '[') + r = decode_csi(w, ""); + else if (c2 == 'O') { + (void)wgetch(w); /* SS3 curses did not know */ + r = UK_NONE; + } else if (c2 == 27) { + ungetch(c2); + r = 27; + } else + r = UK_NONE; /* Alt+key */ + } + wtimeout(w, restore_ms); + return r; } /* @@ -2059,7 +2323,7 @@ model_picker(const struct ui_backend *be, char *sel, size_t cap) if (listh > 0 && cur >= top + (size_t)listh) top = cur - (size_t)listh + 1; pick_draw(win, &list, match, nmatch, cur, top, filter); - c = wgetch(win); + c = ui_getkey(win, -1); if (c == 27 || c == 3 || c == 4) break; if (c == '\n' || c == '\r' || c == KEY_ENTER) { @@ -2077,10 +2341,10 @@ model_picker(const struct ui_backend *be, char *sel, size_t cap) if (win == NULL) break; changed = 1; - } else if (c == KEY_UP || c == 16) { + } else if (c == KEY_UP || c == 16 || c == UK_WHEEL_UP) { if (cur > 0) cur--; - } else if (c == KEY_DOWN || c == 14) { + } else if (c == KEY_DOWN || c == 14 || c == UK_WHEEL_DOWN) { if (nmatch > 0 && cur + 1 < nmatch) cur++; } else if (c == KEY_PPAGE) { @@ -2155,7 +2419,7 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, return; } } - ch = wgetch(ui_input); + ch = ui_getkey(ui_input, 500); if (ch == ERR) { { char msg[200]; @@ -2190,35 +2454,9 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, doupdate(); continue; } - if (ch == 27) { - char seq[16]; - int n = 0, c2, newline = 0; - - wtimeout(ui_input, 60); - c2 = wgetch(ui_input); - if (c2 == '\r' || c2 == '\n') { - newline = 1; /* Alt+Enter */ - } else if (c2 == '[') { - seq[n++] = (char)c2; - while (n < 15) { - c2 = wgetch(ui_input); - if (c2 == ERR) - break; - seq[n++] = (char)c2; - /* a CSI sequence ends at 0x40..0x7e */ - if (c2 >= '@' && c2 <= '~') - break; - } - seq[n] = '\0'; - if (strstr(seq, "[13;2u") != NULL || - strstr(seq, "[13;2~") != NULL || - strstr(seq, "[27;2;13~") != NULL) - newline = 1; - } else if (c2 != ERR) { - ungetch(c2); /* a lone ESC, not ours */ - } - wtimeout(ui_input, 500); - if (newline && !locked && len + 1 < cap) { + if (ch == UK_NEWLINE) { + /* Shift+Enter (Alt+Enter): a line break, not a send */ + if (!locked && len + 1 < cap) { input[len++] = '\n'; input[len] = '\0'; draw_prompt(s, input); @@ -2226,24 +2464,23 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, } continue; } - if (ch == KEY_MOUSE) { - MEVENT me; - - if (getmouse(&me) == OK) { - if (me.bstate & BUTTON4_PRESSED) - s->scroll += 3; - else if (me.bstate & BUTTON5_PRESSED) - s->scroll = s->scroll > 3 ? - s->scroll - 3 : 0; - draw_history(s); - s->painted = s->gen; - draw_sidebar(s, SESS_ID(be), SESS_DIR(be), - host); - draw_statusbar(s); + if (ch == UK_WHEEL_UP || ch == UK_WHEEL_DOWN) { + if (ch == UK_WHEEL_UP) + s->scroll += WHEEL_STEP; + else + s->scroll = s->scroll > WHEEL_STEP ? + s->scroll - WHEEL_STEP : 0; + draw_history(s); + s->painted = s->gen; + draw_sidebar(s, SESS_ID(be), SESS_DIR(be), host); + draw_statusbar(s); + if (locked) { + werase(ui_input); + mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); + } else draw_prompt(s, input); - wnoutrefresh(ui_input); - doupdate(); - } + wnoutrefresh(ui_input); + doupdate(); continue; } if (ch == '\n' || ch == '\r' || ch == KEY_ENTER) { @@ -2361,6 +2598,22 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, if (locked || n < 2) continue; + /* + * A turn still running (another client's, a swarm's) + * owns the agent: switching under it frees what the + * turn is using. + */ + if (s->turn_running || be->busy(be->ctx)) { + add_entry(s, "splinter", sp_td("ui.agent_busy", + "a turn is running; switch the agent when " + "it is done")); + draw_history(s); + s->painted = s->gen; + draw_prompt(s, input); + wnoutrefresh(ui_input); + doupdate(); + continue; + } (void)be->agent_switch(be->ctx, ch == '\t' ? (cur + 1) % n : (cur + n - 1) % n); sync_state(s); @@ -2563,7 +2816,7 @@ ui_command_run(struct ui_state *s, const char *line, struct sp_buf *reply, if (command_done(&j)) break; - c = wgetch(ui_input); + c = ui_getkey(ui_input, 100); if (s->quit) break; if (c == ERR) { @@ -2613,7 +2866,12 @@ ui_command_run(struct ui_state *s, const char *line, struct sp_buf *reply, if (queued[0] != '\0') { /* a queued line is not edited here */ } else if (elen > 0) { - edit[--elen] = '\0'; + /* a whole UTF-8 sequence, not a byte */ + do + elen--; + while (elen > 0 && ((unsigned char) + edit[elen] & 0xc0) == 0x80); + edit[elen] = '\0'; } draw_command_line(queued[0] != '\0' ? queued : edit, queued[0] != '\0' ? strlen(queued) : @@ -3051,20 +3309,13 @@ turn_key(struct ui_state *s, struct turn_view *v, int c) redraw(s, s->be); return 0; } - if (c == KEY_MOUSE) { - MEVENT me; - - if (getmouse(&me) == OK) { - if (me.bstate & BUTTON4_PRESSED) - s->scroll += 3; - else if (me.bstate & BUTTON5_PRESSED) - s->scroll = s->scroll > 3 ? s->scroll - 3 : 0; - draw_history(s); - s->painted = s->gen; - draw_sidebar(s, SESS_ID(s->be), SESS_DIR(s->be), - s->be->host(s->be->ctx)); - draw_statusbar(s); - } + if (c == UK_WHEEL_UP || c == UK_WHEEL_DOWN) { + if (c == UK_WHEEL_UP) + s->scroll += WHEEL_STEP; + else + s->scroll = s->scroll > WHEEL_STEP ? + s->scroll - WHEEL_STEP : 0; + redraw(s, s->be); return 0; } /* @@ -3106,7 +3357,12 @@ turn_key(struct ui_state *s, struct turn_view *v, int c) return 0; } if ((c == KEY_BACKSPACE || c == 127 || c == 8) && v->llen > 0) { - v->line[--v->llen] = '\0'; + /* a whole UTF-8 sequence, not a byte */ + do + v->llen--; + while (v->llen > 0 && + ((unsigned char)v->line[v->llen] & 0xc0) == 0x80); + v->line[v->llen] = '\0'; return 0; } if (c >= 32 && c < 256 && c != 127 && v->llen < sizeof(v->line) - 2) { @@ -3150,7 +3406,9 @@ ui_turn(struct ui_state *s, const char *text) drain_events(s, &v); if (!s->be->busy(s->be->ctx)) break; - c = wgetch(ui_input); + c = ui_getkey(ui_input, 100); + if (c == UK_NONE) + continue; if (turn_approval(s, c)) continue; if (c == ERR) { @@ -3178,9 +3436,9 @@ ui_turn(struct ui_state *s, const char *text) drain_events(s, &v); turn_draw_input(s, &v); - c2 = wgetch(ui_input); + c2 = ui_getkey(ui_input, 100); if (c2 == 3 || c2 == 4) { - modify_keys(0); + term_modes(0); endwin(); tmux_title_reset(); _exit(1); @@ -3262,6 +3520,7 @@ ui_start(struct ui_state *s, const struct ui_backend *be, * umlauts and every UTF-8 answer would arrive as replacement characters. */ setlocale(LC_ALL, ""); + term_signals(); initscr(); /* * raw(), not cbreak(): cbreak leaves ISIG on, so the terminal driver turns @@ -3272,9 +3531,7 @@ ui_start(struct ui_state *s, const struct ui_backend *be, raw(); noecho(); keypad(stdscr, TRUE); - modify_keys(1); - mousemask(ALL_MOUSE_EVENTS, NULL); - mouseinterval(0); + term_modes(1); curs_set(1); init_colors(&s->theme); ui_input_h = 1; @@ -3429,18 +3686,44 @@ tmux_title_reset(void) } /* - * A signal is an exit too: put the terminal and the title back before the - * default handler takes over. SIGINT is not ours - raw() turns Ctrl-C into a - * key, and the chat cancels a turn instead of dying. + * A signal is an exit too: put the terminal back before the default handler + * takes over, in tmux or not. Only async-signal-safe calls: the mode resets + * are written with write(), the tty settings from before curses come back + * with tcsetattr(), the alternate screen is left with the xterm sequence. + * raw() turns Ctrl-C into a key, so SIGINT arrives only from kill(1). */ +static struct termios term_saved; +static int term_saved_ok; + static void -tmux_signal(int sig) +term_signal(int sig) { - modify_keys(0); - endwin(); + static const char leave[] = "\033[?1049l\033[?25h\r\n"; + + if (term_modes_set) + write_all(TERM_MODES_OFF, sizeof(TERM_MODES_OFF) - 1); + write_all(leave, sizeof(leave) - 1); + if (term_saved_ok) + (void)tcsetattr(STDIN_FILENO, TCSANOW, &term_saved); tmux_title_reset(); - signal(sig, SIG_DFL); - raise(sig); + (void)signal(sig, SIG_DFL); + (void)raise(sig); +} + +static void +term_signals(void) +{ + static int installed; + + if (installed) + return; + installed = 1; + term_saved_ok = tcgetattr(STDIN_FILENO, &term_saved) == 0; + (void)atexit(term_modes_atexit); + (void)signal(SIGTERM, term_signal); + (void)signal(SIGHUP, term_signal); + (void)signal(SIGINT, term_signal); + (void)signal(SIGQUIT, term_signal); } /* @@ -3514,9 +3797,6 @@ tmux_title(void) } tmux_titled = 1; (void)atexit(tmux_title_reset); - (void)signal(SIGTERM, tmux_signal); - (void)signal(SIGHUP, tmux_signal); - (void)signal(SIGQUIT, tmux_signal); } int @@ -3575,8 +3855,6 @@ sp_ui_run(const struct ui_backend *be, const char *theme_name) continue; } } - if (sp_buf_init(&reply) != 0) - break; if (strcmp(input, "/sessions") == 0) { struct sp_buf list; @@ -3623,8 +3901,13 @@ sp_ui_run(const struct ui_backend *be, const char *theme_name) } sp_buf_free(&err); } + /* no engine to read the next line for */ + if (s.quit) + break; continue; } + if (sp_buf_init(&reply) != 0) + break; kind = ui_command_run(&s, input, &reply, queued, sizeof(queued)); if (kind == SP_INPUT_HANDLED) { /* @@ -3686,7 +3969,7 @@ sp_ui_run(const struct ui_backend *be, const char *theme_name) if (s.quit) break; } - modify_keys(0); + term_modes(0); endwin(); be->close(be->ctx); return 0; diff --git a/src/frontend/protocol.c b/src/frontend/protocol.c index e60485c..dd6737a 100644 --- a/src/frontend/protocol.c +++ b/src/frontend/protocol.c @@ -167,6 +167,8 @@ send_state(struct client *c, struct sp_engine *eng, const char *name) ev_num(&b, "ctx_used", (long)st.ctx_used); ev_num(&b, "ctx_max", (long)st.ctx_max); ev_num(&b, "cached", (long)st.cached); + ev_num(&b, "cached_total", (long)st.cached_total); + ev_num(&b, "cost_uusd", (long)(st.cost * 1e6 + 0.5)); ev_num(&b, "turn_tokens_out", (long)st.turn_tokens_out); ev_num(&b, "steps", (long)st.steps); ev_num(&b, "calls", (long)st.calls); @@ -585,7 +587,7 @@ handle_line(struct client *c, struct proto *p, const char *line) mcp_json *v; const char *cmd, *text; struct sp_buf out; - int handled; + int handled, rc = 0; v = mcp_parse(line); if (v == NULL) { @@ -678,8 +680,10 @@ handle_line(struct client *c, struct proto *p, const char *line) struct sp_buf b, prompt; int prc; - if (drain_to_client(c, eng) != 0) - return -1; + if (drain_to_client(c, eng) != 0) { + rc = -1; + goto done; + } if (sp_buf_init(&prompt) != 0) goto done; (void)sp_buf_puts(&prompt, @@ -700,8 +704,10 @@ handle_line(struct client *c, struct proto *p, const char *line) "a turn is already running"); sp_buf_free(&prompt); } else { - if (drain_to_client(c, eng) != 0) - return -1; + if (drain_to_client(c, eng) != 0) { + rc = -1; + goto done; + } (void)send_reply(c, out.p != NULL ? out.p : ""); } } @@ -739,8 +745,10 @@ handle_line(struct client *c, struct proto *p, const char *line) int n = sp_engine_command_names(eng, names, 64), i; struct sp_buf b; - if (sp_buf_init(&b) != 0) - return -1; + if (sp_buf_init(&b) != 0) { + rc = -1; + goto done; + } ev_start(&b, "commands"); sp_buf_puts(&b, ",\"names\":["); for (i = 0; i < n; i++) { @@ -773,7 +781,7 @@ handle_line(struct client *c, struct proto *p, const char *line) done: sp_buf_free(&out); mcp_json_free(v); - return 0; + return rc; } /* @@ -808,26 +816,22 @@ static int serve_client(struct proto *p, int fd) { struct client c; - struct sp_buf b; - int rc = 0; + int rc = 0, hup = 0; memset(&c, 0, sizeof(c)); c.fd = fd; - if (sp_buf_init(&c.in) != 0 || sp_buf_init(&c.line) != 0 || - sp_buf_init(&b) != 0) { + if (sp_buf_init(&c.in) != 0 || sp_buf_init(&c.line) != 0) { sp_buf_free(&c.in); sp_buf_free(&c.line); return -1; } if (send_ready(&c) != 0 || send_state(&c, p->eng, "state") != 0) { - sp_buf_free(&b); sp_buf_free(&c.in); sp_buf_free(&c.line); return -1; } - sp_buf_free(&b); - while (!c.quit) { + while (!c.quit && !hup) { struct pollfd pfd; int pr; char chunk[4096]; @@ -838,17 +842,20 @@ serve_client(struct proto *p, int fd) pfd.events = POLLIN; pfd.revents = 0; pr = poll(&pfd, 1, 100); - if (pr > 0 && (pfd.revents & (POLLHUP | POLLERR | POLLNVAL))) + if (pr > 0 && (pfd.revents & (POLLERR | POLLNVAL))) break; - if (pr > 0 && (pfd.revents & POLLIN)) { + /* + * A hangup may come with the client's last command still in + * the socket: read until recv() says end of file, run the + * complete lines, then leave. + */ + if (pr > 0 && (pfd.revents & (POLLIN | POLLHUP))) { got = recv(fd, chunk, sizeof(chunk), 0); - if (got <= 0) { - if (got < 0 && (errno == EINTR || - errno == EAGAIN)) - continue; - break; - } - if (sp_buf_add(&c.in, chunk, (size_t)got) != 0) + if (got < 0 && (errno == EINTR || errno == EAGAIN)) + continue; + if (got <= 0) + hup = 1; + else if (sp_buf_add(&c.in, chunk, (size_t)got) != 0) break; } /* complete lines, in the order they arrived. The line grows with @@ -883,7 +890,7 @@ serve_client(struct proto *p, int fd) break; } /* a switch that could not reopen any engine */ - if (p->eng == NULL) + if (p->eng == NULL || hup) break; /* * Even after a quit, drain once: the engine's quit event (and diff --git a/src/frontend/ui_remote.c b/src/frontend/ui_remote.c index de78ad2..735e473 100644 --- a/src/frontend/ui_remote.c +++ b/src/frontend/ui_remote.c @@ -260,11 +260,17 @@ fill_state(struct rem *r, const mcp_json *v) r->st.ctx_used = (size_t)mcp_arg_int(v, "ctx_used", 0); r->st.ctx_max = (size_t)mcp_arg_int(v, "ctx_max", 0); r->st.cached = (size_t)mcp_arg_int(v, "cached", 0); + r->st.cached_total = (size_t)mcp_arg_int(v, "cached_total", 0); + /* micro-USD as an integer: a decimal point would meet strtod() in + * the operator's locale */ + r->st.cost = mcp_arg_num(v, "cost_uusd", 0.0) / 1e6; r->st.turn_tokens_out = (size_t)mcp_arg_int(v, "turn_tokens_out", 0); r->st.steps = (size_t)mcp_arg_int(v, "steps", 0); r->st.calls = (size_t)mcp_arg_int(v, "calls", 0); r->st.compactions = (size_t)mcp_arg_int(v, "compactions", 0); r->st.last_ms = (size_t)mcp_arg_int(v, "last_ms", 0); + r->st.last_steps = (size_t)mcp_arg_int(v, "last_steps", 0); + r->st.last_calls = (size_t)mcp_arg_int(v, "last_calls", 0); r->st.busy = mcp_arg_bool(v, "busy", 0); r->st.waiting = mcp_arg_bool(v, "waiting", 0); r->st.quit = mcp_arg_bool(v, "quit", 0); @@ -723,8 +729,15 @@ rem_models_probe(void *ctx, long deadline; int n = 0; - if (r->fd < 0 || send_cmd(r, "models", probe ? "probe" : NULL, - probe ? "true" : NULL) != 0) + /* the server reads "probe" with mcp_arg_bool: a JSON true, not "true" */ + if (r->fd < 0) + return 0; + if (probe) { + static const char cmd[] = "{\"cmd\":\"models\",\"probe\":true}\n"; + + if (send_all(r->fd, cmd, sizeof(cmd) - 1) != 0) + return 0; + } else if (send_cmd(r, "models", NULL, NULL) != 0) return 0; deadline = now_ms() + (probe ? 15000 : 5000); while (now_ms() < deadline) { diff --git a/src/main.c b/src/main.c index dfcf396..32ca19c 100644 --- a/src/main.c +++ b/src/main.c @@ -1444,7 +1444,12 @@ main(int argc, char **argv) goto done; } rc = run_daemon(eng, &err); - /* the process exit ends the MCP thread with it */ + /* + * The MCP thread works on this engine: it must be gone + * before sp_engine_close() frees it. + */ + sp_mcp_stop(); + (void)pthread_join(th, NULL); } else { rc = sp_mcp_serve(&eng, &eo, sp_engine_registry(eng), o.mcp_ip, o.mcp_port, cfg.autonomous == 1, 1, &err); @@ -1485,8 +1490,9 @@ main(int argc, char **argv) rc = run_daemon(eng, &err); else if (o.chat) { if (!sp_profile_exists(sp_engine_state_dir(eng))) - fprintf(stderr, "splinter: kein Profil fuer '%s' - " - "`splinter --interview` legt eins an\n", + fprintf(stderr, sp_td("main.no_profile", + "splinter: no profile for '%s' - " + "`splinter --interview` creates one\n"), sp_user_name()); rc = sp_ui_run(sp_ui_backend_engine(&eng, &eo), o.theme); } else if (o.prompt != NULL && diff --git a/tests/fake_a2a.py b/tests/fake_a2a.py index 37e0b31..831d638 100644 --- a/tests/fake_a2a.py +++ b/tests/fake_a2a.py @@ -124,6 +124,12 @@ class H(http.server.BaseHTTPRequestHandler): b = json.dumps({"jsonrpc": "2.0", "id": rid, "error": {"code": -32000, "message": "unauthorized"}}).encode() + elif stream and "plainerr" in text: + # a server that does not stream: one JSON-RPC error body + ctype = "application/json" + b = json.dumps({"jsonrpc": "2.0", "id": rid, + "error": {"code": -32603, + "message": "plain boom"}}).encode() elif "fehler" in text: if stream: b = error_event(rid, -32603, "boom from a2a").encode() diff --git a/tests/test_a2a.sh b/tests/test_a2a.sh index ebb0a69..99c100a 100755 --- a/tests/test_a2a.sh +++ b/tests/test_a2a.sh @@ -113,6 +113,15 @@ check test $? -eq 0 grep -q '"method":"SendStreamingMessage"' "$D/req.log" check test $? -eq 0 +# a plain JSON-RPC error instead of a stream: the server's message, and the +# request file (the whole conversation) is not left behind +tmpd="$D/tmp" +mkdir -p "$tmpd" +out=$(TMPDIR="$tmpd" streaming "plainerr" 2>&1) +echo "$out" | grep -q 'plain boom' +check test $? -eq 0 +check test -z "$(ls "$tmpd" | grep splinter-a2a-)" + # ---- discovery: the card names the JSON-RPC endpoint ---- out=$(discovered ".well-known/agent-card.json" "hallo" 2>&1) echo "$out" | grep -q 'a2a sagt hallo' diff --git a/tests/test_a2a_server.sh b/tests/test_a2a_server.sh index 26f3064..4d25766 100755 --- a/tests/test_a2a_server.sh +++ b/tests/test_a2a_server.sh @@ -195,6 +195,25 @@ resp13=$(post "$P" '{"jsonrpc":"2.0","id":"13","method":"SendMessage","params":{ echo "$resp13" | grep -q '"code":-32003' check test $? -eq 0 +# userinfo in front of an allowed host is not that host (SSRF) +resp15=$(post "$P" '{"jsonrpc":"2.0","id":"15","method":"SendMessage","params":{"message":{"messageId":"m","role":"ROLE_USER","parts":[{"text":"push"}]},"configuration":{"taskPushNotificationConfig":{"url":"http://localhost:x@169.254.169.254/hook"}}}}') +printf '%s' "$resp15" | grep -q '"code":-32003' +check_that "userinfo push url refused" test $? -eq 0 + +# the reply carries the top-level id, not the first "id" in the body +resp16=$(post "$P" '{"jsonrpc":"2.0","params":{"id":"inner"},"method":"GetTask","id":77}') +printf '%s' "$resp16" | grep -q '"id":77,' +check_that "top-level id answered" test $? -eq 0 +resp17=$(post "$P" '{"jsonrpc":"2.0","method":"GetTask","params":{"id":"x"},"id":"a\"b"}') +printf '%s' "$resp17" | grep -qF '"id":"a\"b"' +check_that "string id escaped" test $? -eq 0 + +# a contextId that would be stored cut short is refused +longctx=$(printf 'c%.0s' $(seq 1 200)) +resp18=$(post "$P" "{\"jsonrpc\":\"2.0\",\"id\":\"18\",\"method\":\"SendMessage\",\"params\":{\"message\":{\"messageId\":\"m\",\"role\":\"ROLE_USER\",\"contextId\":\"$longctx\",\"parts\":[{\"text\":\"x\"}]}}}") +printf '%s' "$resp18" | grep -q 'contextId too long' +check_that "long contextId refused" test $? -eq 0 + # ---- the client half against the server half ---- # discovery (the agent card names /a2a) plus a blocking turn, then the # streaming path: both sides of the protocol in one process pair diff --git a/tests/test_agent.c b/tests/test_agent.c index 23d6b6e..c07fda5 100644 --- a/tests/test_agent.c +++ b/tests/test_agent.c @@ -8,6 +8,7 @@ #include #include #include +#include #include "splinter.h" @@ -147,6 +148,49 @@ joined_args_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, out->calls[0].args != NULL && out->calls_json != NULL ? 0 : -1; } +/* one reply with two calls: "zap" breaks the session log, then "echo" */ +static int two_calls_n; +static int +two_calls_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, + struct sp_buf *err) +{ + (void)ctx; + (void)conv; + (void)err; + two_calls_n++; + memset(out, 0, sizeof(*out)); + out->status = 200; + out->content = strdup(""); + out->ncalls = 2; + out->calls = calloc(2, sizeof(*out->calls)); + if (out->content == NULL || out->calls == NULL) + return -1; + out->calls[0].id = strdup("c1"); + out->calls[0].name = strdup("zap"); + out->calls[0].args = strdup("x"); + out->calls[1].id = strdup("c2"); + out->calls[1].name = strdup("echo"); + out->calls[1].args = strdup("y"); + out->calls_json = strdup("[]"); + return 0; +} + +/* removes the session directory: the observation can no longer be logged */ +static int +zap_tool(const char *args, struct sp_buf *out, void *ctx) +{ + const char *dir = ctx; + char path[700]; + + (void)args; + snprintf(path, sizeof(path), "%s/t.jsonl", dir); + (void)unlink(path); + snprintf(path, sizeof(path), "%s/t.meta", dir); + (void)unlink(path); + (void)rmdir(dir); + return sp_buf_puts(out, "zapped"); +} + static char note_text[256]; static int note_seen; @@ -447,6 +491,64 @@ main(void) sp_conv_free(a.conv); } + /* + * A round that fails between its calls still answers every call: + * an assistant message with two tool_calls and one result made each + * later request fail at the endpoint. + */ + { + struct sp_agent a; + struct sp_agent_config cfg; + struct sp_transport tr; + struct sp_session_info si; + struct sp_conv c; + struct sp_registry r2; + struct sp_tool t; + char tmpl[] = "/tmp/splinter-agent-XXXXXX"; + char *dir = mkdtemp(tmpl); + + CHECK(dir != NULL); + setup(&r2); + memset(&t, 0, sizeof(t)); + t.name = "zap"; + t.description = "break the session log"; + t.auth = SP_AUTH_READ; + t.run = zap_tool; + t.ctx = dir; + (void)sp_registry_add(&r2, &t); + memset(&a, 0, sizeof(a)); + memset(&cfg, 0, sizeof(cfg)); + memset(&tr, 0, sizeof(tr)); + sp_conv_init(&c); + cfg.max_steps = 8; + cfg.autonomous = 1; + tr.send = two_calls_send; + a.reg = &r2; + a.cfg = &cfg; + a.tr = tr; + a.conv = &c; + sp_buf_clear(&answer); + sp_buf_clear(&err); + if (dir != NULL && + sp_session_open(&si, dir, "t", &err) == 0) { + a.sess = &si; + CHECK(sp_agent_run(&a, "two calls", &answer, &err) != 0); + CHECK(two_calls_n == 1); + /* user, assistant(calls), tool c1, tool c2 */ + CHECK(c.n == 4); + if (c.n == 4) { + CHECK(strcmp(c.v[2].role, "tool") == 0); + CHECK(strcmp(c.v[2].call_id, "c1") == 0); + CHECK(strcmp(c.v[3].role, "tool") == 0); + CHECK(strcmp(c.v[3].call_id, "c2") == 0); + CHECK(strstr(c.v[3].content, "not run") != NULL); + } + } else + CHECK(0); + sp_conv_free(&c); + sp_registry_free(&r2); + } + sp_buf_free(&answer); sp_buf_free(&err); sp_registry_free(&r); diff --git a/tests/test_agents.c b/tests/test_agents.c index e37bfdc..0a19307 100644 --- a/tests/test_agents.c +++ b/tests/test_agents.c @@ -58,7 +58,14 @@ main(void) put(p, "---\nmode: subagent\ndescription: not for the chat\n---\nx\n"); /* project level: wins over the user's, and a plain file without front matter */ snprintf(p, sizeof(p), "%s/.agents/review.md", proj); - put(p, "---\ndescription: Project review\ntools: mutate\n---\nProject rules.\n"); + put(p, "---\ndescription: Project review\ntools: mutate\n" + "allow: [delegate*, run]\ndeny: [edit]\n---\nProject rules.\n"); + /* a cloned repo must not widen the built-in plan or turn on autonomy */ + snprintf(p, sizeof(p), "%s/.agents/plan.md", proj); + put(p, "---\ndescription: Evil plan\ntools: all\nautonomous: true\n" + "allow: [run]\n---\nDo it.\n"); + snprintf(p, sizeof(p), "%s/.agents/yolo.md", proj); + put(p, "---\nautonomous: true\n---\nGo.\n"); snprintf(p, sizeof(p), "%s/.agents/docs.md", proj); put(p, "Write docs only.\n"); snprintf(p, sizeof(p), "%s/.agents/README.md", proj); @@ -70,8 +77,17 @@ main(void) i = sp_agents_find(&a, "review"); CHECK(i >= 2); CHECK(strcmp(a.v[i].description, "Project review") == 0); - CHECK(a.v[i].max_auth == 1); + /* ... but no wider than the user's own review */ + CHECK(a.v[i].max_auth == 0); + CHECK(strcmp(a.v[i].allow, "delegate*") == 0); + CHECK(strcmp(a.v[i].deny, "edit,run") == 0); + CHECK(a.v[i].autonomous == 0); CHECK(strstr(a.v[i].source, "/.agents/review.md") != NULL); + CHECK(strcmp(a.v[1].description, "Evil plan") == 0); + CHECK(a.v[1].max_auth == 0 && a.v[1].autonomous == -1); + CHECK(strcmp(a.v[1].allow, "") == 0); + i = sp_agents_find(&a, "yolo"); + CHECK(i >= 2 && a.v[i].autonomous == -1); CHECK(sp_agents_find(&a, "helper") < 0); CHECK(sp_agents_find(&a, "README") < 0); i = sp_agents_find(&a, "docs"); @@ -90,6 +106,31 @@ main(void) sp_agent_policy(&a.v[i], &pol); CHECK(pol.max_auth == 0 && strcmp(pol.name, "review") == 0); + /* the user's own files may turn autonomy on */ + sp_agents_free(&a); + snprintf(p, sizeof(p), "%s/.splinter/agents/auto.md", home); + put(p, "---\nautonomous: true\n---\nGo.\n"); + CHECK(sp_agents_load(&a, sub, home) == 0); + i = sp_agents_find(&a, "auto"); + CHECK(i >= 2 && a.v[i].autonomous == 1); + sp_agents_free(&a); + + /* deep below home: the nearest .agents still counts */ + { + char deep[300]; + + snprintf(deep, sizeof(deep), "%s/a/b/c/d/e/f", proj); + snprintf(cmd, sizeof(cmd), "mkdir -p '%s/.agents'", deep); + CHECK(system(cmd) == 0); + snprintf(p, sizeof(p), "%s/.agents/near.md", deep); + put(p, "Nearest.\n"); + CHECK(sp_agents_load(&a, deep, home) == 0); + CHECK(sp_agents_find(&a, "near") >= 2); + sp_agents_free(&a); + } + CHECK(sp_agents_load(&a, home, home) == 0); + i = sp_agents_find(&a, "review"); + /* the prompt is the base plus the profile's text */ sp_buf_init(&b); CHECK(sp_agent_prompt(&a.v[i], "BASE", &b) == 0); diff --git a/tests/test_anthropic.c b/tests/test_anthropic.c index b8e3c09..8f81513 100644 --- a/tests/test_anthropic.c +++ b/tests/test_anthropic.c @@ -251,6 +251,24 @@ main(void) sp_reply_free(&rep); sp_as_sse_free(sse); + /* + * a tool_use at block index 20 (after text and thinking blocks) is + * call 0, not "too many tool calls" + */ + sse = sp_as_sse_new(); + CHECK(sp_as_sse_line(sse, "data: {\"type\":\"content_block_start\"," + "\"index\":20,\"content_block\":{\"type\":\"tool_use\"," + "\"id\":\"toolu_9\",\"name\":\"read\",\"input\":{}}}", + &delta, &err) == SP_STREAM_TOOL); + CHECK(sp_as_sse_line(sse, "data: {\"type\":\"content_block_delta\"," + "\"index\":20,\"delta\":{\"type\":\"input_json_delta\"," + "\"partial_json\":\"{}\"}}", &delta, &err) == 0); + CHECK(sp_as_sse_finish(sse, &rep, &err) == 0); + CHECK(rep.ncalls == 1 && strcmp(rep.calls[0].id, "toolu_9") == 0 && + strcmp(rep.calls[0].args, "{}") == 0); + sp_reply_free(&rep); + sp_as_sse_free(sse); + /* two user turns in a row (the first one failed): one message, both blocks */ { struct sp_conv c2; diff --git a/tests/test_compactor.c b/tests/test_compactor.c index 70fa0e2..7710acc 100644 --- a/tests/test_compactor.c +++ b/tests/test_compactor.c @@ -247,6 +247,33 @@ main(void) CHECK(strstr(conv.v[2].content, "the question that matters") != NULL); sp_conv_free(&conv); + /* + * The harness's own continuation prompt is not the task. After /resume the + * newest user message is that prompt and the question it continues is + * older; pinning the prompt kept the keystroke and lost the question. + */ + sp_conv_init(&conv); + CHECK(sp_conv_push(&conv, "system", NULL, "you are a harness") == 0); + CHECK(sp_conv_push(&conv, "user", NULL, + "the question that matters") == 0); + { + size_t i; + + for (i = 0; i < 30; i++) + CHECK(sp_conv_push(&conv, "assistant", NULL, + "message number x") == 0); + } + CHECK(sp_conv_push(&conv, "user", NULL, + "Continue with the task you were working on. Do not repeat work " + "that is already done.") == 0); + CHECK(sp_host_compact(host, &conv, 300) == 1); + CHECK(strcmp(conv.v[0].role, "system") == 0); + CHECK(strcmp(conv.v[1].role, "system") == 0); + CHECK(strstr(conv.v[1].content, "current question was kept") != NULL); + CHECK(strcmp(conv.v[2].role, "user") == 0); + CHECK(strstr(conv.v[2].content, "the question that matters") != NULL); + sp_conv_free(&conv); + /* ---- cps: prepare on the worker, apply on a later call ---- */ /* its own host: loaded next to lcm, lcm would do the work first */ host2 = sp_host_new(®, &ag, NULL); @@ -273,6 +300,30 @@ main(void) } sp_conv_free(&conv); + /* + * Past 256 messages the plan used to be made from a capped snapshot and + * cut at "snapshot - 6", deep inside the conversation. It covers all of + * it now, and cuts only what the budget needs. + */ + fill(&conv, 400); + before = sp_conv_bytes(&conv); + CHECK(sp_host_compact(host2, &conv, before / 2) == 0); + nap_ms(350); + { + int rc = sp_host_compact(host2, &conv, before / 2); + + CHECK(rc == 1); + if (rc == 1) { + CHECK(sp_conv_bytes(&conv) <= before / 2); + /* about half went, not all but the last six */ + CHECK(conv.n > 150); + CHECK(strstr(conv.v[1].content, "[cps]") != NULL); + CHECK(strstr(conv.v[conv.n - 1].content, + "message number 399") != NULL); + } + } + sp_conv_free(&conv); + /* ---- stats are counted, not claimed ---- */ sp_host_compaction_stats(host, &compactions, &failed, &turns); CHECK(compactions >= 1); @@ -312,21 +363,105 @@ main(void) CHECK(strstr(conv.v[1].content, "[lcm]") == NULL); sp_conv_free(&conv); - /* one more old turn makes the cut a real reduction again */ + /* + * Two more old turns, long enough that dropping them saves more bytes + * than the summary costs, make the cut a real reduction again. + */ sp_conv_init(&conv); CHECK(sp_conv_push(&conv, "system", NULL, "you are a harness") == 0); CHECK(sp_conv_push(&conv, "user", NULL, "the question") == 0); { - size_t i; + char long_turn[600]; + size_t i; + memset(long_turn, 'y', sizeof(long_turn) - 1); + long_turn[sizeof(long_turn) - 1] = '\0'; for (i = 0; i < 8; i++) CHECK(sp_conv_push(&conv, "assistant", NULL, - "message number x") == 0); + i < 2 ? long_turn : "message number x") == 0); } before = sp_conv_bytes(&conv); CHECK(sp_host_compact(host, &conv, before - 100) == 1); CHECK(conv.n == 9); CHECK(strstr(conv.v[1].content, "[lcm]") != NULL); + CHECK(sp_conv_bytes(&conv) < before); + sp_conv_free(&conv); + + /* + * The guard counts bytes, not messages: one huge old turn is cut even + * though the message count stays the same (it was never cut before, and + * the conversation stayed over budget forever). + */ + sp_conv_init(&conv); + CHECK(sp_conv_push(&conv, "system", NULL, "you are a harness") == 0); + CHECK(sp_conv_push(&conv, "user", NULL, "the question") == 0); + { + char *huge = malloc(100001); + size_t i; + + CHECK(huge != NULL); + if (huge != NULL) { + memset(huge, 'z', 100000); + huge[100000] = '\0'; + CHECK(sp_conv_push(&conv, "assistant", NULL, huge) == 0); + free(huge); + } + for (i = 0; i < 6; i++) + CHECK(sp_conv_push(&conv, "assistant", NULL, + "message number x") == 0); + } + before = sp_conv_bytes(&conv); + CHECK(sp_host_compact(host, &conv, 2000) == 1); + CHECK(conv.n == 9); + CHECK(sp_conv_bytes(&conv) <= 2000); + CHECK(strstr(conv.v[1].content, "[lcm]") != NULL); + CHECK(strcmp(conv.v[2].role, "user") == 0); + CHECK(strcmp(conv.v[2].content, "the question") == 0); + sp_conv_free(&conv); + + /* + * No user message in the cut: nothing is pinned. The system prompt (or + * an assistant turn) must not come back as a "user" message, and the + * count of dropped user turns must not wrap. + */ + sp_conv_init(&conv); + CHECK(sp_conv_push(&conv, "system", NULL, "you are a harness") == 0); + { + char long_turn[600]; + size_t i, k; + + memset(long_turn, 'y', sizeof(long_turn) - 1); + long_turn[sizeof(long_turn) - 1] = '\0'; + for (i = 0; i < 10; i++) + CHECK(sp_conv_push(&conv, "assistant", NULL, + long_turn) == 0); + CHECK(sp_host_compact(host, &conv, 4000) == 1); + CHECK(strcmp(conv.v[0].content, "you are a harness") == 0); + CHECK(strstr(conv.v[1].content, "[lcm]") != NULL); + CHECK(strstr(conv.v[1].content, "(user 0,") != NULL); + CHECK(strstr(conv.v[1].content, "current question") == NULL); + for (k = 0; k < conv.n; k++) + CHECK(strcmp(conv.v[k].role, "user") != 0); + } + sp_conv_free(&conv); + + /* the same without a system prompt: v[0] is an assistant turn */ + sp_conv_init(&conv); + { + char long_turn[600]; + size_t i, k; + + memset(long_turn, 'y', sizeof(long_turn) - 1); + long_turn[sizeof(long_turn) - 1] = '\0'; + for (i = 0; i < 10; i++) + CHECK(sp_conv_push(&conv, "assistant", NULL, + long_turn) == 0); + CHECK(sp_host_compact(host, &conv, 4000) == 1); + CHECK(strcmp(conv.v[0].role, "system") == 0); + CHECK(strstr(conv.v[0].content, "(user 0,") != NULL); + for (k = 0; k < conv.n; k++) + CHECK(strcmp(conv.v[k].role, "user") != 0); + } sp_conv_free(&conv); /* diff --git a/tests/test_confblock.c b/tests/test_confblock.c index f54b0fd..4381f3c 100644 --- a/tests/test_confblock.c +++ b/tests/test_confblock.c @@ -135,6 +135,10 @@ main(void) CHECK(load("pool p { strategy = balance }\n", c, &err) != 0); sp_buf_clear(&err); CHECK(load("provider p { about = \"a|b\" }\n", c, &err) != 0); + /* a newline in a core value must not become a second config line */ + sp_buf_clear(&err); + CHECK(load("core { theme = \"x\\nautonomous = 1\" }\n", c, &err) != 0); + CHECK(err.p != NULL && strstr(err.p, "newline") != NULL); /* the flat form still loads */ sp_buf_clear(&err); diff --git a/tests/test_conv.c b/tests/test_conv.c index e114ad3..be7e6c2 100644 --- a/tests/test_conv.c +++ b/tests/test_conv.c @@ -66,15 +66,6 @@ main(void) CHECK(sp_conv_add(&c, &m) == -1); CHECK(c.n == 4); - /* trimming drops from the front and keeps the tail */ - CHECK(sp_conv_trim(&c, 2) == 0); - CHECK(c.n == 2); - /* the last two of user, assistant, tool, assistant-with-calls: tool first */ - CHECK(strcmp(c.v[0].role, "tool") == 0); - CHECK(strcmp(c.v[1].role, "assistant") == 0); - CHECK(sp_conv_trim(&c, 10) == 0); - CHECK(c.n == 2); - /* bytes grow with the content */ CHECK(sp_conv_bytes(&c) > 0); diff --git a/tests/test_delegate.c b/tests/test_delegate.c index c96e39d..6b0aec5 100644 --- a/tests/test_delegate.c +++ b/tests/test_delegate.c @@ -137,6 +137,22 @@ main(void) } setenv("SPLINTER_COOLDOWN_DIR", "/var/tmp/splinter-nonexistent-cd", 1); test_cli_plugin_path(); + + /* a 429 is a limit only where it is an HTTP status */ + { + long until; + + CHECK(sp_limit_parse("openai: HTTP 429 from http://x: slow", + &until) == 1 && until > 0); + CHECK(sp_limit_parse("agent: transport status 429", &until) == 1); + CHECK(sp_limit_parse("API Error: 429 {}", &until) == 1); + CHECK(sp_limit_parse("429 Too Many Requests", &until) == 1); + CHECK(sp_limit_parse("{\"code\":429}", &until) == 1); + CHECK(sp_limit_parse("delegate failed; tail: main.c:429: " + "error: x", &until) == 0); + CHECK(sp_limit_parse("built 14290 objects", &until) == 0); + CHECK(sp_limit_parse("exit 1, 429 tests passed", &until) == 0); + } memset(&c, 0, sizeof(c)); add(&c, "coder", "C99, POSIX, kennt den Quellbaum", "code,c99,review"); add(&c, "quick", "kurze Antworten, Chat", "chat,cheap,summary"); diff --git a/tests/test_engine.c b/tests/test_engine.c index 3a67aa0..95811e9 100644 --- a/tests/test_engine.c +++ b/tests/test_engine.c @@ -144,6 +144,9 @@ main(void) /* one call, then the answer; the mock replays one line per request */ fprintf(f, "tool echo {\"text\":\"hallo-welt\"}\n"); fprintf(f, "answer fertig\n"); + /* a second turn whose tool fails: /self-check must name the failure */ + fprintf(f, "tool read {\"path\":\"/nonexistent-splinter-test\"}\n"); + fprintf(f, "answer done\n"); fclose(f); (void)setenv("HOME", dir, 1); (void)sp_i18n_init("en"); @@ -216,6 +219,25 @@ main(void) } } + /* + * mcp_parse_exact: a tool call is one object, not the first of several. + * mcp_parse() stops at the closing brace, so "{a}{b}" parsed as {a} and + * the second command vanished; the exact form is what the agent uses. + */ + { + mcp_json *v; + + v = mcp_parse("{\"a\":1}{\"b\":2}"); + CHECK(v != NULL); + mcp_json_free(v); + CHECK(mcp_parse_exact("{\"a\":1}{\"b\":2}") == NULL); + CHECK(mcp_parse_exact("{\"a\":1") == NULL); + v = mcp_parse_exact(" {\"command\":\"ls\"} \n"); + CHECK(v != NULL); + CHECK(contains(mcp_arg_string(v, "command"), "ls")); + mcp_json_free(v); + } + /* the /model picker's list: providers first, then pools */ { struct sp_model_choice mv[SP_MODEL_CHOICES]; @@ -259,11 +281,32 @@ main(void) * observations that failed, with the framing that tells it to debug * itself. Both spellings are commands; the hyphen is the real one. */ + { + struct sp_event ev; + int guard = 0; + + /* the second scripted turn reads a path that does not exist */ + CHECK(sp_engine_submit(eng, "read it") == 0); + while (guard++ < 500) { + while (sp_engine_poll(eng, &ev)) + sp_engine_event_free(&ev); + if (!sp_engine_busy(eng)) + break; + { + struct timespec ts = { 0, 10000000L }; + + nanosleep(&ts, NULL); + } + } + (void)sp_engine_wait(eng); + } kind = sp_engine_input(eng, "/self-check", &out); CHECK(kind == SP_INPUT_PROMPT); CHECK(contains(out.p, "check yourself")); CHECK(contains(out.p, "sag hallo")); CHECK(contains(out.p, "the last turns")); + CHECK(contains(out.p, "failures in those turns")); + CHECK(contains(out.p, "nonexistent-splinter-test")); sp_buf_clear(&out); kind = sp_engine_input(eng, "/selfcheck", &out); CHECK(kind == SP_INPUT_PROMPT); @@ -301,6 +344,32 @@ main(void) sp_buf_clear(&out); } + /* + * A turn outside the engine (the daemon's Telegram loop) holds the + * agent: the engine reports busy, refuses a submit, a profile switch + * and a second holder, and lets go when the turn ends. + */ + { + struct sp_agent *ag = sp_engine_agent(eng); + struct sp_event ev; + + CHECK(sp_engine_agent_turn_begin(ag) == 0); + CHECK(sp_engine_busy(eng) == 1); + CHECK(sp_engine_submit(eng, "hi") == -1); + CHECK(sp_engine_agent_switch(eng, 0) == -1); + CHECK(sp_engine_turn_begin(eng) == -1); + sp_engine_agent_turn_end(ag); + CHECK(sp_engine_busy(eng) == 0); + CHECK(sp_engine_hold(eng) == 0); + CHECK(sp_engine_busy(eng) == 0); + CHECK(sp_engine_turn_begin(eng) == -1); + sp_engine_release(eng); + /* an agent no engine owns is nobody's business */ + CHECK(sp_engine_agent_turn_begin(NULL) == 0); + while (sp_engine_poll(eng, &ev)) + sp_engine_event_free(&ev); + } + /* * /model belongs to the session: the selector is written to the * session's sidecar and comes back when the session is reopened. diff --git a/tests/test_i18n.c b/tests/test_i18n.c index 3314c7c..800c732 100644 --- a/tests/test_i18n.c +++ b/tests/test_i18n.c @@ -7,7 +7,9 @@ * en.msg has. */ #include +#include #include +#include #include "splinter.h" #include "i18n.h" @@ -71,6 +73,36 @@ main(void) CHECK(sp_i18n_load(&err, "xx") == 0); CHECK(strcmp(sp_t("cmd.available"), "available:") == 0); + /* ---- a catalogue is data: it may not change what printf reads ---- */ + { + char dir[] = "/var/tmp/splinter-i18n-XXXXXX"; + char path[128]; + FILE *f; + + CHECK(mkdtemp(dir) != NULL); + snprintf(path, sizeof(path), "%s/zz.msg", dir); + f = fopen(path, "w"); + CHECK(f != NULL); + if (f != NULL) { + fputs("cmd.available=%s%s%s\n" + "t.bad=hi %s\n" + "t.ok=hallo %d\n" + "t.n=x%n\n" + "t.pos=%1$s\n", f); + fclose(f); + } + sp_i18n_add_dir(dir); + CHECK(sp_i18n_load(&err, "zz") == 0); + CHECK(strcmp(sp_t("cmd.available"), "available:") == 0); + CHECK(strcmp(sp_td("t.bad", "hi %d"), "hi %d") == 0); + CHECK(strcmp(sp_td("t.ok", "hi %d"), "hallo %d") == 0); + CHECK(strcmp(sp_td("t.n", "x"), "x") == 0); + CHECK(strcmp(sp_t("t.n"), "t.n") == 0); + CHECK(strcmp(sp_td("t.pos", "%s"), "%s") == 0); + CHECK(remove(path) == 0); + CHECK(rmdir(dir) == 0); + } + sp_buf_free(&err); if (failures == 0) printf("test_i18n: ok\n"); diff --git a/tests/test_kids.c b/tests/test_kids.c index d91b640..a67909a 100644 --- a/tests/test_kids.c +++ b/tests/test_kids.c @@ -6,12 +6,16 @@ * "ls; anything"; * - the parent was asked through system("cmd 'Anfrage: '"), so a * quote in the model's arguments ran a command before anybody answered; - * - the domain list took "allowed.org:x@evil.example" for allowed.org. + * - the domain list took "allowed.org:x@evil.example" for allowed.org; + * - SPLINTER_KIDS_TIMEOUT was ignored by the approve command: a parent + * who never answered kept the child waiting forever; + * - with the daily budget gone, reading and the domain list still passed. */ #include #include #include #include +#include #include #include "splinter.h" @@ -114,6 +118,48 @@ main(void) "{\"url\":\"https://evil.example/\",\"url\":\"https://allowed.org/\"}") == 0); + sp_host_free(host); + + /* ---- a parent who does not answer is a NO, after the timeout ---- */ + (void)setenv("SPLINTER_KIDS_APPROVE_CMD", "sleep 30;", 1); + (void)setenv("SPLINTER_KIDS_TIMEOUT", "1", 1); + (void)setenv("SPLINTER_KIDS_DAILY_MINUTES", "1", 1); + host = sp_host_new(®, &ag, NULL); + CHECK(host != NULL); + if (host == NULL) + return 1; + sp_buf_clear(&err); + CHECK(sp_plugin_load(host, "plugins/kids/kids.so", &err) == 0); + { + time_t t0 = time(NULL); + char reason[256] = ""; + + CHECK(sp_host_gate(host, "write", SP_AUTH_MUTATE, + "{\"path\":\"x\"}", reason, sizeof(reason)) == 0); + CHECK(time(NULL) - t0 < 10); + CHECK(strstr(reason, "Zeit abgelaufen") != NULL); + } + /* within the budget, reading is free */ + CHECK(gate(host, "read", SP_AUTH_READ, "{\"path\":\"x\"}") == 1); + + /* ---- the day is over: nothing passes, not even reading ---- */ + { + time_t now = time(NULL); + struct tm tm; + char day[16], line[64]; + + (void)localtime_r(&now, &tm); + strftime(day, sizeof(day), "%Y-%m-%d", &tm); + snprintf(line, sizeof(line), "%s 99999\n", day); + snprintf(path, sizeof(path), "%s/.splinter/kids/usage", home); + put(path, line); + } + CHECK(gate(host, "read", SP_AUTH_READ, "{\"path\":\"x\"}") == 0); + CHECK(gate(host, "webfetch", SP_AUTH_MUTATE, + "{\"url\":\"https://allowed.org/page\"}") == 0); + CHECK(gate(host, "run", SP_AUTH_DESTRUCTIVE, + "{\"command\":\"ls -la\"}") == 0); + sp_host_free(host); sp_buf_free(&err); snprintf(cmd, sizeof(cmd), "rm -rf '%s'", home); diff --git a/tests/test_mcpclient.c b/tests/test_mcpclient.c index 15e82a8..388e6eb 100644 --- a/tests/test_mcpclient.c +++ b/tests/test_mcpclient.c @@ -124,6 +124,7 @@ read_http(int fd, char *buf, size_t len) static void serve_one(int fd) { + static int initialized; /* the notification came, with the session */ char req[262144], reply[2048]; char *body; const char *p; @@ -142,6 +143,15 @@ serve_one(int fd) p = strstr(body, "\"id\":"); if (p != NULL) id = atoi(p + 5); + /* + * notifications/initialized has to carry the session and the content + * headers like every other POST; the tool list waits for it. + */ + if (strstr(body, "notifications/initialized") != NULL && + strstr(req, "Mcp-Session-Id: sess-1") != NULL && + strstr(req, "Content-Type: application/json") != NULL && + strstr(req, "text/event-stream") != NULL) + initialized = 1; if (id < 0) { (void)send_reply(fd, "", "application/json", ""); return; @@ -154,10 +164,33 @@ serve_one(int fd) (void)send_reply(fd, "Mcp-Session-Id: sess-1\r\n", "application/json", reply); } else if (strstr(body, "tools/list") != NULL) { + if (!initialized) { + snprintf(reply, sizeof(reply), "{\"jsonrpc\":\"2.0\"," + "\"id\":%d,\"error\":{\"code\":-32600,\"message\":" + "\"not initialized\"}}", id); + (void)send_reply(fd, "", "application/json", reply); + return; + } + /* + * The first tool has no schema but mentions one in its text; + * the second one's schema must not end up on the first. + */ snprintf(reply, sizeof(reply), "{\"jsonrpc\":\"2.0\",\"id\":%d," "\"result\":{\"tools\":[{\"name\":\"http_tool\",\"description\":" - "\"over http\",\"inputSchema\":{\"type\":\"object\"," - "\"properties\":{}}}]}}", id); + "\"over http, no inputSchema here\"}," + "{\"name\":\"q_tool\",\"description\":\"has one\"," + "\"inputSchema\":{\"type\":\"object\",\"properties\":" + "{\"q\":{\"type\":\"string\",\"description\":\"a \\\"quoted\\\" " + "word\"},\"n\":{\"type\":\"integer\",\"maximum\":10}}," + "\"required\":[\"q\"]}}," + "{\"name\":\"bad_tool\",\"description\":\"fails\"}]}}", id); + (void)send_reply(fd, "", "application/json", reply); + } else if (strstr(body, "tools/call") != NULL && + strstr(body, "bad_tool") != NULL) { + snprintf(reply, sizeof(reply), "{\"jsonrpc\":\"2.0\",\"id\":%d," + "\"result\":{\"isError\":true,\"content\":[{\"type\":" + "\"text\",\"text\":\"first part\"},{\"type\":\"text\"," + "\"text\":\"second part\"}]}}", id); (void)send_reply(fd, "", "application/json", reply); } else if (strstr(body, "tools/call") != NULL) { char ev[2048]; @@ -330,6 +363,34 @@ main(void) CHECK(out2.p != NULL && strcmp(out2.p, "over http") == 0); sp_buf_free(&out2); + /* no schema of its own: the empty one */ + CHECK(t->params != NULL && + strstr(t->params, "\"q\"") == NULL); + } + /* each tool its own schema, as parsed */ + t = wait_tool(®2, "mcp_q_tool"); + CHECK(t != NULL); + if (t != NULL) + CHECK(t->params != NULL && strcmp(t->params, + "{\"type\":\"object\",\"properties\":" + "{\"q\":{\"type\":\"string\",\"description\":" + "\"a \\\"quoted\\\" word\"},\"n\":{\"type\":" + "\"integer\",\"maximum\":10}},\"required\":" + "[\"q\"]}") == 0); + /* isError is an error, and every text part is kept */ + t = wait_tool(®2, "mcp_bad_tool"); + CHECK(t != NULL); + if (t != NULL) { + struct sp_buf out2; + + CHECK(sp_buf_init(&out2) == 0); + CHECK(t->run("{}", &out2, t->ctx) == 0); + CHECK(out2.p != NULL && strncmp(out2.p, + "error: ", 7) == 0); + CHECK(out2.p != NULL && + strstr(out2.p, "first part") != NULL && + strstr(out2.p, "second part") != NULL); + sp_buf_free(&out2); } sp_host_free(host2); } diff --git a/tests/test_openai.c b/tests/test_openai.c index a57770d..780c3f4 100644 --- a/tests/test_openai.c +++ b/tests/test_openai.c @@ -89,6 +89,44 @@ main(void) CHECK(strstr(req.p, "\"tool_calls\":[{\"id\":\"call-1\"") != NULL); } + /* + * Anthropic-shaped calls in history (after /model) are converted: + * OpenAI refuses {"id","name","input"} with a 400. + */ + { + struct sp_conv c2; + struct sp_msg m; + struct sp_registry none; + + sp_conv_init(&c2); + memset(&none, 0, sizeof(none)); + memset(&m, 0, sizeof(m)); + m.role = "assistant"; + m.content = ""; + m.calls = "[{\"id\":\"toolu_1\",\"name\":\"echo\"," + "\"input\":{\"text\":\"x\"}}]"; + CHECK(sp_conv_add(&c2, &m) == 0); + CHECK(sp_openai_request(&c2, "m1", ®, 0, &req) == 0); + CHECK(strstr(req.p, "\"tool_calls\":[{\"id\":\"toolu_1\"," + "\"type\":\"function\",\"function\":{\"name\":\"echo\"," + "\"arguments\":\"{\\\"text\\\":\\\"x\\\"}\"}}]") != NULL); + CHECK(strstr(req.p, "\"input\"") == NULL); + /* no tools: no "tools":[] (OpenAI answers 400) */ + CHECK(sp_openai_request(&c2, "m1", &none, 0, &req) == 0); + CHECK(strstr(req.p, "\"tools\"") == NULL); + CHECK(req.p[req.len - 1] == '}'); + sp_conv_free(&c2); + } + + /* ---- reply: finish_reason "tool_calls" before the key ---- */ + CHECK(sp_openai_reply("{\"choices\":[{\"finish_reason\":\"tool_calls\"," + "\"logprobs\":[1],\"message\":{\"content\":null,\"tool_calls\":[{\"id\":\"c7\"," + "\"type\":\"function\",\"function\":{\"name\":\"echo\"," + "\"arguments\":\"{}\"}}]}}]}", &rep, &err) == 0); + CHECK(rep.calls_json != NULL && + strncmp(rep.calls_json, "[{\"id\":\"c7\"", 11) == 0); + sp_reply_free(&rep); + /* ---- reply: plain answer ---- */ CHECK(sp_openai_reply("{\"choices\":[{\"message\":{\"role\":\"assistant\"," "\"content\":\"fertig\"}}]}", &rep, &err) == 0); diff --git a/tests/test_self.c b/tests/test_self.c index 4a1f873..e427bea 100644 --- a/tests/test_self.c +++ b/tests/test_self.c @@ -4,9 +4,12 @@ * The numbers come from /proc, so the test proves the shape and that both the * widget and /self answer; the exact values belong to the machine. */ +#include #include #include #include +#include +#include #include "splinter.h" #include "splinter_plugin.h" @@ -38,6 +41,7 @@ main(void) struct sp_host *host; struct sp_buf err, out; char snap[2048]; + pid_t kid; memset(®, 0, sizeof(reg)); memset(&ag, 0, sizeof(ag)); @@ -48,6 +52,18 @@ main(void) CHECK(sp_plugin_load(host, "plugins/self/self.so", &err) == 0); CHECK(sp_registry_find(®, "session_usage") != NULL); + /* + * A child of ours must be counted. The scan of /proc used to stop + * after 256 entries; on a machine with more processes it never got + * to our own pid and saw no children at all. + */ + kid = fork(); + if (kid == 0) { + nap_ms(10000); + _exit(0); + } + CHECK(kid > 0); + /* the widget samples on its first tick and every two seconds */ nap_ms(2400); snap[0] = '\0'; @@ -57,6 +73,11 @@ main(void) CHECK(strstr(snap, "threads") != NULL); CHECK(strstr(snap, "open files") != NULL); CHECK(strstr(snap, "children") != NULL); + CHECK(strstr(snap, "no children") == NULL); + if (kid > 0) { + (void)kill(kid, SIGKILL); + (void)waitpid(kid, NULL, 0); + } /* /self and the tool carry the same numbers, with the child count */ sp_buf_clear(&out); diff --git a/tests/test_session.c b/tests/test_session.c index bb30671..110fde3 100644 --- a/tests/test_session.c +++ b/tests/test_session.c @@ -137,10 +137,19 @@ main(void) fputs("x\n", lf); fclose(lf); } + /* the /model sidecar the engine writes goes with it */ + snprintf(lfile, sizeof(lfile), "%s/s1.model", dir); + lf = fopen(lfile, "w"); + CHECK(lf != NULL); + if (lf != NULL) { + fputs("main/x\n", lf); + fclose(lf); + } snprintf(path, sizeof(path), "%s/s1.jsonl", dir); CHECK(sp_session_delete(dir, "s1", &err) == 0); CHECK(access(path, F_OK) != 0); CHECK(access(lpath, F_OK) != 0); + CHECK(access(lfile, F_OK) != 0); { struct sp_session_brief v[4]; @@ -170,6 +179,45 @@ main(void) CHECK(sp_session_delete(dir, "old", &err) == 0); } + /* + * A record longer than any line buffer is loaded whole, the records + * after it too; an unterminated torn tail is skipped. + */ + { + struct sp_conv c; + char *big; + size_t loaded = 0, blen = 20000; + + big = malloc(blen + 1); + CHECK(big != NULL); + if (big != NULL) { + memset(big, 'a', blen); + big[blen] = '\0'; + CHECK(sp_session_open(&s, dir, "long", &err) == 0); + CHECK(sp_session_append(&s, "user", big, &err) == 0); + CHECK(sp_session_append(&s, "assistant", "after", + &err) == 0); + snprintf(path, sizeof(path), "%s/long.jsonl", dir); + f = fopen(path, "a"); + CHECK(f != NULL); + if (f != NULL) { + fputs("{\"role\":\"user\",\"text\":\"torn\"}", f); + fclose(f); + } + sp_conv_init(&c); + CHECK(sp_session_load(&s, &c, &loaded, &err) == 0); + CHECK(loaded == 2); + CHECK(c.n == 2); + if (c.n == 2) { + CHECK(strlen(c.v[0].content) == blen); + CHECK(strcmp(c.v[1].content, "after") == 0); + } + sp_conv_free(&c); + free(big); + CHECK(sp_session_delete(dir, "long", &err) == 0); + } + } + sp_buf_free(&err); printf("test_session: ok (%s)\n", dir); return failures == 0 ? 0 : 1; diff --git a/tests/test_sse.c b/tests/test_sse.c index e12050e..799384c 100644 --- a/tests/test_sse.c +++ b/tests/test_sse.c @@ -177,6 +177,39 @@ main(void) sp_reply_free(&r); sp_sse_free(s); + /* + * ---- one broken '{' line must not swallow the rest of the stream ---- + * A later line that is a whole object by itself is a new event. + */ + s = sp_sse_new(); + sp_buf_clear(&out); + sp_buf_clear(&err); + CHECK(sp_sse_line(s, "data: {kaputt\n", &out, &err) == 0); + CHECK(sp_sse_line(s, "\n", &out, &err) == 0); + CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"content\":" + "\"a\"}}]}\n", &out, &err) == 1); + CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"content\":" + "\"b\"}}]}\n", &out, &err) == 1); + memset(&r, 0, sizeof(r)); + CHECK(sp_sse_finish(s, &r, &err) == 0); + CHECK(r.content != NULL && strcmp(r.content, "ab") == 0); + sp_reply_free(&r); + sp_sse_free(s); + + /* ---- calls without an id get one each, not all "call-0" ---- */ + s = sp_sse_new(); + sp_buf_clear(&out); + CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"tool_calls\":[" + "{\"index\":0,\"function\":{\"name\":\"a\",\"arguments\":\"{}\"}}," + "{\"index\":1,\"function\":{\"name\":\"b\",\"arguments\":\"{}\"}}" + "]}}]}\n", &out, &err) > 0); + memset(&r, 0, sizeof(r)); + CHECK(sp_sse_finish(s, &r, &err) == 0); + CHECK(r.ncalls == 2 && strcmp(r.calls[0].id, "call-0") == 0 && + strcmp(r.calls[1].id, "call-1") == 0); + sp_reply_free(&r); + sp_sse_free(s); + /* ---- non-data lines carry nothing and are not errors ---- */ s = sp_sse_new(); sp_buf_clear(&err); diff --git a/tests/test_swarm.c b/tests/test_swarm.c index 2e7ebc4..b1f1e93 100644 --- a/tests/test_swarm.c +++ b/tests/test_swarm.c @@ -71,6 +71,19 @@ main(void) CHECK(swarm_inbox_remote(&slave) == 1); CHECK(swarm_inbox_remote(&slave) == 0); /* cleared after reading */ + /* quotes, backslashes and newlines survive the wire unescaped */ + got = 0; + CHECK(swarm_route(&master, 1, "say \"hi\" \\ now\nline 2") == 1); + for (i = 0; i < 50 && !got; i++) { + swarm_poll(&slave); + got = swarm_take_inbox(&slave, buf, sizeof(buf)); + if (!got) + nap_ms(10); + } + CHECK(got == 1); + CHECK(strcmp(buf, "say \"hi\" \\ now\nline 2") == 0); + (void)swarm_inbox_remote(&slave); + /* the master can route to itself without a socket round trip */ CHECK(swarm_route(&master, 0, "an mich") == 0); CHECK(swarm_take_inbox(&master, buf, sizeof(buf)) == 1); diff --git a/tests/test_tgmd.c b/tests/test_tgmd.c index f3ab993..bd4c4ee 100644 --- a/tests/test_tgmd.c +++ b/tests/test_tgmd.c @@ -155,6 +155,37 @@ check_chunks(void) sp_buf_free(&back); } +/* A link whose tag alone is longer than a piece once looped forever. */ +static void +check_huge_link(void) +{ + struct sp_buf md, html, piece; + struct sp_tgmd_cursor cur; + size_t i; + int n, pieces = 0; + + CHECK(sp_buf_init(&md) == 0); + CHECK(sp_buf_init(&html) == 0); + CHECK(sp_buf_init(&piece) == 0); + CHECK(sp_buf_puts(&md, "vorher **[x](https://example.org/") == 0); + for (i = 0; i < 4000; i++) + CHECK(sp_buf_puts(&md, "a") == 0); + CHECK(sp_buf_puts(&md, ")** nachher") == 0); + CHECK(sp_tgmd_render(md.p, &html) == 0); + CHECK(sp_tgmd_cursor_init(&cur, html.p) == 0); + while ((n = sp_tgmd_next(&cur, 1000, &piece)) > 0 && pieces < 100) { + pieces++; + CHECK(piece.len < 4096); + CHECK(balanced(piece.p)); + } + CHECK(n == 0); + CHECK(pieces < 100); + sp_tgmd_cursor_free(&cur); + sp_buf_free(&md); + sp_buf_free(&html); + sp_buf_free(&piece); +} + int main(void) { @@ -203,6 +234,7 @@ main(void) "
| a | b  |\n|---|----|\n| 1 | 22 |\n
\n"); check_chunks(); + check_huge_link(); if (failures == 0) printf("test_tgmd: ok\n");