diff --git a/README.md b/README.md index dc7dfc7..f80b015 100644 --- a/README.md +++ b/README.md @@ -533,6 +533,16 @@ is split at tag boundaries, with the open tags closed and reopened per message, and a piece Telegram refuses to parse is sent as plain text instead. `SPLINTER_TG_MARKDOWN=0` turns the rendering off. +`/compact [tokens]` runs the compactors now (default target: `compact_target`, +else 8000 tokens) and reports messages/bytes before and after. With +`compact_threshold` set, the harness compacts automatically once the last +request was larger than that: the conversation is cut to `compact_target` +before the next turn, so the context never grows without bound. Compaction +rewrites the prompt prefix, which invalidates the provider's prompt cache - the +threshold is the knob that trades cache hits for a smaller context. What was +dropped stays in the session log, and the `recall` tool searches it: the model +can look an earlier turn up instead of guessing. + `/new` (or `/reset`) starts a fresh conversation and a fresh session file; the old one stays on disk, and the system prompt is put back. diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 9d7e025..2efd62d 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -243,6 +243,8 @@ lies about what it does. | `autonomous` | `1` runs mutating/destructive tools without asking | | `steps` | tool rounds per turn (default 150) | | `max_bytes` | conversation budget in bytes, `0` = no limit | +| `compact_threshold` | context tokens past which the next request is compacted (`0` = off) | +| `compact_target` | the size compaction aims for, in tokens; `/compact [tokens]` forces it now | | `session_dir` | where session logs go (default `~/.splinter`) | | `system_prompt` | sent once at the start of a conversation | | `telegram_allow` | user ids the gateway answers, comma-separated; empty means nobody | diff --git a/include/splinter.h b/include/splinter.h index f852f0c..fff8290 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -293,6 +293,13 @@ int sp_session_delete(const char *dir, const char *id, struct sp_buf *err); struct sp_agent_config { size_t max_steps; /* tool rounds per turn */ size_t max_bytes; /* request budget */ + /* + * Compaction by tokens: past `compact_threshold` the next request is + * compacted to `compact_target` (both in tokens, 0 = off). The byte + * budget stays the hard ceiling. + */ + size_t compact_threshold; + size_t compact_target; const char *system_prompt; int autonomous; /* 1: run mutate tools without asking */ FILE *approval_in; /* NULL with !autonomous means deny */ diff --git a/plugins/lcm/lcm.c b/plugins/lcm/lcm.c index c8192d2..c8c2a51 100644 --- a/plugins/lcm/lcm.c +++ b/plugins/lcm/lcm.c @@ -15,12 +15,14 @@ * call, nothing that makes a run unreproducible. The harder variant (an LLM * writes the summary) is a different plugin, not a flag on this one. */ +#include #include #include #include #include "splinter.h" #include "splinter_plugin.h" +#include "mcp.h" #define KEEP_TAIL 6 /* messages always kept verbatim */ #define PREVIEW 120 /* chars of the oldest dropped message */ @@ -104,12 +106,102 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, return 1; } +/* case-blind substring for the recall tool */ +static int +has_ci(const char *hay, const char *needle) +{ + size_t n = strlen(needle), i; + const char *p; + + for (p = hay; *p != '\0'; p++) { + for (i = 0; i < n && p[i] != '\0'; i++) + if (tolower((unsigned char)p[i]) != + tolower((unsigned char)needle[i])) + break; + if (i == n) + return 1; + } + return 0; +} + +/* + * What compaction dropped is still in the session log. This reads it: the + * model can go back to an earlier turn instead of guessing, and the operator + * can prove what was said. + */ +static int +lcm_recall(const char *args, struct sp_buf *out, void *ctx) +{ + char query[256] = "", path[800], line[8192]; + struct sp_host *h = ctx; + const char *dir = sp_host_session_dir(h); + const char *id = sp_host_session_id(h); + mcp_json *v; + const char *q; + FILE *f; + int limit = 10, n = 0; + + if (args != NULL && args[0] == '{') { + v = mcp_parse(args); + if (v != NULL) { + q = mcp_arg_string(v, "query"); + if (q != NULL) + snprintf(query, sizeof(query), "%s", q); + limit = mcp_arg_int(v, "limit", 10); + mcp_json_free(v); + } + } + if (query[0] == '\0') + return sp_buf_puts(out, "error: 'query' is required"); + if (limit < 1 || limit > 50) + limit = 10; + if (dir == NULL || *dir == '\0' || id == NULL || *id == '\0') + return sp_buf_puts(out, "error: no session log"); + snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id); + f = fopen(path, "r"); + if (f == NULL) + return sp_buf_puts(out, "error: cannot read the session log"); + while (n < limit && fgets(line, sizeof(line), f) != NULL) { + char *text; + + if (!has_ci(line, query)) + continue; + n++; + text = line; + sp_buf_printf(out, "%s", text); + } + fclose(f); + if (n == 0) + sp_buf_printf(out, "no line in the session log contains '%s'", + query); + return 0; +} + +static const struct sp_tool recall_tool = { + "recall", + "Search the session log for text that is no longer in the context " + "(compaction drops it from the prompt, not from the log). Use it " + "before guessing about something that happened earlier.", + "{\"type\":\"object\",\"properties\":{" + "\"query\":{\"type\":\"string\",\"description\":\"text to find\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"max matching lines, " + "default 10\"}},\"required\":[\"query\"]}", + SP_AUTH_READ, + lcm_recall, + NULL +}; + static const struct sp_compactor lcm = { "lcm", lcm_compact }; static int lcm_init(struct sp_host *h) { - return sp_host_add_compactor(h, &lcm); + static struct sp_tool rt = recall_tool; + + rt.ctx = h; + if (sp_host_add_compactor(h, &lcm) != 0) + return -1; + return sp_host_add_tool(h, &rt); } static const struct sp_plugin lcm_plugin = { diff --git a/src/backend/agent.c b/src/backend/agent.c index ce3ecba..60bf6c1 100644 --- a/src/backend/agent.c +++ b/src/backend/agent.c @@ -424,7 +424,15 @@ guarded_stream(void *ctx, int kind, const char *text) { struct stream_guard *g = ctx; - g->produced = 1; + /* + * Only an answer (or a tool call) makes a retry unsafe. Reasoning that + * was streamed before a provider cut the stream is not an answer: a + * retry may repeat it, but a turn without one would be lost. This is + * why "stream ended with no answer" after a reasoning-only stream used + * to abort with no retry at all. + */ + if (kind == SP_STREAM_TEXT || kind == SP_STREAM_TOOL) + g->produced = 1; if (g->cb != NULL) g->cb(g->ctx, kind, text); } @@ -635,8 +643,18 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, /* compaction happens before the budget is judged, never after */ if (a->host != NULL) { size_t cb = sp_conv_bytes(conv), cn = conv->n; + size_t cbudget = a->cfg->max_bytes; - if (sp_host_compact(a->host, conv, a->cfg->max_bytes) > 0) { + /* + * The token threshold is the automatic compaction: past + * it, the request is compacted to the target instead of + * waiting for the byte ceiling. + */ + if (a->cfg->compact_threshold > 0 && + a->cfg->compact_target > 0 && + a->stats.last_in > a->cfg->compact_threshold) + cbudget = a->cfg->compact_target * 4; + if (sp_host_compact(a->host, conv, cbudget) > 0) { a->stats.compactions++; if (a->cfg != NULL && a->cfg->on_compact != NULL) a->cfg->on_compact(a->cfg->on_compact_ctx, diff --git a/src/backend/config.h b/src/backend/config.h index b6699d1..7eb2d79 100644 --- a/src/backend/config.h +++ b/src/backend/config.h @@ -154,6 +154,8 @@ struct sp_config { size_t nmcp; size_t steps; /* 0: not set */ size_t max_bytes; /* 0: not set */ + size_t compact_threshold; /* tokens, 0 = off */ + size_t compact_target; /* tokens */ long http_timeout; /* seconds for HTTP/SSE requests, 0: default */ long cli_timeout; /* seconds for cli transport, 0: default */ long delegate_timeout; /* seconds for delegate children, 0: default */ diff --git a/src/backend/engine.c b/src/backend/engine.c index e533102..e31a240 100644 --- a/src/backend/engine.c +++ b/src/backend/engine.c @@ -1522,7 +1522,7 @@ int sp_engine_command_names(struct sp_engine *e, char (*names)[64], int max) { static const char *builtin[] = { - "agent", "agents", "connect", "continue", "exit", "model", + "agent", "agents", "compact", "connect", "continue", "exit", "model", "new", "q", "quit", "rename", "reset", "resume", "rm", "status", "swarm", "usage", "widgets" }; @@ -2031,6 +2031,33 @@ sp_engine_input(struct sp_engine *e, const char *line, struct sp_buf *out) sp_usage_report(e->conf, out); return SP_INPUT_HANDLED; } + if (strcmp(name, "compact") == 0) { + size_t before = sp_conv_bytes(&e->conv); + size_t msgs = e->conv.n; + size_t tokens = e->conf != NULL && + e->conf->compact_target > 0 ? + e->conf->compact_target : 8000; + size_t budget = tokens * 4; + int changed; + + if (args[0] != '\0') { + char *end; + unsigned long n = strtoul(args, &end, 10); + + if (*end == '\0' && n > 0 && n < 1000000) { + tokens = (size_t)n; + budget = tokens * 4; + } + } + changed = e->host != NULL ? + sp_host_compact(e->host, &e->conv, budget) : 0; + sp_buf_printf(out, "compact: %zu->%zu msgs, %zu->%zu bytes " + "(target %zu tokens)%s", msgs, e->conv.n, before, + sp_conv_bytes(&e->conv), tokens, + changed ? "" : " - nothing to do"); + ev_push(e, SP_EV_STATE, 0, NULL, NULL); + return SP_INPUT_HANDLED; + } if (strcmp(name, "status") == 0) { cmd_status(e, out); return SP_INPUT_HANDLED; @@ -2396,6 +2423,10 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o, sp_buf_init(&e->steer); e->conf = o->conf; e->base = *o->base; + if (e->conf != NULL) { + e->base.compact_threshold = e->conf->compact_threshold; + e->base.compact_target = e->conf->compact_target; + } e->max_wait = o->conf->max_wait > 0 ? o->conf->max_wait : 12 * 3600; /* * A pool must be able to move the run to another member at a limit -- diff --git a/tests/test_agent.c b/tests/test_agent.c index 2b3458b..9666063 100644 --- a/tests/test_agent.c +++ b/tests/test_agent.c @@ -64,6 +64,29 @@ setup(struct sp_registry *r) (void)sp_registry_add(r, &t); } +/* a stream that thinks, dies without an answer, then answers */ +static int flaky_calls; +static void no_stream(void *ctx, int kind, const char *text) +{ + (void)ctx; (void)kind; (void)text; +} +static int +flaky_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, + struct sp_buf *err, sp_stream_cb cb, void *cbctx) +{ + (void)ctx; (void)conv; + flaky_calls++; + if (flaky_calls == 1) { + if (cb != NULL) + cb(cbctx, SP_STREAM_THINK, "denke nach..."); + sp_buf_puts(err, "openai: stream ended with no answer: "); + return -1; + } + out->status = 200; + out->content = strdup("answer after the retry"); + return 0; +} + static char note_text[256]; static int note_seen; @@ -271,6 +294,37 @@ main(void) CHECK(strstr(m.last_request.p, "observe echo c") == NULL); sp_mock_free(&m); + /* + * A stream that only carried reasoning and then ended without an + * answer must be retried: the thinking is not an answer, and aborting + * without a retry loses the turn. + */ + { + struct sp_agent a; + struct sp_agent_config cfg; + struct sp_transport tr; + + (void)setenv("SPLINTER_RETRY_WAIT_MS", "0", 1); + memset(&a, 0, sizeof(a)); + memset(&cfg, 0, sizeof(cfg)); + memset(&tr, 0, sizeof(tr)); + cfg.max_steps = 4; + cfg.autonomous = 1; + cfg.stream = no_stream; + tr.send_stream = flaky_stream; + a.reg = &r; + a.cfg = &cfg; + a.tr = tr; + flaky_calls = 0; + sp_buf_clear(&answer); + sp_buf_clear(&err); + CHECK(sp_agent_run(&a, "hi", &answer, &err) == 0); + CHECK(flaky_calls == 2); + CHECK(strstr(answer.p, "answer after the retry") != NULL); + sp_conv_free(a.conv); + (void)unsetenv("SPLINTER_RETRY_WAIT_MS"); + } + sp_buf_free(&answer); sp_buf_free(&err); sp_registry_free(&r);