Files
splinter/plugins/lcm/lcm.c
T
lotherk af2001bfee ui, model, cost and idle timeouts
- lcm: the sidebar widget and /status segment show the context, the number of
  compactions, messages and bytes of the last cut, and how many old tool
  outputs were trimmed. The counters are the compactor's own, not an estimate.
- cost: a provider-reported USD cost (usage.cost/cost_usd) is carried through
  sse/openai, the agent and the engine. /cost reports it with the cache share
  and splits judged from plain turns; the notes say that an upstream judge is
  not visible in the provider's usage. The status plugin and junction prefer
  the reported number over list-price arithmetic.
- curses: the running turn's seconds moved from the input line to the status
  bar. Notes and errors are transcript rows below the cause, never text in the
  input line or the status bar; a failed backend request is a status row and is
  retried by the agent. The steer prompt is only "steer> " and what was typed.
- model: /model probe works in the chat. The picker lists the configuration at
  once, then asks the endpoint the session is on what it serves and adds those
  models, so a router's whole menu is selectable. provider/model selectors now
  apply the right provider instead of becoming a model name. The choice is
  written to <session>.model and restored when that session is reopened; /new
  carries the current model into the new session.
- sidebar: plugin titles are bold and underlined (this curses has no italic
  attribute), with a rule between the plugin blocks.
- run/cli: a command timeout is an idle window. Every chunk on stdout or
  stderr resets it, and the process is asked with waitpid(WNOHANG) whether it
  is still there before the window is extended. A long build that keeps
  reporting progress is no longer killed for being long; a silent hang is.
- config: ';' separates settings on one line, so
  plugin lcm { keep = 6; tool_trim = 8192 } parses as two keys.
- tests: lcm widget/status counters, one-line config blocks, session model
  restore and /model probe, cli idle timeout with a talkative and a silent
  command, run output reset, and the UI status/retry rows.

make check: all tests passed.
2026-11-17 23:21:56 +00:00

455 lines
12 KiB
C

/*
* 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 <ctype.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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 */
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 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;
}
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 pin_at = 0;
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.
*/
while (keep_from < conv->n && 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.
*/
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) {
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++) {
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);
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], 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 };
/* "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;
}