Files
splinter/plugins/cli/cli.c
T
lotherkandClaude Opus 5.5 60475016ae cli: one session per splinter session; delegates: bench at the limit, fall back
The cli transport keys the program's own session on SPLINTER_CLI_SESSION
(the splinter session id, plus ':<delegate>' for a delegate child):
claude gets a derived UUID, --session-id first and --resume after, with
one retry when claude disagrees; opencode gets --session ses_<derived>;
other programs can use {session} and {uuid}. Consecutive calls continue
one conversation and hit the provider cache (measured: 17.6k read, 80
written on the second call).

A delegate whose answer is a limit (429, rate/usage/weekly limit, quota)
is benched until the reset it names - claude's "resets 3am
(Europe/Lisbon)" is read through date(1) - in ~/.splinter/cooldown/<id>,
and the task goes to the next delegate that fits. choose() skips benched
delegates, also when one is asked for by name.

run_child now carries the tail of the child's output in its error and
treats a signal as failure; "exited 1" alone hid every limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:33:17 +00:00

497 lines
14 KiB
C

/*
* splinter -- cli: any command-line agent as the model.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Splinter does not need an HTTP endpoint. It needs something that answers.
* This transport runs a program and takes its stdout as the answer, so
* `claude -p`, `opencode run`, `ollama run`, `llm` or a shell script can all be
* the brains -- and each of them brings its own keys, its own quota, its own
* free tier.
*
* Configuration is by environment, deliberately: no config file to drift.
*
* SPLINTER_CLI_CMD the program, default "claude -p". If it contains
* {file}, the prompt file path is substituted there;
* {prompt} substitutes a shell-quoted prompt. Without
* a placeholder the prompt is fed on stdin.
* SPLINTER_CLI_FULL=1 send the whole transcript instead of the last user
* message (the program keeps no history of its own)
* SPLINTER_CLI_TIMEOUT seconds, default 1800
* SPLINTER_CLI_SESSION the session key (set by splinter); empty: no sessions
* SPLINTER_CLI_STATE where the claude resume markers live,
* default ~/.splinter/cli
*
* Trust note, because it matters: the command runs through /bin/sh -c, so the
* string comes from the operator's environment, never from the model. Output
* grows dynamically (capped at 64 MiB) and a non-zero exit is an error with the
* program's own stderr attached -- a silent empty answer is the one thing this
* must not do.
*/
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_plugin.h"
#include "i18n.h"
#define OUT_CAP (64u << 20)
struct cli_cfg {
char cmd[512];
char timeout[16];
int full;
};
static void
render(const struct sp_conv *conv, int full, struct sp_buf *out)
{
size_t i, from = 0;
sp_buf_clear(out);
if (!full) {
for (i = conv->n; i > 0; i--) {
if (conv->v[i - 1].role != NULL &&
strcmp(conv->v[i - 1].role, "user") == 0) {
from = i - 1;
break;
}
}
}
for (i = from; i < conv->n; i++) {
const struct sp_msg *m = &conv->v[i];
if (m->content == NULL || m->content[0] == '\0')
continue;
if (full)
sp_buf_printf(out, "%s: ", m->role != NULL ? m->role :
"?");
if (sp_buf_puts(out, m->content) != 0 ||
sp_buf_puts(out, "\n") != 0)
return;
}
}
/* 's' as one single-quoted shell word */
static int
sh_word(struct sp_buf *b, const char *s)
{
if (sp_buf_puts(b, "'") != 0)
return -1;
for (; *s != '\0'; s++)
if (*s == '\'' ? sp_buf_puts(b, "'\\''") != 0 :
sp_buf_add(b, s, 1) != 0)
return -1;
return sp_buf_puts(b, "'");
}
/*
* Sessions. Every call used to start the program cold: a fresh claude or
* opencode session per turn, no history over there, no warm cache. Now the
* caller's session key ($SPLINTER_CLI_SESSION: the splinter session id, and
* for a delegate that id plus ':' and the delegate's name) maps to one stable
* session id per program, so consecutive calls land in the same conversation.
*
* claude a UUID derived from the key: --session-id the first time,
* --resume after that. Which one is remembered in a marker file;
* if the program disagrees (moved directory, deleted session) the
* other one is tried once.
* opencode --session ses_<derived>, which opencode creates if missing.
* other {session} and {uuid} in the command expand to the key and the
* derived UUID, for programs splinter does not know.
*
* A command that already names a session (--session, --resume, --continue)
* is left alone. SPLINTER_CLI_SESSION set but empty turns all of this off.
*/
enum cli_prog { PROG_OTHER, PROG_CLAUDE, PROG_OPENCODE };
static enum cli_prog
prog_of(const char *cmd)
{
const char *p = cmd, *w, *e, *base;
size_t len;
for (;;) {
while (*p == ' ' || *p == '\t')
p++;
w = p;
while (*p != '\0' && *p != ' ' && *p != '\t')
p++;
e = p;
if (e == w)
return PROG_OTHER;
/* skip NAME=value words in front of the program */
if (memchr(w, '=', (size_t)(e - w)) == NULL)
break;
}
for (base = e; base > w && base[-1] != '/'; base--)
;
len = (size_t)(e - base);
if (len == 6 && strncmp(base, "claude", 6) == 0)
return PROG_CLAUDE;
if (len == 8 && strncmp(base, "opencode", 8) == 0)
return PROG_OPENCODE;
return PROG_OTHER;
}
static uint64_t
fnv64(const char *s, uint64_t h)
{
for (; *s != '\0'; s++) {
h ^= (unsigned char)*s;
h *= 0x100000001b3ULL;
}
return h;
}
/* the same key gives the same UUID, every time, on every machine */
static void
key_uuid(const char *key, char out[37])
{
unsigned char b[16];
uint64_t h1 = fnv64(key, 0xcbf29ce484222325ULL);
uint64_t h2 = fnv64(key, h1 ^ 0x9e3779b97f4a7c15ULL);
int i;
for (i = 0; i < 8; i++) {
b[i] = (unsigned char)(h1 >> (8 * i));
b[8 + i] = (unsigned char)(h2 >> (8 * i));
}
b[6] = (unsigned char)((b[6] & 0x0f) | 0x40); /* version 4 */
b[8] = (unsigned char)((b[8] & 0x3f) | 0x80); /* RFC 4122 variant */
snprintf(out, 37, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
"%02x%02x%02x%02x%02x%02x", b[0], b[1], b[2], b[3], b[4], b[5],
b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]);
}
/* opencode's shape: ses_ and 26 letters and digits */
static void
key_ses(const char *key, char out[31])
{
static const char abc[] =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
uint64_t h = fnv64(key, 0xcbf29ce484222325ULL);
int i;
memcpy(out, "ses_", 4);
for (i = 0; i < 26; i++) {
if (i % 10 == 0)
h = fnv64(key, h + (uint64_t)i);
out[4 + i] = abc[h % 62];
h /= 62;
}
out[30] = '\0';
}
static void
marker_path(const char *uuid, char *buf, size_t len)
{
const char *st = getenv("SPLINTER_CLI_STATE");
const char *home = getenv("HOME");
if (st != NULL && *st != '\0')
snprintf(buf, len, "%s/%s", st, uuid);
else
snprintf(buf, len, "%s/.splinter/cli/%s",
home != NULL ? home : "/tmp", uuid);
}
static int
marker_exists(const char *uuid)
{
char path[600];
marker_path(uuid, path, sizeof(path));
return access(path, F_OK) == 0;
}
static void
marker_set(const char *uuid)
{
char path[600], *slash;
FILE *f;
marker_path(uuid, path, sizeof(path));
slash = strrchr(path, '/');
if (slash != NULL) {
*slash = '\0';
(void)mkdir(path, 0700);
*slash = '/';
}
f = fopen(path, "w");
if (f != NULL)
fclose(f);
}
static int
ci_contains(const char *hay, const char *needle)
{
size_t n = strlen(needle);
for (; *hay != '\0'; hay++)
if (strncasecmp(hay, needle, n) == 0)
return 1;
return 0;
}
/*
* Build the shell line: timeout, the command with placeholders expanded, the
* session arguments, stdin and stderr redirection.
*/
static int
build_cmd(const struct cli_cfg *c, const char *path, const char *prompt,
const char *key, const char *uuid, const char *extra, const char *errpath,
struct sp_buf *cmd)
{
int placeholder;
const char *p = c->cmd;
sp_buf_clear(cmd);
placeholder = strstr(c->cmd, "{file}") != NULL ||
strstr(c->cmd, "{prompt}") != NULL;
if (sp_buf_printf(cmd, "timeout %s ", c->timeout) != 0)
return -1;
while (*p != '\0') {
if (strncmp(p, "{file}", 6) == 0) {
if (sh_word(cmd, path) != 0)
return -1;
p += 6;
} else if (strncmp(p, "{prompt}", 8) == 0) {
if (sh_word(cmd, prompt) != 0)
return -1;
p += 8;
} else if (strncmp(p, "{session}", 9) == 0) {
if (sh_word(cmd, key) != 0)
return -1;
p += 9;
} else if (strncmp(p, "{uuid}", 6) == 0) {
if (sh_word(cmd, uuid) != 0)
return -1;
p += 6;
} else if (sp_buf_add(cmd, p, 1) != 0) {
return -1;
} else
p++;
}
if (extra != NULL && extra[0] != '\0' &&
(sp_buf_puts(cmd, " ") != 0 || sp_buf_puts(cmd, extra) != 0))
return -1;
if (!placeholder &&
(sp_buf_puts(cmd, " < ") != 0 || sh_word(cmd, path) != 0))
return -1;
if (sp_buf_puts(cmd, " 2> ") != 0 || sh_word(cmd, errpath) != 0)
return -1;
return 0;
}
/* run one shell line; stdout into raw, stderr text into errtext */
static int
run_cmd(const char *line, const char *errpath, struct sp_buf *raw,
char *errtext, size_t errcap, int *status, struct sp_buf *err)
{
FILE *p, *ef;
char chunk[4096];
size_t got, en = 0;
sp_buf_clear(raw);
p = popen(line, "r");
if (p == NULL) {
sp_buf_printf(err, "cli: popen: %s", strerror(errno));
return -1;
}
while ((got = fread(chunk, 1, sizeof(chunk), p)) > 0) {
if (raw->len + got > OUT_CAP)
break;
if (sp_buf_add(raw, chunk, got) != 0) {
pclose(p);
sp_buf_puts(err, "cli: out of memory");
return -1;
}
}
*status = pclose(p);
ef = fopen(errpath, "r");
if (ef != NULL) {
en = fread(errtext, 1, errcap - 1, ef);
fclose(ef);
}
errtext[en] = '\0';
(void)unlink(errpath);
if (*status < 0) {
sp_buf_printf(err, "cli: %s", strerror(errno));
return -1;
}
return 0;
}
static int
ok_status(int status)
{
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
}
static int
cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
struct sp_buf *err)
{
struct cli_cfg *c = ctx;
struct sp_buf body, cmd, raw;
char path[512], errpath[540] = "", errtext[512];
char uuid[37] = "", ses[31] = "", extra[96] = "";
const char *tmpdir = getenv("TMPDIR");
const char *key = getenv("SPLINTER_CLI_SESSION");
enum cli_prog prog = prog_of(c != NULL ? c->cmd : "");
int fd, status = 0, resume = 0, sessions;
ssize_t w;
size_t n;
if (c == NULL)
return -1;
if (sp_buf_init(&body) != 0 || sp_buf_init(&cmd) != 0 ||
sp_buf_init(&raw) != 0) {
sp_buf_puts(err, "cli: out of memory");
return -1;
}
render(conv, c->full, &body);
sessions = key != NULL && *key != '\0' &&
strstr(c->cmd, "--session") == NULL &&
strstr(c->cmd, "--resume") == NULL &&
strstr(c->cmd, "--continue") == NULL;
if (key == NULL)
key = "";
key_uuid(key, uuid);
if (sessions && prog == PROG_CLAUDE) {
resume = marker_exists(uuid);
snprintf(extra, sizeof(extra), "%s %s",
resume ? "--resume" : "--session-id", uuid);
} else if (sessions && prog == PROG_OPENCODE) {
key_ses(key, ses);
snprintf(extra, sizeof(extra), "--session %s", ses);
}
if (tmpdir == NULL || *tmpdir == '\0')
tmpdir = "/var/tmp";
snprintf(path, sizeof(path), "%s/splinter-cli-XXXXXX", tmpdir);
fd = mkstemp(path);
if (fd < 0) {
sp_buf_printf(err, "cli: mkstemp: %s", strerror(errno));
goto fail;
}
n = body.len;
w = write(fd, body.p, n);
close(fd);
if (w < 0 || (size_t)w != n) {
sp_buf_printf(err, "cli: short write: %s", strerror(errno));
unlink(path);
goto fail;
}
/*
* The program reads the prompt on stdin unless the command names where it
* goes: {file} becomes the prompt file path, {prompt} becomes the prompt
* as a shell word. timeout guards a hang. stderr goes to a file next to
* the prompt so it never lands in the middle of a curses screen.
*/
snprintf(errpath, sizeof(errpath), "%s.err", path);
if (build_cmd(c, path, body.p != NULL ? body.p : "", key, uuid, extra,
errpath, &cmd) != 0 ||
run_cmd(cmd.p, errpath, &raw, errtext, sizeof(errtext), &status,
err) != 0) {
unlink(path);
goto fail;
}
/*
* claude refuses --session-id for a session it already has and --resume
* for one it cannot find (another directory, a deleted file). Either way
* the other form is right; try it once, it costs no model call.
*/
if (prog == PROG_CLAUDE && extra[0] != '\0' && !ok_status(status) &&
(ci_contains(errtext, "session") ||
ci_contains(errtext, "conversation"))) {
resume = !resume;
snprintf(extra, sizeof(extra), "%s %s",
resume ? "--resume" : "--session-id", uuid);
if (build_cmd(c, path, body.p != NULL ? body.p : "", key, uuid,
extra, errpath, &cmd) != 0 ||
run_cmd(cmd.p, errpath, &raw, errtext, sizeof(errtext),
&status, err) != 0) {
unlink(path);
goto fail;
}
}
unlink(path);
if (prog == PROG_CLAUDE && extra[0] != '\0' && ok_status(status))
marker_set(uuid);
if (WIFEXITED(status) && WEXITSTATUS(status) == 124) {
sp_buf_printf(err, sp_td("cli.timeout", "cli: '%s' timed out after %s s"), c->cmd,
c->timeout);
goto fail;
}
if (!ok_status(status)) {
sp_buf_printf(err, sp_td("cli.failed", "cli: '%s' failed (exit %d): %.400s"), c->cmd,
WIFEXITED(status) ? WEXITSTATUS(status) : -1,
errtext[0] != '\0' ? errtext : raw.p != NULL ? raw.p : "");
goto fail;
}
if (raw.len == 0) {
sp_buf_printf(err, sp_td("cli.no_output", "cli: '%s' produced no output"), c->cmd);
goto fail;
}
out->status = 200;
out->content = strdup(raw.p);
if (out->content == NULL)
goto fail;
sp_buf_free(&body);
sp_buf_free(&cmd);
sp_buf_free(&raw);
return 0;
fail:
if (errpath[0] != '\0')
(void)unlink(errpath);
sp_buf_free(&body);
sp_buf_free(&cmd);
sp_buf_free(&raw);
return -1;
}
static int
cli_init(struct sp_host *h)
{
static struct cli_cfg cfg;
static struct sp_transport tr;
const char *cmd = getenv("SPLINTER_CLI_CMD");
const char *to = getenv("SPLINTER_CLI_TIMEOUT");
const char *full = getenv("SPLINTER_CLI_FULL");
memset(&cfg, 0, sizeof(cfg));
snprintf(cfg.cmd, sizeof(cfg.cmd), "%s",
cmd != NULL && *cmd != '\0' ? cmd : "claude -p");
snprintf(cfg.timeout, sizeof(cfg.timeout), "%s",
to != NULL && *to != '\0' ? to : "1800");
cfg.full = full != NULL && strcmp(full, "0") != 0;
tr.send = cli_send;
tr.ctx = &cfg;
return sp_host_add_transport(h, "cli", tr);
}
static const struct sp_plugin cli_plugin = {
SP_PLUGIN_ABI, "cli", "1.0.0", cli_init, NULL, NULL
};
const struct sp_plugin *
sp_plugin_describe(void)
{
return &cli_plugin;
}