diff --git a/docs/CONFIG.md b/docs/CONFIG.md index db1c4a6..5ba0dd2 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -144,6 +144,15 @@ 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_fallback = claude1, claude0` names cli delegates to use, in order, when +`cli_cmd` is at its limit: their `cmd` and `env=` replace the main ones for +that call. The main command is benched as `cli`, a fallback under its own id - +the same bench delegation uses, so an account at its limit is skipped +everywhere. The session key stays, so claude resumes the same conversation +under the next account. A fallback's `env=` reaches the program through a +0600 file the shell sources, never through a command line `ps` would show. +When every account is benched, the turn fails with the first reset time. + `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/include/splinter.h b/include/splinter.h index 5787541..0ece151 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -294,6 +294,16 @@ const char *sp_memory_user(void); int sp_slash_script(const char *dir, const char *name, const char *args, struct sp_buf *out, struct sp_buf *err); int sp_delegate_prio(const struct sp_config *, const char *id); + +/* + * Limits. sp_limit_parse: is this error text a rate/usage limit (429, "weekly + * limit", "quota", ...) and until when - the reset it names, else an hour. + * The bench is ~/.splinter/cooldown/ ($SPLINTER_COOLDOWN_DIR), shared by + * every splinter on the machine: sp_cooldown_until is 0 when is free. + */ +int sp_limit_parse(const char *err, long *until); +long sp_cooldown_until(const char *id); +void sp_cooldown_set(const char *id, long until, const char *why); int sp_delegate_choose(const struct sp_config *, const char *task, const char *tags, char *id, size_t cap, char *why, size_t whylen, int *score); diff --git a/plugins/cli/cli.c b/plugins/cli/cli.c index 3d7e8d2..5f5944b 100644 --- a/plugins/cli/cli.c +++ b/plugins/cli/cli.c @@ -20,6 +20,9 @@ * 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 * @@ -30,6 +33,8 @@ * must not do. */ #include +#include +#include #include #include #include @@ -42,6 +47,7 @@ #include "splinter.h" #include "splinter_plugin.h" #include "i18n.h" +#include "config.h" #define OUT_CAP (64u << 20) @@ -49,6 +55,10 @@ 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 @@ -249,7 +259,7 @@ ci_contains(const char *hay, const char *needle) 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) + const char *envfile, struct sp_buf *cmd) { int placeholder; const char *p = c->cmd; @@ -257,6 +267,10 @@ build_cmd(const struct cli_cfg *c, const char *path, const char *prompt, 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') { @@ -337,13 +351,48 @@ 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 -cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, - struct sp_buf *err) +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 cli_cfg *c = ctx; 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"); @@ -401,8 +450,17 @@ 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); + 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, &cmd) != 0 || + errpath, envfile, &cmd) != 0 || run_cmd(cmd.p, errpath, &raw, errtext, sizeof(errtext), &status, err) != 0) { unlink(path); @@ -420,7 +478,7 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, 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 || + extra, errpath, envfile, &cmd) != 0 || run_cmd(cmd.p, errpath, &raw, errtext, sizeof(errtext), &status, err) != 0) { unlink(path); @@ -446,6 +504,10 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, 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) @@ -458,12 +520,105 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, 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) { @@ -480,6 +635,7 @@ cli_init(struct sp_host *h) 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); diff --git a/src/config.c b/src/config.c index 8a398ba..db6f4ec 100644 --- a/src/config.c +++ b/src/config.c @@ -419,6 +419,8 @@ load_one(struct sp_config *c, const char *path, struct sp_buf *err) set_str(c->session_dir, sizeof(c->session_dir), val); else if (!strcmp(key, "cli_cmd")) set_str(c->cli_cmd, sizeof(c->cli_cmd), val); + else if (!strcmp(key, "cli_fallback")) + set_str(c->cli_fallback, sizeof(c->cli_fallback), val); else if (!strcmp(key, "cli_env")) { if (add_env(c->cli_env, &c->ncli_env, val, err, path, lineno) != 0) { @@ -549,6 +551,7 @@ sp_config_write_example(const char *path, struct sp_buf *err) "#transport = cli\n" "#cli_cmd = claude -p\n" "#cli_env = CLAUDE_CODE_OAUTH_TOKEN=sk-ant-...\n" + "#cli_fallback = claude1, claude0\n" "\n" "# Plugins to load, one per line. Paths are relative to the working\n" "# directory unless absolute.\n" diff --git a/src/config.h b/src/config.h index ed6f5b3..b6af6bd 100644 --- a/src/config.h +++ b/src/config.h @@ -85,6 +85,7 @@ struct sp_config { char cli_cmd[512]; char cli_env[SP_CONFIG_MAX_ENV][SP_CONFIG_ENV_LEN]; /* NAME=VALUE */ size_t ncli_env; + char cli_fallback[256]; /* cli delegate ids, comma separated */ char memory_url[512]; char memory_key_env[64]; char telegram_allow[256]; /* comma separated user ids */ diff --git a/src/delegate.c b/src/delegate.c index 5b0d83b..d72a1d9 100644 --- a/src/delegate.c +++ b/src/delegate.c @@ -208,7 +208,6 @@ 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, @@ -228,7 +227,7 @@ choose(const struct sp_config *cfg, const char *task, const char *wanted, int score = 0; char reason[192] = ""; - if (cooldown_until(d->id) != 0) + if (sp_cooldown_until(d->id) != 0) continue; /* benched: at its limit until the reset */ snprintf(tags, sizeof(tags), "%s", d->tags); @@ -392,6 +391,8 @@ exec_delegate(const struct del_ctx *c, const struct sp_delegate *d, { const char *ps = getenv("SPLINTER_CLI_SESSION"); + if (cli && !remote) + (void)setenv("SPLINTER_CLI_ID", d->id, 1); if (cli && ps != NULL && *ps != '\0') { snprintf(clisess, sizeof(clisess), "%s:%s", ps, d->id); if (!remote) @@ -406,9 +407,17 @@ exec_delegate(const struct del_ctx *c, const struct sp_delegate *d, if (sp_buf_init(&line) != 0) _exit(127); - if ((d->nenv > 0 || clisess[0] != '\0') && + if ((d->nenv > 0 || clisess[0] != '\0' || cli) && sp_buf_puts(&line, "env ") != 0) _exit(127); + if (cli) { + char kv[64]; + + snprintf(kv, sizeof(kv), "SPLINTER_CLI_ID=%s", d->id); + if (shell_quote(&line, kv) != 0 || + sp_buf_puts(&line, " ") != 0) + _exit(127); + } if (clisess[0] != '\0') { char kv[300]; @@ -739,8 +748,8 @@ cooldown_path(const char *id, char *buf, size_t len) } /* the epoch the delegate is benched until, 0 when it is free */ -static long -cooldown_until(const char *id) +long +sp_cooldown_until(const char *id) { char path[700]; FILE *f; @@ -760,8 +769,8 @@ cooldown_until(const char *id) return until; } -static void -cooldown_set(const char *id, long until, const char *why) +void +sp_cooldown_set(const char *id, long until, const char *why) { char path[700], *slash; FILE *f; @@ -869,8 +878,8 @@ parse_reset(const char *e) } /* Is this error a limit, and until when? Returns 1 and sets *until. */ -static int -looks_limit(const char *e, long *until) +int +sp_limit_parse(const char *e, long *until) { long t; @@ -912,16 +921,16 @@ run_child_fb(const struct del_ctx *c, const struct sp_delegate **dp, sp_buf_clear(reply); sp_buf_clear(err); - if ((until = cooldown_until(d->id)) != 0) { + if ((until = sp_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)) + if (rc == 0 || !sp_limit_parse(err->p, &until)) break; - cooldown_set(d->id, until, err->p); + sp_cooldown_set(d->id, until, err->p); } { char when[32]; @@ -1265,9 +1274,9 @@ par_fallback(struct del_ctx *c, struct job *jobs, size_t njobs, size_t i, time_t tt; struct tm tm; - if (j->out.p == NULL || !looks_limit(j->out.p, &until)) + if (j->out.p == NULL || !sp_limit_parse(j->out.p, &until)) return 0; - cooldown_set(j->d->id, until, j->out.p); + sp_cooldown_set(j->d->id, until, j->out.p); tt = (time_t)until; strftime(when, sizeof(when), "%Y-%m-%d %H:%M", localtime_r(&tt, &tm)); nl = strlen(j->note); @@ -1705,7 +1714,7 @@ static int looks_quota_wait(const char *e, long *ready_at) { long until = 0; - int r = looks_limit(e, &until); + int r = sp_limit_parse(e, &until); if (ready_at != NULL) *ready_at = r ? until : 0; diff --git a/tests/test_cli.c b/tests/test_cli.c index 15c5808..09cdffa 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -20,6 +20,7 @@ #include "splinter.h" #include "splinter_plugin.h" +#include "config.h" static int failures; @@ -256,6 +257,98 @@ main(void) last_log(line, sizeof(line)); CHECK(strcmp(line, first) == 0); + /* + * ---- the main cli at its limit falls back to cli delegates ---- + * acct answers with the token it was given, or with claude's limit + * when that token is listed as spent. + */ + { + struct sp_config conf; + struct sp_host *hf; + char cool[300], sp[400]; + + write_exec("acct", + "#!/bin/sh\n" + "D=$(dirname \"$0\")\n" + "echo \"$TOK\" >> \"$D/acctlog\"\n" + "if grep -qx \"$TOK\" \"$D/spent\" 2>/dev/null; then\n" + " echo \"You've hit your weekly limit ยท resets 3am" + " (Europe/Lisbon)\" >&2; exit 1\n" + "fi\n" + "cat > /dev/null; echo \"ok $TOK\"\n"); + snprintf(cool, sizeof(cool), "%s/cool", tdir); + setenv("SPLINTER_COOLDOWN_DIR", cool, 1); + setenv("TOK", "zero", 1); + setenv("SPLINTER_CLI_SESSION", "", 1); + snprintf(sp, sizeof(sp), "%s/spent", tdir); + + sp_config_init(&conf); + memset(&conf.delegate[0], 0, sizeof(conf.delegate[0])); + snprintf(conf.delegate[0].id, 32, "acc1"); + snprintf(conf.delegate[0].kind, 16, "cli"); + snprintf(conf.delegate[0].cmd, 256, "acct"); + snprintf(conf.delegate[0].env[0], SP_CONFIG_ENV_LEN, + "TOK=one 'quoted'"); + conf.delegate[0].nenv = 1; + conf.delegate[1] = conf.delegate[0]; + snprintf(conf.delegate[1].id, 32, "acc2"); + snprintf(conf.delegate[1].env[0], SP_CONFIG_ENV_LEN, + "TOK=two"); + conf.ndelegates = 2; + snprintf(conf.cli_fallback, sizeof(conf.cli_fallback), + "acc1, acc2"); + + setenv("SPLINTER_CLI_CMD", "acct", 1); + hf = sp_host_new(®, &ag, NULL); + CHECK(hf != NULL); + sp_host_set_config(hf, &conf); + CHECK(sp_plugin_load(hf, "plugins/cli/cli.so", &err) == 0); + + /* the main account is spent: acc1 answers, its token arrives */ + write_exec("spent", "zero\n"); + memset(&rep, 0, sizeof(rep)); + sp_buf_clear(&err); + CHECK(one_turn(hf, "a", &rep, &err) == 0); + CHECK(rep.content != NULL && + strncmp(rep.content, "ok one 'quoted'", 15) == 0); + sp_reply_free(&rep); + snprintf(path, sizeof(path), "%s/cli", cool); + CHECK(access(path, F_OK) == 0); + /* benched: the next turn does not ask the main account */ + snprintf(path, sizeof(path), "%s/acctlog", tdir); + (void)unlink(path); + memset(&rep, 0, sizeof(rep)); + CHECK(one_turn(hf, "b", &rep, &err) == 0); + sp_reply_free(&rep); + { + FILE *f = fopen(path, "r"); + + CHECK(f != NULL); + if (f != NULL) { + CHECK(fgets(line, sizeof(line), f) != NULL && + strcmp(line, "one 'quoted'\n") == 0); + CHECK(fgets(line, sizeof(line), f) == NULL); + fclose(f); + } + } + /* everyone spent: an error that says so and when */ + write_exec("spent", "zero\none 'quoted'\ntwo\n"); + memset(&rep, 0, sizeof(rep)); + sp_buf_clear(&err); + CHECK(one_turn(hf, "c", &rep, &err) == -1); + CHECK(strstr(err.p, "every account at its usage limit") != NULL); + CHECK(strstr(err.p, "ready_at=") != NULL); + snprintf(path, sizeof(path), "%s/acc2", cool); + CHECK(access(path, F_OK) == 0); + sp_reply_free(&rep); + /* no env file is left behind */ + snprintf(cmd, sizeof(cmd), "ls /var/tmp/splinter-cli-*.env " + "2>/dev/null | grep -q ."); + CHECK(system(cmd) != 0); + sp_host_free(hf); + unsetenv("SPLINTER_COOLDOWN_DIR"); + } + sp_host_free(hp); sp_host_free(ho); sp_host_free(hc);