Files
splinter/plugins/cli/cli.c
T
lotherkandClaude Opus 5.5 05c8d936e7 anthropic transport, provider usage APIs, endpoints as /v1 base
- kind = anthropic: the Messages API over curl, OAuth tokens (sk-ant-oat)
  as Bearer with the oauth beta, tool_use/tool_result blocks.
- --doctor spends no tokens: it asks /models and the provider's own usage
  route (ollama /api/balance, opencode go /v1/usage) instead of a tiny turn;
  cli providers are only checked for the program. /usage shows the same
  provider figures, cached for a minute.
- endpoint names the API base (https://host/v1); sp_endpoint_url() builds
  chat/completions (default), messages, models and usage from it. A full
  route is still accepted and cut back to the base.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 19:35:41 +00:00

724 lines
20 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_ID the name this command is benched under at its
* limit; "cli" for the main one, the delegate's id
* in a delegate's child
* 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 <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <time.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"
#include "config.h"
#define OUT_CAP (64u << 20)
struct cli_cfg {
char cmd[512];
char timeout[16];
int full;
struct sp_host *host;
/* for a fallback: the delegate's env=, sourced from a 0600 file */
const char (*env)[SP_CONFIG_ENV_LEN];
size_t nenv;
};
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,
const char *envfile, 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 (envfile != NULL && envfile[0] != '\0' &&
(sp_buf_puts(cmd, ". ") != 0 || sh_word(cmd, envfile) != 0 ||
sp_buf_puts(cmd, " && ") != 0))
return -1;
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.
*
* Not popen(): popen hands back a stream, not a process id, so a cancelled
* turn could only end when the program decided to. `claude -p` under its
* 30-minute timeout therefore held Ctrl-C hostage: the UI set the flag, joined
* the worker, and the worker was still blocked reading a pipe. The child gets
* its own process group (the shell, `timeout`, and the program under it), and
* the read loop polls it, so a cancellation kills the whole tree.
*/
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)
{
const volatile int *cancel = sp_cancel_flag();
char chunk[4096];
FILE *ef;
int fds[2], st = 0, rc = 0;
pid_t child;
size_t en = 0;
sp_buf_clear(raw);
*status = 0;
if (pipe(fds) != 0) {
sp_buf_printf(err, "cli: pipe: %s", strerror(errno));
return -1;
}
child = fork();
if (child < 0) {
sp_buf_printf(err, "cli: fork: %s", strerror(errno));
close(fds[0]);
close(fds[1]);
return -1;
}
if (child == 0) {
/*
* Both sides call setpgid: whoever runs first wins the race, and the
* kill below always reaches the whole tree.
*/
(void)setpgid(0, 0);
close(fds[0]);
if (dup2(fds[1], STDOUT_FILENO) < 0)
_exit(127);
close(fds[1]);
execl("/bin/sh", "sh", "-c", line, (char *)NULL);
_exit(127);
}
(void)setpgid(child, child);
close(fds[1]);
for (;;) {
struct pollfd pfd;
ssize_t got;
int pr;
if (cancel != NULL && *cancel) {
(void)kill(-child, SIGKILL);
sp_buf_puts(err, "cancelled");
rc = -1;
break;
}
pfd.fd = fds[0];
pfd.events = POLLIN;
pfd.revents = 0;
pr = poll(&pfd, 1, 200);
if (pr < 0) {
if (errno == EINTR)
continue;
sp_buf_printf(err, "cli: poll: %s", strerror(errno));
rc = -1;
break;
}
if (pr == 0)
continue;
got = read(fds[0], chunk, sizeof(chunk));
if (got < 0) {
if (errno == EINTR)
continue;
sp_buf_printf(err, "cli: read: %s", strerror(errno));
rc = -1;
break;
}
if (got == 0)
break;
if (raw->len + (size_t)got > OUT_CAP) {
/* over the cap: stop the program instead of holding it */
(void)kill(-child, SIGKILL);
break;
}
if (sp_buf_add(raw, chunk, (size_t)got) != 0) {
(void)kill(-child, SIGKILL);
sp_buf_puts(err, "cli: out of memory");
rc = -1;
break;
}
}
close(fds[0]);
(void)waitpid(child, &st, 0);
*status = st;
ef = fopen(errpath, "r");
if (ef != NULL) {
en = fread(errtext, 1, errcap - 1, ef);
fclose(ef);
}
errtext[en] = '\0';
(void)unlink(errpath);
return rc;
}
static int
ok_status(int status)
{
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
}
/*
* The delegate's env= for a fallback, as `export NAME='value'` lines in a file
* only this user can read, sourced by the shell. Not `env NAME=value cmd`: a
* command line is visible to every user on the machine through ps.
*/
static int
write_envfile(const struct cli_cfg *c, const char *path)
{
struct sp_buf b;
size_t i;
int fd, rc = -1;
if (sp_buf_init(&b) != 0)
return -1;
for (i = 0; i < c->nenv; i++) {
const char *eq = strchr(c->env[i], '=');
if (eq == NULL)
continue;
if (sp_buf_puts(&b, "export ") != 0 ||
sp_buf_add(&b, c->env[i], (size_t)(eq - c->env[i]) + 1) != 0 ||
sh_word(&b, eq + 1) != 0 || sp_buf_puts(&b, "\n") != 0)
goto out;
}
fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0)
goto out;
if (b.len == 0 || write(fd, b.p, b.len) == (ssize_t)b.len)
rc = 0;
close(fd);
out:
sp_buf_free(&b);
return rc;
}
static int
cli_send_one(struct cli_cfg *c, const struct sp_conv *conv,
struct sp_reply *out, struct sp_buf *err)
{
struct sp_buf body, cmd, raw;
char path[512], errpath[540] = "", errtext[512];
char envfile[540] = "";
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 (c->nenv > 0) {
snprintf(envfile, sizeof(envfile), "%s.env", path);
if (write_envfile(c, envfile) != 0) {
sp_buf_printf(err, "cli: env file: %s", strerror(errno));
envfile[0] = '\0';
unlink(path);
goto fail;
}
}
if (build_cmd(c, path, body.p != NULL ? body.p : "", key, uuid, extra,
errpath, envfile, &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, envfile, &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;
}
if (envfile[0] != '\0') {
(void)unlink(envfile);
envfile[0] = '\0';
}
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);
if (envfile[0] != '\0')
(void)unlink(envfile);
sp_buf_free(&body);
sp_buf_free(&cmd);
sp_buf_free(&raw);
return -1;
}
/*
* The main cli at its limit. cli_cmd is tried first, benched as "cli"; then
* the cli delegates named in cli_fallback, in order, each with its own cmd and
* env=, benched under its own id - the same bench the delegation uses, so an
* account at its limit is skipped everywhere. The session key stays the same,
* so claude resumes the same conversation under the next account.
*/
static int
cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
struct sp_buf *err)
{
struct cli_cfg *c = ctx;
const struct sp_config *cfg;
char list[300], *id, *save = NULL;
long until, soonest = 0;
int first = 1, tried = 0, rc = -1;
if (c == NULL)
return -1;
cfg = c->host != NULL ? sp_host_config(c->host) : NULL;
/*
* In a delegate's child the command is that delegate's, and so is the
* bench: SPLINTER_CLI_ID names it. Benching "cli" from there would bench
* the main program for an account it may not even use.
*/
{
const char *self = getenv("SPLINTER_CLI_ID");
snprintf(list, sizeof(list), "%s,%s",
self != NULL && *self != '\0' ? self : "cli",
cfg != NULL ? cfg->cli_fallback : "");
}
for (id = strtok_r(list, ", ", &save); id != NULL;
id = strtok_r(NULL, ", ", &save), first = 0) {
struct cli_cfg alt = *c;
const struct sp_delegate *d = NULL;
size_t k;
if (!first) {
for (k = 0; cfg != NULL && k < cfg->ndelegates; k++)
if (strcmp(cfg->delegate[k].id, id) == 0)
d = &cfg->delegate[k];
if (d == NULL || strcmp(d->kind, "cli") != 0) {
if (c->host != NULL)
(void)sp_host_note(c->host, "cli: "
"cli_fallback names no cli delegate");
continue;
}
snprintf(alt.cmd, sizeof(alt.cmd), "%s",
d->cmd[0] != '\0' ? d->cmd : "claude -p");
alt.env = (const char (*)[SP_CONFIG_ENV_LEN])d->env;
alt.nenv = d->nenv;
}
if ((until = sp_cooldown_until(id)) != 0) {
if (soonest == 0 || until < soonest)
soonest = until;
continue;
}
if (tried > 0 && c->host != NULL) {
char note[96];
snprintf(note, sizeof(note), "cli: falling back to %s",
id);
(void)sp_host_note(c->host, note);
}
tried++;
sp_buf_clear(err);
rc = cli_send_one(&alt, conv, out, err);
if (rc == 0 || !sp_limit_parse(err->p, &until))
return rc;
sp_cooldown_set(id, until, err->p);
if (soonest == 0 || until < soonest)
soonest = until;
}
if (tried == 0 || rc != 0) {
char when[32] = "?";
time_t tt = (time_t)soonest;
struct tm tm;
if (soonest > 0)
strftime(when, sizeof(when), "%Y-%m-%d %H:%M",
localtime_r(&tt, &tm));
if (tried == 0)
sp_buf_clear(err);
sp_buf_printf(err, "%scli: every account at its usage limit, "
"first back %s (WAIT_QUOTA ready_at=%ld)",
err->len > 0 ? " -- " : "", when, soonest);
}
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;
cfg.host = h;
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;
}