# splinter Named after Master Splinter: the one who knows which tools exist, who may use them, and what happened — and trains the ones that do the fighting. A C99/POSIX agent harness with a curses interface: the conversation on three quarters, a sidebar on the last one that says which agent, provider, model and allowance you are on and where the tools will act, a status line above the prompt with the context gauge (`ctx used/max`, cache share, tok/s), and the prompt below it. The conversation starts clear at the top and only ever grows. make # libsplinter.so, the binaries, the plugins make check # the tests, no network, no model make install PREFIX=$HOME/.local # binaries, library, plugins splinter --init-config # writes ~/.splinter/splinter.conf splinter --doctor # does every provider answer? splinter # the chat; Tab switches build / plan splinter -m claude # a provider, a pool, provider/model splinter --model-list # everything -m takes splinter --serve # the engine on a socket, for a GUI splinter --attach # the same curses UI, as a client of it splinterctl --say "hallo" # the reference client for that socket splinter --openai-listen 127.0.0.1 # /v1 for another harness, gw_ tools The working day with several subscriptions (who analyses, who implements, what happens at a limit) is in `docs/WORKFLOW.md`. ## What it does `splinter -p "list the C files" --endpoint http://127.0.0.1:8080/turn` sends a prompt, runs the tools the transport asks for, and prints the answer. Every turn is appended to `~/.splinter/.jsonl` as one JSON object per line. ## What it refuses to do - Send a request that exceeds the configured byte budget (nothing is sent; the turn fails instead of letting an endpoint truncate silently). - Run a tool that is not in the registry (the model is told, not guessed at). - Run a mutating or destructive tool without operator consent, unless `--autonomous` was given. - Skip a denial silently: the denial becomes the observation the model sees. ## Transport protocol The harness speaks a line protocol with its transport, not a vendor API: request user request observe reply answer reply tool A provider adapter translates an OpenAI-compatible endpoint into this shape and back. That is why `make check` needs no network, no key and no model: the mock transport replays replies. ## Layout The harness is a backend and a set of front ends; `docs/FRONTENDS.md` says where the line runs and how to add another one. libsplinter.so every symbol, once; binaries and plugins link to it include/splinter.h the core interface include/splinter_engine.h the engine a front end talks to (events, turns) include/splinter_plugin.h plugin ABI and host API src/backend/engine.c session + agent + turn thread + event queue src/backend/agent.c the loop src/backend/conv.c the conversation (owned messages, no sharing) src/backend/openai.c request shaping + reply parsing, pure functions src/backend/transport*.c HTTP, the mock, the vendor shapes src/backend/session.c append-only JSONL session src/backend/builtin.c read/write/edit/search/list/run/web tools src/backend/tool.c the registry src/backend/config.c the config file src/backend/providers.c -m, /model, pools, failover src/backend/plugin.c dlopen loader, widget registry, worker threads src/backend/md.c markdown tables as aligned text src/backend/telegram.c gateway mode src/backend/a2aserver.c the A2A server src/backend/openai_server.c /v1/chat/completions with gw_ tools src/backend/http.c the HTTP helpers the JSON servers share src/frontend/curses.c transcript, sidebar, prompt src/frontend/ui_backend.h what the screen needs from a backend src/frontend/ui_local.c that backend as the engine in this process src/frontend/ui_remote.c that backend as a socket client (--attach) src/frontend/protocol.c splinter --serve: JSON lines on a Unix socket src/frontend/client.c splinterctl, the reference protocol client src/frontend/ui.h the curses entry point src/main.c launcher: parse, config, engine, front end plugins/clock/ example plugin: a sidebar clock + a tool vendor/netbsd-curses/ NetBSD curses and terminfo, vendored docs/PLUGINS.md the ABI, the threading rules docs/PROTOCOL.md the line protocol a GUI client speaks docs/GATEWAY.md the OpenAI endpoint and its two tool sets tests/ the test binaries, run by `make check` docs/splinter.1 manual page src/www/index*.html the site, written by hand (de, en, pt_BR) ## Front ends The engine is front-end neutral: `sp_engine_submit()` starts a turn on its own thread and everything that happens — streamed text, a step's reasoning, a tool call, its observation, an approval question, the answer — becomes an event the front end drains. The curses interface is one front end; `splinter --serve` is another, and it is what a GUI would use. ```sh splinter --serve # ~/.splinter/splinter.sock splinter --serve --socket /tmp/s.sock splinter --attach --socket /tmp/s.sock # the curses UI, as a client splinterctl --socket /tmp/s.sock --say "list the C files" python3 docs/proto-example.py /tmp/s.sock "list the C files" ``` The screen itself is a client in `--attach` mode: it speaks the same lines a GUI would, shows the server's session and its transcript so far, runs every turn there and switches the server's profiles. That is the proof that the protocol carries everything the front end needs; if `--attach` works, a GUI has no hidden C dependency. The protocol is one JSON object per line (`ready`, `state`, `stream`, `step`, `tool`, `tool_result`, `approval`, `turn`, ...; `input`, `say`, `approve`, `cancel`, `steer`, `state`, `quit`, `sessions`, `open`). `docs/PROTOCOL.md` has the field list and a sequence diagram; `docs/FRONTENDS.md` has the code layout and how to start a GUI on top of it. The socket is `0600` and the server checks the peer's uid. The engine keeps more than one session: `sessions` lists the directory, `open` switches to an id (or `new`/`last`) and sends the state and history of that session. The screen offers the same as `/sessions` and `/open ID`, locally and over the socket; a local switch closes the engine and reopens it from the same options, because plugins keep process globals. `/sessions` shows a title - the first user line until `/rename [ID] TITLE` says otherwise - and `/rm ID` removes a session that is not open. One session is active at a time; over the socket, one client at a time. `--attach` reconnects: if the server dies, the screen says so, keeps running, and attaches again when a server is back on the socket - asking for the session it was on by id, so the conversation continues where it stopped. If that session is gone, it says which one and stays on the server's current session. ## Gateway: another harness, splinter's tools `splinter --openai-listen 127.0.0.1` serves `/v1/chat/completions` for another harness. The model sees splinter's local tools as `gw_read`, `gw_write`, `gw_run`, ... and the caller's own tools under their own names: * a `gw_*` call is executed by splinter, on the host where splinter runs, and the caller only sees the final answer; * any other tool call is returned to the calling harness, which runs it where it runs and sends the results back in the next request. That is how one conversation can act in both places, without a name collision between a local `read` and a caller's `read`. Beyond loopback a `SPLINTER_GATEWAY_TOKEN` is required, and local mutating tools need `--autonomous`. `docs/GATEWAY.md` has the details and examples. ## Plugins and themes A plugin is a `.so` against `libsplinter.so`, exporting `sp_plugin_describe()`. It can register tools (with authorization classes the loop enforces) and widgets. A widget's `tick()` runs on its own thread and publishes a line of text, which the sidebar shows; `/widgets` prints the same lines into the transcript. See `docs/PLUGINS.md`. The default theme is `Xresources`: it takes `*foreground`, `*background` and `*color0`..`*color15` from `xrdb -query` (or `~/.Xresources` without X) and paints the UI with them, so the harness looks like the terminal it runs in. Without any of those resources it keeps the terminal's own colour indices. Two flat themes are the readable ones: `light` is a white page with black text, `dark` the same inverted. The chat, the sidebar and the input line share the page colour; only the status line above the prompt is a separate surface (light grey on `light`, dark grey on `dark`). That is the shape to reach for when a palette leaves the conversation unreadable: `theme = light` in the config or `--theme light`. Every CDE palette from the desktop's `.dp` files is a theme as well, 42 of them including `Default` and `MakroSlate`. A palette is used the way the desktop uses it: set 5 is the chat background, set 4 the input area, set 1 the user's lines, set 7 the model's answer, set 3 its reasoning, set 6 tool calls, set 8 status and session notes, and set 2 observations, with black or white text by CDE's own rule. Role colours keep their hue and are moved away from the background only when they would disappear into it. `--list-themes` prints the names, `--theme NAME` picks one, and `theme = NAME` in the config makes it the default. ## Talking to a model ```sh ./splinter -p "say hi" --endpoint http://127.0.0.1:8080/v1 \ --model qwen2.5-coder-7b --api-key-env SPLINTER_API_KEY ``` The adapter shapes the whole conversation into one `chat/completions` request, including the tool table, and parses `content` and `tool_calls` back. The provider's raw `tool_calls` array is stored verbatim in the conversation and sent back unchanged on the next round: re-encoding it would be a silently different JSON. `content: null` is an empty answer, not an error; a reply without choices, or a provider `error` object, is an error that quotes the provider's own message. ## Any program as the model ```sh SPLINTER_CLI_CMD="claude -p" ./splinter -p "hi" --plugin plugins/cli/cli.so --transport cli ``` The `cli` transport runs a program and takes its stdout as the answer, so `claude -p`, `opencode run`, `ollama run` or a script can be the brains. The OpenAI adapter stays the default for local endpoints. ## Claude without the CLI Anthropic speaks its own shape, not `chat/completions`, so it is a transport of its own (`kind = anthropic`). It is called over the API with the operator's own token -- no `claude` process, no child, nothing to freeze: ``` provider claude-a { kind = anthropic endpoint = https://api.anthropic.com/v1 model = claude-sonnet-5-5 key = "sk-ant-oat01-..." # or key_env = CLAUDE_CODE_OAUTH_TOKEN limit = 40/5h } ``` A `sk-ant-oat` token (Claude Code) is sent as a Bearer token with the oauth beta and Claude Code's first system block, which the API insists on; an `sk-ant-api` key goes as `x-api-key`. Tools become `tool_use` blocks and their observations `tool_result` blocks; the system prompt is the top-level `system` field. Three accounts are three providers and one pool: ```sh splinter -m claude # the pool: the account with the most room first splinter -m claude-a # one account splinter -m claude/claude-opus-5-5 # the pool, another of its models ``` `--doctor` checks each one by asking for its model list and reading the local usage record; it never sends a completion request, so it spends no tokens. ## Another agent: A2A ```sh SPLINTER_A2A_URL=https://agent.example/rpc \ SPLINTER_A2A_TOKEN=... \ ./splinter -p "hi" --plugin plugins/a2a/a2a.so --transport a2a ``` The client half of Agent2Agent: one `SendMessage` over JSON-RPC 2.0 with a text part, blocking, and a direct `Message` or a completed `Task` as the answer. In the UI the turn streams: `SendStreamingMessage`, artifact text appearing as it arrives. The task and context ids are kept for the session, so the next turn continues the same A2A context. `SPLINTER_A2A_CARD` discovers the JSON-RPC endpoint from an agent card; `SPLINTER_A2A_URL` sets it directly. One-shot mode streams by default; `--no-stream` asks for the blocking send. The transport sends text. A file goes with `a2a_send` — a message plus a `file` part (base64, 8 MiB cap, media type guessed from the name) — and a file the other side sends back is saved (`SPLINTER_A2A_INBOX`, default `$TMPDIR/splinter-a2a-inbox`) and named by path in the answer. `a2a_get_task`, `a2a_cancel_task` and `a2a_subscribe` (the SSE events of a task, as one text) use the same endpoint. Push notifications are not sent by the client. ## The other direction: splinter as an A2A server ```sh SPLINTER_A2A_SERVER_TOKEN=... \ ./splinter --a2a-server-listen 127.0.0.1 --a2a-listen-port 8099 ``` Another agent can send `SendMessage` to `POST /a2a` and read `GetTask` or `ListTasks`; the agent card is served at `/.well-known/agent-card.json`. `SendStreamingMessage` streams the answer as SSE artifact updates, then a completed status. A `contextId` is a conversation: the next message with it continues. Without one the server creates a context and returns it in the task. A `taskPushNotificationConfig` in the request posts the completed task to a webhook: loopback is always allowed, other hosts need `SPLINTER_A2A_PUSH_ALLOW`; the config's token travels as `X-A2A-Notification-Token`, its authentication as `Authorization`. Binary `file`/`raw` parts are written into the session's `inbox/` and described to the model by path (a text model cannot read a PNG, the agent around it can); URL parts are fetched from loopback or a host in `SPLINTER_A2A_URL_ALLOW`. `SubscribeToTask` replays the stored task state once and ends the stream — the server answers one request at a time, so there is no progress to watch. Beyond loopback the bearer token is required; there is no TLS, so put it behind ssh or a tunnel. ## Configuration `splinter` alone starts the chat: endpoint, model, plugins, theme and session directory come from `~/.splinter/splinter.conf` (or `$SPLINTER_CONFIG`), written in blocks: `core { }`, `provider NAME { }`, `pool NAME { }`. Command line wins over the file, the file wins over the built-in default, and an unknown key is an error with the line you wrote. Providers (several accounts, usage limits per window, pools that balance or fail over) and agent profiles are in `docs/CONFIG.md`; `splinter --init-config` writes a commented starter. ## Streaming Answers arrive as they are produced, not as one block: the adapter reads SSE, appends text deltas to the transcript as they arrive and a tool call as its own line, and a reasoning model's own `reasoning_content` is shown dimmed, in sequence, instead of being hidden. In one-shot mode the text goes straight to stdout as it comes. A data object split across SSE events, a blank line between its lines and a truncated trailing fragment are all tolerated: the parser buffers until the object is complete and drops a fragment that never is, instead of failing a turn that already has its answer. `test_sse` feeds recorded lines: plain text, a tool call split across three chunks, two calls in one turn, a pretty-printed object across events, a truncated tail, and the keepalive lines that carry nothing. A request that fails before anything was streamed is tried again three times, five seconds apart; a broken connection, a missing status, a 5xx and a stream that carried no answer qualify, a 401 or 404 does not. After the first streamed chunk the retry stops, because printing the same answer twice is worse than reporting the provider's error. The wait is visible where the failure happened: a status row `retrying in 5 s: ...` joins the transcript below the call, so a pause does not look like a hang and nothing is printed into the input line. Ctrl-C during a wait ends it at once. A stream is never cut for being slow: a router may wait minutes for an upstream without sending anything but keepalive lines, and a byte-per-second guard cut exactly those with "Less than 1 bytes/sec". The overall HTTP timeout is the only limit. ## Colour, measured A CDE palette is eight mid-tones; painted literally, a role can sit a few percent away from the background, and nothing is readable. Two safeguards live in `theme.c`: text on a surface follows CDE's rule (black on light, white on dark), and a role that is too close to the background is pushed away from it until it is legible. The push keeps the hue, and each role gets a slightly different minimum, so even a monochrome palette yields distinguishable steps. The 256-colour path picks the nearest cube or grey-ramp entry instead of rounding channels down, which used to turn a dark orange into grey 240. `Xresources` themes follow the same rules with colour0..15. The other half was a real bug: `COLORS` was read before `start_color()`, so it was 0, the code took the eight-basic-colour path, and the whole palette collapsed to white on black. ## Screen encoding, measured The vendored NetBSD curses emits Latin-1 bytes for wide characters (`ü` becomes `0xFC`); ncurses passes UTF-8 through. So the UI transliterates for display (`gruen`), while the conversation and the session log keep the exact UTF-8. That is a defect in the ported library, recorded here instead of being papered over with a claim that it works. ## What you see, and what is on disk The chat draws a transcript: `[time] `, `[time] ~ denkt:` for the model's reasoning, `[time] >> Run du -sh ../xsrc` for a tool call, `[time] | output` for what the tool returned, `[time] ` for the answer. A turn that calls tools therefore reads in order: reasoning, text before the call, the call, the output, text after it. A call is one row and it says what happened in the words a person would use: the tool as a capitalized verb, then its one interesting argument - the command of a `run`, the path of a `read`, the pattern of a `search`. No JSON, no `command:` in front of the value, and no second copy of the arguments in the prompt: the model's encoding is not the reader's business. Call rows are painted in the accent colour, their output dim underneath, so a run of shell calls is a list of calls and not a grey column of the same word. The same records go to `/logs//session.log`, in the order they happened: the user's words, the model's answer, its reasoning, every call with its arguments, every observation, failures and token counts. `wire.jsonl` next to it keeps the request bodies and replies, raw. The log is the complete record - the screen keeps sixteen rows and 4 KiB of a long observation, whichever comes first, and says how many lines are left out, so an `ls -la` or a 300 KB JSON dump does not bury the conversation; the log has all of it. ## Input history Up and Down walk through what was typed before, like a shell. The list is kept in `/history`, so the next session starts with it. ## Steering while a turn runs The turn runs on its own thread, so the keyboard stays live. Every tool call is one row in the transcript, in the words of the call itself - `>> Run echo a` - because "it did something" is not information. The reasoning is inserted before those rows: it came first, and the log should read in the order things happened. While it runs, the input line is only `steer> ` and what is typed, and the status line above it carries the elapsed seconds as its first meter: the call belongs in the transcript, and in the prompt it was a second copy that pushed the steer hint off the right edge. Nothing else is written into the input line or the status bar; an error is a transcript row below the row that caused it, and a backend request that failed before any answer is retried (the status row says so). A steer is picked up at the next step boundary; in a single-step turn it becomes the next message instead of being dropped. Curses is only ever touched by the UI thread. A name is not text: `SP_STREAM_TOOL` carries the name of a call that has begun, and the answer text is built from `SP_STREAM_TEXT` alone. The stream used to be classified by looking for `tool_calls` in the raw line, which broke as soon as the provider sent `"content":null` beside the call - the name landed in the answer and two `read` calls were printed as ` readread`. The kind now comes from the parser (`sp_sse_kind`). ## Compaction `focus` keeps a short recap of the session's goal in front of the model every seven turns — one inserted system message, never twice in a turn, nothing until a goal is set. `/goal ` sets the goal and starts that recap turn; the model's answer is remembered and injected later. The goal is stored in the session's `.meta`, so a resumed session finds it; `/continue` starts the next turn from it. `/goal` alone shows it. There is no separate `/recap`: recapping is what a goal does. Both work in the TUI and with `-p`. ## Languages UI strings live in `share/locale/.msg`, plain `key = text` files read at startup — no gettext, no `.mo`, nothing to build. The language comes from `locale` in the config, else `SPLINTER_LOCALE`, `LC_ALL`, `LC_MESSAGES`, `LANG`. A missing translation falls back to English; a key that exists nowhere is shown as itself, so nothing is silently empty. `test_i18n` fails if `de.msg` misses a key that `en.msg` has. Ships with `en` and `de`. Plugins translate their own strings with `sp_t()`. ## Hosts: one fleet A delegate may name a host. The whole invocation then goes through ssh, so claude, opencode or another splinter run where the model or the network is: provider remote { about = "on a remote host" tags = [remote] host = build.example.org endpoint = http://10.0.0.2:8080/v1 model = ... } delegate and delegate_parallel both honour it, and the report names the host like any other model. The remote needs splinter at the same path and its own keys - nothing crosses the jump except the task. Proven: a delegate with host=build.example.org ran on the remote host and answered from a provider reachable only over the wireguard link. A failing delegate can be run without a model, which is how the child's own error text and exit status are inspected: ./splinter --delegate claude0 -p "sage nur: beta" The observation carries the delegate line, the child's exit status and the task or job state; no model turn, no transport. ## A fleet in one directory `src/swarm.c` is the local variant. The first splinter started in a directory binds `.splinter-swarm.sock` and becomes the master; later ones join as slaves. `/swarm ` sends a line to the least busy peer, `/swarm ` picks one, `/swarm ls` lists them, and a routed command runs there. It is IPC between processes that share a working directory — not A2A, and not a network protocol. ## First run: the interview splinter --interview No questionnaire: the model talks to you. Its system prompt says to get to know you - what you work on, the tools you reach for, how you want to be spoken to, what you never want - one question at a time, and to end with a compact summary followed by the single line `INTERVIEW_COMPLETE`. That summary is written to `~/.splinter/USER.txt` (0600) and put into the system prompt of every later session, so the harness starts out knowing who it is working with. The marker itself never reaches the file or the transcript. The interview needs a provider like any chat; Telegram has the same `/interview`, with the conversation in the chat. An installation from before `USER.txt` still has `~/.splinter/profile/.md`; it is read as the fallback until the first new interview. Starting the chat without either prints a hint, once. ## Piped input cat /etc/passwd | splinter "explain the file" Anything on standard input becomes context, framed and labelled with its size: [stdin: 12 bytes] ... [/stdin] The question and the bytes are kept apart, so the model knows which is which. A binary input is reported as binary instead of being sprayed into the request, the size is capped at 192 KiB (with `[truncated]`), and `--no-stdin` ignores the pipe entirely. With no prompt at all, the input becomes the prompt. ## Gateway mode `--daemon` turns splinter into a Telegram bot: long-poll `getUpdates`, one turn per message, reply. No curses, no terminal. ~/.splinter/telegram.token the token, mode 0600 (or SPLINTER_TELEGRAM_TOKEN) telegram_allow = 8300935 who is answered, comma separated; nobody by default The token is read from a file or the environment and never from an argument, and the message loop keeps no state on disk beyond the session: a restart re-delivers the last update, which costs one duplicated answer and never a lost message. Signature handling is the session's business, not the gateway's. A bot cannot start a conversation - the user has to write first, otherwise the API answers `chat not found`. That is Telegram, not the harness. The bot registers the commands that actually exist with `setMyCommands`: `/start`, `/help`, `/interview`, `/new`, `/model`, `/connect`, every command a loaded plugin registers (`/goal`, `/quota`, ...) and every program in `~/.splinter/commands/` whose name is a valid Telegram command (lower-case, digits, underscore, at most 32). `/start` and `/help` answer with the short text plus that live list. An approval arrives as a message with **Yes/No buttons**; the callback answers the button, removes the buttons and writes the ack file. The text form `ok ` / `no ` still works. The model's markdown is rendered as Telegram HTML: bold, italic, strike, inline code, fenced blocks, links (also ``) and quotes become tags, everything else is escaped. An image is sent as a photo with the alt text as caption: `![alt](https://…)` is fetched by Telegram, `![alt](/path/to.png)` (or `file:///…`) is uploaded from this machine. A local file that is not an image goes out as a document (`sendDocument`, at most 50 MiB). The photo guard still checks the bytes — PNG/JPEG/GIF/WebP up to 10 MiB — so a text file cannot ride in as a photo; a missing or unreadable file stays a reference in the chat. Images inside code or a table stay text. Tables are laid out as columns inside a `
` block. A long answer
is split at tag boundaries, with the open tags closed and reopened per
message, and a piece Telegram refuses to parse is sent as plain text instead.
`SPLINTER_TG_MARKDOWN=0` turns the rendering off.

`/compact [tokens]` runs the compactors now (default target: `compact_target`,
else 8000 tokens) and reports messages/bytes before and after. The `lcm`
widget in the sidebar keeps the running numbers (context, compactions,
messages cut, last cut in messages and bytes, trimmed tool outputs), and the
status line carries a `compact N` segment. With
`compact_threshold` set, the harness compacts automatically once the last
request was larger than that: the conversation is cut to `compact_target`
before the next turn, so the context never grows without bound. Compaction
rewrites the prompt prefix, which invalidates the provider's prompt cache - the
threshold is the knob that trades cache hits for a smaller context. What was
dropped stays in the session log, and the `recall` tool searches it: the model
can look an earlier turn up instead of guessing.

`/cost` reports what the session has cost: provider-reported dollars (if the
provider puts `cost` in its usage object), tokens, and the cache share of the
last request. It splits turns into `judged` and `plain`, because a judged model
is an upstream alias that runs a judge first: the provider's usage object
carries only the final answer, so the judge's own tokens and dollars are not in
these numbers. What is measurable is the difference in latency and reported
tokens per turn. The sidebar's cost segment prefers the reported dollars over
list-price arithmetic.

`/new` (or `/reset`) starts a fresh conversation and a fresh session file; the
old one stays on disk, and the system prompt is put back.

`/model` lists the models the config names (the main endpoint, every delegate
with a model, every exit) as buttons and points the running transport at the
one you press. The choice is written to the session's sidecar
(`.model`) and comes back when that session is opened again, so one
conversation can sit on a different model without changing what a new one
starts on. `/model ` keeps the endpoint and takes another model from it.
`/model probe` asks the configured endpoints `/v1/models` and lists what they
really serve.

In the curses chat, `/model` alone opens a picker: Up/Down move, typing filters
by provider or model, Enter takes the highlighted selector, Esc cancels. After
the configured list appears, the picker asks the endpoint this session is on
what it serves and adds those models, so a router's whole menu is selectable
and not only the one alias in the config. It is the same list the clients get
from the `models` protocol command (with `probe`), so `--attach`
has it too, and the actual switch is still the ordinary `/model `
command.

`/connect` works the same in the TUI, one answer per line. It adds a provider
in four answers — name, endpoint, model, key
variable (or `-` for none); `ollama` and `opencode` stand for their usual
endpoint. It writes the line to `.d/20-connect.conf`, so the next start
has the provider too, runs one tiny turn against it to prove endpoint, model
and key work, and offers to use it right away.

`/interview` starts the same model-driven interview as `splinter --interview`
in the chat; `/new` leaves it. A program in
`commands/` answers in the chat: its output is the reply. In the
TUI the same program's output becomes context for the model instead. A typo
such as `/nosuch` is answered with the command list, not sent to the model.

`docs/splinter-gateway.service` is a systemd user unit if it should survive a
logout.

## The exit ring

`plugins/ring/ring.so` holds several ways to reach a model and walks them in
order when one is rate limited:

    exit = go    | OpenCode Go    | endpoint=... | model=...
    exit = groq  | Groq free tier | endpoint=... | model=... | key_env=GROQ_KEY
    exit = local | local | endpoint=... | model=...

Run it with `--transport ring`. Only pressure moves the ring: 429, 5xx, "rate
limit", "quota". A dead host or a bad key stops the turn where it is - a ring
that treats every failure as "try the next" hides real breakage behind a random
provider. Proven against two fake providers: the first answered 429, the ring
moved on and the second answered; a dead port did not move it.

## Providers from the environment

Nothing to configure if the keys are already there:

    OLLAMA_KEY            OLLAMA_KEY_0 .. OLLAMA_KEY_N
    CLAUDE_CODE_OAUTH_TOKEN        CLAUDE_CODE_OAUTH_TOKEN_0 .. _N

Each Ollama key becomes a delegate *and* an exit in the ring, with the endpoint
from `OLLAMA_ENDPOINT` (default `https://ollama.com/v1`) and the
model from `OLLAMA_MODEL`. Each Claude token becomes a `cli` delegate that runs
`claude -p`. Several keys mean several accounts, and the ring uses them in order.

The keys are copied into memory and passed to children through the environment -
never on a command line, never into a log.

    $ OLLAMA_KEY=... CLAUDE_CODE_OAUTH_TOKEN=... splinter --choose "plane die arbeit"
    claude-3   score=4   prio=10   task mentions 'plan'
    $ OLLAMA_KEY=... splinter --choose "implementier das"
    ollama-2   score=3   prio=0    task mentions 'implement'

Parallel handover uses `delegate_parallel` with a list of tasks - each picks its
own model, up to eight run at once, and the answers come back labelled:

    [parallel: 2 task(s), 12018 ms wall]

    ## task 1 | model slow | score 5 | 12018 ms | exit 0 | 75 B | requested tag 'slow'
    > sag A
    ...

    ## task 2 | model fast | score 5 | 16 ms | exit 0 | 74 B | requested tag 'fast'
    ...

    ## summary
    - slow: 1 task(s), 12018 ms total
    - fast: 1 task(s), 16 ms total

The summary gets who did what, how long it took and whether it worked - not a wall
of answers. A delegate that is slow or failing is visible in the header before
anybody reads its prose.

`max_parallel` still applies: a delegate that is full skips the task with a note
instead of queueing it.

That is the workflow the tool is built for: a strong model plans and defines the
work, the local models implement it, and `delegate` is the handover.

## Delegation

Work can be handed to another model. A delegate is a `provider` block in the
config - no profiles, no directories, nothing to keep in sync:

    provider coder {
        about = "C99, POSIX, knows the source tree"
        tags = [code, c99, review]
        prio = 5
        max_parallel = 2
        endpoint = http://127.0.0.1:8080/v1
        model = Qwen3.6-35B
    }
    provider quick { about = "short answers" tags = [chat, cheap] endpoint = ... model = ... }

Which provider takes a task is decided by words, with synonyms (docs/CONFIG.md,
"How a task finds its provider"); a private task only goes to a provider tagged
`private`.

`prio` breaks ties (higher wins), `max_parallel` caps how many calls may run on
one delegate at once - a busy delegate answers "busy", it does not queue
silently. `kind=cli` and `cmd=claude -p` turn a delegate into a program instead
of an endpoint.

The `delegate` tool takes a task and, optionally, tags. splinter picks the model
itself: a requested tag counts 5, a tag found in the task 3, a word of the
description 1. The observation starts with the choice and the reason, so a wrong
pick is visible instead of mysterious:

    [delegate coder, score 7: task mentions 'code']

`--choose "text"` prints that decision without running anything:
`coder  7  task mentions 'code'`. The child is splinter in one-shot mode with its
own context; the tool is classed destructive, so the operator approves the
delegation once.

## Resuming

`--resume` loads the newest session in the session directory back into the
conversation and puts it on screen. It continues that session id rather than
opening a fresh one beside it - the first version did the latter, which looked
like a resume and was none. The agent profile comes back too: the engine keeps
the session's profile in `.agent`, so a session left in plan resumes
in plan; the model it was left on is in `.model` and comes back too.

## MCP

`plugins/mcp/mcp.so` speaks MCP to a server and registers its tools. The config
names the servers; two transports, one block each:

    mcp junction {
        url    = http://172.25.206.16:8090/mcp
        header = "Authorization: Bearer ${JUNCTION_TOKEN}"
    }
    mcp files {
        cmd = "npx -y @modelcontextprotocol/server-filesystem /home"
    }

`url` is the streamable-HTTP transport: one POST per JSON-RPC message, answered
with one JSON object or with an SSE stream of `data:` lines - both are read, and
the `Mcp-Session-Id` a server hands out is echoed back. `cmd` starts a program
whose stdin/stdout carry the same messages. A header travels to curl through its
stdin config, so the token is never in `ps`.

Each tool keeps the schema the server published, so the model sees its
parameters; the class is `mutate`, because a server can do anything and the
harness does not pretend to know better. With one server the tools are
`mcp_`; with several, `mcp__`. Proven against both: a stdio
test server (the model called `mcp_add(17, 25)` and answered 42) and a socket
server that speaks HTTP and SSE.

The one-server form from before still works:

    SPLINTER_MCP_CMD="npx -y @modelcontextprotocol/server-filesystem /home" \
      splinter --plugin plugins/mcp/mcp.so

The other direction, splinter as the server, is `--mcp-server-listen IP`:
newline-delimited JSON-RPC over TCP, read tools only unless `--autonomous`.
On 127.x it needs nothing; on any other address it refuses to start without
`SPLINTER_MCP_TOKEN`, and every connection must begin with the line
`AUTH `. There is no TLS: across a network you do not own, tunnel it.

    SPLINTER_MCP_TOKEN=$(cat ~/.splinter/mcp.token) \
      splinter --mcp-server-listen 0.0.0.0
    (echo "AUTH $(cat ~/.splinter/mcp.token)"; cat requests.jsonl) | nc host 8098

Beside the file tools the server offers the session tools, so another agent can
work with splinter itself:

    splinter_sessions  list the sessions (current marked)
    splinter_state     model, endpoint, profile, session, busy, tokens
    splinter_models    the selectors /model takes
    splinter_agents    the profiles
    splinter_history   the open session's user and assistant messages
    splinter_say       send a prompt, wait, return the answer
    splinter_open      switch to a session (id, new, last)
    splinter_model     switch the model (any /model selector)
    splinter_agent     switch the profile by name
    splinter_steer     type into the running turn
    splinter_cancel    cancel the running turn
    splinter_approve   answer a pending approval (allow true|false)

`say` starts a real turn, so the server needs a provider: give it `-m` (or run
`--daemon --mcp-server-listen`, where the Telegram daemon and the MCP server
share one engine). A turn that parks on an approval is returned as the
question, not as a failure; `splinter_approve` answers it. The first line of
`splinter_say` is the answer, then the step and tool-call counts.

## Tools

Every tool declares its class, and the loop enforces it - never the model, never
the prompt.

- `read` (read): numbered lines, offset and limit, refuses binary files, says
  where it stopped.
- `search` (read): literal string over a directory tree, capped at 100 hits.
- `list` (read): a directory.
- `write` (mutate): writes a file, up to 4 MiB.
- `edit` (mutate): replaces exactly one occurrence; a non-unique `old` is an
  error, because an ambiguous edit is a wrong edit waiting to happen.
- `run` (destructive): a shell command; the exit status is an observation.
  Its own process group, stdin `/dev/null`, an environment without splinter's
  API keys and tokens, so `run env` cannot hand them to the model. It is killed
  after `SPLINTER_RUN_TIMEOUT` seconds (default 600, or `run_timeout` in the
  config) **without output**: every line on stdout or stderr resets the window,
  and the process itself is checked before it is extended, so a long build that
  reports progress is not killed for being long.
- `webfetch` (mutate): http(s) only, curl started without a shell. Not read:
  a URL the model picks is a message out of the machine.
- `echo` (read), `clock` (read).

Mutate and destructive tools ask first, unless `--autonomous` is set. In the
chat the question sits where the prompt is, worded like the transcript row -
`Run  touch x (destructive)?  y/N` - and the turn waits on it; `n` or Esc
denies, and the model is told
`error: denied by operator`. This used to be dead code in the TUI: the prompt
read stdin behind curses' back, so with `--autonomous` off every such tool was
silently denied.

## Shell escape

`!command` runs it here and puts the output into the conversation, so the model
sees what the operator saw. Capped at 4 KiB: a runaway command must not eat the
budget in one keystroke.

## Slash commands

A leading `/` never reaches the model: the UI asks the host, the host asks the
plugins. A plugin registers what it handles (`/goal` today); an
unknown command lists what exists instead of being sent as a prompt.

Compaction is a plugin, not a switch in the loop. Two ship here: `lcm`
(deterministic front-trim with an in-band system message saying what went) and
`cps` (continuous parallel compression: plans are prepared on a worker thread
from an index of the conversation, then spliced in instantly). Details and the
ABI in `docs/PLUGINS.md`.

## Limits, stated

- Tool arguments reach the tool as one string; each tool validates its own.
- MCP tools are all `mutate`, so they ask before they run.
- The ring only retries on rate limits; a 500 from a broken endpoint also counts
  as pressure, so a provider that fails hard gets skipped rather than fixed.
- No retrieval tiers over old sessions. Compaction is a plugin (lcm); it cuts the
  conversation, it does not remember what it cut.
- A `tick()` that never returns hangs the exit: the host can stop a thread only
  between ticks, not inside one.
- Plugins are not sandboxed. They run in the process with full rights; the
  authorization classes protect the harness from the *model*, not from code you
  chose to load.

## License

BSD-3-Clause.