Files
splinter/docs/PLUGINS.md
T
lotherk ddf0ec5462 tools: valid schemas; sse: surface in-stream errors
A judged request sends the whole tool list to the judge. Claude validates the
schemas and rejected the request with 400
"tools.22.function.parameters.type: Field required": delegate_due and
delegate_jobs declared "parameters": {} instead of an object schema. junction
wrapped that 400 in the stream as data: {"error":{...,"code":400}}, but the SSE
parser ignored anything that was not a choice - so the turn ended with
"stream ended with no answer" and the one line explaining it was lost. Three
sessions stopped that way at the same minute.

- delegate_due/delegate_jobs now carry {"type":"object","properties":{}}.
- test_engine walks every registered tool and fails when parameters.type is
  not "object"; this catches the next schema before a judge does.
- sp_sse_line recognises a top-level error object, reports its message and
  remembers its code; the transport puts the code in the reply status.
- a 4xx from the stream ends the turn with the real message and is not
  retried; an empty 2xx stream and a 5xx still are. 402/429/529 stay with the
  usage-limit path, which already handles them.
- test_sse feeds the junction 400 event and checks message and code.
- README and docs/PLUGINS say why a tool schema needs type:object.

make check: all tests passed.
2026-11-18 06:28:23 +00:00

523 lines
23 KiB
Markdown

# Plugins
A splinter plugin is a shared object that links against `libsplinter.so` and
exports one symbol:
```c
const struct sp_plugin *sp_plugin_describe(void);
```
The struct, the ABI number and the host functions are in
`include/splinter_plugin.h`. Nothing else is stable. `SP_PLUGIN_ABI` changes
whenever that header changes in a way that breaks an old plugin, and a plugin
with the wrong number is refused at load time with the two numbers in the
message.
## Build
```sh
cc -std=c99 -shared -fPIC -o myplugin.so myplugin.c -L. -lsplinter \
-Wl,-rpath,'$ORIGIN'
```
`splinter --plugin ./myplugin.so --chat` loads it before the first turn. A
plugin that fails to load is reported on stderr and skipped; the harness keeps
working.
## Configuration
In the config file every plugin has its own block (`docs/CONFIG.md`,
"Plugins"):
```
plugin mine {
path = ~/my/myplugin.so # omitted: the shipped plugin "mine"
depth = 3
hosts = [a, b]
server a { url = http://a/mcp }
}
```
Everything but `path` and `enabled` is the plugin's own, and it reads it
through the host by the block's name:
```c
const char *d = sp_host_plugin_config(host, "mine", "depth"); /* "3" */
const char *h = sp_host_plugin_config(host, "mine", "hosts"); /* "a,b" */
const char *u = sp_host_plugin_config(host, "mine", "server.a.url");
```
A missing key is NULL; the value is a string, parsing is the plugin's job.
To see every setting (the servers it was given, say), walk them in file order:
```c
const char *key, *val;
size_t i;
for (i = 0; (val = sp_host_plugin_config_at(host, "mine", i, &key)) != NULL; i++)
/* key = "depth", "hosts", "server.a.url", ... */;
```
Both work from `init()` on. The config is read once at start; a value does
not change while the plugin runs. The `mcp` plugin is the one exception to
the dotted names: its `server NAME { }` blocks become the MCP server list it
always read (`sp_host_config()`), so `plugin mcp { server ... }` and the old
`mcp NAME { }` block mean the same.
## What a plugin may do
| hook | thread | may block | may touch curses |
|------------|---------------|-----------|------------------|
| `init()` | main | no | no |
| `run()` | main | yes | no |
| `tick()` | its own | yes | no |
| `draw()` | main (UI) | no | no |
Streaming is a transport concern, not a plugin one: `sp_transport.send_stream`
is optional, and a transport that cannot stream leaves it NULL — the loop then
falls back to the one-shot call.
`tick()` runs on a thread the host creates and can stop. It may read files,
wait on sockets, sleep. It must not assume it is the only thread.
What the plugin wants to say is published as a widget line:
```c
sp_host_widget_text(host, "mywidget", "42 items");
```
The host copies the string under a mutex, so a stack buffer is fine and the
worker never hands the UI a pointer it could free.
## Widgets
```c
static const struct sp_widget w = {
.name = "clock",
.tick = clock_tick, /* worker thread, publishes text */
.draw = NULL, /* NULL: render the published text */
.ctx = NULL,
.interval_ms = 1000, /* 0: tick once */
};
sp_host_add_widget(host, &w);
```
The sidebar lists one line per widget, `name: text`; `/widgets` prints the same
lines into the transcript. `draw()` exists for widgets that need more than one
line; it runs on the UI thread and must be fast, because it holds up the rest of
the screen while it runs.
## Threads, honestly
- One thread per widget with a `tick`. A widget without `tick` gets no thread.
- The host joins every thread in `sp_host_free()`, setting a stop flag first.
A `tick` that never returns therefore hangs the exit; that is a bug in the
plugin, not something the host can fix from outside.
- No plugin is `dlclose()`d. Unmapping code that a thread might still be
inside is how a harness dies in a way nobody can debug.
- The host pointer is thread-safe only for `sp_host_widget_text()` and
`sp_host_note()`. Everything else belongs to the main thread. That is a
rule, not an accident.
## Tools
A plugin registers tools with the same authorization classes the builtins use:
```c
struct sp_tool t = { 0 };
t.name = "clock";
t.description = "Report the local date and time.";
/*
* parameters is a JSON schema, and its root must say "type":"object".
* A bare {} is rejected by judges that validate the tool list (Claude did,
* and the whole request failed), even when the model itself would accept it.
*/
t.params = "{\"type\":\"object\",\"properties\":{}}";
t.auth = SP_AUTH_READ;
t.run = clock_tool;
sp_host_add_tool(host, &t);
```
`SP_AUTH_READ` runs. `SP_AUTH_MUTATE` and `SP_AUTH_DESTRUCTIVE` ask the
operator unless the harness was started with `--autonomous`. The loop decides
this, not the plugin.
## Compaction
A compactor runs on the main thread before every request, with the whole
conversation in hand, and may rewrite it:
```c
struct sp_compactor {
.const char *name;
int (*compact)(struct sp_host *, struct sp_conv *, size_t budget_bytes,
unsigned turn);
};
```
Return 1 when it changed something, 0 when there was nothing to do, -1 on
failure. A failure is counted and the turn continues: a broken compactor must
not take the conversation with it.
Two come with the tree.
**lcm** — deterministic, lossy, honest. If the conversation does not fit the
budget, it first cuts **old tool outputs** to a head and a tail with a marker
in between (their middle stays in the session log, where the `recall` tool
finds it); only when that is not enough does it keep the leading system message
and the last six messages and put one system message in between that says how
many messages went, of which roles, and quotes the head of the oldest dropped
turn. No second model is called, so a run stays reproducible and costs nothing
extra. `plugin lcm { keep = 6; tool_trim = 8192 }` sets the verbatim tail and
the byte cap per old observation; `tool_trim = 0` turns the trim off.
What it did is visible while it runs - the counters are the compactor's own, not
a second estimate:
```
lcm: ctx 12.3k/32k
compacted 3 cut 41 msgs
last 60->22 msgs 180.2k->44.1k B
tools trimmed 7
```
The first line is the context the last request carried against the window; then
the number of compactions and how many messages they removed in total; how the
last cut looked in messages and bytes; and how many old tool outputs were
trimmed. `/status` gets one segment, `compact 3`, next to the other meters.
**cps** — continuous parallel compression. The expensive part (deciding what
would go) is computed on the widget's worker thread from an *index* of the
conversation — role, size, and 64 bytes of head per message, copied under a
mutex. The worker never touches the conversation itself. When the budget is
hit, the main thread splices an already-prepared plan in one pass. Its widget
line shows `idle (applied N, prepared M)` or `plan ready: cut X/Y, A -> B B`,
so "continuous" is visible rather than claimed.
The limit is stated in both files: they can decide *which* messages go, not
summarise their text, because summarising needs the text and the text is not
the worker's to read.
## Transports
A transport turns a conversation into an answer. The built-in one speaks
OpenAI's `chat/completions`; a plugin can provide others:
```c
struct sp_transport tr = { my_send, my_ctx };
sp_host_add_transport(host, "cli", tr);
```
then `splinter --plugin ... --transport cli`.
**cli** ships with the tree and makes *any program* the model — `claude -p`,
`opencode run`, `ollama run`, a shell script. Each brings its own keys, its own
quota, its own free tier:
```sh
SPLINTER_CLI_CMD="claude -p" ./splinter -p "hi" --plugin plugins/cli/cli.so --transport cli
SPLINTER_CLI_CMD="opencode run" ./splinter -p "hi" --plugin plugins/cli/cli.so --transport cli
```
- `SPLINTER_CLI_CMD` — the program, default `claude -p`
- `SPLINTER_CLI_FULL=1` — send the whole transcript instead of the last user
message (for programs that keep no history of their own)
- `SPLINTER_CLI_TIMEOUT` — seconds of silence before the program is killed,
default 1800 (or `cli_timeout` in the config); output on stdout or stderr
resets the window, so a long answer that keeps printing is not cut off
- `SPLINTER_CLI_CMD` may include `{file}` (prompt file path) or `{prompt}` (shell-quoted prompt); without a placeholder the prompt is passed on stdin
The command comes from the operator's environment and runs through `/bin/sh -c`;
it is never built from model output. Output is capped at 4 MiB, a non-zero exit
returns the program's own stderr, and a program that prints nothing is an error
— an empty answer must never look like a real one.
## focus
Long conversations drift: ten turns in, the model is deep in a detail and the
reason the session exists is somewhere behind it. `focus` puts the goal back on
the table.
```
/goal splinter zu einem agent-harness machen, das hermes ersetzt
```
`/goal <text>` sets it and starts a turn: the prompt asks the model for a short
recap (3-5 bullets, what must be true at the end, the first steps, open
questions). The plugin remembers that answer and injects it every seventh turn
— never twice in one turn, nothing at all when no goal is set. `/goal` alone
shows the goal. There is no `/recap`: recapping is what a goal does. The goal is
stored in the session's `.meta`, so a resume, `/open` or `/continue` finds it
again. `/continue` starts a turn that picks the goal up where the session
stopped. That works in the TUI and in a one-shot run
(`splinter -p "/goal ..."`); it is not a config key, because a goal belongs to
the conversation in front of you. `SPLINTER_FOCUS_EVERY` sets the interval
(default 7 turns).
The goal is in the prompt from the first request, not from the seventh turn:
when a goal exists and has not been announced in this session yet (config,
resume, planner), the compactor inserts it once, before the newest user
message.
A goal ends. Every text that carries the goal — the first announcement, the
recap prompt, `/continue`, the periodic reminder — tells the model to end its
final answer with the single line `GOAL_COMPLETE` when the goal is fully
achieved. The plugin then records `goal_state=succeeded` beside the goal in the
session `.meta` (it also watches the session log from its tick, so the state
changes without waiting for the next turn), stops reminding, writes one
`goal succeeded: …` note into the transcript, and shows `[done]` in the sidebar.
Only an answer written after the goal went into a prompt can close it, so an
old `GOAL_COMPLETE` cannot mark a goal that was set later. `/goal` reports the
state; a new goal opens a new one.
It registers as a compactor and inserts one system message — *before* the newest
user message, so the model reads recap then request and answers the request. If
the model has not answered the recap prompt yet, the goal text stands in. Its
widget line shows the goal, `[done]` when it is reached, and the warning is
never printed twice in one turn.
It is a reminder, not an instruction: the user can change direction at any
time, and the message says so on its face.
## junction
The fleet router, evaluated from the outside. junction answers `/mcp` with
```
X-Junction-Mcp: 1
```
and that header is the identity: a 200 with the header is junction, a 200
without it is "not junction, or a proxy in front of it" — a health check that
trusts any answer is wrong exactly when it matters.
The widget is only what belongs to the model this run is on: its name (from
the engine, not from the provider's configured default — `/model` can switch
the model without touching the config) and the targets the matching
`/status` rule sends it to. Nothing else: a `!` marks a target whose own
health probe is failing.
```
junction
deepseek-v4.1-flash
serving opencode-go1
route opencode-go0
opencode-go1
opencode-go2
ollama0-splinter
4/4 up
```
`serving` is the `X-Junction-Endpoint` of the **last real answer** - the
provider says which upstream actually served it, and the transport publishes
it (`sp_host_served_by`). That is not the route: junction may pick another
target per request, and a fallback can differ from every rule. `(no request
yet)` until the first answer. The route below is what the matching rule would
use; the rule is chosen by exact model match, then glob (`*`, `?`), then
catch-all, and rules with a `path` describe another route (`/v1/models`). A
target whose probe is down gets the `!`.
Everything else is `/junction`, not the sidebar: uptime, MCP servers, queue,
requests, endpoints with p95 and exhausted counts, the model count from
`/v1/models`, and **every response header** of every probe grouped by source.
That includes `X-Junction-Ms`/`X-Junction-Cache` and the probe's own
`X-Junction-Endpoint` (which is `/v1/models` -> `opencode-go`, not the
conversation's route). junction accepts `/status`, `/v1/status`, `/queue` and
`/v1/queue` as the same route; the plugin remembers which one answered and
only tries the whole list when it stops. It does not count a second time.
That is a widget, a status segment (`junction 20m up`), the tool
`junction_status` and `/junction`. The address and the key come from the
plugin's own block, else from the `mcp junction` server, else from
`SPLINTER_JUNCTION_URL` / `SPLINTER_JUNCTION_TOKEN`. The header is never
printed: it carries the key. `interval` (milliseconds, default 5000) sets how
often the tick asks; `models_interval` (default 60000) how often the model
route is probed, because that one goes upstream and the other two do not.
## self
What the session costs the machine, and what its children cost:
```
self
84M rss 3.2% cpu
18 thr 41 fd
kids 3 120M 1.4% cpu
io 12M r 300k w
```
The process itself from `/proc/self/status` (VmRSS, Threads), `/proc/self/fd`
(count) and `/proc/self/io` (bytes); the children from one pass over
`/proc/<pid>/stat`, following the parent chain: `run` calls, MCP server
children, delegates, a CLI transport. CPU is the delta between two samples
(2 s by default, `interval` in ms), so it says what is happening now; IO is
cumulative for the session. `/self` and the `session_usage` tool print the
same numbers with the pid and the child count.
## Zustimmung (ack)
Ein Werkzeug, das etwas aendert, braucht ein Ja von einem Menschen. Der Mensch
kann am Terminal sitzen, am Telefon, oder hinter einem Skript - es koennen
mehrere Kanaele sein, und die erste Antwort gewinnt.
Der Mechanismus ist zwei Dateien, damit nicht zwei Prozesse um dieselben
Telegram-Updates streiten:
~/.splinter/ack/pending/<id> die Anfrage (0600)
~/.splinter/ack/pending/<id>.answer die Antwort (0600)
Der blockierte Prozess wartet nur auf die Datei. Kanaele sind Melder: sie stossen
die Anfrage nach draussen (ein Kommando pro Kanal), und wer die Antwort liest -
das Gateway, ein Telefon, ein Skript - legt die Antwortdatei ab.
SPLINTER_ACK_CHANNELS="telegram-ask,mastodon-ask" # Kommandos, Komma-getrennt
SPLINTER_ACK_TTL=120 # Sekunden, Default 120
SPLINTER_ACK_DIR=~/.splinter/ack # optional
SPLINTER_ACK_BY=konrad # wer antwortet (beim --ack)
Im Telegram-Chat antwortet ein Programm aus <code>commands/</code> direkt; im
TUI geht seine Ausgabe als Kontext ans Modell. Ein unbekannter Slash-Befehl
antwortet mit der Liste, statt an das Modell zu gehen.
Antworten, aus jedem Prozess:
splinter --ack 482915307 yes # yes, y, ok, ja
splinter --ack 482915307 no # no, n, nein - jedes andere Wort ist ein Fehler
splinter --ack-list
Ein Timeout ist ein Nein. Stille ist keine Zustimmung.
Das Telegram-Gateway registriert seine Befehle beim Start: die der geladenen
Plugins, die Programme in `~/.splinter/commands/` mit gueltigem Telegram-Namen
und `/start`, `/help`, `/interview`; `/help` listet sie im Chat. `/interview`
startet dasselbe modellgetriebene Interview wie `splinter --interview` im Chat;
die Zusammenfassung landet in `~/.splinter/USER.txt`, `/new` beendet es. Die Anfrage selbst legt es als
Nachricht mit **Ja/Nein-Knoepfen** vor.
Der Knopf ist ein `callback_query`, kein Text: das Gateway prueft denselben
Allow-List-Eintrag, antwortet dem Knopf, entfernt die Knoepfe und legt die
Antwortdatei ab. Die Textform `ok <id>` / `no <id>` bleibt als Rueckfall.
Regeln, die der Code durchsetzt:
- Die Id ist zufaellig (6-9 Ziffern) und wird nie wiederverwendet; sie ist nicht
die pid. Eine Antwort gilt genau einer Anfrage.
- Nur die erste Antwort zaehlt; eine zweite wird abgewiesen.
- Ist die Anfrage beantwortet oder abgelaufen, wird sie geloescht. Eine spaete
Antwort scheitert mit "no open request", statt auf die naechste Anfrage zu
warten.
- Ein ack-Verzeichnis, das nicht dem Benutzer gehoert oder fuer andere
schreibbar ist, wird abgelehnt: dort koennte jeder ein Ja hinlegen.
- Grenze: Jeder Prozess unter derselben uid kann antworten. Wer das Kind am
selben Konto vom Zustimmen abhalten will, braucht eine eigene uid fuer splinter
(oder einen Kanal, dessen Antwort der lokale Benutzer nicht schreiben kann).
## provider
Per-`(provider, key)` quota and usage, shared by every splinter that uses the
same key: state is written under `~/.splinter/providers/` with `flock` and an
atomic rename. `preflight` can delay or refuse a request before it is sent;
`account` records the status and token counts afterwards. A 429, 402 or 529
becomes a quota wait, 503 and 408 a short backoff. Ollama is treated as local
(backoff only, no quota) unless a quota is configured. `SPLINTER_PROVIDER_PROBE`
and `SPLINTER_QUOTA_PROBE_URL` enable an optional probe.
## scheduler
The other half of a quota wait: once a minute it looks for one durable
delegation job that is due (`waiting_quota`, `waiting_poll` or `queued` with
`run_after`/`next_poll_at` reached) and retries it. With `provider` and the
delegate job tools, "quota is back in three days" becomes a scheduled retry
instead of a lost task.
## a2a
Another agent as the backend, over the Agent2Agent protocol. The transport is
selected like any other:
SPLINTER_A2A_URL=https://agent.example/rpc \
SPLINTER_A2A_TOKEN=... \
splinter --plugin plugins/a2a/a2a.so --transport a2a -p "..."
It sends `SendMessage` as JSON-RPC 2.0 with one text part, blocking, and reads
either a direct `Message` or a `Task` in `TASK_STATE_COMPLETED`; text parts,
text/plain `raw` parts (base64) and string `data` parts from the status message
and the artifacts are joined. A binary `file` or `raw` part is saved
(`SPLINTER_A2A_INBOX`, default `$TMPDIR/splinter-a2a-inbox`) and named in the
answer by path, so the agent can open it; a `url` part is ignored on the client. `SPLINTER_A2A_FULL=1` sends the
whole transcript instead of the last user turn, and `SPLINTER_A2A_TIMEOUT` sets
the curl timeout (default 300 seconds). The task id and context id are remembered
for the session, so the next turn stays in the same A2A context; a terminal task
loses its id, a context keeps it.
When the UI is driving the turn (`sp_agent_config.stream` is set), the transport
uses `SendStreamingMessage` instead and hands artifact/message text to the screen
as it arrives. Intermediate status notes are progress and are not appended; a
completed status message is the answer only when no artifact or direct message
text came. One-shot mode streams too unless `--no-stream` asks for the blocking
`SendMessage` path.
The endpoint can be configured directly (`SPLINTER_A2A_URL`) or discovered:
`SPLINTER_A2A_CARD` names the agent card, and the first call picks the
`JSONRPC` entry from `supportedInterfaces` (or the older single `url` field).
The discovered URL is kept for the session.
The transport sends text; `a2a_send` (destructive) sends a message with an
optional `file` part — base64, 8 MiB cap, `mimeType` guessed from the name when
not given — and returns the other side's answer, saving a file it sends back.
The client does not send push notifications. With a local transport, the plugin
also registers `a2a_get_task`, `a2a_cancel_task` and `a2a_subscribe`
(read/destructive/read); they use the same endpoint or card.
The first two return the raw task/error JSON; the subscription reads the SSE
events (`statusUpdate`, `artifactUpdate`, a whole task) into one text: the
state, the message and the artifact text, in the order the server sent them.
`tests/fake_a2a.py` and `tests/test_a2a.sh` pin the blocking wire shape, both
result forms, the bearer token, a JSON-RPC error, streaming and discovery;
`tests/test_a2a_ui.sh` drives the streaming path through tmux.
## a2a server
The reverse direction is not a plugin: `src/a2aserver.c` is built in, because it
needs the agent and its authorization model, not only a transport.
SPLINTER_A2A_SERVER_TOKEN=... \
splinter --a2a-server-listen 127.0.0.1 --a2a-listen-port 8099
`POST /a2a` speaks JSON-RPC: `SendMessage` runs one turn in the conversation
named by `contextId` (or a fresh one, whose id comes back in the task), stores
the completed Task and returns it;
`SendStreamingMessage` runs the same turn and writes SSE `artifactUpdate` events
as the transport produces text (a non-streaming transport sends its whole answer
as one artifact), followed by a completed `statusUpdate`; `GetTask` returns the
stored Task itself and `ListTasks` lists them (optionally by `contextId`); `GET /.well-known/agent-card.json` serves a card with the `JSONRPC`
interface. One request at a time, one connection at a time.
A `taskPushNotificationConfig` in the `SendMessage`/`SendStreamingMessage`
configuration posts the completed task to that webhook (payload: one
`StreamResponse` with `task`). Loopback is allowed by default; any other host
needs `SPLINTER_A2A_PUSH_ALLOW` (comma separated, `*` for all), which keeps a
client from turning the server into an SSRF probe. The config token travels as
`X-A2A-Notification-Token`, the authentication as `Authorization`. The four
push-config methods (`CreateTaskPushNotificationConfig`, `Get...`, `List...`,
`Delete...`) manage the same configs in memory.
A text/plain `url` part is fetched from loopback or a host in
`SPLINTER_A2A_URL_ALLOW` (same syntax, 1 MiB cap, no redirects). A binary part
arrives as `file { name, mimeType, bytes }` or `raw` + `mediaType`; it is
written to the session's `inbox/` (0600, 8 MiB cap) and the prompt says
`[file <name> at <path> (mime, n bytes)]`, because a text model cannot read a
PNG but the agent around it can. The same is true for a binary `url` part.
A mutating tool that needs approval pauses the task in
`TASK_STATE_INPUT_REQUIRED`; the assistant call is already in the context, the
tool has not run. Another `SendMessage` with the same `taskId` and a
`yes`/`no` answer resumes it (`sp_agent_resume`); `CancelTask` cancels it.
`SendStreamingMessage` has nowhere to resume, so it denies mutating tools
instead of pausing.
`SubscribeToTask` sends the state the task has now (status update with its
message) and ends the stream: one request at a time means a task cannot make
progress while a subscription is open, so a live feed would be a promise the
server cannot keep. Beyond loopback
`SPLINTER_A2A_SERVER_TOKEN` is required and checked as
`Authorization: Bearer ...`; there is no TLS.