/* * splinter -- lcm: lossy compression memory for the conversation. * * Copyright (c) 2026 Konrad Lother * SPDX-License-Identifier: BSD-3-Clause * * The rule this plugin follows: a conversation that does not fit the budget is * cut from the front, but never silently. What is dropped is replaced by one * system message that says how much went, of which roles, and quotes the head * of the oldest dropped turn — so a model (and a human reading the session log) * can tell the difference between "the user never said that" and "that was * compacted away". * * Deterministic on purpose: no second model, no summary that costs another * 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 #include #include "splinter.h" #include "splinter_plugin.h" #include "mcp.h" #define KEEP_TAIL 6 /* default: messages always kept verbatim */ #define PREVIEW 120 /* chars of the oldest dropped message */ #define TOOL_TRIM 8192 /* default: older tool outputs are cut to this */ #define RECALL_HIT 1600 /* bytes shown of one matching line */ #define RECALL_TOTAL 12000 /* bytes of matches, so recall stays cheap */ static size_t keep_tail = KEEP_TAIL; static size_t tool_trim = TOOL_TRIM; /* what the widget and the status segment show; written by the compactor */ static pthread_mutex_t lcm_lock = PTHREAD_MUTEX_INITIALIZER; static unsigned compactions; static size_t dropped_total; static unsigned trimmed_total; static size_t last_msgs_from, last_msgs_to; static size_t last_bytes_from, last_bytes_to; static int 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) { size_t i = 0; while (s[i] != '\0' && i < n && s[i] != '\n' && i + 1 < cap) { unsigned char c = (unsigned char)s[i]; out[i] = (c >= 32 && c != 127) ? (char)c : ' '; i++; } out[i] = '\0'; } /* * Tool outputs are the bulk of a long conversation. Before messages are * dropped, every old observation is cut to a head and a tail with a marker in * between; the middle is still in the session log, where the recall tool finds * it. The recent tail (the messages we keep verbatim) is never touched, so the * model always has the output it just asked for. */ static int trim_tools(struct sp_conv *conv, size_t first, size_t end, size_t cap) { size_t i; int n = 0; if (cap == 0) return 0; for (i = first; i < end; i++) { struct sp_msg *m = &conv->v[i]; size_t len, head, tail, off, room; char *hint = "", *nb; if (!is_role(m, "tool") || m->content == NULL) continue; len = strlen(m->content); if (len <= cap) continue; head = cap / 2; tail = cap / 4; if (head + tail >= len) continue; { static char hbuf[72]; first_line(m->content, hbuf, sizeof(hbuf), 60); hint = hbuf; } nb = malloc(head + tail + 512); if (nb == NULL) continue; memcpy(nb, m->content, head); off = head; room = head + tail + 512 - off; off += (size_t)snprintf(nb + off, room, "\n[lcm] %zu bytes of tool output cut; recall \"%s\"\n", len - head - tail, hint); memcpy(nb + off, m->content + len - tail, tail); off += tail; nb[off] = '\0'; free(m->content); m->content = nb; n++; } 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) { size_t bytes, i, drop, first, keep_from; size_t msgs_before, bytes_before; char preview[PREVIEW + 1]; char summary[512]; size_t n_user = 0, n_asst = 0, n_tool = 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; (void)turn; (void)h; if (conv == NULL || conv->n <= keep_tail + 1) return 0; if (budget == 0) return 0; /* no byte budget: nothing to do */ bytes = sp_conv_bytes(conv); msgs_before = conv->n; bytes_before = bytes; if (bytes <= budget) return 0; /* fits: nothing to do */ /* a leading system prompt stays; everything else may go */ first = is_role(&conv->v[0], "system") ? 1 : 0; keep_from = conv->n - keep_tail; /* * 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. * * Walk BACK to that assistant, not forward past the results. Forward * was the first try and it silently shrank the tail: a turn with two * results at the boundary kept four messages where keep_tail says six. * Measured 2026-11-21 on system + user + [assistant, tool, tool] x4 + * user: fifteen messages, tail of six, result was a tail of four. */ while (keep_from < conv->n && keep_from > first && is_role(&conv->v[keep_from], "tool")) keep_from--; if (keep_from >= conv->n || keep_from <= first) return 0; /* * First the cheap cut: old tool outputs. If that is enough the messages * stay, and only the observations shrink. */ trimmed = trim_tools(conv, first, keep_from, tool_trim); if (trimmed > 0) { pthread_mutex_lock(&lcm_lock); trimmed_total += (unsigned)trimmed; pthread_mutex_unlock(&lcm_lock); bytes = sp_conv_bytes(conv); if (bytes <= budget) { pthread_mutex_lock(&lcm_lock); compactions++; dropped_total += 0; last_msgs_from = last_msgs_to = conv->n; last_bytes_from = bytes_before; last_bytes_to = bytes; pthread_mutex_unlock(&lcm_lock); return 1; } } /* * 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. 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")) 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) pin_name = strdup(conv->v[pin_at].name); 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 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_bytes <= add_bytes) { free(pin_content); free(pin_name); if (trimmed > 0) { pthread_mutex_lock(&lcm_lock); compactions++; last_msgs_from = last_msgs_to = conv->n; last_bytes_from = bytes_before; last_bytes_to = sp_conv_bytes(conv); pthread_mutex_unlock(&lcm_lock); return 1; } return 0; } 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[first], &conv->v[keep_from], (conv->n - keep_from) * sizeof(*conv->v)); conv->n = first + (conv->n - keep_from); { struct sp_msg m; memset(&m, 0, sizeof(m)); m.role = "system"; m.content = summary; if (sp_conv_insert(conv, first, &m) != 0) goto fail; } if (pinned) { struct sp_msg m; memset(&m, 0, sizeof(m)); m.role = "user"; m.name = pin_name; m.content = pin_content; if (sp_conv_insert(conv, first + 1, &m) != 0) goto fail; } { pthread_mutex_lock(&lcm_lock); compactions++; dropped_total += drop; last_msgs_from = msgs_before; last_msgs_to = conv->n; last_bytes_from = bytes_before; last_bytes_to = sp_conv_bytes(conv); pthread_mutex_unlock(&lcm_lock); } free(pin_content); free(pin_name); return 1; fail: free(pin_content); free(pin_name); 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]; char *line = NULL; size_t linecap = 0; ssize_t len; 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"); /* * getline, not fgets: one session line is one JSON object, and an * observation can be tens of KiB. An 8 KiB buffer cut such a line into * pieces, so a match in the middle came back without its context and a * long hit was printed in full. A hit now shows head and tail and says * how much was cut; the whole answer is bounded. */ while (n < limit && (len = getline(&line, &linecap, f)) != -1) { if (!has_ci(line, query)) continue; n++; if ((size_t)len > RECALL_HIT) { size_t head = RECALL_HIT - 400, tail = 400; sp_buf_printf(out, "%.*s\n[lcm] %zd bytes cut (recall)\n", (int)head, line, len - (ssize_t)(head + tail)); sp_buf_puts(out, line + len - (ssize_t)tail); if (line[len - 1] != '\n') sp_buf_puts(out, "\n"); } else { sp_buf_puts(out, line); } if (out->len >= RECALL_TOTAL) { sp_buf_puts(out, "... more matches not shown (recall " "limit)\n"); break; } } free(line); 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, NULL }; static const struct sp_compactor lcm = { "lcm", lcm_compact }; /* "12.3k" for a token count, "842" below a thousand */ static void human(size_t n, char *buf, size_t cap) { if (n >= 1000000) snprintf(buf, cap, "%.1fM", (double)n / 1e6); else if (n >= 1000) snprintf(buf, cap, "%.1fk", (double)n / 1e3); else snprintf(buf, cap, "%zu", n); } /* * What compaction did, in the sidebar: the context the last request carried, * how often lcm cut, and how the last cut looked. The counters are the * compactor's own, not a second estimate. */ static int lcm_tick(struct sp_host *h, const char *name, void *ctx) { struct sp_meter m; char used[24], max[24], text[512]; unsigned c; size_t dropped, from, to; unsigned trimmed; size_t bf, bt; (void)ctx; sp_host_meter_get(h, &m); pthread_mutex_lock(&lcm_lock); c = compactions; dropped = dropped_total; trimmed = trimmed_total; from = last_msgs_from; to = last_msgs_to; bf = last_bytes_from; bt = last_bytes_to; pthread_mutex_unlock(&lcm_lock); human(m.ctx_used, used, sizeof(used)); if (m.ctx_max > 0) human(m.ctx_max, max, sizeof(max)); else snprintf(max, sizeof(max), "?"); snprintf(text, sizeof(text), "ctx %s/%s\n" "compacted %u cut %zu msgs\n" "last %zu->%zu msgs %zu->%zu B\n" "tools trimmed %u", used, max, c, dropped, from, to, bf, bt, trimmed); return sp_host_widget_text(h, name, text); } static void lcm_status(struct sp_host *h, char *buf, size_t len) { unsigned c; (void)h; pthread_mutex_lock(&lcm_lock); c = compactions; pthread_mutex_unlock(&lcm_lock); snprintf(buf, len, "compact %u", c); } static int lcm_init(struct sp_host *h) { static struct sp_tool rt = recall_tool; const char *v; v = sp_host_plugin_config(h, "lcm", "keep"); if (v != NULL && atoi(v) > 0 && atoi(v) < 1000) keep_tail = (size_t)atoi(v); v = sp_host_plugin_config(h, "lcm", "tool_trim"); if (v != NULL && atoi(v) >= 0) tool_trim = (size_t)atoi(v); static const struct sp_widget w = { "lcm", lcm_tick, NULL, NULL, 2000 }; static const struct sp_status seg = { "compact", lcm_status }; rt.ctx = h; if (sp_host_add_compactor(h, &lcm) != 0) return -1; if (sp_host_add_widget(h, &w) != 0) return -1; if (sp_host_add_status(h, &seg) != 0) return -1; return sp_host_add_tool(h, &rt); } static const struct sp_plugin lcm_plugin = { SP_PLUGIN_ABI, "lcm", "1.0.0", lcm_init, NULL, NULL }; const struct sp_plugin * sp_plugin_describe(void) { return &lcm_plugin; }