diff --git a/plugins/cps/cps.c b/plugins/cps/cps.c index 81184c6..061a0ef 100644 --- a/plugins/cps/cps.c +++ b/plugins/cps/cps.c @@ -37,7 +37,9 @@ struct snap_msg { static struct { pthread_mutex_t lock; - size_t n; + size_t n; /* messages in the snapshot, <= SNAP_MAX */ + 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]; int requested; int ready; @@ -58,6 +60,8 @@ copy_snapshot(const struct sp_conv *conv) pthread_mutex_lock(&cps.lock); cps.n = n; + cps.total = conv->n; + cps.bytes = sp_conv_bytes(conv); for (i = 0; i < n; i++) { const struct sp_msg *m = &conv->v[i]; @@ -84,7 +88,13 @@ cps_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, return 0; pthread_mutex_lock(&cps.lock); - if (cps.ready && cps.n == conv->n && + /* + * 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. + */ + if (cps.ready && cps.total == conv->n && + cps.bytes == sp_conv_bytes(conv) && (budget == 0 || sp_conv_bytes(conv) > budget)) { apply = 1; } else { @@ -104,7 +114,11 @@ cps_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, cps.applied++; pthread_mutex_unlock(&cps.lock); - if (cut <= 1 || cut > conv->n) + /* a tool result goes with the call it answers, never alone */ + while (cut < conv->n && conv->v[cut].role != NULL && + strcmp(conv->v[cut].role, "tool") == 0) + cut++; + if (cut <= 1 || cut >= conv->n) return 0; for (i = 1; i < cut; i++) { free(conv->v[i].role); diff --git a/plugins/lcm/lcm.c b/plugins/lcm/lcm.c index 1c7e081..591d6c8 100644 --- a/plugins/lcm/lcm.c +++ b/plugins/lcm/lcm.c @@ -25,75 +25,80 @@ #define KEEP_TAIL 6 /* messages always kept verbatim */ #define PREVIEW 120 /* chars of the oldest dropped message */ +static int +is_role(const struct sp_msg *m, const char *role) +{ + return m->role != NULL && strcmp(m->role, role) == 0; +} + static int lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, unsigned turn) { - size_t bytes, i, drop, keep_from; + size_t bytes, i, drop, first, keep_from; char preview[PREVIEW + 1]; char summary[512]; size_t n_user = 0, n_asst = 0, n_tool = 0; - const char *oldest = NULL; + const char *oldest; (void)turn; + (void)h; if (conv == NULL || conv->n <= KEEP_TAIL + 1) return 0; bytes = sp_conv_bytes(conv); if (budget > 0 && bytes <= budget) return 0; /* fits: nothing to do */ - /* keep a leading system message, drop everything up to the tail */ + /* a leading system prompt stays; everything else may go */ + first = is_role(&conv->v[0], "system") ? 1 : 0; keep_from = conv->n - KEEP_TAIL; - if (keep_from <= 1) + /* + * The tail must not start with a tool result: its assistant turn, the + * one carrying the tool_call, would be gone, and a provider answers an + * orphaned tool message with a 400. Such results go with their call. + */ + while (keep_from < conv->n && is_role(&conv->v[keep_from], "tool")) + keep_from++; + if (keep_from >= conv->n || keep_from <= first) return 0; - drop = keep_from; - if (conv->n > 0 && strcmp(conv->v[0].role, "system") == 0) - drop--; /* the system prompt stays */ + drop = keep_from - first; - oldest = conv->v[conv->n - KEEP_TAIL].content; - for (i = 1; i < conv->n - KEEP_TAIL; i++) { - const char *r = conv->v[i].role; - - if (r == NULL) - continue; - if (strcmp(r, "user") == 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 (strcmp(r, "assistant") == 0) + else if (is_role(&conv->v[i], "assistant")) n_asst++; - else if (strcmp(r, "tool") == 0) + 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 %d messages follows. " + "to fit %zu bytes; the verbatim tail of %zu messages follows. " "Oldest dropped turn began with: \"%s\"", - drop, n_user, n_asst, n_tool, budget, KEEP_TAIL, preview); + drop, n_user, n_asst, n_tool, budget, conv->n - keep_from, preview); - /* remove [1 .. conv->n-KEEP_TAIL) */ - for (i = 1; i < conv->n - KEEP_TAIL; i++) { + for (i = first; i < keep_from; i++) { free(conv->v[i].role); free(conv->v[i].name); free(conv->v[i].call_id); free(conv->v[i].content); free(conv->v[i].calls); } - memmove(&conv->v[1], &conv->v[conv->n - KEEP_TAIL], - KEEP_TAIL * sizeof(*conv->v)); - conv->n = 1 + KEEP_TAIL; + memmove(&conv->v[first], &conv->v[keep_from], + (conv->n - keep_from) * sizeof(*conv->v)); + conv->n = first + (conv->n - keep_from); { struct sp_msg m; - size_t at = (conv->n > 0 && - strcmp(conv->v[0].role, "system") == 0) ? 1 : 0; memset(&m, 0, sizeof(m)); m.role = "system"; m.content = summary; - if (sp_conv_insert(conv, at, &m) != 0) + if (sp_conv_insert(conv, first, &m) != 0) return -1; } - (void)h; return 1; } diff --git a/src/builtin.c b/src/builtin.c index f85c3e5..78e8ce0 100644 --- a/src/builtin.c +++ b/src/builtin.c @@ -85,9 +85,10 @@ tool_echo(const char *args, struct sp_buf *out, void *ctx) static char secret_env[SECRET_MAX][96] = { "SPLINTER_API_KEY", "SPLINTER_TELEGRAM_TOKEN", "SPLINTER_MEM_KEY", - "SPLINTER_DELEGATE_KEY_*", "CLAUDE_CODE_OAUTH_TOKEN", "OLLAMA_KEY" + "SPLINTER_DELEGATE_KEY_*", "CLAUDE_CODE_OAUTH_TOKEN", "OLLAMA_KEY", + "SPLINTER_OLLAMA_KEY_*", "SPLINTER_MCP_TOKEN" }; -static size_t nsecret_env = 6; +static size_t nsecret_env = 8; int sp_secret_env_add(const char *name) diff --git a/src/config.c b/src/config.c index 8b40644..30d044b 100644 --- a/src/config.c +++ b/src/config.c @@ -520,6 +520,7 @@ scan_family(struct sp_config *c, const char *base, int is_ollama, size_t base_id for (i = 0; i < 64; i++) { char name[128], token[512], id[48]; const char *val; + int exit_added; if (i == 0) snprintf(name, sizeof(name), "%s", base); @@ -561,9 +562,12 @@ scan_family(struct sp_config *c, const char *base, int is_ollama, size_t base_id d->max_parallel = 1; added++; } + exit_added = 0; if (c->nexits < SP_CONFIG_MAX_DELEGATES) { struct sp_exit *e = &c->exit[c->nexits++]; + exit_added = 1; + memset(e, 0, sizeof(*e)); snprintf(e->id, sizeof(e->id), "ollama-%zu", c->nexits - 1); @@ -581,7 +585,12 @@ scan_family(struct sp_config *c, const char *base, int is_ollama, size_t base_id snprintf(envname, sizeof(envname), "SPLINTER_OLLAMA_KEY_%zu", base_idx + added); (void)setenv(envname, token, 1); - if (c->nexits > 0 && base_idx + added < 64) { + /* + * Only the exit made just now. With the table full, + * exit[nexits - 1] was the operator's own last exit, and + * this key replaced its key - sent to an unrelated endpoint. + */ + if (exit_added) { snprintf(c->exit[c->nexits - 1].key_env, sizeof(c->exit[0].key_env), "%s", envname); diff --git a/src/delegate.c b/src/delegate.c index 24db1a6..5175ae5 100644 --- a/src/delegate.c +++ b/src/delegate.c @@ -677,10 +677,10 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) long start; struct sp_buf err; - if (sp_buf_init(&err) != 0) - return -1; if (c->cfg->ndelegates == 0) return sp_buf_puts(out, "error: no delegate configured"); + if (sp_buf_init(&err) != 0) + return -1; v = args != NULL && args[0] == '{' ? mcp_parse(args) : NULL; tasks = v != NULL ? mcp_arg(v, "tasks") : NULL; @@ -763,10 +763,7 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) break; if (now_ms() - start > DELEGATE_TIMEOUT_MS) { sp_buf_puts(out, "[parallel: timeout, killing the rest]\n"); - for (i = 0; i < njobs; i++) - if (!jobs[i].done) - (void)kill(jobs[i].pid, SIGKILL); - break; + break; /* the loop below kills and reaps */ } if (ready <= 0) continue; @@ -811,6 +808,27 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) } } + /* + * Whatever is still running here was left by the timeout or by a poll() + * error: kill it, close its pipe and reap it. Before, each timeout left + * up to eight zombies and eight open fds behind, and the poll error path + * left the children running. + */ + for (i = 0; i < njobs; i++) { + if (jobs[i].done) + continue; + (void)kill(jobs[i].pid, SIGKILL); + if (jobs[i].fd >= 0) { + close(jobs[i].fd); + jobs[i].fd = -1; + } + while (waitpid(jobs[i].pid, NULL, 0) < 0 && errno == EINTR) + ; + jobs[i].done = 1; + jobs[i].end_ms = now_ms(); + jobs[i].status = -1; + } + /* * The planner needs to know who did what and how long it took - not just * a wall of answers. One header per task, then a summary with the totals diff --git a/src/telegram.c b/src/telegram.c index 263f7df..b498ffe 100644 --- a/src/telegram.c +++ b/src/telegram.c @@ -222,6 +222,25 @@ send_message(const char *token, long chat_id, const char *text, return rc; } +/* + * A Telegram id as a long. mcp_arg_int truncated to int: user ids above 2^31 + * (most accounts made in recent years) became garbage and were never + * allowed(), and supergroup chats (-100...) got replies sent nowhere. Telegram + * promises ids fit in 52 bits, so the double the parser holds is exact. + */ +static long +tg_id(const mcp_json *obj, const char *key) +{ + double d; + + if (obj == NULL) + return 0; + d = mcp_arg_num(obj, key, 0); + if (!(d > -4503599627370496.0 && d < 4503599627370496.0)) + return 0; /* NaN or beyond 2^52: not an id */ + return (long)d; +} + /* Is this update for a user we answer? */ static int allowed(const char *allow, long id) @@ -249,6 +268,18 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token, sp_buf_init(&answer) != 0 || sp_buf_init(&aerr) != 0) return -1; + /* + * Without a token every poll is a connection reset: a daemon that loops on + * that fills a log and burns a core while doing nothing. Refuse to start and + * say why, instead of pretending to listen. + */ + if (token == NULL || *token == '\0') { + fprintf(stderr, "splinter: no telegram token " + "(SPLINTER_TELEGRAM_TOKEN or telegram_token_env) - the gateway " + "needs one to listen\n"); + return -1; + } + (void)signal(SIGINT, on_signal); (void)signal(SIGTERM, on_signal); fprintf(stderr, "splinter: gateway listening (allow: %s)\n", @@ -293,19 +324,16 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token, volatile int tstop = 0; struct typing ty; int typing_on = 0; - long chat_id, from; - int update_id; + long chat_id, from, update_id; - update_id = mcp_arg_int(update, "update_id", 0); - offset = (long)update_id + 1; + update_id = tg_id(update, "update_id"); + offset = update_id + 1; msg = mcp_arg(update, "message"); if (msg == NULL) continue; text = mcp_arg_string(msg, "text"); - chat_id = mcp_arg_int(mcp_arg(msg, "chat"), - "id", 0); - from = mcp_arg_int(mcp_arg(msg, "from"), - "id", 0); + chat_id = tg_id(mcp_arg(msg, "chat"), "id"); + from = tg_id(mcp_arg(msg, "from"), "id"); if (text == NULL || *text == '\0' || chat_id == 0) continue; if (!allowed(allow, from)) { diff --git a/tests/test_compactor.c b/tests/test_compactor.c index 4ce6934..1eb21fb 100644 --- a/tests/test_compactor.c +++ b/tests/test_compactor.c @@ -125,6 +125,50 @@ main(void) CHECK(compactions >= 1); CHECK(failed == 0); + /* + * ---- lcm never leaves a tool result without its call ---- + * system, user, then [assistant+tool_calls, tool, tool] x 4, then a user: + * fifteen messages, and the verbatim tail of six would begin with a tool + * result whose assistant turn is cut away. A provider answers that with + * a 400. + */ + { + struct sp_conv tc; + struct sp_msg m; + char big[300]; + size_t k; + int orphan = 0; + + sp_conv_init(&tc); + memset(big, 'x', sizeof(big) - 1); + big[sizeof(big) - 1] = '\0'; + sp_conv_push(&tc, "system", NULL, "you are a harness"); + sp_conv_push(&tc, "user", NULL, big); + for (k = 0; k < 4; k++) { + memset(&m, 0, sizeof(m)); + m.role = "assistant"; + m.content = ""; + m.calls = "[{\"id\":\"c\",\"type\":\"function\"}]"; + CHECK(sp_conv_add(&tc, &m) == 0); + sp_conv_push(&tc, "tool", "read", big); + sp_conv_push(&tc, "tool", "read", big); + } + sp_conv_push(&tc, "user", NULL, "and now?"); + CHECK(tc.n == 15); + CHECK(strcmp(tc.v[tc.n - 6].role, "tool") == 0); + CHECK(sp_host_compact(host, &tc, 400) == 1); + for (k = 1; k < tc.n; k++) + if (strcmp(tc.v[k].role, "tool") == 0 && + strcmp(tc.v[k - 1].role, "assistant") != 0 && + strcmp(tc.v[k - 1].role, "tool") != 0) + orphan = 1; + CHECK(!orphan); + CHECK(strcmp(tc.v[0].role, "system") == 0); + CHECK(strstr(tc.v[1].content, "[lcm]") != NULL); + CHECK(strcmp(tc.v[tc.n - 1].content, "and now?") == 0); + sp_conv_free(&tc); + } + /* ---- a plugin that is not a compactor cannot register one ---- */ CHECK(sp_host_add_compactor(host, NULL) == -1); diff --git a/tests/test_config.c b/tests/test_config.c index 00c83b0..7e17190 100644 --- a/tests/test_config.c +++ b/tests/test_config.c @@ -162,6 +162,37 @@ main(void) (void)unsetenv("CLAUDE_CODE_OAUTH_TOKEN"); } + /* + * ---- a full exit table keeps the operator's keys ---- + * With no room for another exit, an OLLAMA_KEY used to overwrite the + * key_env of the last configured exit: that key then went to an + * unrelated endpoint. + */ + { + struct sp_config c; + size_t k; + + sp_config_init(&c); + for (k = 0; k < SP_CONFIG_MAX_DELEGATES; k++) { + snprintf(c.exit[k].id, sizeof(c.exit[k].id), "mine-%zu", k); + snprintf(c.exit[k].key_env, sizeof(c.exit[k].key_env), + "MY_KEY_%zu", k); + } + c.nexits = SP_CONFIG_MAX_DELEGATES; + (void)setenv("OLLAMA_KEY", "k1", 1); + (void)sp_config_scan_env(&c); + CHECK(c.nexits == SP_CONFIG_MAX_DELEGATES); + { + char want[64]; + + snprintf(want, sizeof(want), "MY_KEY_%d", + SP_CONFIG_MAX_DELEGATES - 1); + CHECK(strcmp(c.exit[SP_CONFIG_MAX_DELEGATES - 1].key_env, + want) == 0); + } + (void)unsetenv("OLLAMA_KEY"); + } + /* ---- drop-ins: a directory next to the config, read in name order ---- */ { char dir[512], main_c[600], drop[600];