From 60475016ae1094a6714c4013565e4a32599aea48 Mon Sep 17 00:00:00 2001 From: lotherk Date: Mon, 9 Nov 2026 20:33:17 +0000 Subject: [PATCH] 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 ':' 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_; 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/, 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 --- TODO.md | 5 + docs/CONFIG.md | 32 ++++ plugins/cli/cli.c | 359 ++++++++++++++++++++++++++++++++++-------- src/delegate.c | 339 +++++++++++++++++++++++++++++++++++++-- src/main.c | 6 + tests/test_cli.c | 170 ++++++++++++++++++++ tests/test_delegate.c | 103 ++++++++++++ 7 files changed, 933 insertions(+), 81 deletions(-) diff --git a/TODO.md b/TODO.md index 906968a..7780512 100644 --- a/TODO.md +++ b/TODO.md @@ -43,6 +43,11 @@ Entscheidung, keine Diagnose. Naechster Schritt: Kind mit `SPLINTER_DUMP_REQUEST` und ungefiltertem stderr laufen lassen, Exit-Code der CLI von dem von splinter trennen. +Stand 2026-11-09: der Fehler traegt jetzt die letzten 400 Bytes der Ausgabe des +Kindes ("exited 1: ... You've hit your weekly limit"), vorher nur den Code. Ein +Limit benchet den Delegate, der naechste uebernimmt (`test_delegate`, echt +belegt mit claude0 -> claude1). + ## 4. Kids-Zustimmung ist gegen einen Stub geprueft, nicht gegen Telegram `sp_ack_*` (Datei-Mechanismus, 7 Checks in `tests/test_ack.c`), `tg-ask` (Versand, diff --git a/docs/CONFIG.md b/docs/CONFIG.md index b315883..a3d99ec 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -83,6 +83,17 @@ delegates can run the same CLI with two different accounts. With `host=` it is sent in front of the remote command as `env 'NAME=VALUE'`. A value cannot contain `|`. A literal token in the file is a secret in the file: `chmod 600`. +### Limits: bench and fall back + +A delegate whose answer says it is at its limit - a 429, "rate limit", "usage +limit", claude's "You've hit your weekly limit · resets 3am (Europe/Lisbon)" - +is benched until that reset, and the same task goes to the next delegate that +fits (the request's tags plus the benched one's). The bench is a file, +`~/.splinter/cooldown/` holding the epoch, so every splinter on the machine +skips it, even when it is asked for by name; delete the file to unbench early. +A reset that cannot be read benches for an hour. Only when nothing else fits +does the job wait (`waiting_quota`) for the reset. + ## Example: local model ``` @@ -110,6 +121,27 @@ theme = Delphinium program, e.g. `cli_env = CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-...`. It overwrites an exported variable of the same name. +### Sessions + +A cli program keeps its own conversation across calls. splinter exports its +session id as `SPLINTER_CLI_SESSION`; a cli delegate extends it with its name +(`sess-...:claude0`), so every delegate has its own conversation per splinter +session, and `claude0` and `claude1` never share one. From that key: + +- `claude`: a UUID derived from the key, `--session-id` on the first call, + `--resume` after that (remembered in `~/.splinter/cli/`, or + `$SPLINTER_CLI_STATE`). If claude disagrees - session moved or deleted - the + other form is tried once, which costs no model call. +- `opencode`: `--session ses_`, created by opencode if missing. +- anything else: `{session}` and `{uuid}` in the command expand to the key and + the UUID. + +Consecutive calls stay in one conversation, so the provider's prompt cache +covers the history: measured with claude, the second call read 17.6k tokens +from cache and wrote 80. A command that already says `--session`, `--resume` +or `--continue` is left alone; an exported empty `SPLINTER_CLI_SESSION` turns +sessions off. Only the newest user message is sent - the program has the rest. + `cli_cmd` may contain `{file}` (the prompt temp-file path) or `{prompt}` (a shell-quoted prompt). Without a placeholder the prompt is fed on stdin, which works for `claude -p`, `ollama run`, and similar tools. For CLIs that take the diff --git a/plugins/cli/cli.c b/plugins/cli/cli.c index 2781736..3d7e8d2 100644 --- a/plugins/cli/cli.c +++ b/plugins/cli/cli.c @@ -19,6 +19,9 @@ * 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 @@ -27,9 +30,12 @@ * must not do. */ #include +#include #include #include #include +#include +#include #include #include @@ -87,6 +93,250 @@ sh_word(struct sp_buf *b, const char *s) 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_, 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) @@ -94,11 +344,13 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, 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"); - int fd, status; + 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; - FILE *p; if (c == NULL) return -1; @@ -109,6 +361,22 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, } 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); @@ -133,81 +401,42 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, * the prompt so it never lands in the middle of a curses screen. */ snprintf(errpath, sizeof(errpath), "%s.err", path); - sp_buf_printf(&cmd, "timeout %s ", c->timeout); - if (strstr(c->cmd, "{file}") != NULL || strstr(c->cmd, "{prompt}") != NULL) { - const char *p = c->cmd; - - while (*p != '\0') { - if (strncmp(p, "{file}", 6) == 0) { - if (sh_word(&cmd, path) != 0) - goto fail_build; - p += 6; - } else if (strncmp(p, "{prompt}", 8) == 0) { - if (sh_word(&cmd, body.p != NULL ? body.p : "") != 0) - goto fail_build; - p += 8; - } else if (sp_buf_add(&cmd, p, 1) != 0) { - goto fail_build; - } else - p++; - } - if (sp_buf_puts(&cmd, " 2> ") != 0 || sh_word(&cmd, errpath) != 0) - goto fail_build; - } else { - sp_buf_printf(&cmd, "%s < ", c->cmd); - if (sh_word(&cmd, path) != 0 || sp_buf_puts(&cmd, " 2> ") != 0 || - sh_word(&cmd, errpath) != 0) { -fail_build: - unlink(path); - unlink(errpath); - goto fail; - } - } - p = popen(cmd.p, "r"); - if (p == NULL) { - sp_buf_printf(err, "cli: popen: %s", strerror(errno)); + 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; } - { - char chunk[4096]; - size_t got; - - 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); - 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; } } - status = pclose(p); unlink(path); - errtext[0] = '\0'; - { - FILE *ef = fopen(errpath, "r"); - size_t en = 0; + if (prog == PROG_CLAUDE && extra[0] != '\0' && ok_status(status)) + marker_set(uuid); - if (ef != NULL) { - en = fread(errtext, 1, sizeof(errtext) - 1, ef); - fclose(ef); - } - errtext[en] = '\0'; - (void)unlink(errpath); - } - - if (status < 0) { - sp_buf_printf(err, "cli: %s", strerror(errno)); - goto fail; - } 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 (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + 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 : ""); diff --git a/src/delegate.c b/src/delegate.c index 3c33b09..d67ec91 100644 --- a/src/delegate.c +++ b/src/delegate.c @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -207,6 +208,8 @@ lower(char *dst, size_t cap, const char *src) * the description. Ties go to the earlier entry: predictable beats clever when * someone is reading the log at night. */ +static long cooldown_until(const char *id); + static const struct sp_delegate * choose(const struct sp_config *cfg, const char *task, const char *wanted, int *score_out, char *why, size_t whylen) @@ -225,6 +228,9 @@ choose(const struct sp_config *cfg, const char *task, const char *wanted, int score = 0; char reason[192] = ""; + if (cooldown_until(d->id) != 0) + continue; /* benched: at its limit until the reset */ + snprintf(tags, sizeof(tags), "%s", d->tags); for (t = strtok_r(tags, ",", &save); t != NULL; t = strtok_r(NULL, ",", &save)) { @@ -314,7 +320,7 @@ exec_delegate(const struct del_ctx *c, const struct sp_delegate *d, int n = 0, i; int cli = strcmp(d->kind, "cli") == 0; int remote = d->host[0] != '\0'; - char envname[96], plug[600]; + char envname[96], plug[600], clisess[256] = ""; argv[n++] = (char *)c->self; argv[n++] = "--no-config"; @@ -379,6 +385,19 @@ exec_delegate(const struct del_ctx *c, const struct sp_delegate *d, if (!remote) sp_config_apply_env((const char (*)[SP_CONFIG_ENV_LEN])d->env, d->nenv); + /* + * One cli session per (splinter session, delegate): consecutive calls to + * claude0 continue claude0's conversation, claude1 keeps its own. + */ + { + const char *ps = getenv("SPLINTER_CLI_SESSION"); + + if (cli && ps != NULL && *ps != '\0') { + snprintf(clisess, sizeof(clisess), "%s:%s", ps, d->id); + if (!remote) + (void)setenv("SPLINTER_CLI_SESSION", clisess, 1); + } + } if (remote) { struct sp_buf line; @@ -387,8 +406,18 @@ exec_delegate(const struct del_ctx *c, const struct sp_delegate *d, if (sp_buf_init(&line) != 0) _exit(127); - if (d->nenv > 0 && sp_buf_puts(&line, "env ") != 0) + if ((d->nenv > 0 || clisess[0] != '\0') && + sp_buf_puts(&line, "env ") != 0) _exit(127); + if (clisess[0] != '\0') { + char kv[300]; + + snprintf(kv, sizeof(kv), "SPLINTER_CLI_SESSION=%s", + clisess); + if (shell_quote(&line, kv) != 0 || + sp_buf_puts(&line, " ") != 0) + _exit(127); + } for (e = 0; e < d->nenv; e++) if (shell_quote(&line, d->env[e]) != 0 || sp_buf_puts(&line, " ") != 0) @@ -469,9 +498,21 @@ run_child(const struct del_ctx *c, const struct sp_delegate *d, int st = 0; (void)waitpid(child, &st, 0); - if (WIFEXITED(st) && WEXITSTATUS(st) != 0) { - sp_buf_printf(err, "delegate: '%s' exited %d", - d->id, WIFEXITED(st) ? WEXITSTATUS(st) : -1); + /* + * The child's own words go with the exit code: "exited 1" + * alone hid every rate limit, and a limit nobody can read + * cannot bench anyone. A child killed by a signal failed + * too, it did not succeed quietly. + */ + if (!WIFEXITED(st) || WEXITSTATUS(st) != 0) { + const char *tail = out->p != NULL ? out->p : ""; + size_t tl = strlen(tail); + + if (tl > 400) + tail += tl - 400; + sp_buf_printf(err, "delegate: '%s' exited %d: %s", + d->id, WIFEXITED(st) ? WEXITSTATUS(st) : -1, + tail); return -1; } } @@ -673,6 +714,253 @@ jobrec_read(const struct del_ctx *c, const char *id, struct jobrec *j) +/* + * Cooldown. A delegate at its limit - claude's "You've hit your weekly limit + * · resets 3am (Europe/Lisbon)", a 429, opencode's "usage limit reached" - is + * benched until the reset it names, and choose() skips it. The bench is a file + * per delegate (~/.splinter/cooldown/, the epoch it may come back), so + * every splinter on the machine sees it, not only the one that got the 429. + * When the reset cannot be read, an hour: asking again after that costs one + * refused call, not a model turn. + */ +#define COOLDOWN_DEFAULT 3600 + +static void +cooldown_path(const char *id, char *buf, size_t len) +{ + const char *dir = getenv("SPLINTER_COOLDOWN_DIR"); + const char *home = getenv("HOME"); + + if (dir != NULL && *dir != '\0') + snprintf(buf, len, "%s/%s", dir, id); + else + snprintf(buf, len, "%s/.splinter/cooldown/%s", + home != NULL ? home : "/tmp", id); +} + +/* the epoch the delegate is benched until, 0 when it is free */ +static long +cooldown_until(const char *id) +{ + char path[700]; + FILE *f; + long until = 0; + + cooldown_path(id, path, sizeof(path)); + f = fopen(path, "r"); + if (f == NULL) + return 0; + if (fscanf(f, "%ld", &until) != 1) + until = 0; + fclose(f); + if (until <= (long)time(NULL)) { + (void)unlink(path); + return 0; + } + return until; +} + +static void +cooldown_set(const char *id, long until, const char *why) +{ + char path[700], *slash; + FILE *f; + + cooldown_path(id, path, sizeof(path)); + slash = strrchr(path, '/'); + if (slash != NULL) { + *slash = '\0'; + (void)mkdir(path, 0700); + *slash = '/'; + } + f = fopen(path, "w"); + if (f == NULL) + return; + fprintf(f, "%ld\n%.300s\n", until, why != NULL ? why : ""); + fclose(f); +} + +static int +has_ci(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; +} + +/* + * "resets 3am (Europe/Lisbon)" -> the next 3am in Lisbon. The phrase goes to + * date(1) as data: only letters, digits and a few separators survive, and the + * whole argument is one quoted word. A time of day already past today means + * tomorrow. + */ +static long +parse_reset(const char *e) +{ + const char *p, *q; + char when[64] = "", tz[64] = "", arg[160], cmd[256]; + size_t n = 0; + long t = 0, now = (long)time(NULL); + FILE *fp; + struct sp_buf line; + + /* the old claude form: "...limit reached|1755000000" */ + p = strchr(e, '|'); + if (p != NULL && isdigit((unsigned char)p[1])) { + t = strtol(p + 1, NULL, 10); + if (t > now) + return t; + } + p = strstr(e, "ready_at="); + if (p != NULL && (t = strtol(p + 9, NULL, 10)) > now) + return t; + p = strstr(e, "resets "); + if (p == NULL) + p = strstr(e, "reset at "); + if (p == NULL) + return 0; + p = strchr(p, ' ') + 1; + if (strncmp(p, "at ", 3) == 0) + p += 3; + for (q = p; *q != '\0' && *q != '(' && *q != '\n' && *q != '.' && + n + 1 < sizeof(when); q++) + if (isalnum((unsigned char)*q) || *q == ' ' || *q == ':') + when[n++] = *q; + when[n] = '\0'; + while (n > 0 && when[n - 1] == ' ') + when[--n] = '\0'; + if (*q == '(') { + for (n = 0, q++; *q != '\0' && *q != ')' && n + 1 < sizeof(tz); + q++) + if (isalnum((unsigned char)*q) || *q == '/' || + *q == '_' || *q == '-' || *q == '+') + tz[n++] = *q; + tz[n] = '\0'; + } + if (when[0] == '\0') + return 0; + if (tz[0] != '\0') + snprintf(arg, sizeof(arg), "TZ=\"%s\" %s", tz, when); + else + snprintf(arg, sizeof(arg), "%s", when); + if (sp_buf_init(&line) != 0) + return 0; + if (sp_buf_puts(&line, "date -d ") != 0 || shell_quote(&line, arg) != 0 || + sp_buf_puts(&line, " +%s 2>/dev/null") != 0) { + sp_buf_free(&line); + return 0; + } + snprintf(cmd, sizeof(cmd), "%s", line.p); + sp_buf_free(&line); + fp = popen(cmd, "r"); + if (fp == NULL) + return 0; + if (fscanf(fp, "%ld", &t) != 1) + t = 0; + (void)pclose(fp); + if (t <= 0) + return 0; + if (t <= now) + t += 86400; /* "3am" was this morning: it means tomorrow */ + return t > now ? t : 0; +} + +/* Is this error a limit, and until when? Returns 1 and sets *until. */ +static int +looks_limit(const char *e, long *until) +{ + long t; + + *until = 0; + if (e == NULL) + return 0; + if (!(strstr(e, "429") != NULL || has_ci(e, "rate limit") || + has_ci(e, "rate_limit") || has_ci(e, "usage limit") || + has_ci(e, "weekly limit") || has_ci(e, "daily limit") || + has_ci(e, "hit your limit") || has_ci(e, "limit reached") || + has_ci(e, "quota") || strstr(e, "WAIT_QUOTA") != NULL)) + return 0; + t = parse_reset(e); + *until = t > 0 ? t : (long)time(NULL) + COOLDOWN_DEFAULT; + return 1; +} + +/* + * Run d; if it is at its limit, bench it and give the task to the next + * delegate that fits - same request, the benched one no longer competes. *dp + * ends as the delegate that ran last, and the running[] slot moves with it so + * the caller's decrement hits the right one. A busy fallback is not taken: the + * limit error stands and the job waits as before. + */ +static int +run_child_fb(const struct del_ctx *c, const struct sp_delegate **dp, + const char *task, const char *wanted, struct sp_buf *reply, + struct sp_buf *err, struct sp_buf *note) +{ + const struct sp_delegate *d = *dp, *next; + size_t tries; + int rc; + + for (tries = 0; ; tries++) { + char want[300], why[192]; + long until; + int score; + size_t from, to; + + sp_buf_clear(reply); + sp_buf_clear(err); + if ((until = cooldown_until(d->id)) != 0) { + /* named explicitly, but benched: do not spend a call */ + sp_buf_printf(err, "delegate '%s' at its limit (WAIT_QUOTA " + "ready_at=%ld)", d->id, until); + rc = -1; + } else { + rc = run_child(c, d, task, reply, err); + if (rc == 0 || !looks_limit(err->p, &until)) + break; + cooldown_set(d->id, until, err->p); + } + { + char when[32]; + time_t tt = (time_t)until; + struct tm tm; + + strftime(when, sizeof(when), "%Y-%m-%d %H:%M", + localtime_r(&tt, &tm)); + sp_buf_printf(note, "[%s at its limit, benched until %s]\n", + d->id, when); + } + if (tries + 1 >= c->cfg->ndelegates) + break; + /* what was asked, plus what the benched one was good for */ + snprintf(want, sizeof(want), "%s,%s", + wanted != NULL ? wanted : "", d->tags); + next = choose(c->cfg, task, want, &score, why, sizeof(why)); + if (next == NULL || next == d) + break; + from = (size_t)(d - c->cfg->delegate); + to = (size_t)(next - c->cfg->delegate); + DEL_LOCK(); + if (to < SP_CONFIG_MAX_DELEGATES && + running[to] >= next->max_parallel) { + DEL_UNLOCK(); + break; + } + if (from < SP_CONFIG_MAX_DELEGATES && running[from] > 0) + running[from]--; + if (to < SP_CONFIG_MAX_DELEGATES) + running[to]++; + DEL_UNLOCK(); + sp_buf_printf(note, "[falling back to %s]\n", next->id); + d = next; + *dp = d; + } + return rc; +} + static const struct sp_delegate *find_delegate(const struct sp_config *cfg, const char *id); static int looks_transient(const char *e); static int looks_quota_wait(const char *e, long *ready_at); @@ -788,7 +1076,14 @@ tool_delegate(const char *args, struct sp_buf *out, void *ctx) snprintf(detail, sizeof(detail), "%.140s", task); task_id = sp_host_task_begin(c->host, label, detail); } - if (run_child(c, d, task, &reply, &err) != 0) { + const struct sp_delegate *ran = d; + int child_rc = run_child_fb(c, &ran, task, wanted, &reply, &err, out); + + if (ran != d) { + d = ran; + snprintf(jr.delegate_id, sizeof(jr.delegate_id), "%s", d->id); + } + if (child_rc != 0) { sp_host_task_end(c->host, task_id, 1, 0); { size_t slot = (size_t)(d - c->cfg->delegate); @@ -1337,14 +1632,12 @@ looks_transient(const char *e) static int looks_quota_wait(const char *e, long *ready_at) { - const char *p; - if (ready_at) *ready_at = 0; - if (!e) return 0; - if (!strstr(e,"quota") && !strstr(e,"Quota") && !strstr(e,"rate limit") && !strstr(e,"WAIT_QUOTA")) - return 0; - p = strstr(e, "ready_at="); - if (p && ready_at) *ready_at = strtol(p + 9, NULL, 10); - return 1; + long until = 0; + int r = looks_limit(e, &until); + + if (ready_at != NULL) + *ready_at = r ? until : 0; + return r; } @@ -1546,7 +1839,14 @@ sp_delegate_retry_job(const char *id, int force, struct sp_buf *out) task_id = sp_host_task_begin(c->host,label,detail); } sp_buf_printf(out,"[retry job %s -> %s attempt %d]\n", jr.id, d->id, jr.attempts); - if (run_child(c,d,jr.task.p?jr.task.p:"",&reply,&err)!=0) { + const struct sp_delegate *ran = d; + int child_rc = run_child_fb(c, &ran, jr.task.p?jr.task.p:"", NULL, &reply, &err, out); + + if (ran != d) { + d = ran; + snprintf(jr.delegate_id, sizeof(jr.delegate_id), "%s", d->id); + } + if (child_rc != 0) { sp_host_task_end(c->host,task_id,1,0); { size_t slot=(size_t)(d-c->cfg->delegate); DEL_LOCK(); if(slot0) running[slot]--; DEL_UNLOCK(); } jr.status=1; jr.ended_ms=now_ms(); @@ -1691,7 +1991,14 @@ tool_delegate_submit(const char *args, struct sp_buf *out, void *ctx) } snprintf(jr.state, sizeof(jr.state), "running"); jobrec_write(c, &jr); - if (run_child(c, d, task, &reply, &err) != 0) { + const struct sp_delegate *ran = d; + int child_rc = run_child_fb(c, &ran, task, wanted, &reply, &err, out); + + if (ran != d) { + d = ran; + snprintf(jr.delegate_id, sizeof(jr.delegate_id), "%s", d->id); + } + if (child_rc != 0) { sp_host_task_end(c->host, task_id, 1, 0); { size_t slot = (size_t)(d - c->cfg->delegate); DEL_LOCK(); if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] > 0) running[slot]--; DEL_UNLOCK(); } jr.status = 1; jr.ended_ms = now_ms(); diff --git a/src/main.c b/src/main.c index e47f247..d6a224e 100644 --- a/src/main.c +++ b/src/main.c @@ -597,6 +597,12 @@ open_session(struct opts *o, struct sp_session_info *sess, struct sp_buf *err) return 3; } (void)sp_log_open(sess->dir, sess->id); + /* + * The cli transport keys the program's own session on this, so claude or + * opencode continue one conversation for the whole splinter session. A + * delegate child inherits its parent's key (plus its name), never its own. + */ + (void)setenv("SPLINTER_CLI_SESSION", sess->id, 0); return 0; } diff --git a/tests/test_cli.c b/tests/test_cli.c index 6933949..15c5808 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -5,10 +5,18 @@ * the transport is wrong, not an endpoint. What is checked: the prompt reaches * the program's stdin, its stdout becomes the answer, a program that prints * nothing is an error, and a non-zero exit carries the program's own words. + * + * Sessions: a fake claude that behaves like the real one about ids (refuses + * --session-id for a session it has, --resume for one it lacks) shows that + * consecutive calls land in one session, that a lost marker heals, and that + * another splinter session gets another id. A fake opencode shows the same + * for --session. */ #include #include #include +#include +#include #include "splinter.h" #include "splinter_plugin.h" @@ -22,6 +30,57 @@ static int failures; } \ } while (0) +static char tdir[256]; + +static void +write_exec(const char *name, const char *body) +{ + char path[400]; + FILE *f; + + snprintf(path, sizeof(path), "%s/%s", tdir, name); + f = fopen(path, "w"); + CHECK(f != NULL); + if (f == NULL) + return; + fputs(body, f); + fclose(f); + CHECK(chmod(path, 0755) == 0); +} + +/* the last line of the fake's argument log */ +static void +last_log(char *buf, size_t len) +{ + char path[400], line[512]; + FILE *f; + + buf[0] = '\0'; + snprintf(path, sizeof(path), "%s/log", tdir); + f = fopen(path, "r"); + if (f == NULL) + return; + while (fgets(line, sizeof(line), f) != NULL) { + line[strcspn(line, "\n")] = '\0'; + snprintf(buf, len, "%s", line); + } + fclose(f); +} + +static struct sp_host * +host_for(struct sp_registry *reg, struct sp_agent *ag, const char *cmd, + struct sp_buf *err) +{ + struct sp_host *h; + + setenv("SPLINTER_CLI_CMD", cmd, 1); + h = sp_host_new(reg, ag, NULL); + CHECK(h != NULL); + if (h != NULL) + CHECK(sp_plugin_load(h, "plugins/cli/cli.so", err) == 0); + return h; +} + static int one_turn(struct sp_host *host, const char *text, struct sp_reply *out, struct sp_buf *err) @@ -94,6 +153,117 @@ main(void) CHECK(strstr(err.p, "kaputt") != NULL); sp_reply_free(&rep); + /* ---- sessions ---- */ + { + struct sp_host *hc, *ho, *hp; + char line[512], first[512], path[1024], cmd[1100]; + const char *oldpath = getenv("PATH"); + char *u; + + snprintf(tdir, sizeof(tdir), "/tmp/splinter-cli-test-XXXXXX"); + CHECK(mkdtemp(tdir) != NULL); + write_exec("claude", + "#!/bin/sh\n" + "D=$(dirname \"$0\")\n" + "echo \"$*\" >> \"$D/log\"\n" + "id=none\n" + "while [ $# -gt 0 ]; do\n" + " case $1 in\n" + " --session-id) if [ -e \"$D/s.$2\" ]; then\n" + " echo \"Error: Session ID $2 is already in use.\" >&2;" + " exit 1; fi; : > \"$D/s.$2\"; id=$2; shift;;\n" + " --resume) [ -e \"$D/s.$2\" ] || { echo \"No conversation" + " found with session ID: $2\" >&2; exit 1; }; id=$2; shift;;\n" + " esac; shift\n" + "done\n" + "cat > /dev/null\n" + "echo \"ok $id\"\n"); + write_exec("opencode", + "#!/bin/sh\n" + "echo \"$*\" >> \"$(dirname \"$0\")/log\"\n" + "cat > /dev/null; echo ok\n"); + snprintf(line, sizeof(line), "%s:%s", tdir, + oldpath != NULL ? oldpath : "/usr/bin:/bin"); + setenv("PATH", line, 1); + snprintf(path, sizeof(path), "%s/state", tdir); + setenv("SPLINTER_CLI_STATE", path, 1); + setenv("SPLINTER_CLI_SESSION", "sess-1:claude0", 1); + + hc = host_for(®, &ag, "claude -p", &err); + /* first call starts the session */ + memset(&rep, 0, sizeof(rep)); + CHECK(one_turn(hc, "eins", &rep, &err) == 0); + sp_reply_free(&rep); + last_log(first, sizeof(first)); + CHECK(strncmp(first, "-p --session-id ", 16) == 0); + CHECK(strlen(first) == 16 + 36); + u = first + 16; + /* second call continues it */ + memset(&rep, 0, sizeof(rep)); + CHECK(one_turn(hc, "zwei", &rep, &err) == 0); + CHECK(rep.content != NULL && strstr(rep.content, u) != NULL); + sp_reply_free(&rep); + last_log(line, sizeof(line)); + snprintf(cmd, sizeof(cmd), "-p --resume %s", u); + CHECK(strcmp(line, cmd) == 0); + /* the marker is gone, the session is not: one retry heals it */ + snprintf(path, sizeof(path), "%s/state/%s", tdir, u); + CHECK(unlink(path) == 0); + memset(&rep, 0, sizeof(rep)); + sp_buf_clear(&err); + CHECK(one_turn(hc, "drei", &rep, &err) == 0); + CHECK(rep.content != NULL && strstr(rep.content, u) != NULL); + sp_reply_free(&rep); + last_log(line, sizeof(line)); + CHECK(strcmp(line, cmd) == 0); + CHECK(access(path, F_OK) == 0); + /* another session key, another id */ + setenv("SPLINTER_CLI_SESSION", "sess-1:claude1", 1); + memset(&rep, 0, sizeof(rep)); + CHECK(one_turn(hc, "vier", &rep, &err) == 0); + sp_reply_free(&rep); + last_log(line, sizeof(line)); + CHECK(strncmp(line, "-p --session-id ", 16) == 0); + CHECK(strcmp(line + 16, u) != 0); + /* empty key: no session arguments at all */ + setenv("SPLINTER_CLI_SESSION", "", 1); + memset(&rep, 0, sizeof(rep)); + CHECK(one_turn(hc, "fuenf", &rep, &err) == 0); + sp_reply_free(&rep); + last_log(line, sizeof(line)); + CHECK(strcmp(line, "-p") == 0); + /* a command that names its own session is left alone */ + setenv("SPLINTER_CLI_SESSION", "sess-1:claude0", 1); + hp = host_for(®, &ag, "claude -p --resume mine", &err); + write_exec("s.mine", ""); + memset(&rep, 0, sizeof(rep)); + CHECK(one_turn(hp, "sechs", &rep, &err) == 0); + sp_reply_free(&rep); + last_log(line, sizeof(line)); + CHECK(strcmp(line, "-p --resume mine") == 0); + + /* opencode: one ses_ id, the same on every call */ + ho = host_for(®, &ag, "opencode run -m x/y", &err); + memset(&rep, 0, sizeof(rep)); + CHECK(one_turn(ho, "a", &rep, &err) == 0); + sp_reply_free(&rep); + last_log(first, sizeof(first)); + CHECK(strncmp(first, "run -m x/y --session ses_", 25) == 0); + CHECK(strlen(first) == 21 + 30); + memset(&rep, 0, sizeof(rep)); + CHECK(one_turn(ho, "b", &rep, &err) == 0); + sp_reply_free(&rep); + last_log(line, sizeof(line)); + CHECK(strcmp(line, first) == 0); + + sp_host_free(hp); + sp_host_free(ho); + sp_host_free(hc); + setenv("PATH", oldpath != NULL ? oldpath : "/usr/bin:/bin", 1); + snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tdir); + (void)system(cmd); + } + sp_host_free(host3); sp_host_free(host2); sp_host_free(host); diff --git a/tests/test_delegate.c b/tests/test_delegate.c index 23ea142..3bed551 100644 --- a/tests/test_delegate.c +++ b/tests/test_delegate.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -180,6 +181,108 @@ main(void) (void)system(line); } + /* + * ---- a delegate at its limit is benched and the task goes on ---- + * Fake ssh: host "spent" answers like claude with an empty account, host + * "fresh" answers. Two delegates fit the same task; the better one is the + * spent one. + */ + { + struct sp_config c; + struct sp_registry r; + struct sp_buf out; + char tdir[64] = "/tmp/splinter-cool-XXXXXX"; + char path[400], line[400], cool[100]; + const char *oldpath = getenv("PATH"); + const struct sp_tool *t; + FILE *f; + long until = 0; + + CHECK(mkdtemp(tdir) != NULL); + snprintf(path, sizeof(path), "%s/ssh", tdir); + f = fopen(path, "w"); + CHECK(f != NULL); + if (f != NULL) { + fprintf(f, "#!/bin/sh\n" + "echo \"$4\" >> '%s/hosts'\n" + "if [ \"$4\" = spent ]; then\n" + " echo \"You've hit your weekly limit · resets 3am" + " (Europe/Lisbon)\"; exit 1\n" + "fi\n" + "echo 'antwort von fresh'\n", tdir); + fclose(f); + } + (void)chmod(path, 0755); + snprintf(line, sizeof(line), "%s:%s", tdir, + oldpath != NULL ? oldpath : "/usr/bin:/bin"); + (void)setenv("PATH", line, 1); + snprintf(cool, sizeof(cool), "%s/cool", tdir); + (void)setenv("SPLINTER_COOLDOWN_DIR", cool, 1); + + memset(&c, 0, sizeof(c)); + add(&c, "claude0", "first account", "big"); + snprintf(c.delegate[0].host, sizeof(c.delegate[0].host), "spent"); + c.delegate[0].prio = 9; + c.delegate[0].max_parallel = 1; + add(&c, "claude1", "second account", "big"); + snprintf(c.delegate[1].host, sizeof(c.delegate[1].host), "fresh"); + c.delegate[1].prio = 5; + c.delegate[1].max_parallel = 1; + memset(&r, 0, sizeof(r)); + CHECK(sp_delegate_register(&r, &c, NULL) == 0); + t = sp_registry_find(&r, "delegate"); + CHECK(t != NULL); + CHECK(sp_buf_init(&out) == 0); + + /* the spent one is tried, benched, and the task still gets done */ + if (t != NULL) + (void)t->run("{\"task\":\"x\",\"tags\":\"big\"}", &out, + t->ctx); + if (getenv("TEST_VERBOSE") != NULL) + fprintf(stderr, "fallback said: %s\n", out.p); + CHECK(out.p != NULL && strstr(out.p, "antwort von fresh") != NULL); + CHECK(out.p != NULL && strstr(out.p, "falling back to claude1") != NULL); + snprintf(path, sizeof(path), "%s/claude0", cool); + f = fopen(path, "r"); + CHECK(f != NULL); + if (f != NULL) { + CHECK(fscanf(f, "%ld", &until) == 1); + fclose(f); + } + /* until the next 3am in Lisbon: in the future, within a day */ + CHECK(until > (long)time(NULL)); + CHECK(until <= (long)time(NULL) + 86400 + 3600); + + /* benched: the next task does not knock on the spent door */ + snprintf(path, sizeof(path), "%s/hosts", tdir); + (void)unlink(path); + sp_buf_clear(&out); + if (t != NULL) + (void)t->run("{\"task\":\"y\",\"tags\":\"big\"}", &out, + t->ctx); + CHECK(out.p != NULL && strstr(out.p, "antwort von fresh") != NULL); + /* not even when it is asked for by name */ + sp_buf_clear(&out); + if (t != NULL) + (void)t->run("{\"task\":\"z\",\"delegate\":\"claude0\"}", + &out, t->ctx); + CHECK(out.p != NULL && strstr(out.p, "antwort von fresh") != NULL); + f = fopen(path, "r"); + CHECK(f != NULL); + if (f != NULL) { + while (fgets(line, sizeof(line), f) != NULL) + CHECK(strncmp(line, "spent", 5) != 0); + fclose(f); + } + + sp_buf_free(&out); + sp_registry_free(&r); + (void)setenv("PATH", oldpath != NULL ? oldpath : "/usr/bin:/bin", 1); + (void)unsetenv("SPLINTER_COOLDOWN_DIR"); + snprintf(line, sizeof(line), "rm -rf '%s'", tdir); + (void)system(line); + } + if (failures == 0) printf("test_delegate: ok\n"); return failures == 0 ? 0 : 1;