sessions: a resumed session is the whole transcript, not a chat log

A session file was written as if it were a chat: role and text, nothing
else. Reading it back kept "user" and "assistant" and dropped everything
else - and nearly every line of an agent transcript is an observation.
Measured on three real sessions: 21 of 1507 messages came back, 8 of 1356,
3 of 317. --resume then sent 1% of the conversation and the model had no
idea what it was continuing.

Three writers had to change with the loader:

  - A turn that asked for tools wrote no line at all (agent.c only wrote
    when ncalls == 0). It now goes out with its tool_calls, and each result
    with the name of its tool and its call id; a provider rejects a tool
    message without them.
  - {"role":"user","text":""} came from the steer path and showed the model
    a blank human turn it answered. sp_session_append_rec writes nothing
    when text and calls are both empty.
  - A record from the old format has no name and no call id. It is paired
    with the next unanswered call of its pending assistant turn, or given a
    synthetic one (recovered-N). Dropping it is what emptied every resume;
    keeping it unpaired is what a provider answers with 400.

The same pass gives the core its own compactor (compact.c): a thread digest
- one line per dropped message, OPERATOR: 800 chars, assistant: 300, tool
result 160 - so the model keeps the story, not a count. lcm stays a plugin
that runs after it; sp_core_compactor() is the fallback only when no plugin
registered one, because running both eats the conversation before lcm sees
work to do.

Two bugs fell out of the same area:

  - The plugin host was only built when a plugin was configured, so a
    plugin-less run had no compactor at all: over max_bytes the turn was
    refused instead of compacted (90 KB session, budget 8000, "nothing
    sent").
  - lcm walked *forward* past tool results at the tail boundary, which
    silently shrank the tail: a turn with two results kept four messages
    where keep_tail says six. Walking back to the assistant that carries
    the call keeps six and no orphan.

And the .meta sidecar is shared now: the core rewrote it with only the keys
it knew, so anything a plugin put there was gone on the next open. It
carries unknown lines through (extra[8][160]), which is what lets a plugin
mark a session in the core's own file.

Tests: tests/test_corecompact.c (10 checks, no plugin), the resume cases in
tests/test_session.c, and the tail-size check in tests/test_compactor.c.
Each was seen red on the old code before it was green on the new.
This commit is contained in:
lotherk committed 2026-11-21 21:25:51 +00:00
1 parent 226fff3461
commit f7120882fa
15 files changed
+1753 -35

No files matched your search

+40 -5
View File
@@ -332,9 +332,17 @@ run_one(struct sp_agent *a, struct sp_conv *conv,
sp_buf_puts(err, "agent: out of memory");
return -1;
}
if (a->sess != NULL &&
sp_session_append(a->sess, "observation", obs->p, err) != 0)
return -1;
if (a->sess != NULL) {
struct sp_sess_rec rec;
memset(&rec, 0, sizeof(rec));
rec.role = "tool";
rec.text = obs->p;
rec.name = call->name;
rec.call_id = call->id;
if (sp_session_append_rec(a->sess, &rec, err) != 0)
return -1;
}
return 0;
}
@@ -788,9 +796,10 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
sp_buf_free(&steer);
}
/* 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;
int changed = 0;
/*
* The token threshold is the automatic compaction: past
@@ -801,7 +810,14 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
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) {
/*
* The engine always builds the host, plugins or not:
* it is how the compactor learns whether the tools
* exist. A fallback here would compact without that
* knowledge and lose the hint.
*/
changed = sp_host_compact(a->host, conv, cbudget);
if (changed > 0) {
a->stats.compactions++;
if (a->cfg != NULL && a->cfg->on_compact != NULL)
a->cfg->on_compact(a->cfg->on_compact_ctx,
@@ -957,6 +973,25 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
sp_reply_free(&reply);
goto oom;
}
/*
* A turn that asks for tools used to leave no line at
* all, so a resumed session had answers with no calls
* and results with no name. Write the turn with its
* tool_calls; the results follow as they run.
*/
if (a->sess != NULL) {
struct sp_sess_rec rec;
memset(&rec, 0, sizeof(rec));
rec.role = "assistant";
rec.text = reply.content;
rec.calls = reply.calls_json;
if (sp_session_append_rec(a->sess, &rec,
err) != 0) {
sp_reply_free(&reply);
goto out;
}
}
}
for (i = 0; i < reply.ncalls; i++) {
int r = run_one(a, conv, &reply.calls[i], 0, 0, &obs,
+540
View File
@@ -0,0 +1,540 @@
/*
* splinter -- compact: the compactor the core owns.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Compaction used to live only in the lcm plugin, which made `compact_threshold`
* and `compact_target` dead settings: the agent read them, built a budget from
* them, and handed it to a compactor list that was empty unless a plugin had
* been loaded. A harness whose own configuration does nothing is worse than one
* that has no such configuration, because the operator believes it is working.
*
* So the core carries a compactor of its own, and it runs when no plugin does.
*
* Two things were learned the hard way, and they shape everything below.
*
* 1. A cut that leaves only a statistic line loses the thread. lcm replaced the
* dropped range with "[lcm] 42 messages compacted out (user 12, ...)" and
* quoted 120 characters of the oldest one. The model then no longer knew what
* the work was, re-asked, and the operator called it "losing the fade" - a
* correct complaint. What has to survive is not a count, it is the story:
* who asked what, in order.
*
* 2. Tool output is where the bytes are, and the head of an observation is the
* part that matters. Trimming bodies saves most of the budget before any
* message has to go.
*
* So the order of work is:
*
* 1. trim every tool body outside the verbatim tail
* 2. still over budget: build a THREAD DIGEST of the dropped range. Every user
* message survives nearly whole; every assistant turn keeps its opening;
* every observation is reduced to a line. The digest is one system message.
* 3. the newest real user message is pinned after the digest, so the question
* being answered is never something the model has to infer.
* 4. if the digest plus the tail still exceeds the budget, the caps shrink
* step by step, cheapest role first. The digest is never dropped whole.
*
* Nothing here calls a second model: a summary that costs a request and makes a
* run unreproducible is a different feature, not a flag on this one.
*
* The tail boundary never lands on a "tool" message: its assistant turn carries
* the tool_call, and a provider rejects an orphaned tool result with a 400.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "splinter.h"
#include "splinter_plugin.h"
#define COMPACT_KEEP_TAIL 6 /* messages always kept verbatim */
#define COMPACT_KEEP_HEAD 8 /* leading system messages never digested */
#define COMPACT_TOOL_TRIM 2048 /* a tool body outside the tail */
/* Per-role caps inside the digest. User text is the thread: keep it nearly
* whole. An assistant turn is mostly restating its tool call, so its opening
* is enough. An observation is already trimmed by then. */
#define CAP_USER 800
#define CAP_ASSISTANT 300
#define CAP_TOOL 160
#define CAP_MIN_USER 120
#define CAP_MIN_ASSISTANT 40
#define CAP_MIN_TOOL 0
struct caps {
size_t user;
size_t assistant;
size_t tool;
};
static size_t
msg_bytes(const struct sp_msg *m)
{
size_t n = 16; /* JSON scaffolding, estimated */
n += m->role != NULL ? strlen(m->role) : 0;
n += m->name != NULL ? strlen(m->name) : 0;
n += m->content != NULL ? strlen(m->content) : 0;
n += m->calls != NULL ? strlen(m->calls) : 0;
return n;
}
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 prompt ("Continue with the task ...") arrives as
* a user message but is not the question. Pinning it keeps the keystroke and
* loses the task it was meant to continue - measured on a session resumed after
* a rate limit, which woke up with the prompt, one tool call and no task.
*/
static int
is_continuation(const struct sp_msg *m)
{
static const char *prefix[] = {
"Continue with the task",
"Setze die Aufgabe",
NULL
};
size_t i;
if (m->content == NULL)
return 0;
for (i = 0; prefix[i] != NULL; i++)
if (strncmp(m->content, prefix[i], strlen(prefix[i])) == 0)
return 1;
return 0;
}
/*
* Cut long tool outputs in [from, to). The head of an observation is the part
* worth keeping: a tool prints its answer, then a stack of context. The marker
* says the cut happened, so a model does not read a trimmed result as complete.
*/
static int
trim_tools(struct sp_conv *conv, size_t from, size_t to, size_t limit)
{
size_t i;
int trimmed = 0;
for (i = from; i < to; i++) {
struct sp_msg *m = &conv->v[i];
size_t len;
char *cut;
if (!is_role(m, "tool") || m->content == NULL)
continue;
len = strlen(m->content);
if (len <= limit)
continue;
cut = malloc(limit + 96);
if (cut == NULL)
return trimmed;
memcpy(cut, m->content, limit);
snprintf(cut + limit, 96, "\n[... %zu bytes trimmed by compaction]",
len - limit);
free(m->content);
m->content = cut;
trimmed++;
}
return trimmed;
}
/* Append text with newlines flattened to spaces: the digest is a transcript of
* one message, not a document with its own layout. */
static void
append_flat(struct sp_buf *b, const char *s, size_t cap)
{
size_t i;
if (s == NULL)
return;
for (i = 0; i < cap && s[i] != '\0'; i++) {
char c = s[i];
if (c == '\n' || c == '\r' || c == '\t')
c = ' ';
sp_buf_add(b, &c, 1);
}
if (s[i] != '\0')
sp_buf_puts(b, "...");
}
/*
* The thread: one line per dropped message, in order. A user turn gets its
* opening nearly whole - that is the task and the corrections to it. An
* assistant turn gets its opening, which is what it claimed to be doing. An
* observation gets enough to recognise it.
*/
/*
* Does the registry offer history_search? Passed in rather than looked up here,
* because build_digest runs inside the shrink loop and the answer never changes.
*/
static int
build_digest(struct sp_conv *conv, size_t from, size_t to, struct caps caps,
int searchable, struct sp_buf *out)
{
size_t i;
size_t users = 0, assistants = 0, tools = 0, other = 0;
if (sp_buf_init(out) != 0)
return -1;
for (i = from; i < to; i++) {
if (is_role(&conv->v[i], "user"))
users++;
else if (is_role(&conv->v[i], "assistant"))
assistants++;
else if (is_role(&conv->v[i], "tool"))
tools++;
else
other++;
}
sp_buf_puts(out, "[thread so far - compacted] ");
sp_buf_printf(out, "%zu earlier messages: %zu from the operator, %zu "
"assistant turns, %zu tool results", to - from, users, assistants,
tools);
if (other > 0)
sp_buf_printf(out, ", %zu other", other);
sp_buf_puts(out, ". In order:\n");
/*
* Say where the rest went. Without this line the model reads a summary
* that stops mid-thought and believes that is all there ever was: it
* re-asks the operator what the operator already answered, which is the
* exact complaint ("losing the fade") this digest exists to fix. The
* tool is named only when it is really registered - a prompt pointing at
* a missing tool teaches the model to call nothing.
*/
if (searchable)
sp_buf_puts(out, "\n[The full transcript is still on disk. "
"Call history_search with the words of what you are looking "
"for to get it back: it searches this whole session by "
"meaning, not just what is quoted here.]\n");
for (i = from; i < to; i++) {
struct sp_msg *m = &conv->v[i];
if (is_role(m, "user")) {
sp_buf_puts(out, "\nOPERATOR: ");
append_flat(out, m->content, caps.user);
} else if (is_role(m, "assistant")) {
if (m->content == NULL && m->calls != NULL)
continue; /* a bare tool call says nothing yet */
sp_buf_puts(out, "\n assistant: ");
append_flat(out, m->content, caps.assistant);
} else if (is_role(m, "tool")) {
if (caps.tool == 0)
continue;
sp_buf_puts(out, "\n ");
if (m->name != NULL) {
sp_buf_puts(out, m->name);
sp_buf_puts(out, " -> ");
} else
sp_buf_puts(out, "tool -> ");
append_flat(out, m->content, caps.tool);
}
}
return 0;
}
/* Free the strings of [from, to) and close the gap. The vector, not the count. */
static void
drop_range(struct sp_conv *conv, size_t from, size_t to)
{
size_t i;
for (i = from; i < to; 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[from], &conv->v[to],
(conv->n - to) * sizeof(*conv->v));
conv->n = from + (conv->n - to);
}
/* Bytes that [from, to) currently costs. */
static size_t
range_bytes(struct sp_conv *conv, size_t from, size_t to)
{
size_t i, total = 0;
for (i = from; i < to; i++)
total += msg_bytes(&conv->v[i]);
return total;
}
static int
core_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
unsigned turn)
{
struct sp_buf digest;
struct sp_registry *reg;
int searchable;
struct caps caps;
size_t bytes, drop_bytes, tail_bytes;
char *best_p = NULL;
size_t best_len = 0;
size_t first, keep_from;
long pin_at = -1;
char *pin_content = NULL;
char *pin_name = NULL;
size_t pin_extra = 0;
int trimmed, pinned = 0;
int attempt;
(void)turn;
/*
* Whether the escape hatch exists decides whether the digest advertises
* it. The embedding index is on by default, but `embed = off` is a
* supported choice and the prompt must not lie about it.
*/
reg = h != NULL ? sp_host_registry(h) : NULL;
searchable = reg != NULL && sp_registry_find(reg, "history_search") != NULL;
if (conv == NULL || conv->n == 0 || budget == 0)
return 0;
bytes = sp_conv_bytes(conv);
if (bytes <= budget)
return 0; /* fits: nothing to do */
if (conv->n <= COMPACT_KEEP_TAIL + 1)
return 0; /* too short to cut anything meaningful */
/*
* The leading system messages stay. Plural, because a compactor plugin
* that ran before this one put its own summary there - lcm's "[lcm] 42
* messages compacted out", cps' plan. That message is the result of work
* somebody already paid for, and digesting it away would replace the
* plugin's summary with a worse one. The cap keeps a pathological lead of
* system messages from eating the whole budget.
*/
for (first = 0; first < conv->n && first < COMPACT_KEEP_HEAD &&
is_role(&conv->v[first], "system"); first++)
;
keep_from = conv->n - COMPACT_KEEP_TAIL;
/*
* The tail must not begin with a tool result: its assistant turn, the
* one carrying the tool_call, would be cut away and a provider answers
* an orphaned tool message with a 400. Walk BACK to that assistant
* rather than forward past the results.
*
* Forward was the first try and it quietly broke the promise this
* constant makes: a turn with two tool results in the tail boundary
* kept four messages instead of six, because each result pushed the
* start further in. Measured on system + user + [assistant, tool, tool]
* x4 + user: 15 messages, tail of six, result was a tail of four. Going
* back costs the bytes of one call record and keeps the size.
*/
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;
/* 1. trim every tool body outside the verbatim tail */
trimmed = trim_tools(conv, first, conv->n, COMPACT_TOOL_TRIM);
bytes = sp_conv_bytes(conv);
if (bytes <= budget)
return trimmed > 0 ? 1 : 0;
/* 2. the question being answered, pinned after the digest */
{
size_t i;
for (i = conv->n; i > first; i--) {
if (!is_role(&conv->v[i - 1], "user"))
continue;
if (is_continuation(&conv->v[i - 1]))
continue;
pin_at = (long)(i - 1);
break;
}
}
if (pin_at >= 0 && (size_t)pin_at >= keep_from) {
/* it is already in the verbatim tail: nothing to pin */
pin_at = -1;
}
if (pin_at >= 0) {
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;
if (pinned)
pin_extra = strlen(pin_content) +
(pin_name != NULL ? strlen(pin_name) : 0) + 20;
}
caps.user = CAP_USER;
caps.assistant = CAP_ASSISTANT;
caps.tool = CAP_TOOL;
/*
* What the digest has to beat is not the budget - it is what it replaces.
* If it costs more than the range it stands in for, the rewrite makes the
* conversation bigger and the next request pays for nothing. Shrink the
* caps until the digest is smaller than the range, user text last: that is
* the thread.
*
* The digest may also take at most its share of the budget, unless the
* verbatim tail alone already leaves less room than that.
*/
/*
* The digest has two hard limits, and it must satisfy both:
*
* a) smaller than the range it replaces, or the rewrite grows the
* conversation and the next request pays for nothing
* b) small enough that the digest plus the verbatim tail fits the
* budget, or the turn is refused for exceeding it anyway
*
* (b) is the one that was missing: with a budget of 900 and a tail of
* 1000 the digest could satisfy (a) all day and the request still went
* out at 3776 bytes. When the tail alone already exceeds the budget,
* (b) has no answer and (a) is the only rule left.
*
* Beyond those, the caps decide how much of the thread survives.
* Shrinking them is a last resort: the thread IS the point, and a digest
* that fits but says nothing is the failure this file exists to avoid.
*/
drop_bytes = range_bytes(conv, first, keep_from);
tail_bytes = range_bytes(conv, keep_from, conv->n);
{
size_t room = drop_bytes > pin_extra + 64 ?
drop_bytes - pin_extra - 64 : 0;
size_t fit = budget > tail_bytes + pin_extra ?
budget - tail_bytes - pin_extra : 0;
if (fit > 0 && fit < room)
room = fit;
/*
* Shrink until it fits, but keep the best attempt: when even the
* smallest caps overshoot, the smallest digest is still worth more
* than no thread at all. The best one is copied out as a plain
* buffer, so ownership stays in one place.
*/
best_p = NULL;
best_len = 0;
for (attempt = 0; attempt < 16; attempt++) {
if (build_digest(conv, first, keep_from, caps,
searchable, &digest) != 0) {
free(best_p);
free(pin_content);
free(pin_name);
return -1;
}
if (digest.len == 0) {
sp_buf_free(&digest);
break;
}
if (best_p == NULL || digest.len < best_len) {
char *copy = malloc(digest.len + 1);
if (copy != NULL) {
memcpy(copy, digest.p, digest.len + 1);
free(best_p);
best_p = copy;
best_len = digest.len;
}
}
if (digest.len <= room) {
sp_buf_free(&digest);
break;
}
sp_buf_free(&digest);
if (caps.tool > CAP_MIN_TOOL) {
caps.tool = caps.tool / 2;
continue;
}
if (caps.assistant > CAP_MIN_ASSISTANT) {
caps.assistant = caps.assistant / 2;
continue;
}
if (caps.user > CAP_MIN_USER) {
caps.user = caps.user * 3 / 4;
continue;
}
break; /* nothing left to shrink */
}
if (best_p == NULL) {
free(pin_content);
free(pin_name);
return trimmed > 0 ? 1 : 0;
}
/*
* Rule (a), enforced rather than merely computed. The shrink loop
* stops at the minimum caps and keeps the smallest attempt even
* when that attempt is still too big - and then the rewrite went
* out anyway, replacing a short range with a longer digest plus a
* pinned question. Measured on the case /resume produced: 317
* bytes in, 476 bytes out, on a budget of 217. A compactor that
* grows the conversation is worse than none, because the next
* request pays for it and the turn is refused for size.
*
* There is nothing else to try at this point, so the honest
* answer is "I could not help": the tool bodies were already
* trimmed above, which is where the easy bytes were.
*/
if (best_len + pin_extra >= drop_bytes) {
free(best_p);
free(pin_content);
free(pin_name);
return trimmed > 0 ? 1 : 0;
}
if (sp_buf_init(&digest) != 0) {
free(best_p);
free(pin_content);
free(pin_name);
return -1;
}
sp_buf_add(&digest, best_p, best_len);
free(best_p);
}
drop_range(conv, first, keep_from);
{
struct sp_msg m;
memset(&m, 0, sizeof(m));
m.role = "system";
m.content = digest.p;
if (sp_conv_insert(conv, first, &m) != 0) {
sp_buf_free(&digest);
free(pin_content);
free(pin_name);
return -1;
}
}
if (pinned && pin_content != NULL && pin_content[0] != '\0') {
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) {
sp_buf_free(&digest);
free(pin_content);
free(pin_name);
return -1;
}
}
sp_buf_free(&digest);
free(pin_content);
free(pin_name);
return 1;
}
static const struct sp_compactor compact = { "compact", core_compact };
const struct sp_compactor *
sp_core_compactor(void)
{
return &compact;
}
+40 -2
View File
@@ -34,6 +34,7 @@
#include "config.h"
#include "folder.h"
#include "i18n.h"
#include "embed.h"
#include "log.h"
#include "mcp.h"
#include "prompt.h"
@@ -79,6 +80,8 @@ struct sp_engine {
struct sp_session_info sess;
struct sp_conv conv;
struct sp_host *host;
/* the session's embedding index: background thread, never on the turn */
struct sp_embed_ctx *emb;
struct sp_mock mock;
int have_mock;
@@ -1146,6 +1149,12 @@ engine_compact(void *ctx, size_t before, size_t after, size_t mb, size_t ma)
snprintf(msg, sizeof(msg), sp_t("ui.compacted"), mb, ma, t1, t2, b1,
b2);
ev_push(e, SP_EV_ENTRY, 0, "splinter", msg);
/*
* What compaction just dropped stays in the session file, and this is
* the moment it becomes worth finding again. The call only raises a
* flag; the embedding runs on its own thread.
*/
sp_embed_note_compaction(e->emb);
}
/* ----------------------------------------------------------------- turns */
@@ -2254,6 +2263,8 @@ cmd_new(struct sp_engine *e, struct sp_buf *out)
&e->agents.v[e->agent_cur], base, &e->policy);
(void)sp_log_open(e->sess.dir, e->sess.id);
sp_logf("session", "started: %s", e->sess.id);
/* the new session gets its own index; the old one stays on disk */
sp_embed_bind(e->emb, e->sess.dir, e->sess.id);
profile_save(e);
{
char sel[320];
@@ -2406,6 +2417,14 @@ cmd_status(struct sp_engine *e, struct sp_buf *out)
sp_buf_printf(out, sp_t("status.compact_value"), comp, failed, turns,
e->snapshot.compactions);
sp_buf_puts(out, "\n");
sp_buf_printf(out, " %-8s ", sp_t("status.embed"));
{
char etex[256];
sp_embed_status(e->emb, etex, sizeof(etex));
sp_buf_puts(out, etex);
}
sp_buf_puts(out, "\n");
sp_buf_printf(out, " %-8s ", sp_t("status.limits"));
sp_buf_printf(out, sp_t("status.limits_value"), e->base.max_bytes,
e->base.max_steps, e->base.autonomous ?
@@ -3076,8 +3095,13 @@ load_plugins(struct sp_engine *e, const struct sp_engine_opts *o,
struct sp_host *host;
size_t k;
if (o->nplugins == 0)
return 0;
/*
* The host is created even without a single plugin: it is what carries
* the registry to the core compactor and the gate to the tools. Skiping
* it here left a plugin-less run with no compactor at all, so max_bytes
* killed every turn whose conversation was over the ceiling - the
* compaction that was supposed to save it could not be reached.
*/
host = sp_host_new(&e->reg, &e->ag, &e->sess);
if (host == NULL) {
sp_buf_puts(err, "cannot create plugin host");
@@ -3336,6 +3360,14 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o,
}
if (open_session(e, o, err, &code) != 0)
goto fail;
/*
* The index belongs to the session, so it is created with it. It starts
* its own thread and begins reading the file in the background: a
* resumed session is searchable without anything having been compacted.
*/
e->emb = sp_embed_new(e->conf);
if (e->emb != NULL)
sp_embed_bind(e->emb, e->sess.dir, e->sess.id);
if (session_model_read(e, saved, sizeof(saved)) == 0) {
struct sp_choice ch;
@@ -3381,6 +3413,11 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o,
sp_buf_puts(err, "cannot register folder_history or delegate");
goto fail;
}
/* history_search: the way back into what compaction dropped */
if (e->emb != NULL && sp_embed_register(&e->reg, e->emb) != 0) {
sp_buf_puts(err, "cannot register history_search");
goto fail;
}
if (pick_transport(e, o, err) != 0) {
code = -2; /* a configuration the user can fix */
goto fail;
@@ -3514,6 +3551,7 @@ sp_engine_close(struct sp_engine *e)
free(e->turn_text);
sp_agents_free(&e->agents);
sp_conv_free(&e->conv);
sp_embed_free(e->emb);
sp_host_free(e->host);
sp_registry_free(&e->reg);
if (e->have_mock)
+47
View File
@@ -60,6 +60,8 @@ struct sp_host {
size_t msg_head, msg_n;
const struct sp_compactor *compact[MAX_COMPACTORS];
size_t ncompact;
/* set by a plugin that is preparing a plan; lasts one call */
int compact_hold;
const struct sp_gate *gate[MAX_COMPACTORS];
size_t ngate;
const struct sp_status *status[MAX_STATUS];
@@ -468,6 +470,27 @@ sp_host_compact(struct sp_host *h, struct sp_conv *conv, size_t budget)
if (h == NULL || conv == NULL)
return 0;
/*
* The plugins get their turn first, and the core is the backstop.
*
* The old rule was "any plugin compactor means the core stays out", and
* it was wrong twice over. compact_threshold and compact_target are core
* settings, so a configuration whose plugins happened to register one
* made them dead - the operator set a limit and the conversation grew
* past the window until the provider cut it (254k of 131k, 2026-11-21).
* And most plugin "compactors" do not compact at all: focus and reminder
* insert one message and return 0 or 1. A plugin that inserts a goal
* reminder must not be the reason an oversized request goes out whole.
*
* So the core always gets a look, and decides for itself: core_compact()
* returns 0 without touching anything when the conversation already fits
* the budget. That is the check that separates "focus inserted a
* reminder into a small conversation" (616 bytes under a 1-byte budget
* in a test, every real turn under its real budget) from "lcm cut the
* transcript in half". Only the second kind of turn gets a digest, and
* then it comes after the plugin's own work, so that work is what
* survives where it did something.
*/
for (i = 0; i < h->ncompact; i++) {
rc = h->compact[i]->compact(h, conv, budget,
(unsigned)h->turns);
@@ -478,9 +501,33 @@ sp_host_compact(struct sp_host *h, struct sp_conv *conv, size_t budget)
h->failed++;
}
}
/*
* A plugin that answered "not yet, my plan is still being prepared" asked
* for one round of room. Its next call applies the plan. Cutting the
* conversation in between would invalidate that plan, which is the bug
* this flag exists to prevent.
*/
if (h->compact_hold) {
h->compact_hold = 0;
return changed;
}
rc = sp_core_compactor()->compact(h, conv, budget, (unsigned)h->turns);
if (rc > 0) {
changed = 1;
h->compactions++;
} else if (rc < 0) {
h->failed++;
}
return changed;
}
void
sp_host_compactor_hold(struct sp_host *h)
{
if (h != NULL)
h->compact_hold = 1;
}
size_t
sp_host_compaction_stats(struct sp_host *h, size_t *compactions,
size_t *failed, unsigned *turns)
+362 -13
View File
@@ -57,6 +57,15 @@ struct session_meta {
char title[96];
char goal[1001]; /* the session's /goal, one line */
char goal_state[16]; /* open | succeeded: the model said GOAL_COMPLETE */
/*
* Lines the core does not own. A plugin that marks a session (foreign=
* hermes:h-1 names where an imported conversation came from) writes into
* the same file, and every reopen, rename or /goal rewrites it: without
* carrying them through, the plugin's own marker was gone the first time
* the session was opened again.
*/
char extra[8][160];
size_t nextra;
};
/* a title is one line, no control bytes, at most 95 bytes of UTF-8 */
@@ -144,6 +153,17 @@ meta_read(const char *dir, const char *id, struct session_meta *m)
snprintf(m->goal, sizeof(m->goal), "%s", v);
else if (strcmp(line, "goal_state") == 0)
snprintf(m->goal_state, sizeof(m->goal_state), "%s", v);
else if (m->nextra < sizeof(m->extra) / sizeof(m->extra[0])) {
size_t cap = sizeof(m->extra[0]);
size_t lk = strlen(line), lv = strlen(v), use, kv;
kv = lk < cap - 2 ? lk : cap - 2;
use = cap - 1 - kv - 1;
if (lv > use)
lv = use;
snprintf(m->extra[m->nextra++], cap, "%.*s=%.*s",
(int)kv, line, (int)lv, v);
}
}
fclose(f);
return 0;
@@ -154,6 +174,7 @@ meta_write(const char *dir, const char *id, const struct session_meta *m)
{
char path[700], tmp[800];
FILE *f;
size_t i;
snprintf(path, sizeof(path), "%s/%s.meta", dir, id);
snprintf(tmp, sizeof(tmp), "%s.tmp", path);
@@ -168,6 +189,8 @@ meta_write(const char *dir, const char *id, const struct session_meta *m)
fprintf(f, "goal=%s\n", m->goal);
if (m->goal_state[0] != '\0')
fprintf(f, "goal_state=%s\n", m->goal_state);
for (i = 0; i < m->nextra; i++)
fprintf(f, "%s\n", m->extra[i]);
if (fclose(f) != 0) {
(void)unlink(tmp);
return -1;
@@ -300,6 +323,13 @@ sp_session_open(struct sp_session_info *info, const char *dir,
* A session belongs to the directory it was started in. That is what '-c'
* needs: the last session that happened *here*, not the last one anywhere.
* The title and the original creation time survive a reopen.
*
* The cwd is only filled in when it is still empty, i.e. for a new
* session. Taking getcwd() unconditionally looked right for a new one
* and rewrote the field for an existing one: /open from another
* directory, and every import (which sets the source's directory),
* then claimed this directory instead of the one the conversation ran
* in - and '-c' picked that session up from the wrong place.
*/
{
struct session_meta m;
@@ -309,7 +339,7 @@ sp_session_open(struct sp_session_info *info, const char *dir,
memset(&m, 0, sizeof(m));
m.created = (long)now;
}
if (getcwd(m.cwd, sizeof(m.cwd)) == NULL)
if (m.cwd[0] == '\0' && getcwd(m.cwd, sizeof(m.cwd)) == NULL)
snprintf(m.cwd, sizeof(m.cwd), "?");
if (m.created == 0)
m.created = (long)now;
@@ -395,27 +425,71 @@ sp_session_list(const char *dir, struct sp_session_brief *v, size_t max)
return (int)n;
}
/*
* The record writer. Everything the conversation needs to be sent again is
* written here: role, the text, and for a tool result the name of the tool and
* the call it answers, and for an assistant turn its tool_calls. Without those
* three a resumed session cannot be replayed to a provider - the provider
* rejects a "tool" message with no matching tool_call, so the old loader simply
* dropped every observation instead.
*/
int
sp_session_append(const struct sp_session_info *info, const char *role,
const char *text, struct sp_buf *err)
sp_session_append_rec(const struct sp_session_info *info,
const struct sp_sess_rec *rec, struct sp_buf *err)
{
struct sp_buf line;
char path[640];
int fd, rc;
if (info == NULL || rec == NULL || rec->role == NULL) {
sp_buf_puts(err, "session: no record");
return -1;
}
/*
* A record with neither text nor calls says nothing. Writing it put
* {"role":"user","text":""} into the file and every resume showed the
* model a blank human turn - which it then answered. Drop it here, at the
* one place that writes.
*/
if ((rec->text == NULL || rec->text[0] == '\0') &&
(rec->calls == NULL || rec->calls[0] == '\0'))
return 0;
if (sp_buf_init(&line) != 0) {
sp_buf_puts(err, "session: out of memory");
return -1;
}
rc = sp_buf_puts(&line, "{\"role\":\"");
if (rc == 0)
rc = sp_json_escape(&line, role);
rc = sp_json_escape(&line, rec->role);
if (rc == 0)
rc = sp_buf_puts(&line, "\",\"text\":\"");
if (rc == 0)
rc = sp_json_escape(&line, text);
rc = sp_json_escape(&line, rec->text != NULL ? rec->text : "");
if (rc == 0)
rc = sp_buf_puts(&line, "\"}\n");
rc = sp_buf_puts(&line, "\"");
if (rc == 0 && rec->name != NULL && rec->name[0] != '\0') {
rc = sp_buf_puts(&line, ",\"name\":\"");
if (rc == 0)
rc = sp_json_escape(&line, rec->name);
if (rc == 0)
rc = sp_buf_puts(&line, "\"");
}
if (rc == 0 && rec->call_id != NULL && rec->call_id[0] != '\0') {
rc = sp_buf_puts(&line, ",\"call_id\":\"");
if (rc == 0)
rc = sp_json_escape(&line, rec->call_id);
if (rc == 0)
rc = sp_buf_puts(&line, "\"");
}
if (rc == 0 && rec->calls != NULL && rec->calls[0] != '\0') {
/* raw JSON array: written verbatim, never re-escaped */
rc = sp_buf_puts(&line, ",\"calls\":");
if (rc == 0)
rc = sp_buf_puts(&line, rec->calls);
}
if (rc == 0)
rc = sp_buf_puts(&line, "}\n");
if (rc != 0) {
sp_buf_puts(err, "session: out of memory");
sp_buf_free(&line);
@@ -442,12 +516,13 @@ sp_session_append(const struct sp_session_info *info, const char *role,
* otherwise. Written once, so a long conversation does not rewrite the
* sidecar on every turn.
*/
if (rc == 0 && role != NULL && strcmp(role, "user") == 0) {
if (rc == 0 && strcmp(rec->role, "user") == 0 && rec->text != NULL &&
rec->text[0] != '\0') {
struct session_meta m;
if (meta_read(info->dir, info->id, &m) == 0 &&
m.title[0] == '\0') {
title_from_text(text, m.title, sizeof(m.title));
title_from_text(rec->text, m.title, sizeof(m.title));
if (m.title[0] != '\0')
(void)meta_write(info->dir, info->id, &m);
}
@@ -455,6 +530,18 @@ sp_session_append(const struct sp_session_info *info, const char *role,
return rc;
}
int
sp_session_append(const struct sp_session_info *info, const char *role,
const char *text, struct sp_buf *err)
{
struct sp_sess_rec rec;
memset(&rec, 0, sizeof(rec));
rec.role = role;
rec.text = text;
return sp_session_append_rec(info, &rec, err);
}
int
sp_session_count(const struct sp_session_info *info, size_t *n,
struct sp_buf *err)
@@ -499,27 +586,188 @@ sp_session_count(const struct sp_session_info *info, size_t *n,
* reconstructing something else. Records this build does not understand (a
* thinking entry, a tool line) are skipped and counted, never guessed at.
*/
/*
* Serialize a parsed JSON value back to text.
*
* The loader needs this because a record's "calls" is a JSON value inside a
* JSON line: the raw text cannot be sliced out with strstr, since an argument
* may itself contain the characters that delimit it. Slicing until the first
* newline worked only while every argument was single-line; the first tool
* result with a \n in its content produced a request the provider could not
* parse (measured: json.decoder.JSONDecodeError at char 2309).
*/
static void
json_write(struct sp_buf *out, const mcp_json *v)
{
size_t i;
if (v == NULL) {
sp_buf_puts(out, "null");
return;
}
switch (v->t) {
case MCP_NULL:
sp_buf_puts(out, "null");
break;
case MCP_BOOL:
sp_buf_puts(out, v->b ? "true" : "false");
break;
case MCP_NUM:
if (v->n == (double)(long)v->n)
sp_buf_printf(out, "%ld", (long)v->n);
else
sp_buf_printf(out, "%.17g", v->n);
break;
case MCP_STR:
sp_buf_puts(out, "\"");
sp_json_escape(out, v->s != NULL ? v->s : "");
sp_buf_puts(out, "\"");
break;
case MCP_ARR:
sp_buf_puts(out, "[");
for (i = 0; i < v->count; i++) {
if (i > 0)
sp_buf_puts(out, ",");
json_write(out, v->items[i]);
}
sp_buf_puts(out, "]");
break;
case MCP_OBJ:
sp_buf_puts(out, "{");
for (i = 0; i < v->count; i++) {
if (i > 0)
sp_buf_puts(out, ",");
sp_buf_puts(out, "\"");
sp_json_escape(out, v->keys[i]);
sp_buf_puts(out, "\":");
json_write(out, v->items[i]);
}
sp_buf_puts(out, "}");
break;
}
}
/*
* Collect the "id" of every call in a tool_calls array, in order. The raw JSON
* is parsed rather than pattern-matched: a tool name may contain the word id,
* an argument may contain an id, and taking the wrong one pairs a result with
* the wrong call - which a provider accepts and the model then reads as a lie.
*/
/* The id of the synthetic call the loader had to invent, so the next
* observation can reuse the same assistant turn while it is still last. */
static char last_synth_id[32];
static size_t synth_seq;
/*
* Insert an assistant turn that carries one tool call, so the result that
* follows has a call to answer. Used only when reading a file that predates the
* format - a replay of an old session must not cost the model its evidence.
*/
static int
synth_call(struct sp_conv *conv, const char *name)
{
struct sp_msg am;
char calls[512];
struct sp_buf id;
if (sp_buf_init(&id) != 0)
return 0;
sp_buf_printf(&id, "recovered-%zu", ++synth_seq);
snprintf(calls, sizeof(calls),
"[{\"id\":\"%s\",\"type\":\"function\",\"function\":"
"{\"name\":\"%s\",\"arguments\":\"{}\"}}]", id.p, name);
memset(&am, 0, sizeof(am));
am.role = (char *)"assistant";
am.content = (char *)"";
am.calls = calls;
snprintf(last_synth_id, sizeof(last_synth_id), "%s", id.p);
sp_buf_free(&id);
return sp_conv_add(conv, &am) == 0;
}
static size_t
sp_session_ids(const char *calls_json, char **out, size_t max)
{
mcp_json *v;
const mcp_json *arr;
size_t i, n = 0;
if (calls_json == NULL || out == NULL || max == 0)
return 0;
v = mcp_parse(calls_json);
if (v == NULL)
return 0;
arr = v;
if (v->t == MCP_OBJ) {
const mcp_json *t = mcp_arg(v, "tool_calls");
if (t != NULL)
arr = t;
}
for (i = 0; i < mcp_array_len(arr) && n < max; i++) {
const mcp_json *one = mcp_array_at(arr, i);
const char *id = mcp_arg_string(one, "id");
if (id == NULL || id[0] == '\0')
continue;
out[n] = strdup(id);
if (out[n] == NULL)
break;
n++;
}
mcp_json_free(v);
return n;
}
/*
* Read a session back as a conversation a provider will accept.
*
* The first version kept only "user" and "assistant" lines, because the file
* was read as a chat log. It is not a chat log: it is the transcript of an
* agent run, and 99% of its lines are observations. Resuming then handed the
* model a handful of questions with no answers and no evidence between them
* (measured on a real session: 21 of 1507 lines), so it re-did work it had
* already done or asked what the task was.
*
* Two rules make the replay valid:
*
* - A "tool" message needs the name of its tool and the id of the call it
* answers. Records written before this format carry neither; such a line is
* paired with the nearest preceding assistant turn that has calls and no
* answer yet, and the missing id is taken from that call. A tool result
* with no call to answer is dropped - a provider rejects it with a 400, so
* keeping it would break the whole resume.
* - An assistant turn carries its raw tool_calls. Without them the calls are
* gone and their results become orphans.
*/
int
sp_session_load(const struct sp_session_info *info, struct sp_conv *conv,
size_t *loaded, struct sp_buf *err)
{
char path[640];
(void)err;
char *line = NULL;
size_t linecap = 0, n = 0;
ssize_t len;
FILE *f;
/* the calls of the last assistant turn, still waiting for results */
char *pending_calls = NULL; /* raw JSON of that turn */
char *pending_ids[64];
size_t pending_n = 0;
size_t pending_used = 0;
(void)err;
if (loaded != NULL)
*loaded = 0;
snprintf(path, sizeof(path), "%s/%s.jsonl", info->dir, info->id);
f = fopen(path, "r");
if (f == NULL)
return 0; /* nothing to resume from */
/* whole lines, however long: a fixed buffer split big records */
while ((len = getline(&line, &linecap, f)) > 0) {
mcp_json *v;
const char *role, *text;
const char *role, *text, *name, *call_id;
const mcp_json *calls;
/*
* A record is a complete, newline-terminated JSON object. An
@@ -533,13 +781,114 @@ sp_session_load(const struct sp_session_info *info, struct sp_conv *conv,
continue;
role = mcp_arg_string(v, "role");
text = mcp_arg_string(v, "text");
if (role != NULL && text != NULL &&
(strcmp(role, "user") == 0 || strcmp(role, "assistant") == 0)) {
if (sp_conv_push(conv, role, NULL, text) == 0)
name = mcp_arg_string(v, "name");
call_id = mcp_arg_string(v, "call_id");
calls = mcp_arg(v, "calls");
if (role == NULL || text == NULL) {
mcp_json_free(v);
continue;
}
if (strcmp(role, "user") == 0 || strcmp(role, "system") == 0) {
/*
* A blank user line is noise from an older writer; a
* provider answers it by asking what was meant.
*/
if (text[0] != '\0') {
if (sp_conv_push(conv, role, NULL, text) == 0)
n++;
}
} else if (strcmp(role, "assistant") == 0) {
/* free whatever the previous turn left unclaimed */
free(pending_calls);
pending_calls = NULL;
{
size_t i;
for (i = 0; i < pending_n; i++)
free(pending_ids[i]);
}
pending_n = pending_used = 0;
{
struct sp_msg am;
memset(&am, 0, sizeof(am));
am.role = (char *)"assistant";
am.content = (char *)text;
am.calls = NULL;
if (calls != NULL) {
/*
* Re-serialize the value, never slice
* the line: an argument may contain
* the delimiters of its own record.
*/
struct sp_buf cb;
if (sp_buf_init(&cb) == 0) {
json_write(&cb, calls);
pending_calls = cb.p;
am.calls = pending_calls;
pending_n = sp_session_ids(
pending_calls, pending_ids, 64);
}
}
if (sp_conv_add(conv, &am) == 0)
n++;
pending_used = 0;
}
} else if (strcmp(role, "tool") == 0 ||
strcmp(role, "observation") == 0) {
struct sp_msg tm;
const char *use_id = call_id;
/*
* An old record has no name and no id. Take the next
* unanswered call of the pending assistant turn.
*
* An observation with no call to answer is the common
* case in files written before this format: the writer
* never stored the assistant turn's tool_calls, so there
* is nothing to pair with. Dropping the line is what made
* a resumed session 99% empty, and keeping it unpaired is
* what a provider rejects with 400. So the pair is built
* here: a synthetic assistant turn carrying exactly the
* calls these results answer, inserted before them.
*/
if (use_id == NULL && pending_n > 0 &&
pending_used < pending_n)
use_id = pending_ids[pending_used];
if (use_id == NULL || use_id[0] == '\0') {
if (!synth_call(conv, (name != NULL && name[0] != '\0') ?
name : "tool"))
continue;
use_id = last_synth_id;
}
if (pending_n > 0 && pending_used < pending_n)
pending_used++;
memset(&tm, 0, sizeof(tm));
tm.role = "tool";
tm.name = (char *)((name != NULL && name[0] != '\0') ? name :
"tool");
tm.call_id = (char *)use_id;
tm.content = (char *)text;
if (sp_conv_add(conv, &tm) == 0)
n++;
}
mcp_json_free(v);
}
/*
* The ids were strdup'd for the tool results that follow; once the file
* is read they have no owner left. The conversation keeps the call_id
* strings of the messages it was given, not these.
*/
{
size_t i;
/* every id, used or not: an unanswered call leaks too */
for (i = 0; i < pending_n; i++)
free(pending_ids[i]);
}
free(pending_calls);
free(line);
fclose(f);
if (loaded != NULL)