Files
splinter/include/splinter_plugin.h
lotherk f7120882fa 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.
2026-11-21 21:25:51 +00:00

322 lines
14 KiB
C

/*
* splinter -- plugin ABI.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* A plugin is a shared object loaded with dlopen(). It links against
* libsplinter.so, never against the binary, so there is exactly one copy of
* every symbol in the process.
*
* What a plugin may do, and where:
*
* init() called once, on the main thread, before any turn. Register
* tools and widgets here. May fail; a failed plugin is unloaded
* from the set and reported, never half-used.
* run() called on the main thread while a turn is being handled.
* tick() called on the widget's own thread, so it may block, read
* files, wait on sockets. It must NOT touch curses and must NOT
* assume it is the only thread.
* draw() called on the UI thread only, must be fast and non-blocking.
* A widget without draw() is rendered from its published text.
*
* Text that should appear in the sidebar is published with
* sp_host_widget_text(); the host copies it under a mutex, so the string does
* not have to outlive the call.
*/
#ifndef SPLINTER_PLUGIN_H
#define SPLINTER_PLUGIN_H
#include <stdint.h>
#include "splinter.h"
/*
* Raise this whenever a struct a plugin hands to the host changes shape. It
* stayed 1 while struct sp_gate gained block_turn: a gate built against the old
* header would have had the host read past its struct and call what it found.
* 2: sp_gate.block_turn, sp_task_ops, sp_status, commands and transports.
*/
#define SP_PLUGIN_ABI 2u
struct sp_host;
struct sp_widget {
const char *name; /* unique in the sidebar */
int (*tick)(struct sp_host *, const char *name, void *ctx);
void (*draw)(struct sp_host *, const char *name, void *ctx);
void *ctx;
unsigned interval_ms; /* 0: tick once, then stop */
};
/*
* A compactor runs on the main thread before every request, with the whole
* conversation in hand. It may rewrite it. Returning 1 means "changed", 0
* "nothing to do", -1 "failed" - and a failure is reported, never ignored.
*/
struct sp_compactor {
const char *name;
int (*compact)(struct sp_host *, struct sp_conv *,
size_t budget_bytes, unsigned turn);
};
/*
* A command is what the operator types with a leading slash: /goal <text>.
* The UI does not know any command by name; it asks the host, and the host asks
* the plugins. A plugin that wants one registers it here.
*
* Return 0 and put the reply in `out`; return -1 to say "not mine".
*/
typedef int (*sp_cmd_fn)(struct sp_host *, const char *args, struct sp_buf *out,
void *ctx);
/*
* A gate decides whether a tool may run, before the operator is asked and before
* the authorization class is applied. It exists so a plugin can hold a policy the
* core does not know: kid mode, a sandbox, a host-level allow list.
*
* Return 1 to allow (skips the operator prompt), 0 to deny, -1 to say "no
* opinion" - then the normal rules apply.
*/
struct sp_gate {
const char *name;
int (*check)(struct sp_host *, const char *tool,
int auth, const char *args, char *reason,
size_t reason_len);
/*
* Optional: refuse the whole turn before the model is called. Used by kid
* mode when the day's minutes are gone - a message the child reads, not a
* hang, and not a model that has to be trusted to obey.
*/
int (*block_turn)(struct sp_host *, char *msg, size_t len);
};
/*
* What the status line is allowed to know. The harness owns the numbers - a
* plugin must not count tokens twice or guess a price.
*/
struct sp_meter {
size_t ctx_used; /* tokens the last request carried */
size_t ctx_max; /* the window, 0 = unknown */
size_t tok_in; /* this session */
size_t tok_out;
size_t cached; /* tokens the provider served from cache */
size_t cached_total; /* the same for the whole session */
long tps; /* output tokens per second, last turn */
double cost; /* session cost, filled from the price config */
unsigned tasks_running;
unsigned tasks_max;
};
/* A status segment: a name and a renderer, drawn in the order registered. */
struct sp_status {
const char *name;
void (*render)(struct sp_host *, char *buf, size_t len);
};
/*
* Tasks owned by someone else. The delegate runs a model on another host and the
* tasks plugin shows it; neither knows the other, so the harness passes an entry
* through this little interface: begin gives an id, end closes it with a status
* and whatever was spent.
*/
struct sp_task_ops {
int (*begin)(struct sp_host *, const char *label, const char *detail);
void (*end)(struct sp_host *, int id, int status, size_t tokens);
};
struct sp_plugin {
uint32_t abi; /* must equal SP_PLUGIN_ABI */
const char *name;
const char *version;
int (*init)(struct sp_host *);
int (*run)(struct sp_host *, const char *input,
struct sp_buf *out);
void (*shutdown)(struct sp_host *);
};
/* Every plugin exports exactly this. */
const struct sp_plugin *sp_plugin_describe(void);
/* ---- host API, implemented by splinter, called by plugins ---- */
uint32_t sp_host_abi(struct sp_host *);
int sp_host_add_tool(struct sp_host *, const struct sp_tool *);
int sp_host_add_widget(struct sp_host *, const struct sp_widget *);
int sp_host_widget_text(struct sp_host *, const char *widget,
const char *text);
int sp_host_note(struct sp_host *, const char *text);
/* a line for the chat transcript; safe from any thread */
int sp_host_status_msg(struct sp_host *, const char *text);
int sp_host_status_take(struct sp_host *, char *buf, size_t len);
int sp_host_add_compactor(struct sp_host *, const struct sp_compactor *);
/*
* The compactor the core registers itself, before any plugin. It is what
* compact_threshold and compact_target drive; a plugin that compacts too runs
* after it.
*/
const struct sp_compactor *sp_core_compactor(void);
/*
* "Leave this conversation alone for this round."
*
* A compactor that works asynchronously - it copies the conversation, hands it
* to a worker and applies the plan on its next call - cannot survive the core
* cutting the conversation between the snapshot and the apply: the plan is
* made for a conversation that no longer exists, the size check fails, and the
* work is thrown away every round while the conversation keeps growing.
*
* So a plugin in that state calls this before returning 0. The host then keeps
* the core compactor out of this one call and asks again next time, which is
* when the plan lands. The flag lasts one call and is not remembered.
*/
void sp_host_compactor_hold(struct sp_host *);
int sp_host_add_gate(struct sp_host *, const struct sp_gate *);
int sp_host_add_status(struct sp_host *, const struct sp_status *);
const struct sp_meter *sp_host_meter(struct sp_host *);
/*
* The model the engine is on right now. The config says what a provider was
* configured with; /model can change the model without touching it, and a
* plugin that shows routing must not guess (it did, and named the wrong
* route). Empty until the engine sets it.
*/
const char *sp_host_model(struct sp_host *h);
void sp_host_set_model(struct sp_host *h, const char *model);
/*
* The upstream that served the last model request, when the provider says
* (junction: X-Junction-Endpoint). The model is what was asked for; this is
* who answered, and a router may pick a different one per request.
*/
const char *sp_host_served_by(struct sp_host *h);
void sp_host_set_served_by(struct sp_host *h, const char *endpoint);
/*
* The judge schedule of the last judged response (X-Junction-Judge-Next,
* -In, -Next-Step/Every/Target/Model/Cache). A plugin can say when the next
* escalation happens without calling the model itself.
*/
struct sp_judge_next {
int valid;
int next; /* counter value */
int in; /* calls remaining */
int step, every; /* the next judge's position in the chain */
char target[64];
char model[128];
char cache[8];
};
void sp_host_set_judge_next(struct sp_host *,
const struct sp_judge_next *);
int sp_host_judge_next(struct sp_host *, struct sp_judge_next *);
/* X-Junction-Cache of the last response: off, 5m or 1h; "" when unknown */
const char *sp_host_cache_mode(struct sp_host *);
void sp_host_set_cache_mode(struct sp_host *, const char *mode);
void sp_host_set_meter(struct sp_host *, const struct sp_meter *);
/*
* Thread-safe: a copy under the host lock, and a change of only the caller's
* fields under the lock. Use these from any thread but the UI's; the two above
* remain for the UI thread and for reading a single field.
*/
void sp_host_meter_get(struct sp_host *, struct sp_meter *out);
void sp_host_meter_update(struct sp_host *,
void (*fn)(struct sp_meter *, void *), void *ctx);
size_t sp_host_status_text(struct sp_host *, char *buf, size_t len);
void sp_host_set_task_ops(struct sp_host *, const struct sp_task_ops *);
int sp_host_task_begin(struct sp_host *, const char *label, const char *detail);
void sp_host_task_end(struct sp_host *, int id, int status, size_t tokens);
/* Ask every gate. Returns 1 allowed, 0 denied (reason filled), -1 no opinion. */
int sp_host_gate(struct sp_host *, const char *tool, int auth,
const char *args, char *reason, size_t reason_len);
int sp_host_turn_blocked(struct sp_host *, char *msg, size_t len);
int sp_host_add_command(struct sp_host *, const char *name, sp_cmd_fn,
void *ctx);
int sp_host_command(struct sp_host *, const char *name, const char *args,
struct sp_buf *out);
size_t sp_host_command_help(struct sp_host *, struct sp_buf *out);
int sp_host_add_transport(struct sp_host *, const char *name,
struct sp_transport);
struct sp_transport *sp_host_transport(struct sp_host *, const char *name);
/* ---- provider: quota/usage/burst policy, pluggable (per key, shared state) ---- */
enum sp_prov_decision { SP_PROV_ADMIT = 0, SP_PROV_DELAY, SP_PROV_WAIT_QUOTA, SP_PROV_DENY };
struct sp_prov_result {
enum sp_prov_decision decision;
long retry_after_s; /* seconds to wait (DELAY) */
long ready_at; /* unix timestamp when quota/backoff ends (WAIT_QUOTA) */
char reason[256];
};
struct sp_provider_ops {
void *ctx;
int (*preflight)(void *ctx, const char *provider, const char *key_id,
struct sp_prov_result *out);
void (*account)(void *ctx, const char *provider, const char *key_id,
long http_status, size_t tokens_in, size_t tokens_out);
};
void sp_host_set_provider(struct sp_host *, const struct sp_provider_ops *);
enum sp_prov_decision sp_host_provider_preflight(struct sp_host *, const char *provider,
const char *key_id, struct sp_prov_result *out);
void sp_host_provider_account(struct sp_host *, const char *provider, const char *key_id,
long http_status, size_t tokens_in, size_t tokens_out);
/* shared per-(provider,key_id) usage/quota state (~/.splinter/providers/...), flock+atomic.
* Provider plugins use this for cross-instance, per-key tracking. */
struct sp_prov_state {
long quota_ready_at; long backoff_until;
unsigned req_count; unsigned long tok_in, tok_out;
long last_status, last_update, last_429_at;
char note[128];
};
int sp_provstate_load(const char *provider, const char *key_id, struct sp_prov_state *out);
int sp_provstate_update(const char *provider, const char *key_id,
void (*fn)(struct sp_prov_state *s, void *ctx), void *ctx);
void sp_provstate_account(const char *provider, const char *key_id,
long http_status, size_t tok_in, size_t tok_out, long retry_after_s);
int sp_provstate_preflight(const char *provider, const char *key_id,
long now, long *ready_at, char *reason, size_t reason_cap);
/* Stable fingerprint of a secret key (never stores/returns the secret). */
char *sp_key_fingerprint(const char *secret, char *buf, size_t cap);
int sp_host_compact(struct sp_host *, struct sp_conv *, size_t budget);
size_t sp_host_compaction_stats(struct sp_host *, size_t *compactions,
size_t *failed, unsigned *turns);
void sp_host_turn(struct sp_host *);
/* The loaded configuration, so plugins (the exit ring) can read it. */
const void *sp_host_config(struct sp_host *);
void sp_host_set_config(struct sp_host *, const void *);
/*
* A plugin's own configuration, from its block in the config file:
*
* plugin lcm {
* keep = 40
* server junction { url = http://... }
* }
*
* sp_host_plugin_config(h, "lcm", "keep") is "40", a nested block gives
* dotted keys ("server.junction.url"), a list "a,b,c". NULL when the key is
* not set (or no config is loaded). 'plugin' is the block's name.
*
* sp_host_plugin_config_at() walks every setting of 'plugin' in file order:
* index 0, 1, ... until it returns NULL; *key gets the setting's name.
*/
const char *sp_host_plugin_config(struct sp_host *, const char *plugin,
const char *key);
const char *sp_host_plugin_config_at(struct sp_host *, const char *plugin,
size_t i, const char **key);
struct sp_registry *sp_host_registry(struct sp_host *);
/* ---- host side, implemented by splinter, called by the harness ---- */
struct sp_host *sp_host_new(struct sp_registry *, struct sp_agent *,
struct sp_session_info *);
void sp_host_free(struct sp_host *);
const char *sp_host_session_dir(struct sp_host *);
const char *sp_host_session_id(struct sp_host *);
/* Retry a durable delegation job (scheduler/worker). 0 on handled (see out). */
int sp_delegate_retry_job(const char *id, int force, struct sp_buf *out);
/* Scheduler tick: retry one due waiting_quota/waiting_poll job if any. */
int sp_delegate_tick(struct sp_buf *out);
int sp_plugin_load(struct sp_host *, const char *path,
struct sp_buf *err);
size_t sp_host_widget_snapshot(struct sp_host *, char *buf, size_t len);
size_t sp_host_widget_count(struct sp_host *);
#endif /* SPLINTER_PLUGIN_H */