diff --git a/Makefile b/Makefile index cee5bf9..0942e14 100644 --- a/Makefile +++ b/Makefile @@ -23,13 +23,17 @@ CURSES_A = $(CURSES_DIR)/libcurses/libcurses.a \ LIB = libsplinter.so LIBOBJ = src/buf.o src/tool.o src/session.o src/conv.o src/transport.o \ src/json.o src/sse.o src/openai.o src/transport_openai.o src/builtin.o \ - src/agent.o src/theme.o src/palettes.o src/decomp.o src/i18n.o src/delegate.o src/telegram.o src/log.o src/cmdscript.o src/folder.o src/interview.o src/ack.o src/mcpserver.o src/skills.o src/memory.o src/prompt.o src/config.o src/plugin.o src/curl.o + src/agent.o src/theme.o src/palettes.o src/decomp.o src/i18n.o src/delegate.o src/telegram.o src/log.o src/cmdscript.o src/folder.o src/interview.o src/ack.o src/mcpserver.o src/skills.o src/memory.o src/prompt.o src/config.o src/plugin.o src/curl.o src/swarm.o src/provstate.o BIN = splinter BINOBJ = src/main.o src/ui.o PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \ plugins/cli/cli.so plugins/focus/focus.so plugins/mcp/mcp.so \ plugins/ring/ring.so plugins/reminder/reminder.so \ - plugins/kids/kids.so plugins/status/status.so plugins/tasks/tasks.so + plugins/kids/kids.so plugins/status/status.so plugins/tasks/tasks.so \ + plugins/provider/provider.so \ + plugins/scheduler/scheduler.so \ + plugins/planner/planner.so \ + plugins/tmux/tmux.so TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \ tests/test_transport tests/test_agent tests/test_openai \ tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_cli tests/test_compactor tests/test_secrets tests/test_mcpclient tests/test_kids tests/test_lifecycle @@ -201,6 +205,7 @@ check: $(LIB) $(BIN) $(PLUGIN) $(TESTS) export LD_LIBRARY_PATH=.; \ for t in $(TESTS); do echo "== $$t"; ./$$t; done; \ echo "== tests/test_gateway.sh"; sh tests/test_gateway.sh; \ + echo "== tests/test_ui.sh"; sh tests/test_ui.sh; \ echo "all tests passed" # The installed binary finds its own library through an rpath relative to itself @@ -224,3 +229,17 @@ clean: # is a hard error - the same rule as the program's own catalogues. www: python3 tools/gen_www.py + +plugins/provider/provider.so: plugins/provider/provider.c $(LIB) + $(CC) $(CFLAGS) -shared -o $@ plugins/provider/provider.c -L. -lsplinter \ + $(PLUGIN_RPATH) $(LIBS) + +plugins/scheduler/scheduler.so: plugins/scheduler/scheduler.c $(LIB) + $(CC) $(CFLAGS) -shared -o $@ plugins/scheduler/scheduler.c -L. -lsplinter \ + $(PLUGIN_RPATH) $(LIBS) +plugins/planner/planner.so: plugins/planner/planner.c $(LIB) + $(CC) $(CFLAGS) -shared -o $@ plugins/planner/planner.c -L. -lsplinter \ + $(PLUGIN_RPATH) $(LIBS) +plugins/tmux/tmux.so: plugins/tmux/tmux.c $(LIB) + $(CC) $(CFLAGS) -shared -o $@ plugins/tmux/tmux.c -L. -lsplinter \ + $(PLUGIN_RPATH) $(LIBS) diff --git a/README.md b/README.md index 4e085df..d3d2cdb 100644 --- a/README.md +++ b/README.md @@ -375,8 +375,8 @@ the prompt. 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`, killed after `SPLINTER_RUN_TIMEOUT` - seconds (default 300), and an environment without splinter's API keys and - tokens, so `run env` cannot hand them to the model. + seconds (default 600) or `run_timeout` in the config, and an environment without + splinter's API keys and tokens, so `run env` cannot hand them to the model. - `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). diff --git a/docs/CONFIG.md b/docs/CONFIG.md index a2c3ffb..b315883 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -43,7 +43,7 @@ lies about what it does. | `theme` | CDE palette name (`splinter --list-themes`) | | `locale` | language code (`de`, `en`); catalogues live in `share/locale` | | `autonomous` | `1` runs mutating/destructive tools without asking | -| `steps` | tool rounds per turn (default 8) | +| `steps` | tool rounds per turn (default 150) | | `max_bytes` | conversation budget in bytes, `0` = no limit | | `session_dir` | where session logs go (default `~/.splinter`) | | `system_prompt` | sent once at the start of a conversation | @@ -68,6 +68,7 @@ exit = groq | Groq free tier | endpoint=https://api.groq.com/openai/v1/chat/comp delegate = coder | C99, POSIX, kennt den Quellbaum | endpoint=http://kontron:8080/v1/chat/completions | model=qwen | tags=code,review | prio=5 | max_parallel=2 delegate = far | the same, on another machine | host=buildbox | endpoint=... | model=... delegate = claude-cli | Claude Code | kind=cli | cmd=claude -p | tags=plan +delegate = claude-b | Claude Code, second account | kind=cli | cmd=claude -p | env=CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-... ``` `exit` fields: `endpoint`, `model`, `key_env`; the second field is the label. @@ -76,6 +77,12 @@ delegate = claude-cli | Claude Code | kind=cli | cmd=claude -p | tags=plan ssh target: the child splinter runs there, with that machine's keys. An unnamed field is the description the selection reads. +`env=NAME=VALUE` (repeatable, up to 8) sets a variable for the delegate's +child right before it starts, overwriting whatever the parent exported - so two +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`. + ## Example: local model ``` @@ -94,10 +101,21 @@ session_dir = /home/lotherk/.splinter ``` transport = cli cli_cmd = claude -p +cli_timeout = 1800 plugin = /home/lotherk/src/splinter/plugins/cli/cli.so theme = Delphinium ``` +`cli_env = NAME=VALUE` (repeatable, up to 8) sets a variable for the cli +program, e.g. `cli_env = CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-...`. It +overwrites an exported variable of the same name. + +`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 +message as an argument, use e.g. `cli_cmd = opencode run --format default {file}` +or pass the prompt via a flag your CLI supports. + With both `endpoint` and `transport` set, `transport` wins — it is the more specific instruction. diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md index 35446dd..e3a3b9e 100644 --- a/docs/PLUGINS.md +++ b/docs/PLUGINS.md @@ -156,7 +156,8 @@ SPLINTER_CLI_CMD="opencode run" ./splinter -p "hi" --plugin plugins/cli/cli.so - `SPLINTER_CLI_CMD` — the program, default `claude -p` - `SPLINTER_CLI_FULL=1` — send the whole transcript instead of the last user message (for programs that keep no history of their own) -- `SPLINTER_CLI_TIMEOUT` — seconds, default 600 +- `SPLINTER_CLI_TIMEOUT` — seconds, default 1800 (or `cli_timeout` in the config) +- `SPLINTER_CLI_CMD` may include `{file}` (prompt file path) or `{prompt}` (shell-quoted prompt); without a placeholder the prompt is passed on stdin The command comes from the operator's environment and runs through `/bin/sh -c`; it is never built from model output. Output is capped at 4 MiB, a non-zero exit diff --git a/docs/splinter.1 b/docs/splinter.1 index 72f6fa7..aa46270 100644 --- a/docs/splinter.1 +++ b/docs/splinter.1 @@ -58,7 +58,7 @@ This needs no network and is how the test suite drives the loop. Run mutating tools without asking. Read-only tools never ask. .It Fl -steps Ar N -Maximum tool rounds per turn (default 8). +Maximum tool rounds per turn (default 150). .It Fl -max-bytes Ar N Request budget in bytes; 0 means no limit. .It Fl -session Ar DIR diff --git a/include/splinter.h b/include/splinter.h index a19b0bf..5787541 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -114,6 +114,7 @@ struct sp_reply { long status; long tokens_in; /* provider-reported, 0 when unknown */ long tokens_out; + long retry_after_s; /* parsed Retry-After header, 0 unknown */ char *content; /* assistant text, may be "" */ struct sp_toolcall *calls; char *calls_json; /* the provider's own tool_calls array */ @@ -145,6 +146,9 @@ struct sp_transport { struct sp_reply *out, struct sp_buf *err, sp_stream_cb, void *cbctx); void *ctx; + /* optional: provider/key identity for quota/usage tracking (plugins) */ + const char *provider; /* e.g. "openai-compat", "ollama", "opencode" */ + const char *key_id; /* stable key fingerprint/id, never the secret */ }; void sp_reply_free(struct sp_reply *); @@ -231,6 +235,11 @@ struct sp_agent_config { const char *observation); void *tool_end_ctx; + /* Called when the conversation was compacted to fit the budget. */ + void (*on_compact)(void *ctx, size_t before, size_t after, + size_t msgs_before, size_t msgs_after); + void *on_compact_ctx; + /* incremental output, if the transport and the caller both support it */ sp_stream_cb stream; void *stream_ctx; diff --git a/include/splinter_plugin.h b/include/splinter_plugin.h index f01db79..0243071 100644 --- a/include/splinter_plugin.h +++ b/include/splinter_plugin.h @@ -150,6 +150,14 @@ int sp_host_add_gate(struct sp_host *, const struct sp_gate *); int sp_host_add_status(struct sp_host *, const struct sp_status *); const struct sp_meter *sp_host_meter(struct sp_host *); void sp_host_set_meter(struct sp_host *, const struct sp_meter *); +/* + * Thread-safe: a copy under the host lock, and a change of only the caller's + * fields under the lock. Use these from any thread but the UI's; the two above + * remain for the UI thread and for reading a single field. + */ +void sp_host_meter_get(struct sp_host *, struct sp_meter *out); +void sp_host_meter_update(struct sp_host *, + void (*fn)(struct sp_meter *, void *), void *ctx); size_t sp_host_status_text(struct sp_host *, char *buf, size_t len); void sp_host_set_task_ops(struct sp_host *, const struct sp_task_ops *); int sp_host_task_begin(struct sp_host *, const char *label, const char *detail); @@ -166,6 +174,46 @@ size_t sp_host_command_help(struct sp_host *, struct sp_buf *out); int sp_host_add_transport(struct sp_host *, const char *name, struct sp_transport); struct sp_transport *sp_host_transport(struct sp_host *, const char *name); + +/* ---- provider: quota/usage/burst policy, pluggable (per key, shared state) ---- */ +enum sp_prov_decision { SP_PROV_ADMIT = 0, SP_PROV_DELAY, SP_PROV_WAIT_QUOTA, SP_PROV_DENY }; +struct sp_prov_result { + enum sp_prov_decision decision; + long retry_after_s; /* seconds to wait (DELAY) */ + long ready_at; /* unix timestamp when quota/backoff ends (WAIT_QUOTA) */ + char reason[256]; +}; +struct sp_provider_ops { + void *ctx; + int (*preflight)(void *ctx, const char *provider, const char *key_id, + struct sp_prov_result *out); + void (*account)(void *ctx, const char *provider, const char *key_id, + long http_status, size_t tokens_in, size_t tokens_out); +}; +void sp_host_set_provider(struct sp_host *, const struct sp_provider_ops *); +enum sp_prov_decision sp_host_provider_preflight(struct sp_host *, const char *provider, + const char *key_id, struct sp_prov_result *out); +void sp_host_provider_account(struct sp_host *, const char *provider, const char *key_id, + long http_status, size_t tokens_in, size_t tokens_out); + +/* shared per-(provider,key_id) usage/quota state (~/.splinter/providers/...), flock+atomic. + * Provider plugins use this for cross-instance, per-key tracking. */ +struct sp_prov_state { + long quota_ready_at; long backoff_until; + unsigned req_count; unsigned long tok_in, tok_out; + long last_status, last_update, last_429_at; + char note[128]; +}; +int sp_provstate_load(const char *provider, const char *key_id, struct sp_prov_state *out); +int sp_provstate_update(const char *provider, const char *key_id, + void (*fn)(struct sp_prov_state *s, void *ctx), void *ctx); +void sp_provstate_account(const char *provider, const char *key_id, + long http_status, size_t tok_in, size_t tok_out, long retry_after_s); +int sp_provstate_preflight(const char *provider, const char *key_id, + long now, long *ready_at, char *reason, size_t reason_cap); +/* Stable fingerprint of a secret key (never stores/returns the secret). */ +char *sp_key_fingerprint(const char *secret, char *buf, size_t cap); + int sp_host_compact(struct sp_host *, struct sp_conv *, size_t budget); size_t sp_host_compaction_stats(struct sp_host *, size_t *compactions, size_t *failed, unsigned *turns); @@ -180,6 +228,11 @@ struct sp_registry *sp_host_registry(struct sp_host *); struct sp_host *sp_host_new(struct sp_registry *, struct sp_agent *, struct sp_session_info *); void sp_host_free(struct sp_host *); +const char *sp_host_session_dir(struct sp_host *); +/* Retry a durable delegation job (scheduler/worker). 0 on handled (see out). */ +int sp_delegate_retry_job(const char *id, int force, struct sp_buf *out); +/* Scheduler tick: retry one due waiting_quota/waiting_poll job if any. */ +int sp_delegate_tick(struct sp_buf *out); int sp_plugin_load(struct sp_host *, const char *path, struct sp_buf *err); size_t sp_host_widget_snapshot(struct sp_host *, char *buf, size_t len); diff --git a/plugins/cli/cli.c b/plugins/cli/cli.c index 15f02a4..2781736 100644 --- a/plugins/cli/cli.c +++ b/plugins/cli/cli.c @@ -12,15 +12,19 @@ * * Configuration is by environment, deliberately: no config file to drift. * - * SPLINTER_CLI_CMD the program, default "claude -p" + * 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 600 + * SPLINTER_CLI_TIMEOUT seconds, default 1800 * * 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 is - * capped at 4 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. + * 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 #include @@ -33,7 +37,7 @@ #include "splinter_plugin.h" #include "i18n.h" -#define OUT_CAP (4u << 20) +#define OUT_CAP (64u << 20) struct cli_cfg { char cmd[512]; @@ -123,18 +127,41 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, } /* - * The program reads the prompt on stdin; timeout guards a hang. Its - * stderr goes to a file next to the prompt: on the terminal it landed in - * the middle of the curses screen, and the error message below promised - * "the program's own stderr" while it quoted stdout. The paths are quoted; - * TMPDIR is the operator's, but a space in it still broke the command. + * 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); - sp_buf_printf(&cmd, "timeout %s %s < ", c->timeout, c->cmd); - if (sh_word(&cmd, path) != 0 || sp_buf_puts(&cmd, " 2> ") != 0 || - sh_word(&cmd, errpath) != 0) { - unlink(path); - goto fail; + 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) { @@ -147,12 +174,8 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, size_t got; while ((got = fread(chunk, 1, sizeof(chunk), p)) > 0) { - if (raw.len + got > OUT_CAP) { - sp_buf_puts(err, "cli: output over 4 MiB, aborted"); - pclose(p); - unlink(path); - goto fail; - } + if (raw.len + got > OUT_CAP) + break; if (sp_buf_add(&raw, chunk, got) != 0) { pclose(p); unlink(path); @@ -225,7 +248,7 @@ cli_init(struct sp_host *h) 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 : "600"); + to != NULL && *to != '\0' ? to : "1800"); cfg.full = full != NULL && strcmp(full, "0") != 0; tr.send = cli_send; diff --git a/plugins/cps/cps.c b/plugins/cps/cps.c index 061a0ef..f97d36d 100644 --- a/plugins/cps/cps.c +++ b/plugins/cps/cps.c @@ -93,9 +93,13 @@ cps_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, * Comparing against cps.n, which stops at SNAP_MAX, meant that past 256 * messages no plan ever applied - compaction just stopped. */ + if (budget == 0) { + pthread_mutex_unlock(&cps.lock); + return 0; /* no byte budget: nothing to do */ + } if (cps.ready && cps.total == conv->n && cps.bytes == sp_conv_bytes(conv) && - (budget == 0 || sp_conv_bytes(conv) > budget)) { + sp_conv_bytes(conv) > budget) { apply = 1; } else { pthread_mutex_unlock(&cps.lock); diff --git a/plugins/focus/focus.c b/plugins/focus/focus.c index 436c4b9..78023c0 100644 --- a/plugins/focus/focus.c +++ b/plugins/focus/focus.c @@ -22,6 +22,7 @@ * not appended after it: the model then reads goal -> request and answers the * request, instead of reading the request and treating the goal as a reply. */ +#include #include #include #include @@ -32,6 +33,13 @@ #define GOAL_MAX 1000 +/* + * goal, force and reminders are shared by three threads: /goal and /recap run + * on the UI thread, the compactor on the turn thread, the tick on its own. + * One lock for all of them; the tick used to read the goal while /goal was + * rewriting it. + */ +static pthread_mutex_t focus_lock = PTHREAD_MUTEX_INITIALIZER; static char goal[GOAL_MAX + 1]; static unsigned every = 5; static unsigned last_reminder; @@ -47,21 +55,27 @@ focus_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, struct sp_msg m; size_t at; + char g[GOAL_MAX + 1]; + (void)budget; (void)h; - if (goal[0] == '\0' || conv == NULL || conv->n == 0) + if (conv == NULL || conv->n == 0) return 0; - if (!force && (turn == 0 || (turn % every) != 0)) + pthread_mutex_lock(&focus_lock); + if (goal[0] == '\0' || (!force && (turn == 0 || (turn % every) != 0)) || + turn == last_reminder) { /* one reminder per turn, always */ + pthread_mutex_unlock(&focus_lock); return 0; - if (turn == last_reminder) - return 0; /* one reminder per turn, always */ + } + snprintf(g, sizeof(g), "%s", goal); + pthread_mutex_unlock(&focus_lock); { char rem[1024]; snprintf(rem, sizeof(rem), sp_td("focus.reminder", "Before answering, check whether the last step moved closer " - "to the goal. If not, say so and name the next step. Goal: %s"), goal); + "to the goal. If not, say so and name the next step. Goal: %s"), g); snprintf(text, sizeof(text), "[focus] %s", rem); } @@ -77,11 +91,13 @@ focus_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, if (sp_conv_insert(conv, at, &m) != 0) return -1; + pthread_mutex_lock(&focus_lock); last_reminder = turn; force = 0; reminders++; snprintf(widget_text, sizeof(widget_text), "%u reminders, every %u turns", reminders, every); + pthread_mutex_unlock(&focus_lock); return 1; } @@ -94,13 +110,19 @@ static int focus_command(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx) { + char g[GOAL_MAX + 1]; + unsigned n; + (void)ctx; + pthread_mutex_lock(&focus_lock); if (args == NULL || *args == '\0') { - if (goal[0] == '\0') + snprintf(g, sizeof(g), "%s", goal); + n = reminders; + pthread_mutex_unlock(&focus_lock); + if (g[0] == '\0') return sp_buf_puts(out, sp_td("focus.none", "no goal set (/goal )")); return sp_buf_printf(out, sp_td("focus.status", - "goal: %s (%u reminders, every %u turns)"), goal, - reminders, every); + "goal: %s (%u reminders, every %u turns)"), g, n, every); } snprintf(goal, sizeof(goal), "%.*s", GOAL_MAX, args); if (strlen(args) > GOAL_MAX) @@ -108,15 +130,17 @@ focus_command(struct sp_host *h, const char *args, struct sp_buf *out, reminders = 0; last_reminder = 0; force = 0; + snprintf(g, sizeof(g), "%s", goal); + pthread_mutex_unlock(&focus_lock); /* publish now, so the sidebar does not wait for the next tick */ { char line[192]; - snprintf(line, sizeof(line), "%.60s%s", goal, - strlen(goal) > 60 ? "..." : ""); + snprintf(line, sizeof(line), "%.60s%s", g, + strlen(g) > 60 ? "..." : ""); (void)sp_host_widget_text(h, "focus", line); } - return sp_buf_printf(out, sp_td("focus.set", "goal set: %s"), goal); + return sp_buf_printf(out, sp_td("focus.set", "goal set: %s"), g); } static int @@ -126,10 +150,15 @@ recap_command(struct sp_host *h, const char *args, struct sp_buf *out, (void)h; (void)args; (void)ctx; - if (goal[0] == '\0') + pthread_mutex_lock(&focus_lock); + if (goal[0] == '\0') { + pthread_mutex_unlock(&focus_lock); return sp_buf_puts(out, sp_td("focus.none", "no goal set (/goal )")); + } force = 1; /* the next turn gets a reminder */ - return sp_buf_puts(out, "Erinnerung fuer den naechsten Turn eingeplant"); + pthread_mutex_unlock(&focus_lock); + return sp_buf_puts(out, sp_td("focus.recap", + "reminder scheduled for the next turn")); } static int @@ -138,12 +167,14 @@ focus_tick(struct sp_host *h, const char *name, void *ctx) char line[192]; (void)ctx; + pthread_mutex_lock(&focus_lock); if (goal[0] == '\0') snprintf(line, sizeof(line), "%s", sp_td("focus.widget_none", "no goal (/goal )")); else - snprintf(line, sizeof(line), "%.44s%s | %u", - goal, strlen(goal) > 44 ? "..." : "", reminders); + snprintf(line, sizeof(line), "%.44s%s | %u", + goal, strlen(goal) > 44 ? "..." : "", reminders); + pthread_mutex_unlock(&focus_lock); return sp_host_widget_text(h, name, line); } diff --git a/plugins/lcm/lcm.c b/plugins/lcm/lcm.c index 591d6c8..c8192d2 100644 --- a/plugins/lcm/lcm.c +++ b/plugins/lcm/lcm.c @@ -45,8 +45,10 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, (void)h; if (conv == NULL || conv->n <= KEEP_TAIL + 1) return 0; + if (budget == 0) + return 0; /* no byte budget: nothing to do */ bytes = sp_conv_bytes(conv); - if (budget > 0 && bytes <= budget) + if (bytes <= budget) return 0; /* fits: nothing to do */ /* a leading system prompt stays; everything else may go */ diff --git a/plugins/planner/planner.c b/plugins/planner/planner.c new file mode 100644 index 0000000..d02258d --- /dev/null +++ b/plugins/planner/planner.c @@ -0,0 +1,345 @@ +/* + * splinter -- persistent session plan/tasks (/tasks), distinct from background jobs. + * + * Session-scoped task list persisted in /plan_tasks.json. + * Model tools add/update tasks; /tasks controls focus/work selection. + * Integrates with /goal (focus plugin) to prevent drift. + */ +#include +#include +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "splinter_plugin.h" + +#define PT_MAX 128 +#define PT_DESC 1024 + +struct ptask { + int id; + char status[24]; /* todo, doing, done, blocked, waiting_quota */ + char desc[PT_DESC]; + char run_after[64]; /* unix ts or empty; auto-schedule hint */ + char note[256]; + long created, updated; + int active; +}; + +static struct sp_host *host_ref; +static struct ptask tasks[PT_MAX]; +static size_t ntasks; +static int next_id = 1; +static int current_id = -1; +static char session_dir[512]; + +static const char *store_path(void) { + static char p[600]; + if (!session_dir[0]) return NULL; + snprintf(p, sizeof(p), "%s/plan_tasks.json", session_dir); + return p; +} + +static void ensure_dir(void) { + const char *d = sp_host_session_dir(host_ref); + if (d && *d) snprintf(session_dir, sizeof(session_dir), "%s", d); +} + +static void save_tasks(void) { + FILE *f; size_t i; const char *p; + ensure_dir(); p = store_path(); if (!p) return; + f = fopen(p, "w"); if (!f) return; + fprintf(f, "[\n"); + for (i = 0; i < ntasks; i++) { + struct ptask *t = &tasks[i]; + /* minimal json; escape quotes/newlines crudely */ + char esc[PT_DESC*2]; size_t j=0,k; + for (k=0; t->desc[k] && j+6 < sizeof(esc); k++) { + char c=t->desc[k]; + if (c=='"'||c=='\\') { esc[j++]='\\'; esc[j++]=c; } + else if (c=='\n') { esc[j++]='\\'; esc[j++]='n'; } + else if ((unsigned char)c >= 32) esc[j++]=c; + else esc[j++]=' '; + } + esc[j]='\0'; + fprintf(f, " %s{\"id\":%d,\"status\":\"%s\",\"desc\":\"%s\",\"run_after\":\"%s\",\"note\":\"%s\",\"created\":%ld,\"updated\":%ld}%s\n", + i?",":"", t->id, t->status, esc, t->run_after, t->note, t->created, t->updated, (i+1status,sizeof(t->status),"todo"); + t->id=load_int(obj,"id"); if(t->id<=0) t->id=next_id; + load_str(obj,"status",t->status,sizeof(t->status)); + load_str(obj,"desc",t->desc,sizeof(t->desc)); + load_str(obj,"run_after",t->run_after,sizeof(t->run_after)); + load_str(obj,"note",t->note,sizeof(t->note)); + t->created=load_int(obj,"created"); t->updated=load_int(obj,"updated"); + if(t->id>=next_id) next_id=t->id+1; + if(strcmp(t->status,"doing")==0) current_id=t->id; + ntasks++; + p=end+1; + } +} + +static struct ptask *find_task(int id) { + size_t i; for(i=0;i0) snprintf(b,sizeof(b),"/tasks: #%d active | todo %d doing %d done %d", current_id,todo,doing,done); + else snprintf(b,sizeof(b),"/tasks: %zu tasks | todo %d doing %d done %d", ntasks,todo,doing,done); + sp_host_widget_text(host_ref,"plan",b); +} + +static void focus_task(struct ptask *t) { + struct sp_buf out; + if(!t||!host_ref) return; + if(sp_buf_init(&out)!=0) return; + /* set /goal via focus plugin command */ + sp_host_command(host_ref, "goal", t->desc, &out); + sp_buf_free(&out); +} + +static int tool_add(const char *args, struct sp_buf *out, void *ctx) { + char desc[PT_DESC], ra[64]; struct ptask *t; + (void)ctx; ensure_dir(); load_tasks(); + desc[0]=ra[0]='\0'; + jstr(args,"description",desc,sizeof(desc)); + if(!desc[0]) jstr(args,"desc",desc,sizeof(desc)); + if(!desc[0]) jstr(args,"task",desc,sizeof(desc)); + if(!desc[0]){ return sp_buf_puts(out,"error: description required"); } + if(ntasks>=PT_MAX){ return sp_buf_puts(out,"error: task limit"); } + t=&tasks[ntasks++]; memset(t,0,sizeof(*t)); + t->id=next_id++; snprintf(t->status,sizeof(t->status),"todo"); + snprintf(t->desc,sizeof(t->desc),"%.1023s",desc); + jstr(args,"run_after",ra,sizeof(ra)); + if(ra[0]) { char ra2[64]; parse_run_after(ra,ra2,sizeof(ra2)); snprintf(t->run_after,sizeof(t->run_after),"%.63s",ra2); } + t->created=t->updated=(long)time(NULL); + save_tasks(); publish_widget(); + sp_buf_printf(out,"added plan task #%d: %s\n", t->id, t->desc); + return 0; +} + +static int tool_list(const char *args, struct sp_buf *out, void *ctx) { + size_t i; (void)args;(void)ctx; ensure_dir(); load_tasks(); + if(ntasks==0) return sp_buf_puts(out,"(no plan tasks) use plan_task_add\n"); + sp_buf_puts(out,"plan tasks (session-persistent):\n"); + for(i=0;iid, t->status, + (t->id==current_id)?" *":"", t->desc, + t->run_after[0]?" (run_after=":"", t->run_after, t->run_after[0]?")":"", t->note[0]?" #":"", t->note[0]?t->note:""); + } + sp_buf_puts(out,"use /tasks work | /tasks all | /tasks choose\n"); + return 0; +} + +static int tool_update(const char *args, struct sp_buf *out, void *ctx) { + char ids[32], st[24], desc[PT_DESC], ra[64], note[256]; int id; struct ptask *t; + (void)ctx; ensure_dir(); load_tasks(); + ids[0]=st[0]=desc[0]=ra[0]=note[0]='\0'; + jstr(args,"id",ids,sizeof(ids)); if(!ids[0]) jstr(args,"task_id",ids,sizeof(ids)); + id = ids[0]?atoi(ids):0; + if(id<=0){ return sp_buf_puts(out,"error: id required"); } + t=find_task(id); if(!t){ sp_buf_printf(out,"error: no task #%d\n",id); return 0; } + jstr(args,"status",st,sizeof(st)); + jstr(args,"description",desc,sizeof(desc)); if(!desc[0]) jstr(args,"desc",desc,sizeof(desc)); + if(jstr(args,"run_after",ra,sizeof(ra))==NULL && strstr(args,"run_after")) ra[0]='\0'; /* allow clear */ + else jstr(args,"run_after",ra,sizeof(ra)); + jstr(args,"note",note,sizeof(note)); + if(st[0]){ + snprintf(t->status,sizeof(t->status),"%.23s",st); + if(strcmp(st,"doing")==0){ current_id=t->id; focus_task(t); } + else if(current_id==t->id && strcmp(st,"doing")!=0) current_id=-1; + } + if(desc[0]) snprintf(t->desc,sizeof(t->desc),"%.1023s",desc); + if(strstr(args,"run_after")) { char ra2[64]; if(ra[0]) parse_run_after(ra,ra2,sizeof(ra2)); else ra2[0]='\0'; snprintf(t->run_after,sizeof(t->run_after),"%.63s",ra2); } + if(note[0]) snprintf(t->note,sizeof(t->note),"%.255s",note); + t->updated=(long)time(NULL); + save_tasks(); publish_widget(); + sp_buf_printf(out,"task #%d -> [%s] %s\n", t->id, t->status, t->desc); + return 0; +} + +static void mark_doing(struct ptask *t){ + size_t i; + for(i=0;istatus,sizeof(t->status),"doing"); current_id=t->id; t->updated=(long)time(NULL); focus_task(t); } + else current_id=-1; +} + +static int cmd_tasks(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx){ + (void)ctx; host_ref=h; ensure_dir(); load_tasks(); + if(!args||!*args||strcmp(args,"ls")==0||strcmp(args,"list")==0) return tool_list(NULL,out,NULL); + if(strncmp(args,"add ",4)==0){ + struct sp_buf a; if(sp_buf_init(&a)!=0) return -1; + sp_buf_printf(&a,"{\"description\":\"%s\"}", args+4); + { int rc=tool_add(a.p,out,NULL); sp_buf_free(&a); return rc; } + } + if(strncmp(args,"work",4)==0){ + const char *p=args+4; while(*p==' ') p++; + if(strcmp(p,"all")==0){ + struct ptask *t=next_todo(); + if(!t) return sp_buf_puts(out,"no todo tasks left\n"); + mark_doing(t); save_tasks(); publish_widget(); + return sp_buf_printf(out,"working all: started with #%d [%s] %s\n(complete it, then /tasks choose/next)\n", t->id,t->status,t->desc); + } + if(*p){ + int id=atoi(p); struct ptask *t=find_task(id); + if(!t) return sp_buf_printf(out,"no task #%d\n", id); + mark_doing(t); save_tasks(); publish_widget(); + return sp_buf_printf(out,"working on #%d: %s\n(goal/focus set; avoid drift)\n", t->id, t->desc); + } + } + if(strcmp(args,"choose")==0||strcmp(args,"next")==0){ + struct ptask *t=next_todo(); + if(!t) return sp_buf_puts(out,"no todo tasks\n"); + mark_doing(t); save_tasks(); publish_widget(); + return sp_buf_printf(out,"chose #%d: %s\n", t->id, t->desc); + } + if(strncmp(args,"done",4)==0){ + int id=current_id; const char *p=args+4; while(*p==' ') p++; if(*p) id=atoi(p); + struct ptask *t=find_task(id); + if(!t) return sp_buf_puts(out,"no current/task to mark done\n"); + snprintf(t->status,sizeof(t->status),"done"); t->updated=(long)time(NULL); + if(current_id==id) current_id=-1; + save_tasks(); publish_widget(); + return sp_buf_printf(out,"task #%d done\n", id); + } + if(strncmp(args,"wait",4)==0 || strncmp(args,"quota",5)==0){ + const char *p = args + (args[0]=='q'?5:4); + int id = 0; + char ra[64], ra2[64]; + ra[0]='\0'; ra2[0]='\0'; + while(*p==' ') p++; + id = atoi(p); + while(*p && *p!=' ') p++; + while(*p==' ') p++; + if(*p) { + size_t n=0; + while(*p && *p!=' ' && n+1status,sizeof(t->status),"waiting_quota"); + snprintf(t->run_after,sizeof(t->run_after),"%.63s",ra2); + if(*p) snprintf(t->note,sizeof(t->note),"%.200s",p); + else snprintf(t->note,sizeof(t->note),"quota wait (auto-scheduled)"); + t->updated=(long)time(NULL); + if(current_id==id) current_id=-1; + save_tasks(); publish_widget(); + return sp_buf_printf(out,"task #%d waiting_quota run_after=%s (auto-scheduled)\n", id, t->run_after); + } + } + return sp_buf_puts(out,"usage: /tasks [ls|add |work |work all|choose|next|done [id]|wait <+secs|epoch> [note]]\n"); +} + +static int tick(struct sp_host *h, const char *name, void *c){ + long now = (long)time(NULL); size_t i; int changed=0; + (void)name;(void)c; host_ref=h; ensure_dir(); load_tasks(); + for(i=0;istatus,"waiting_quota")==0 && t->run_after[0]){ + long ra = strtol(t->run_after,NULL,10); + if(ra>0 && now >= ra){ + snprintf(t->status,sizeof(t->status),"todo"); + snprintf(t->note,sizeof(t->note),"quota ready, auto-scheduled"); + t->run_after[0]='\0'; t->updated=now; changed=1; + } + } + } + if(changed) save_tasks(); + publish_widget(); return 0; +} + +static const struct sp_tool t_add = {"plan_task_add","Add a persistent session plan task (distinct from background jobs). Args: description, optional run_after(unix ts for quota/auto-schedule).","{\"type\":\"object\",\"properties\":{\"description\":{\"type\":\"string\"},\"run_after\":{\"type\":\"string\"}},\"required\":[\"description\"]}", SP_AUTH_MUTATE, tool_add, NULL}; +static const struct sp_tool t_list = {"plan_task_list","List persistent session plan tasks (/tasks).","{\"type\":\"object\",\"properties\":{}}", SP_AUTH_READ, tool_list, NULL}; +static const struct sp_tool t_upd = {"plan_task_update","Update a session plan task. Args: id, status(todo|doing|done|blocked|waiting_quota), description, run_after, note.","{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"},\"status\":{\"type\":\"string\"},\"description\":{\"type\":\"string\"},\"run_after\":{\"type\":\"string\"},\"note\":{\"type\":\"string\"}},\"required\":[\"id\"]}", SP_AUTH_MUTATE, tool_update, NULL}; +static const struct sp_widget w = {"plan", tick, NULL, NULL, 5000}; + +static int init(struct sp_host *h){ + host_ref=h; ensure_dir(); load_tasks(); publish_widget(); + sp_host_add_tool(h,&t_add); sp_host_add_tool(h,&t_list); sp_host_add_tool(h,&t_upd); + sp_host_add_command(h,"tasks",cmd_tasks,NULL); + sp_host_add_widget(h,&w); + return 0; +} +static const struct sp_plugin plugin = {SP_PLUGIN_ABI,"planner","0.1",init,NULL,NULL}; +const struct sp_plugin *sp_plugin_describe(void){ return &plugin; } diff --git a/plugins/provider/provider.c b/plugins/provider/provider.c new file mode 100644 index 0000000..7678f9e --- /dev/null +++ b/plugins/provider/provider.c @@ -0,0 +1,277 @@ +/* + * splinter -- provider adapters (OpenCode/Ollama/openai-compat), per-key quota/usage. + * + * Plugin-format adapters: dispatch by tr.provider ("opencode","ollama","openai-compat"). + * Shared per-(provider,key_id) state in ~/.splinter/providers/ (flock+atomic), so + * multiple instances sharing a key see the same quota/burst view. + * + * - preflight: blocks on quota_ready_at; short backoff delays (<=30s) allowed by caller. + * - account: records status/tokens; 429/402/529 -> quota wait (Retry-After honored by + * transport/agent when known; defaults here). 503/408 -> short backoff. + * - Ollama (local): quota gating relaxed (transient/backoff only) unless explicit quota. + * - OpenCode/cloud: quota exhausted -> WAIT_QUOTA with ready_at; "quota back in N days" + * surfaced via reason/note and durable delegation jobs (waiting_quota+run_after) + + * scheduler auto-retry. Optional probe via SPLINTER_QUOTA_PROBE_URL (GET, bearer from + * SPLINTER_QUOTA_PROBE_KEY) when SPLINTER_PROVIDER_PROBE=1. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "splinter_plugin.h" + +static int is_ollama(const char *p) { return p && strcmp(p,"ollama")==0; } +static int is_opencode(const char *p){ return p && (strcmp(p,"opencode")==0 || strcmp(p,"open-code")==0); } + +struct probe_apply { long ready; long now; }; +static void probe_apply_fn(struct sp_prov_state *s, void *p){ + struct probe_apply *c=p; + if (c->ready > s->quota_ready_at) s->quota_ready_at = c->ready; + if (c->ready > 0) snprintf(s->note,sizeof(s->note),"quota probe ready_at=%ld", c->ready); + s->last_update = c->now; +} +static void probe_apply(const char *provider, const char *key_id, long ready){ + struct probe_apply c; c.ready=ready; c.now=(long)time(NULL); + sp_provstate_update(provider,key_id,probe_apply_fn,&c); +} + +static void run_probe(const char *provider, const char *key_id) +{ + const char *on = getenv("SPLINTER_PROVIDER_PROBE"); + const char *url = getenv("SPLINTER_QUOTA_PROBE_URL"); + const char *key = getenv("SPLINTER_QUOTA_PROBE_KEY"); + const char *kenv = getenv("SPLINTER_QUOTA_PROBE_KEY_ENV"); + char buf[4096]; + size_t n = 0; + long ready = 0, ra = 0; + const char *q; + int in_pipe[2], out_pipe[2], devnull; + pid_t pid; + int st = 0; + char cfg[4096]; + size_t off = 0, len; + ssize_t wr, rd; + + if (!on || strcmp(on, "1") != 0 || !url || !*url) return; + if ((!key || !*key) && kenv && *kenv) key = getenv(kenv); + if (strncmp(url, "http://", 7) != 0 && strncmp(url, "https://", 8) != 0) return; + if (strpbrk(url, "\"\\\n\r") != NULL) return; + if (key && *key && strpbrk(key, "\"\\\n\r") != NULL) return; + + if (pipe(in_pipe) != 0) return; + if (pipe(out_pipe) != 0) { + close(in_pipe[0]); + close(in_pipe[1]); + return; + } + pid = fork(); + if (pid < 0) { + close(in_pipe[0]); close(in_pipe[1]); + close(out_pipe[0]); close(out_pipe[1]); + return; + } + if (pid == 0) { + char *const argv[] = {"curl", "-fsS", "-m", "10", "-K", "-", NULL}; + dup2(in_pipe[0], 0); + dup2(out_pipe[1], 1); + devnull = open("/dev/null", O_WRONLY); + if (devnull >= 0) { + dup2(devnull, 2); + close(devnull); + } + close(in_pipe[0]); close(in_pipe[1]); + close(out_pipe[0]); close(out_pipe[1]); + execvp(argv[0], argv); + _exit(127); + } + + close(in_pipe[0]); + close(out_pipe[1]); + len = (size_t)snprintf(cfg, sizeof(cfg), "url = \"%s\"\n", url); + if (len < sizeof(cfg) && key && *key) { + int m = snprintf(cfg + len, sizeof(cfg) - len, + "header = \"Authorization: Bearer %s\"\n", key); + len = (m < 0 || (size_t)m >= sizeof(cfg) - len) ? sizeof(cfg) : len + (size_t)m; + } + /* An over-long config is never sent: curl then reads an empty config and + * fails, and the exit status below discards the result. */ + if (len >= sizeof(cfg)) + len = 0; + { + void (*old_pipe)(int) = signal(SIGPIPE, SIG_IGN); + off = 0; + while (off < len) { + wr = write(in_pipe[1], cfg + off, len - off); + if (wr <= 0) break; + off += (size_t)wr; + } + close(in_pipe[1]); + signal(SIGPIPE, old_pipe); + } + + n = 0; + for (;;) { + char rbuf[1024]; + rd = read(out_pipe[0], rbuf, sizeof(rbuf)); + if (rd <= 0) break; + if (n < sizeof(buf) - 1) { + size_t take = (size_t)rd; + if (take > sizeof(buf) - 1 - n) take = sizeof(buf) - 1 - n; + memcpy(buf + n, rbuf, take); + n += take; + } + } + buf[n] = '\0'; + close(out_pipe[0]); + while (waitpid(pid, &st, 0) < 0 && errno == EINTR) + ; + + if (WIFEXITED(st) && WEXITSTATUS(st) == 0) { + q = strstr(buf, "\"quota_ready_at\""); if (q) { q = strchr(q, ':'); if (q) ready = strtol(q + 1, NULL, 10); } + q = strstr(buf, "\"retry_after\""); if (q) { q = strchr(q, ':'); if (q) ra = strtol(q + 1, NULL, 10); } + if (ready <= 0 && ra > 0) ready = (long)time(NULL) + ra; + if (ready > 0) probe_apply(provider, key_id, ready); + } +} + +static int +prov_preflight(void *ctx, const char *provider, const char *key_id, + struct sp_prov_result *out) +{ + long now = (long)time(NULL); + long ready = 0; + int r; + (void)ctx; + if (!out) return 0; + out->decision = SP_PROV_ADMIT; + if (!provider || !*provider || !key_id || !*key_id) + return 0; + /* ollama local: no cloud quota gating unless state explicitly says quota */ + if (is_ollama(provider)) { + struct sp_prov_state st; + if (sp_provstate_load(provider,key_id,&st)==0 && st.quota_ready_at > now) { + out->decision = SP_PROV_WAIT_QUOTA; + out->ready_at = st.quota_ready_at; + out->retry_after_s = st.quota_ready_at - now; + snprintf(out->reason,sizeof(out->reason),"ollama quota/backoff until %ld", st.quota_ready_at); + } + return 0; + } + r = sp_provstate_preflight(provider, key_id, now, &ready, + out->reason, sizeof(out->reason)); + if (r == 1) { + out->decision = SP_PROV_WAIT_QUOTA; + out->ready_at = ready; + out->retry_after_s = ready > now ? ready - now : 0; + if (out->retry_after_s > 3600) + snprintf(out->reason, sizeof(out->reason), + "%s quota exhausted: wait ~%ldh (ready_at=%ld), auto-scheduled when quota returns", + is_opencode(provider)?"opencode":"provider", + out->retry_after_s/3600, ready); + else if (!out->reason[0]) + snprintf(out->reason, sizeof(out->reason), + "quota/backoff until %ld (auto-schedule)", ready); + /* optional probe to refine ready_at */ + run_probe(provider, key_id); + } else if (r == 2) { + out->decision = SP_PROV_DELAY; + out->ready_at = ready; + out->retry_after_s = ready > now ? ready - now : 0; + } + return 0; +} + +static void +prov_account(void *ctx, const char *provider, const char *key_id, + long http_status, size_t tokens_in, size_t tokens_out) +{ + long ra = 0; + (void)ctx; + if (!provider || !*provider || !key_id || !*key_id) + return; + if (is_ollama(provider) && (http_status==429||http_status==402||http_status==529)) { + /* local ollama shouldn't quota like cloud, but handle gracefully */ + ra = 30; + } + /* retry_after_s: transport/agent apply parsed Retry-After via quota_hint/provstate; + * here we record status/tokens and apply status-based defaults. */ + sp_provstate_account(provider, key_id, http_status, tokens_in, tokens_out, ra); + /* on quota exhaustion, probe for accurate ready_at (opt-in) */ + if (http_status==429 || http_status==402 || http_status==529) + run_probe(provider, key_id); +} + +static const struct sp_provider_ops ops = { .ctx=NULL, .preflight=prov_preflight, .account=prov_account }; + +static void fmt_dur(long s, char *out, size_t cap){ + if(s>=86400) snprintf(out,cap,"%ldd%ldh",s/86400,(s%86400)/3600); + else if(s>=3600) snprintf(out,cap,"%ldh%ldm",s/3600,(s%3600)/60); + else snprintf(out,cap,"%lds",s); +} + +static int +cmd_quota(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx) +{ + char dir[512]; DIR *dp; struct dirent *prov; + const char *home = getenv("HOME"); + long now=(long)time(NULL); + (void)h;(void)args;(void)ctx; + if(!home) home="/tmp"; + snprintf(dir,sizeof(dir),"%s/.splinter/providers", home); + sp_buf_puts(out,"per-key provider quota/usage (shared):\n"); + dp=opendir(dir); + if(!dp){ sp_buf_puts(out," (no provider state yet)\n"); return 0; } + while((prov=readdir(dp))!=NULL){ + char pdir[600]; DIR *dp2; struct dirent *kf; + if(prov->d_name[0]=='.') continue; + snprintf(pdir,sizeof(pdir),"%.300s/%.255s",dir,prov->d_name); + dp2=opendir(pdir); if(!dp2) continue; + while((kf=readdir(dp2))!=NULL){ + char *dot, path[700], kid[64]; struct sp_prov_state st; char dur[32]; + if(kf->d_name[0]=='.') continue; + dot=strstr(kf->d_name,".json"); if(!dot) continue; + { size_t kl=(size_t)(dot-kf->d_name); if(kl>=sizeof(kid)) kl=sizeof(kid)-1; memcpy(kid,kf->d_name,kl); kid[kl]='\0'; } + snprintf(path,sizeof(path),"%.400s/%.255s",pdir,kf->d_name); + (void)path; + if(sp_provstate_load(prov->d_name,kid,&st)==0){ + sp_buf_printf(out," %s/%s req=%u tok=%lu/%lu status=%ld", + prov->d_name,kid,st.req_count,st.tok_in,st.tok_out,st.last_status); + if(st.quota_ready_at>now){ fmt_dur(st.quota_ready_at-now,dur,sizeof(dur)); sp_buf_printf(out," WAIT_QUOTA %s (ready_at=%ld)",dur,st.quota_ready_at); } + else if(st.backoff_until>now){ fmt_dur(st.backoff_until-now,dur,sizeof(dur)); sp_buf_printf(out," backoff %s",dur); } + if(st.note[0]) sp_buf_printf(out," [%s]",st.note); + sp_buf_puts(out,"\n"); + } + } + closedir(dp2); + } + closedir(dp); + sp_buf_puts(out,"adapters: opencode, ollama, openai-compat (per-key). probe: SPLINTER_PROVIDER_PROBE=1 + SPLINTER_QUOTA_PROBE_URL/KEY.\n"); + return 0; +} + +static int +provider_init(struct sp_host *h) +{ + sp_host_set_provider(h, &ops); + sp_host_add_command(h, "quota", cmd_quota, NULL); + return 0; +} + +static const struct sp_plugin plugin = { + SP_PLUGIN_ABI, "provider", "0.2", provider_init, NULL, NULL +}; + +const struct sp_plugin * +sp_plugin_describe(void) +{ + return &plugin; +} diff --git a/plugins/ring/ring.c b/plugins/ring/ring.c index d9fe488..b982e85 100644 --- a/plugins/ring/ring.c +++ b/plugins/ring/ring.c @@ -21,6 +21,7 @@ * failure: asking the next exit would show the operator a second answer after * half of the first one. */ +#include #include #include #include @@ -38,9 +39,11 @@ struct ring { size_t n; int last; /* which exit served the last turn */ int used[MAX_EXITS]; + /* last and used are written by the turn thread, read by the widget */ + pthread_mutex_t lock; }; -static struct ring ring; +static struct ring ring = { .lock = PTHREAD_MUTEX_INITIALIZER }; /* Pressure - a limit or a provider that is down - is worth another exit. */ static int @@ -89,8 +92,16 @@ build(void) e->key_env : "SPLINTER_API_KEY"; const char *key = getenv(env); - ring.tr[ring.n] = sp_openai_transport(e->endpoint, e->model, - key, sp_host_registry(ring.host), 300); + { + const char *hto = getenv("SPLINTER_HTTP_TIMEOUT"); + long hto_s = hto != NULL && *hto != '\0' ? + strtol(hto, NULL, 10) : 0; + + if (hto_s <= 0) + hto_s = 900; + ring.tr[ring.n] = sp_openai_transport(e->endpoint, e->model, + key, sp_host_registry(ring.host), hto_s); + } if (ring.tr[ring.n].send == NULL) { publish("ring: cannot build an exit"); return -1; @@ -121,8 +132,10 @@ ring_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, rc = r->tr[i].send(r->tr[i].ctx, conv, out, &e); status = out->status; if (rc == 0) { + pthread_mutex_lock(&r->lock); r->last = (int)i; r->used[i]++; + pthread_mutex_unlock(&r->lock); snprintf(line, sizeof(line), "%s (%zu/%zu)", r->cfg->exit[i].label, i + 1, r->n); (void)sp_host_widget_text(r->host, "ring", line); @@ -191,8 +204,10 @@ ring_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, &seen); status = out->status; if (rc == 0) { + pthread_mutex_lock(&r->lock); r->last = (int)i; r->used[i]++; + pthread_mutex_unlock(&r->lock); snprintf(line, sizeof(line), "%s (%zu/%zu)", r->cfg->exit[i].label, i + 1, r->n); (void)sp_host_widget_text(r->host, "ring", line); @@ -232,6 +247,7 @@ ring_widget(struct sp_host *h, const char *name, void *ctx) (void)sp_host_widget_text(ring.host, name, "no exits"); return 0; } + pthread_mutex_lock(&r->lock); snprintf(line, sizeof(line), "%.16s |", r->cfg->exit[r->last].label); for (i = 0; i < r->n; i++) { char bit[16]; @@ -239,6 +255,7 @@ ring_widget(struct sp_host *h, const char *name, void *ctx) snprintf(bit, sizeof(bit), " %d", r->used[i]); strncat(line, bit, sizeof(line) - strlen(line) - 1); } + pthread_mutex_unlock(&r->lock); (void)sp_host_widget_text(ring.host, name, line); return 0; } @@ -257,6 +274,7 @@ ring_init(struct sp_host *h) struct sp_transport t; memset(&ring, 0, sizeof(ring)); + (void)pthread_mutex_init(&ring.lock, NULL); ring.host = h; ring.cfg = sp_host_config(h); if (ring.cfg == NULL || ring.cfg->nexits == 0) { diff --git a/plugins/scheduler/scheduler.c b/plugins/scheduler/scheduler.c new file mode 100644 index 0000000..c99d6fe --- /dev/null +++ b/plugins/scheduler/scheduler.c @@ -0,0 +1,87 @@ +/* + * splinter -- delegation scheduler (auto-retry due jobs). + * + * Ticks periodically and retries one due durable delegation job + * (waiting_quota / waiting_poll / queued with run_after/next_poll_at reached). + * This enables "quota back in N days -> auto-scheduled" when combined with + * provider preflight/account and durable job records. + */ +#include +#include +#include + +#include "splinter.h" +#include "splinter_plugin.h" + +static struct sp_host *host_ref; +static char last_status[256]; +static long last_run; + +static void +publish(struct sp_host *h) +{ + char buf[320]; + if (!h) return; + if (last_status[0]) + snprintf(buf, sizeof(buf), "sched: %s", last_status); + else + snprintf(buf, sizeof(buf), "sched: idle"); + sp_host_widget_text(h, "scheduler", buf); +} + +static int +sched_tick(struct sp_host *h, const char *name, void *ctx) +{ + struct sp_buf out; + long now = (long)time(NULL); + int rc; + (void)name; (void)ctx; + if (now - last_run < 15) + return 0; + last_run = now; + if (sp_buf_init(&out) != 0) + return 0; + rc = sp_delegate_tick(&out); + if (out.p && strstr(out.p, "none due") == NULL) { + snprintf(last_status, sizeof(last_status), "%.200s", + out.p ? out.p : (rc == 0 ? "ok" : "err")); + } else if (last_status[0] == '\0') { + snprintf(last_status, sizeof(last_status), "idle"); + } + sp_buf_free(&out); + publish(h ? h : host_ref); + return 0; +} + +static const struct sp_widget widget = { + "scheduler", + sched_tick, + NULL, + NULL, + 30000 /* 30s */ +}; + +static int +scheduler_init(struct sp_host *h) +{ + host_ref = h; + snprintf(last_status, sizeof(last_status), "idle"); + (void)sp_host_add_widget(h, &widget); + publish(h); + return 0; +} + +static const struct sp_plugin plugin = { + SP_PLUGIN_ABI, + "scheduler", + "0.1", + scheduler_init, + NULL, + NULL +}; + +const struct sp_plugin * +sp_plugin_describe(void) +{ + return &plugin; +} diff --git a/plugins/status/status.c b/plugins/status/status.c index 437e6f9..894ed3a 100644 --- a/plugins/status/status.c +++ b/plugins/status/status.c @@ -56,10 +56,12 @@ render_clock(struct sp_host *h, char *buf, size_t len) static void render_ctx(struct sp_host *h, char *buf, size_t len) { - const struct sp_meter *m = sp_host_meter(h); + struct sp_meter mm; + const struct sp_meter *m = &mm; char used[24], max[24], bar[BAR_WIDTH + 1]; size_t filled = 0, i; + sp_host_meter_get(h, &mm); human(m->ctx_used, used, sizeof(used)); if (m->ctx_max == 0) { snprintf(buf, len, "ctx %s", used); @@ -80,8 +82,10 @@ render_ctx(struct sp_host *h, char *buf, size_t len) static void render_rate(struct sp_host *h, char *buf, size_t len) { - const struct sp_meter *m = sp_host_meter(h); + struct sp_meter mm; + const struct sp_meter *m = &mm; + sp_host_meter_get(h, &mm); if (m->tps <= 0) { buf[0] = '\0'; return; @@ -92,9 +96,11 @@ render_rate(struct sp_host *h, char *buf, size_t len) static void render_tokens(struct sp_host *h, char *buf, size_t len) { - const struct sp_meter *m = sp_host_meter(h); + struct sp_meter mm; + const struct sp_meter *m = &mm; char in[24], out[24]; + sp_host_meter_get(h, &mm); human(m->tok_in, in, sizeof(in)); human(m->tok_out, out, sizeof(out)); snprintf(buf, len, "%s in / %s out", in, out); @@ -103,8 +109,10 @@ render_tokens(struct sp_host *h, char *buf, size_t len) static void render_cost(struct sp_host *h, char *buf, size_t len) { - const struct sp_meter *m = sp_host_meter(h); + struct sp_meter mm; + const struct sp_meter *m = &mm; + sp_host_meter_get(h, &mm); if (price_in == 0 && price_out == 0) { buf[0] = '\0'; return; @@ -122,9 +130,11 @@ render_cost(struct sp_host *h, char *buf, size_t len) static void render_cache(struct sp_host *h, char *buf, size_t len) { - const struct sp_meter *m = sp_host_meter(h); + struct sp_meter mm; + const struct sp_meter *m = &mm; char hit[24]; + sp_host_meter_get(h, &mm); if (m->ctx_used == 0 || m->cached == 0) { buf[0] = '\0'; return; @@ -137,8 +147,10 @@ render_cache(struct sp_host *h, char *buf, size_t len) static void render_tasks(struct sp_host *h, char *buf, size_t len) { - const struct sp_meter *m = sp_host_meter(h); + struct sp_meter mm; + const struct sp_meter *m = &mm; + sp_host_meter_get(h, &mm); if (m->tasks_max == 0) { buf[0] = '\0'; return; diff --git a/plugins/tasks/tasks.c b/plugins/tasks/tasks.c index 08406c8..e92f51c 100644 --- a/plugins/tasks/tasks.c +++ b/plugins/tasks/tasks.c @@ -72,20 +72,26 @@ running_count(void) return n; } +static void +set_task_fields(struct sp_meter *m, void *ctx) +{ + const unsigned *run = ctx; + + m->tasks_running = *run; + m->tasks_max = max_parallel; +} + +/* + * Only the task fields, under the host's lock. A copy of the whole meter, + * changed and written back, raced with the UI doing the same with the token + * fields: whichever wrote last erased the other's update. + */ static void publish_meter(struct sp_host *h) { - struct sp_meter m = *sp_host_meter(h); - int i, run = 0; + unsigned run = (unsigned)running_count(); - pthread_mutex_lock(&tasks_lock); - for (i = 0; i < ntasks; i++) - if (tasks[i].running) - run++; - pthread_mutex_unlock(&tasks_lock); - m.tasks_running = (unsigned)run; - m.tasks_max = max_parallel; - sp_host_set_meter(h, &m); + sp_host_meter_update(h, set_task_fields, &run); } static void @@ -121,6 +127,22 @@ refresh_widget(struct sp_host *h) extern char **environ; +/* + * The end of a task, under tasks_lock: that is the lock task_list, the widget + * and running_count read 'running', 'status' and 'ended' under. They used to + * be written under the task's own lock only - two locks guarding one field + * guard nothing. + */ +static void +task_finish(struct task *t, int status) +{ + pthread_mutex_lock(&tasks_lock); + t->status = status; + t->ended = time(NULL); + t->running = 0; + pthread_mutex_unlock(&tasks_lock); +} + /* * Run the task in its own process group, so task_kill can stop the shell and * everything it started. popen() gave no pid: t->pid stayed 0, and @@ -146,10 +168,8 @@ task_run(void *arg) free(envp); pthread_mutex_lock(&t->lock); sp_buf_printf(&t->out, "error: %s", strerror(errno)); - t->status = 127; - t->running = 0; - t->ended = time(NULL); pthread_mutex_unlock(&t->lock); + task_finish(t, 127); return NULL; } for (i = 0, j = 0; i < n; i++) @@ -179,10 +199,8 @@ task_run(void *arg) close(fds[0]); pthread_mutex_lock(&t->lock); sp_buf_printf(&t->out, "error: fork: %s", strerror(errno)); - t->status = 127; - t->running = 0; - t->ended = time(NULL); pthread_mutex_unlock(&t->lock); + task_finish(t, 127); return NULL; } (void)setpgid(child, child); @@ -206,11 +224,7 @@ task_run(void *arg) pthread_mutex_lock(&tasks_lock); t->pid = 0; /* reaped: the id may be reused */ pthread_mutex_unlock(&tasks_lock); - pthread_mutex_lock(&t->lock); - t->status = st; - t->running = 0; - t->ended = time(NULL); - pthread_mutex_unlock(&t->lock); + task_finish(t, st); return NULL; } diff --git a/plugins/tmux/tmux.c b/plugins/tmux/tmux.c new file mode 100644 index 0000000..1ffec9c --- /dev/null +++ b/plugins/tmux/tmux.c @@ -0,0 +1,377 @@ +/* + * tmux proxy plugin: drives a CLI tool in an underlying tmux session. + * - init checks `tmux` is installed; refuses to load if not. + * - background watcher process detects new pane output and extracts/appends deltas + * to /tmux_watch.log (no fixed sleep in ask; ask waits on the feed). + * Commands: /tmux start |attach |send |keys |capture [n]|ask |read [wait_ms]|watch start|stop|status|stop + * Tools: tmux_start, tmux_send, tmux_capture, tmux_read, tmux_ask, tmux_status, tmux_watch + */ +#define _DEFAULT_SOURCE +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "splinter_plugin.h" + +static struct sp_host *host_ref; +static char target[128]; +static char sess_dir[512]; + +static int have_tmux(void){ + char *a[]={"tmux","-V",NULL}; struct sp_buf o; int rc; + if(sp_buf_init(&o)!=0) return 0; + { int p[2]; pid_t pid; int st=0; char b[64]; ssize_t n; + if(pipe(p)!=0){ sp_buf_free(&o); return 0; } + pid=fork(); + if(pid==0){ dup2(p[1],1); dup2(p[1],2); close(p[0]); close(p[1]); execvp("tmux",a); _exit(127); } + close(p[1]); while((n=read(p[0],b,sizeof(b)))>0) sp_buf_add(&o,b,(size_t)n); close(p[0]); waitpid(pid,&st,0); + rc = (WIFEXITED(st) && WEXITSTATUS(st)==0); + } + sp_buf_free(&o); return rc; +} + +static void ensure_sess(void){ const char *d=sp_host_session_dir(host_ref); if(d&&*d) snprintf(sess_dir,sizeof(sess_dir),"%s",d); } +static void spath(const char *name, char *out, size_t cap){ ensure_sess(); if(sess_dir[0]) snprintf(out,cap,"%s/%s",sess_dir,name); else snprintf(out,cap,"/tmp/splinter-%s",name); } +static void state_path(char *out,size_t cap){ spath("tmux_target",out,cap); } +static void feed_path(char *out,size_t cap){ spath("tmux_watch.log",out,cap); } +static void wpid_path(char *out,size_t cap){ spath("tmux_watch.pid",out,cap); } + +static void save_target(void){ char p[600]; FILE *f; state_path(p,sizeof(p)); f=fopen(p,"w"); if(f){ fprintf(f,"%s\n",target); fclose(f);} } +static void load_target(void){ char p[600]; FILE *f; target[0]='\0'; state_path(p,sizeof(p)); f=fopen(p,"r"); if(f){ if(fgets(target,sizeof(target),f)){ size_t n=strlen(target); while(n&&(target[n-1]=='\n'||target[n-1]=='\r')) target[--n]='\0'; } fclose(f);} } + +static int run_argv(char *const argv[], struct sp_buf *out){ + int pfd[2]; pid_t pid; char buf[4096]; ssize_t n; int st=0; + if(pipe(pfd)!=0) return -1; + pid=fork(); + if(pid<0){ close(pfd[0]); close(pfd[1]); return -1; } + if(pid==0){ dup2(pfd[1],1); dup2(pfd[1],2); close(pfd[0]); close(pfd[1]); execvp(argv[0],argv); _exit(127); } + close(pfd[1]); while((n=read(pfd[0],buf,sizeof(buf)))>0) sp_buf_add(out,buf,(size_t)n); close(pfd[0]); + waitpid(pid,&st,0); return WIFEXITED(st)?WEXITSTATUS(st):-1; +} + +static int tmux_capture_n(const char *tgt, int lines, struct sp_buf *out){ + char sarg[32]; snprintf(sarg,sizeof(sarg),"-%d", lines>0?lines:300); + { char *a[]={"tmux","capture-pane","-t",(char*)tgt,"-p","-S",sarg,NULL}; return run_argv(a,out); } +} +static int tmux_has_session(const char *name){ + char nm[128],*dot; char *a[]={"tmux","has-session","-t",nm,NULL}; struct sp_buf o; int rc; + snprintf(nm,sizeof(nm),"%.120s",name); dot=strchr(nm,':'); if(dot)*dot='\0'; + if(sp_buf_init(&o)!=0) return 0; + rc=run_argv(a,&o); sp_buf_free(&o); return rc==0; +} +static int tmux_send_lit(const char *tgt, const char *text, struct sp_buf *out){ + char *a1[]={"tmux","send-keys","-t",(char*)tgt,"-l","--",(char*)text,NULL}; + char *a2[]={"tmux","send-keys","-t",(char*)tgt,"Enter",NULL}; + int rc=run_argv(a1,out); if(rc==0) rc=run_argv(a2,out); return rc; +} + +/* delta: bytes in neu after the longest common prefix with old (simple, robust enough) */ +static void extract_delta(const char *old, const char *neu, struct sp_buf *out){ + size_t i=0; size_t ol=old?strlen(old):0, nl=neu?strlen(neu):0; + while(i
    0 && kill(pid,0)==0) return pid; } + return -1; +} + +/* watcher child: polls capture-pane, detects new output, appends delta to feed */ +static void watcher_loop(const char *tgt, const char *sd){ + char prev[65536]; size_t prevn=0; char fp[600], sp[600], pp[600]; + prev[0]='\0'; + snprintf(fp,sizeof(fp),"%s/tmux_watch.log",sd); + snprintf(pp,sizeof(pp),"%s/tmux_watch.pid",sd); + snprintf(sp,sizeof(sp),"%s/tmux_watch.state",sd); + { FILE *f=fopen(pp,"w"); if(f){ fprintf(f,"%d\n",(int)getpid()); fclose(f);} } + /* seed prev from current pane so we don't dump history */ + { + struct sp_buf o; if(sp_buf_init(&o)==0){ tmux_capture_n(tgt,300,&o); if(o.p){ size_t n=o.len; if(n>=sizeof(prev)) n=sizeof(prev)-1; memcpy(prev,o.p,n); prev[n]='\0'; prevn=n; } sp_buf_free(&o); } + } + for(;;){ + struct sp_buf cur, d; struct timespec ts; + ts.tv_sec=0; ts.tv_nsec=300*1000*1000; nanosleep(&ts,NULL); + if(!tmux_has_session(tgt)) continue; + if(sp_buf_init(&cur)!=0||sp_buf_init(&d)!=0){ if(cur.p) sp_buf_free(&cur); continue; } + tmux_capture_n(tgt,300,&cur); + if(cur.p && (prevn!=cur.len || memcmp(prev,cur.p, cur.len0){ + FILE *f=fopen(fp,"a"); + if(f){ + /* marker helps consumers; also write raw delta */ + fwrite(d.p,1,d.len,f); + if(d.len==0 || ((char*)d.p)[d.len-1]!='\n') fputc('\n',f); + fflush(f); fclose(f); + } + } + { size_t n=cur.len; if(n>=sizeof(prev)) n=sizeof(prev)-1; memcpy(prev,cur.p,n); prev[n]='\0'; prevn=n; } + { FILE *f=fopen(sp,"w"); if(f){ fprintf(f,"%ld %zu\n",(long)time(NULL),prevn); fclose(f);} } + } + sp_buf_free(&cur); sp_buf_free(&d); + } +} + +static int watcher_start(struct sp_buf *out){ + pid_t pid; char p[600]; + load_target(); ensure_sess(); + if(!target[0]) return sp_buf_puts(out,"error: no tmux target\n"); + if(!sess_dir[0]) return sp_buf_puts(out,"error: no session dir\n"); + if(watcher_pid()>0) return sp_buf_printf(out,"watcher already running (pid %d) for %s\n",(int)watcher_pid(),target); + /* clear feed for a fresh watch session? keep; append is fine */ + pid=fork(); + if(pid<0) return sp_buf_puts(out,"error: fork failed\n"); + if(pid==0){ + /* detach */ + setsid(); + { int fd=open("/dev/null",O_RDWR); if(fd>=0){ dup2(fd,0); dup2(fd,1); dup2(fd,2); if(fd>2) close(fd);} } + watcher_loop(target, sess_dir); + _exit(0); + } + wpid_path(p,sizeof(p)); + sp_buf_printf(out,"watcher started (pid %d) for %s -> %s/tmux_watch.log\n",(int)pid,target,sess_dir); + return 0; +} +static int watcher_stop(struct sp_buf *out){ + pid_t pid=watcher_pid(); char p[600]; + if(pid<=0){ sp_buf_puts(out,"watcher not running\n"); } + else { + kill(pid,SIGTERM); + sp_buf_printf(out,"watcher stopped (pid %d)\n",(int)pid); + } + wpid_path(p,sizeof(p)); unlink(p); + return 0; +} + +/* read new extracted content from watcher feed. offset tracked in tmux_watch.off */ +static long read_off(void){ char p[600],b[64]; FILE *f; long o=0; spath("tmux_watch.off",p,sizeof(p)); f=fopen(p,"r"); if(f){ if(fgets(b,sizeof(b),f)) o=strtol(b,NULL,10); fclose(f);} return o; } +static void write_off(long o){ char p[600]; FILE *f; spath("tmux_watch.off",p,sizeof(p)); f=fopen(p,"w"); if(f){ fprintf(f,"%ld\n",o); fclose(f);} } + +static int tool_read(const char *args, struct sp_buf *out, void *ctx){ + char fp[600]; FILE *f; long off, sz; int wait_ms=0; long start; struct timespec t0; + (void)ctx; ensure_sess(); feed_path(fp,sizeof(fp)); + if(args && strstr(args,"\"wait_ms\"")){ const char *p=strstr(args,"\"wait_ms\""); p=strchr(p,':'); + if(p) wait_ms=atoi(p+1); + } + clock_gettime(CLOCK_MONOTONIC,&t0); start=t0.tv_sec*1000+t0.tv_nsec/1000000; + off=read_off(); sz=file_size(fp); + while(sz<=off && wait_ms>0){ + struct timespec ts; long now; + ts.tv_sec=0; ts.tv_nsec=200*1000*1000; nanosleep(&ts,NULL); + clock_gettime(CLOCK_MONOTONIC,&t0); now=t0.tv_sec*1000+t0.tv_nsec/1000000; + if(now-start >= wait_ms) break; + sz=file_size(fp); + } + if(sz<=off) return sp_buf_puts(out,"(no new watcher output)\n"); + f=fopen(fp,"r"); if(!f) return sp_buf_puts(out,"(no feed)\n"); + fseek(f,off,SEEK_SET); + { + char buf[4096]; size_t n; size_t total=0; + sp_buf_puts(out,"[tmux watcher output]\n"); + while((n=fread(buf,1,sizeof(buf),f))>0){ sp_buf_add(out,buf,n); total+=n; } + write_off(off+(long)total); + } + fclose(f); + return 0; +} + +static int tool_send(const char *args, struct sp_buf *out, void *ctx){ + char text[4096]; const char *p,*e; size_t n=0; + (void)ctx; load_target(); + if(!target[0]) return sp_buf_puts(out,"error: no tmux target\n"); + text[0]='\0'; + if(args){ + p=strstr(args,"\"text\""); if(!p) p=strstr(args,"\"input\""); + if(p){ p=strchr(p,':'); if(p) p=strchr(p,'"'); if(p){ p++; e=p; while(*e && !(*e=='"'&&e[-1]!='\\') && n+1120?"...":""); + return 0; +} + +static int tool_capture(const char *args, struct sp_buf *out, void *ctx){ + int lines=200; const char *p; + (void)ctx; load_target(); + if(!target[0]) return sp_buf_puts(out,"error: no tmux target\n"); + if(args){ p=strstr(args,"\"lines\""); if(p){ p=strchr(p,':'); + if(p) lines=atoi(p+1); + } + } + if(lines<=0||lines>5000) lines=200; + sp_buf_printf(out,"[tmux pane %s last %d]\n",target,lines); + tmux_capture_n(target,lines,out); + return 0; +} + +static int tool_ask(const char *args, struct sp_buf *out, void *ctx){ + /* proxy: send, then wait for watcher feed (background process extracts) */ + char text[4096]; const char *p,*e; size_t n=0; int wait_ms=15000, quiet_ms=1200; + long base_off, last_sz, last_change, start; struct timespec t0; + char fp[600]; + (void)ctx; load_target(); ensure_sess(); feed_path(fp,sizeof(fp)); + if(!target[0]) return sp_buf_puts(out,"error: no tmux target\n"); + if(watcher_pid()<=0){ sp_buf_puts(out,"(starting watcher...)\n"); watcher_start(out); } + text[0]='\0'; + if(args){ + p=strstr(args,"\"wait_ms\""); if(p){ p=strchr(p,':'); + if(p) wait_ms=atoi(p+1);} + p=strstr(args,"\"quiet_ms\""); if(p){ p=strchr(p,':'); + if(p) quiet_ms=atoi(p+1);} + p=strstr(args,"\"text\""); if(!p) p=strstr(args,"\"input\""); + if(p){ p=strchr(p,':'); if(p) p=strchr(p,'"'); if(p){ p++; e=p; while(*e && !(*e=='"'&&e[-1]!='\\') && n+1 %s] %.120s%s\n", target, text, strlen(text)>120?"...":""); + base_off = file_size(fp); /* consume from here */ + tmux_send_lit(target,text,out); + sp_buf_puts(out,"[waiting on watcher for new output...]\n"); + clock_gettime(CLOCK_MONOTONIC,&t0); start=t0.tv_sec*1000+t0.tv_nsec/1000000; last_change=start; last_sz=base_off; + while(1){ + struct timespec ts; long now, sz; + ts.tv_sec=0; ts.tv_nsec=200*1000*1000; nanosleep(&ts,NULL); + clock_gettime(CLOCK_MONOTONIC,&t0); now=t0.tv_sec*1000+t0.tv_nsec/1000000; + sz=file_size(fp); + if(sz>last_sz){ last_sz=sz; last_change=now; } + if(last_sz>base_off && (now-last_change)>=quiet_ms) break; /* stable new output */ + if((now-start)>=wait_ms) break; + } + if(last_sz>base_off){ + FILE *f=fopen(fp,"r"); + if(f){ + char buf[4096]; size_t nr; + fseek(f,base_off,SEEK_SET); + sp_buf_puts(out,"\n--- watcher extracted (new) ---\n"); + while((nr=fread(buf,1,sizeof(buf),f))>0) sp_buf_add(out,buf,nr); + fclose(f); + write_off(last_sz); + } + } else { + sp_buf_puts(out,"(timeout: no new watcher output; /tmux capture to inspect pane)\n"); + } + return 0; +} + +static int tool_start(const char *args, struct sp_buf *out, void *ctx){ + char cmd[1024], name[64]; const char *p,*e; size_t n=0; struct sp_buf o; + (void)ctx; cmd[0]='\0'; name[0]='\0'; + if(args){ + p=strstr(args,"\"cmd\""); if(!p) p=strstr(args,"\"command\""); + if(p){ p=strchr(p,':'); if(p){ p=strchr(p,'"'); if(p){ p++; e=p; while(*e && !(*e=='"'&&e[-1]!='\\') && n+10?"running":"stopped",(int)pid,target); return 0; } + return watcher_start(out); +} + +static int tool_status(const char *args, struct sp_buf *out, void *ctx){ + (void)args;(void)ctx; load_target(); + sp_buf_printf(out,"tmux target: %s\n", target[0]?target:"(none)"); + sp_buf_printf(out,"tmux installed: %s, watcher: %s (pid %d)\n", have_tmux()?"yes":"no", watcher_pid()>0?"running":"stopped",(int)watcher_pid()); + return 0; +} + +static int cmd_tmux(struct sp_host *h, const char *args, struct sp_buf *out, void *vctx){ + (void)vctx; host_ref=h; load_target(); + if(!args||!*args||strcmp(args,"status")==0) return tool_status(NULL,out,NULL); + if(strncmp(args,"attach ",7)==0){ const char *t=args+7; while(*t==' ') t++; snprintf(target,sizeof(target),"%.120s",t); save_target(); sp_buf_printf(out,"target=%s\n",target); watcher_start(out); return 0; } + if(strncmp(args,"start ",6)==0){ struct sp_buf a; char esc[1200]; size_t i,j=0; const char *c=args+6; while(*c==' ') c++; for(i=0;c[i]&&j+2|attach |send |keys |capture [n]|read [wait_ms]|ask |watch [start|stop|status]|status|stop\n watcher: background process detects new text & extracts to feed; ask waits on feed (no fixed sleep)\n"); +} + +static int tick(struct sp_host *h, const char *name, void *ctx){ + (void)name;(void)ctx; host_ref=h; load_target(); + { char b[128]; if(target[0]) snprintf(b,sizeof(b),"tmux:%.100s %s", target, watcher_pid()>0?"[watch]":"[no-watch]"); else snprintf(b,sizeof(b),"tmux:-"); sp_host_widget_text(h,"tmux",b); } + return 0; +} + +static const struct sp_tool Tstatus={"tmux_status","tmux proxy target+watcher status.","{\"type\":\"object\",\"properties\":{}}",SP_AUTH_READ,tool_status,NULL}; +static const struct sp_tool Tcap ={"tmux_capture","Snapshot tmux pane (direct). Args: lines.","{\"type\":\"object\",\"properties\":{\"lines\":{\"type\":\"integer\"}}}",SP_AUTH_READ,tool_capture,NULL}; +static const struct sp_tool Tread ={"tmux_read","Read NEW output extracted by the background watcher feed. Args: wait_ms (wait for new data).","{\"type\":\"object\",\"properties\":{\"wait_ms\":{\"type\":\"integer\"}}}",SP_AUTH_READ,tool_read,NULL}; +static const struct sp_tool Tsend ={"tmux_send","Send literal text+Enter to tmux target CLI.","{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"}},\"required\":[\"text\"]}",SP_AUTH_MUTATE,tool_send,NULL}; +static const struct sp_tool Task ={"tmux_ask","Proxy: send text then wait on WATCHER feed for new extracted output (quiet-stable), no fixed sleep. Args: text, wait_ms, quiet_ms.","{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"},\"wait_ms\":{\"type\":\"integer\"},\"quiet_ms\":{\"type\":\"integer\"}},\"required\":[\"text\"]}",SP_AUTH_MUTATE,tool_ask,NULL}; +static const struct sp_tool Tstart ={"tmux_start","Start cmd in detached tmux session, set target, start watcher. Args: cmd,name.","{\"type\":\"object\",\"properties\":{\"cmd\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"}},\"required\":[\"cmd\"]}",SP_AUTH_DESTRUCTIVE,tool_start,NULL}; +static const struct sp_tool Twatch ={"tmux_watch","Control background watcher process (detects/extracts new output). Args: cmd start|stop|status.","{\"type\":\"object\",\"properties\":{\"cmd\":{\"type\":\"string\"}}}",SP_AUTH_MUTATE,tool_watch,NULL}; +static const struct sp_widget W={"tmux",tick,NULL,NULL,5000}; + +static int init(struct sp_host *h){ + if(!have_tmux()){ + /* tmux not installed -> don't load plugin */ + return -1; + } + host_ref=h; load_target(); + sp_host_add_tool(h,&Tstatus); sp_host_add_tool(h,&Tcap); sp_host_add_tool(h,&Tread); + sp_host_add_tool(h,&Tsend); sp_host_add_tool(h,&Task); sp_host_add_tool(h,&Tstart); sp_host_add_tool(h,&Twatch); + sp_host_add_command(h,"tmux",cmd_tmux,NULL); + sp_host_add_widget(h,&W); + return 0; +} +static const struct sp_plugin plugin={SP_PLUGIN_ABI,"tmux","0.2",init,NULL,NULL}; +const struct sp_plugin *sp_plugin_describe(void){ return &plugin; } diff --git a/share/locale/de.msg b/share/locale/de.msg index 0cda165..6486a33 100644 --- a/share/locale/de.msg +++ b/share/locale/de.msg @@ -31,7 +31,6 @@ role.error = fehler cmd.unknown = unbekanntes Kommando: /%s cmd.available = verfuegbar: -shell.no_output = (keine Ausgabe, exit %d) err.oom = kein Speicher err.theme = Farbschema @@ -39,10 +38,8 @@ err.session = Sitzung err.plugin_failed = Plugin fehlgeschlagen role.tool = werkzeug -ui.running_steer = laeuft %lds | Enter steuert, Ctrl-C bricht ab err.thread = Turn-Thread laesst sich nicht starten err.turn_failed = Turn fehlgeschlagen -err.followup_failed = Nachfrage fehlgeschlagen sidebar.script = Skript focus.reminder = Pruefe vor der Antwort, ob der letzte Schritt naeher am Ziel war; wenn nicht, sage das und nenne den naechsten Schritt. Ziel: %s focus.set = Ziel gesetzt: %s @@ -55,9 +52,41 @@ cli.timeout = cli: '%s' lief nach %s s in das Zeitlimit cli.failed = cli: '%s' scheiterte (exit %d): %.400s focus.widget_none = kein Ziel (/goal ) ui.prompt_mark = > +ui.steer_mark = steuern> +ui.swarm_locked = [Schwarm gesperrt] sidebar.ms = %ld ms ui.empty = - ui.approve = %s ausfuehren (%s) %.60s? y/N auth.mutate = aendert Dateien auth.destructive = zerstoerend role.diff = aenderung + +# Zustimmung (ack): Kanalnachrichten, Antworten des Gateways, Terminal +ack.request = Zustimmung %d: %s %s +ack.how = Antwort: ok %d / no %d +ack.prompt = Zustimmung %d: %s %s (%ds) - 'splinter --ack %d yes' oder hier y/N: +ack.pending = Zustimmung %d: %s %s (%ds) +ack.approved_by = splinter: zugestimmt von %s +ack.none = keine offenen Anfragen +ack.granted = Zustimmung erteilt. +ack.refused = Abgelehnt. +ack.gone = Diese Anfrage gibt es nicht (mehr). +ack.waiting = Ich warte noch auf eine Zustimmung: ok %d / no %d +focus.recap = Erinnerung fuer den naechsten Turn eingeplant + +# openai transport +openai.oom = openai: kein Speicher +openai.build_request = openai: Anfrage kann nicht gebaut werden +openai.fdopen = openai: fdopen: %s +openai.mkstemp = openai: mkstemp: %s +openai.short_write = openai: kurzer Schreibvorgang: %s +openai.read_failed = openai: Lesen fehlgeschlagen +openai.transfer_failed = openai: Uebertragung fehlgeschlagen fuer %s +openai.unparseable = openai: Antwort nicht lesbar (kein Status) +openai.stream_failed = openai: Stream fehlgeschlagen fuer %s: %.300s +openai.no_sse = openai: Endpoint sendete keine SSE-Daten: %.300s +openai.stream_no_answer = openai: Stream endete ohne Antwort: %.300s + +# delegate +delegate.timeout = Delegate: '%s' Zeitueberschreitung +delegate.parallel_timeout = [parallel: Zeitueberschreitung, Rest wird beendet] diff --git a/share/locale/en.msg b/share/locale/en.msg index 65b1cab..eaac690 100644 --- a/share/locale/en.msg +++ b/share/locale/en.msg @@ -30,7 +30,6 @@ role.error = error cmd.unknown = unknown command: /%s cmd.available = available: -shell.no_output = (no output, exit %d) err.oom = out of memory err.theme = theme @@ -38,10 +37,8 @@ err.session = session err.plugin_failed = plugin failed role.tool = tool -ui.running_steer = running %lds | Enter steers, Ctrl-C cancels err.thread = cannot start the turn thread err.turn_failed = turn failed -err.followup_failed = follow-up failed sidebar.script = script focus.reminder = Before answering, check whether the last step moved closer to the goal. If not, say so and name the next step. Goal: %s focus.set = goal set: %s @@ -54,9 +51,41 @@ cli.timeout = cli: '%s' timed out after %s s cli.failed = cli: '%s' failed (exit %d): %.400s focus.widget_none = no goal (/goal ) ui.prompt_mark = > +ui.steer_mark = steer> +ui.swarm_locked = [swarm locked] sidebar.ms = %ld ms ui.empty = - ui.approve = run %s (%s) %.60s? y/N auth.mutate = changes files auth.destructive = destructive role.diff = diff + +# approvals (ack): channel messages, the gateway's replies, the terminal +ack.request = Approval %d: %s %s +ack.how = Answer: ok %d / no %d +ack.prompt = approval %d: %s %s (%ds) - 'splinter --ack %d yes' or y/N here: +ack.pending = approval %d: %s %s (%ds) +ack.approved_by = splinter: approved by %s +ack.none = no open requests +ack.granted = Approved. +ack.refused = Refused. +ack.gone = There is no such request (any more). +ack.waiting = Still waiting for an approval: ok %d / no %d +focus.recap = reminder scheduled for the next turn + +# openai transport +openai.oom = openai: out of memory +openai.build_request = openai: cannot build the request +openai.fdopen = openai: fdopen: %s +openai.mkstemp = openai: mkstemp: %s +openai.short_write = openai: short write: %s +openai.read_failed = openai: read failed +openai.transfer_failed = openai: transfer failed for %s +openai.unparseable = openai: unparseable response (no status) +openai.stream_failed = openai: stream failed for %s: %.300s +openai.no_sse = openai: endpoint sent no SSE data: %.300s +openai.stream_no_answer = openai: stream ended with no answer: %.300s + +# delegate +delegate.timeout = delegate: '%s' timed out +delegate.parallel_timeout = [parallel: timeout, killing the rest] diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg index 4f0a8ee..4126cd9 100644 --- a/share/locale/pt_BR.msg +++ b/share/locale/pt_BR.msg @@ -6,9 +6,10 @@ ui.ready = pronto. Enter envia, Ctrl-D sai. ui.working = trabalhando... -ui.running_steer = rodando %lds | Enter direciona, Ctrl-C cancela ui.steering_queued = direcionamento na fila ui.prompt_mark = > +ui.steer_mark = direcionar> +ui.swarm_locked = [enxame bloqueado] ui.approve = executar %s (%s) %.60s? y/N sidebar.session = sessao @@ -38,7 +39,6 @@ role.diff = alteracao cmd.unknown = comando desconhecido: /%s cmd.available = disponiveis: -shell.no_output = (sem saida, exit %d) err.oom = sem memoria err.theme = tema @@ -46,7 +46,6 @@ err.session = sessao err.plugin_failed = plugin falhou err.thread = nao foi possivel iniciar a thread do turno err.turn_failed = turno falhou -err.followup_failed = continuacao falhou ui.empty = - auth.mutate = altera arquivos @@ -64,3 +63,33 @@ cps.plan = plano pronto: corte %zu/%zu, %zu -> %zu B cli.no_output = cli: '%s' nao produziu saida cli.timeout = cli: '%s' passou do limite de %s s cli.failed = cli: '%s' falhou (exit %d): %.400s + +# aprovacoes (ack): mensagens dos canais, respostas do gateway, terminal +ack.request = Aprovacao %d: %s %s +ack.how = Resposta: ok %d / no %d +ack.prompt = aprovacao %d: %s %s (%ds) - 'splinter --ack %d yes' ou y/N aqui: +ack.pending = aprovacao %d: %s %s (%ds) +ack.approved_by = splinter: aprovado por %s +ack.none = nenhum pedido aberto +ack.granted = Aprovado. +ack.refused = Recusado. +ack.gone = Esse pedido nao existe (mais). +ack.waiting = Ainda aguardando uma aprovacao: ok %d / no %d +focus.recap = lembrete agendado para o proximo turno + +# openai transport +openai.oom = openai: sem memoria +openai.build_request = openai: nao foi possivel montar a requisicao +openai.fdopen = openai: fdopen: %s +openai.mkstemp = openai: mkstemp: %s +openai.short_write = openai: escrita incompleta: %s +openai.read_failed = openai: falha na leitura +openai.transfer_failed = openai: falha na transferencia para %s +openai.unparseable = openai: resposta ilegivel (sem status) +openai.stream_failed = openai: stream falhou para %s: %.300s +openai.no_sse = openai: endpoint nao enviou dados SSE: %.300s +openai.stream_no_answer = openai: stream terminou sem resposta: %.300s + +# delegate +delegate.timeout = delegate: '%s' excedeu o tempo +delegate.parallel_timeout = [paralelo: tempo esgotado, encerrando o resto] diff --git a/src/ack.c b/src/ack.c index cee3819..102880f 100644 --- a/src/ack.c +++ b/src/ack.c @@ -34,6 +34,7 @@ #include #include "splinter.h" +#include "i18n.h" #include "ack.h" static char ack_root[512]; @@ -245,9 +246,15 @@ sp_ack_notify(int id, struct sp_buf *log) request_field(id, "args", args, sizeof(args)); if (strlen(args) > 300) memcpy(args + 297, "...", 4); - snprintf(msg, sizeof(msg), "Zustimmung %d: %s %s\n" - "Antwort: ok %d / no %d", id, tool[0] != '\0' ? tool : "?", args, - id, id); + { + char head[480], how[100]; + + snprintf(head, sizeof(head), sp_td("ack.request", + "Approval %d: %s %s"), id, tool[0] != '\0' ? tool : "?", args); + snprintf(how, sizeof(how), sp_td("ack.how", + "Answer: ok %d / no %d"), id, id); + snprintf(msg, sizeof(msg), "%s\n%s", head, how); + } snprintf(list, sizeof(list), "%s", chans); for (tok = strtok_r(list, ",", &save); tok != NULL; tok = strtok_r(NULL, ",", &save)) { @@ -387,7 +394,8 @@ sp_ack_list(struct sp_buf *out) snprintf(dir, sizeof(dir), "%s/pending", root); n = scandir(dir, &ents, NULL, alphasort); if (n < 0) { - sp_buf_puts(out, "keine offenen Anfragen\n"); + sp_buf_printf(out, "%s\n", sp_td("ack.none", + "no open requests")); return 0; } for (i = 0; i < n; i++) { diff --git a/src/agent.c b/src/agent.c index e9ad59c..8247bad 100644 --- a/src/agent.c +++ b/src/agent.c @@ -26,6 +26,7 @@ #include #include "splinter.h" +#include "i18n.h" #include "splinter_plugin.h" #include "ack.h" #include "log.h" @@ -42,6 +43,26 @@ struct ack_thread { int stop; /* read end of the stop pipe */ }; + +struct quota_set_ctx { long status; long now; long retry_after_s; }; +static void quota_set_fn(struct sp_prov_state *st, void *p) { + struct quota_set_ctx *c = p; + long ra = 0; + if (c->retry_after_s > 0) ra = c->now + c->retry_after_s; + else if (c->status == 429 || c->status == 402) ra = c->now + 60; + else if (c->status == 529) ra = c->now + 120; + if (ra > 0 && st->quota_ready_at < ra) st->quota_ready_at = ra; + if (ra > 0) st->last_429_at = c->now; + if (ra > 0) snprintf(st->note, sizeof(st->note), "quota %ld ready_at=%ld", c->status, ra); +} +static void quota_hint(const char *provider, const char *key_id, long status, long retry_after_s) { + struct quota_set_ctx c; + if (!provider||!*provider||!key_id||!*key_id) return; + if (status!=429 && status!=402 && status!=529) return; + c.status = status; c.now = (long)time(NULL); c.retry_after_s = retry_after_s; + sp_provstate_update(provider, key_id, quota_set_fn, &c); +} + static void * ack_stdin_thread(void *arg) { @@ -112,12 +133,12 @@ ack_approval(struct sp_agent *a, const struct sp_tool *t, const char *args) sp_buf_free(&log); } if (a->cfg->approval_out != NULL) - fprintf(a->cfg->approval_out, "Zustimmung %d: %s %s " - "(%ds) - 'splinter --ack %d yes' oder hier y/N: ", id, t->name, - args, ttl, id); + fprintf(a->cfg->approval_out, sp_td("ack.prompt", + "approval %d: %s %s (%ds) - 'splinter --ack %d yes' or y/N " + "here: "), id, t->name, args, ttl, id); else - fprintf(stderr, "Zustimmung %d: %s %s (%ds)\n", id, t->name, args, - ttl); + fprintf(stderr, sp_td("ack.pending", "approval %d: %s %s (%ds)\n"), + id, t->name, args, ttl); if (a->cfg->approval_out != NULL) fflush(a->cfg->approval_out); @@ -139,7 +160,8 @@ ack_approval(struct sp_agent *a, const struct sp_tool *t, const char *args) close(stop[1]); } if (yes && who[0] != '\0') - fprintf(stderr, "splinter: zugestimmt von %s\n", who); + fprintf(stderr, sp_td("ack.approved_by", + "splinter: approved by %s\n"), who); return yes; } @@ -299,9 +321,16 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer, sp_buf_free(&steer); } /* compaction happens before the budget is judged, never after */ - if (a->host != NULL && - sp_host_compact(a->host, conv, a->cfg->max_bytes) > 0) - a->stats.compactions++; + if (a->host != NULL) { + size_t cb = sp_conv_bytes(conv), cn = conv->n; + + if (sp_host_compact(a->host, conv, a->cfg->max_bytes) > 0) { + a->stats.compactions++; + if (a->cfg != NULL && a->cfg->on_compact != NULL) + a->cfg->on_compact(a->cfg->on_compact_ctx, + cb, sp_conv_bytes(conv), cn, conv->n); + } + } sent = sp_conv_bytes(conv); if (a->cfg->max_bytes > 0 && sent > a->cfg->max_bytes) { sp_buf_printf(err, "agent: conversation budget exceeded " @@ -312,6 +341,31 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer, a->stats.bytes_sent += sent; a->stats.steps++; + { + struct sp_prov_result pr; + enum sp_prov_decision pd; + + pd = sp_host_provider_preflight(a->host, a->tr.provider, + a->tr.key_id, &pr); + if (pd == SP_PROV_WAIT_QUOTA || pd == SP_PROV_DENY) { + sp_buf_printf(err, + "provider quota/policy: %s (ready_at=%ld retry_after=%lds)", + pr.reason[0] ? pr.reason : "denied", + pr.ready_at, pr.retry_after_s); + goto out; + } + if (pd == SP_PROV_DELAY && pr.retry_after_s > 0) { + if (pr.retry_after_s <= 30) + sleep((unsigned)pr.retry_after_s); + else { + sp_buf_printf(err, + "provider quota/policy: %s (ready_at=%ld retry_after=%lds)", + pr.reason[0] ? pr.reason : "delay", + pr.ready_at, pr.retry_after_s); + goto out; + } + } + } { int sent_rc; @@ -324,11 +378,18 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer, sent_rc = a->tr.send(a->tr.ctx, conv, &reply, err); if (sent_rc != 0) { + sp_host_provider_account(a->host, a->tr.provider, + a->tr.key_id, reply.status, 0, 0); sp_reply_free(&reply); goto out; } } if (reply.status < 200 || reply.status > 299) { + sp_host_provider_account(a->host, a->tr.provider, + a->tr.key_id, reply.status, + (size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0), + (size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0)); + quota_hint(a->tr.provider, a->tr.key_id, reply.status, reply.retry_after_s); sp_buf_printf(err, "agent: transport status %ld", reply.status); sp_reply_free(&reply); @@ -339,6 +400,10 @@ sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer, reply.tokens_in : 0); a->stats.tokens_out += (size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0); + sp_host_provider_account(a->host, a->tr.provider, a->tr.key_id, + reply.status, + (size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0), + (size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0)); if (reply.ncalls == 0) { const char *text = reply.content != NULL ? diff --git a/src/buf.c b/src/buf.c index a5da702..daab792 100644 --- a/src/buf.c +++ b/src/buf.c @@ -115,25 +115,54 @@ int sp_json_escape(struct sp_buf *b, const char *s) { static const char hex[] = "0123456789abcdef"; - unsigned char c; + const unsigned char *p = (const unsigned char *)s; + + while (*p != '\0') { + unsigned char c = *p; - for (; *s != '\0'; s++) { - c = (unsigned char)*s; switch (c) { - case '"': if (sp_buf_puts(b, "\\\"") != 0) return -1; break; - case '\\': if (sp_buf_puts(b, "\\\\") != 0) return -1; break; - case '\n': if (sp_buf_puts(b, "\\n") != 0) return -1; break; - case '\r': if (sp_buf_puts(b, "\\r") != 0) return -1; break; - case '\t': if (sp_buf_puts(b, "\\t") != 0) return -1; break; + case '"': if (sp_buf_puts(b, "\\\"") != 0) return -1; p++; break; + case '\\': if (sp_buf_puts(b, "\\\\") != 0) return -1; p++; break; + case '\n': if (sp_buf_puts(b, "\\n") != 0) return -1; p++; break; + case '\r': if (sp_buf_puts(b, "\\r") != 0) return -1; p++; break; + case '\t': if (sp_buf_puts(b, "\\t") != 0) return -1; p++; break; default: if (c < 0x20) { char esc[7] = { '\\', 'u', '0', '0', hex[c >> 4], hex[c & 0xf], '\0' }; if (sp_buf_puts(b, esc) != 0) return -1; - } else { - if (sp_buf_add(b, (const char *)&c, 1) != 0) + p++; + } else if (c < 0x80) { + if (sp_buf_add(b, (const char *)p, 1) != 0) return -1; + p++; + } else { + /* Valid UTF-8 passes through; invalid bytes become \u00XX + * so the JSON string stays well-formed UTF-8. */ + size_t n = 0; + + if ((c & 0xe0) == 0xc0 && (p[1] & 0xc0) == 0x80 && + c >= 0xc2) + n = 2; + else if ((c & 0xf0) == 0xe0 && (p[1] & 0xc0) == 0x80 && + (p[2] & 0xc0) == 0x80) + n = 3; + else if ((c & 0xf8) == 0xf0 && (p[1] & 0xc0) == 0x80 && + (p[2] & 0xc0) == 0x80 && (p[3] & 0xc0) == 0x80 && + c <= 0xf4) + n = 4; + if (n > 0) { + if (sp_buf_add(b, (const char *)p, n) != 0) + return -1; + p += n; + } else { + char esc[7] = { '\\', 'u', '0', '0', + hex[c >> 4], hex[c & 0xf], '\0' }; + if (sp_buf_puts(b, esc) != 0) + return -1; + p++; + } } break; } diff --git a/src/builtin.c b/src/builtin.c index 78e8ce0..ac7ca11 100644 --- a/src/builtin.c +++ b/src/builtin.c @@ -127,7 +127,7 @@ sp_secret_env_is(const char *entry) extern char **environ; #define RUN_MAX_OUTPUT (1u << 20) -#define RUN_TIMEOUT_S 300 +#define RUN_TIMEOUT_S 600 /* * Run a shell command for the model. diff --git a/src/cmdscript.c b/src/cmdscript.c index 7041d5b..e61dfe5 100644 --- a/src/cmdscript.c +++ b/src/cmdscript.c @@ -29,8 +29,8 @@ #include "splinter.h" #include "cmdscript.h" -#define CMD_TIMEOUT_MS 60000 -#define CMD_MAX_BYTES 262144 +#define CMD_TIMEOUT_MS 300000 +#define CMD_MAX_BYTES (4u << 20) /* * Where the programs live: $SPLINTER_COMMANDS_DIR, else ~/.splinter/commands. diff --git a/src/config.c b/src/config.c index 30d044b..8a398ba 100644 --- a/src/config.c +++ b/src/config.c @@ -146,6 +146,68 @@ parse_exit(struct sp_exit *e, const char *val, struct sp_buf *err, return 0; } +/* + * NAME=VALUE with a name the shell would accept. A bad name is an error, not + * a silently dropped variable: the whole point is that the program sees it. + */ +static int +valid_env(const char *s) +{ + const char *p = s; + + if (!((*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z') || *p == '_')) + return 0; + for (p++; *p != '\0' && *p != '='; p++) + if (!((*p >= 'A' && *p <= 'Z') || (*p >= 'a' && *p <= 'z') || + (*p >= '0' && *p <= '9') || *p == '_')) + return 0; + return *p == '='; +} + +static int +add_env(char (*env)[SP_CONFIG_ENV_LEN], size_t *n, const char *val, + struct sp_buf *err, const char *path, unsigned lineno) +{ + if (!valid_env(val)) { + sp_buf_printf(err, "config: %s:%u: env wants NAME=VALUE, got " + "'%.40s'", path, lineno, val); + return -1; + } + if (*n == SP_CONFIG_MAX_ENV) { + sp_buf_printf(err, "config: %s:%u: more than %d env entries", + path, lineno, SP_CONFIG_MAX_ENV); + return -1; + } + if (strlen(val) >= SP_CONFIG_ENV_LEN) { + sp_buf_printf(err, "config: %s:%u: env entry longer than %d", + path, lineno, SP_CONFIG_ENV_LEN - 1); + return -1; + } + snprintf(env[(*n)++], SP_CONFIG_ENV_LEN, "%s", val); + return 0; +} + +void +sp_config_apply_env(const char (*env)[SP_CONFIG_ENV_LEN], size_t n) +{ + size_t i; + + for (i = 0; i < n; i++) { + char name[128]; + const char *eq = strchr(env[i], '='); + size_t len; + + if (eq == NULL) + continue; + len = (size_t)(eq - env[i]); + if (len >= sizeof(name)) + continue; + memcpy(name, env[i], len); + name[len] = '\0'; + (void)setenv(name, eq + 1, 1); + } +} + static int parse_delegate(struct sp_delegate *d, const char *val, struct sp_buf *err, const char *path, unsigned lineno) @@ -196,6 +258,13 @@ parse_delegate(struct sp_delegate *d, const char *val, struct sp_buf *err, snprintf(d->model, sizeof(d->model), "%s", s + 6); else if (!strncmp(s, "key_env=", 8)) snprintf(d->key_env, sizeof(d->key_env), "%s", s + 8); + else if (!strncmp(s, "env=", 4)) { + if (add_env(d->env, &d->nenv, s + 4, err, path, + lineno) != 0) { + free(copy); + return -1; + } + } else if (strchr(s, '=') == NULL) { snprintf(d->about, sizeof(d->about), "%s", s); first = 0; @@ -350,10 +419,26 @@ 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_env")) { + if (add_env(c->cli_env, &c->ncli_env, val, err, path, + lineno) != 0) { + fclose(f); + return -1; + } + } else if (!strcmp(key, "steps")) c->steps = (size_t)strtoul(val, NULL, 10); else if (!strcmp(key, "max_bytes")) c->max_bytes = (size_t)strtoul(val, NULL, 10); + else if (!strcmp(key, "http_timeout") || + !strcmp(key, "request_timeout")) + c->http_timeout = strtol(val, NULL, 10); + else if (!strcmp(key, "cli_timeout")) + c->cli_timeout = strtol(val, NULL, 10); + else if (!strcmp(key, "delegate_timeout")) + c->delegate_timeout = strtol(val, NULL, 10); + else if (!strcmp(key, "run_timeout")) + c->run_timeout = strtol(val, NULL, 10); else if (!strcmp(key, "env_delegates")) c->env_delegates = (!strcmp(val, "1") || !strcmp(val, "true") || !strcmp(val, "yes")) ? 1 : 0; @@ -463,6 +548,7 @@ sp_config_write_example(const char *path, struct sp_buf *err) "# model. Use either this or endpoint/model, not both.\n" "#transport = cli\n" "#cli_cmd = claude -p\n" + "#cli_env = CLAUDE_CODE_OAUTH_TOKEN=sk-ant-...\n" "\n" "# Plugins to load, one per line. Paths are relative to the working\n" "# directory unless absolute.\n" @@ -481,9 +567,16 @@ sp_config_write_example(const char *path, struct sp_buf *err) "\n" "# Tool rounds per turn, and the conversation budget in bytes\n" "# (0 = no limit).\n" - "steps = 8\n" + "steps = 150\n" "max_bytes = 0\n" "\n" + "# Timeouts in seconds. Local models can take long to answer: raise\n" + "# these instead of failing mid-turn. 0 means the built-in default.\n" + "#http_timeout = 900\n" + "#cli_timeout = 1800\n" + "#delegate_timeout = 900\n" + "#run_timeout = 600\n" + "\n" "# Where session logs go (default ~/.splinter).\n" "#session_dir = ~/.splinter\n" "\n" diff --git a/src/config.h b/src/config.h index e0e49a2..ed6f5b3 100644 --- a/src/config.h +++ b/src/config.h @@ -30,6 +30,14 @@ */ #define SP_CONFIG_MAX_DELEGATES 8 +/* + * Extra environment for a program splinter starts: NAME=VALUE, set in the + * child right before exec. Lets two delegates run the same cli with two + * different accounts. + */ +#define SP_CONFIG_MAX_ENV 8 +#define SP_CONFIG_ENV_LEN 512 + /* * An exit is one way to reach a model: an endpoint, a model name and where its * key lives. The ring tries them in order, so a rate limit costs a step, not the @@ -56,6 +64,8 @@ struct sp_delegate { char endpoint[512]; char model[256]; char key_env[64]; + char env[SP_CONFIG_MAX_ENV][SP_CONFIG_ENV_LEN]; /* NAME=VALUE */ + size_t nenv; }; struct sp_config { @@ -73,6 +83,8 @@ struct sp_config { char system_prompt[1024]; char session_dir[512]; char cli_cmd[512]; + char cli_env[SP_CONFIG_MAX_ENV][SP_CONFIG_ENV_LEN]; /* NAME=VALUE */ + size_t ncli_env; char memory_url[512]; char memory_key_env[64]; char telegram_allow[256]; /* comma separated user ids */ @@ -81,6 +93,10 @@ struct sp_config { size_t nplugins; size_t steps; /* 0: not set */ size_t max_bytes; /* 0: not set */ + long http_timeout; /* seconds for HTTP/SSE requests, 0: default */ + long cli_timeout; /* seconds for cli transport, 0: default */ + long delegate_timeout; /* seconds for delegate children, 0: default */ + long run_timeout; /* seconds for the run tool, 0: default */ int autonomous; /* -1 not set, 0 off, 1 on */ /* * Delegates built from environment tokens (CLAUDE_CODE_OAUTH_TOKEN and the @@ -114,4 +130,7 @@ int sp_config_load(struct sp_config *, const char *path, struct sp_buf *err); /* Write a commented starter file. Returns 0 or -1. */ int sp_config_write_example(const char *path, struct sp_buf *err); +/* Set every NAME=VALUE of 'env' in this process, overwriting. */ +void sp_config_apply_env(const char (*env)[SP_CONFIG_ENV_LEN], size_t n); + #endif /* SPLINTER_CONFIG_H */ diff --git a/src/delegate.c b/src/delegate.c index 5175ae5..3c33b09 100644 --- a/src/delegate.c +++ b/src/delegate.c @@ -28,14 +28,35 @@ #include #include #include +#include #include "splinter.h" #include "splinter_plugin.h" +#include "i18n.h" #include "mcp.h" #include "config.h" -#define DELEGATE_TIMEOUT_MS 300000 -#define DELEGATE_MAX_BYTES 65536 +#include +#include +#include + +#define DELEGATE_TIMEOUT_MS_DEFAULT 900000 +#define DELEGATE_MAX_BYTES_CAP (64u << 20) /* safety cap; buffers grow */ + +static long +delegate_timeout_ms(const struct sp_config *cfg) +{ + const char *e = getenv("SPLINTER_DELEGATE_TIMEOUT"); + long s = 0; + + if (e != NULL && *e != '\0') + s = strtol(e, NULL, 10); + if (s <= 0 && cfg != NULL) + s = cfg->delegate_timeout; + if (s <= 0) + return DELEGATE_TIMEOUT_MS_DEFAULT; + return s * 1000; +} struct del_ctx { const struct sp_config *cfg; @@ -293,9 +314,8 @@ 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 maxbuf[32], envname[96], plug[600]; + char envname[96], plug[600]; - snprintf(maxbuf, sizeof(maxbuf), "%d", DELEGATE_MAX_BYTES); argv[n++] = (char *)c->self; argv[n++] = "--no-config"; argv[n++] = "-p"; @@ -316,8 +336,12 @@ exec_delegate(const struct del_ctx *c, const struct sp_delegate *d, "/plugins/cli/cli.so"); if (d->cmd[0] != '\0') (void)setenv("SPLINTER_CLI_CMD", d->cmd, 1); - if (d->key[0] != '\0' && !remote) - (void)setenv("CLAUDE_CODE_OAUTH_TOKEN", d->key, 1); + if (d->key[0] != '\0' && !remote) { + const char *kenv = d->key_env[0] != '\0' ? + d->key_env : "CLAUDE_CODE_OAUTH_TOKEN"; + + (void)setenv(kenv, d->key, 1); + } argv[n++] = "--transport"; argv[n++] = "cli"; argv[n++] = "--plugin"; @@ -329,7 +353,7 @@ exec_delegate(const struct del_ctx *c, const struct sp_delegate *d, argv[n++] = (char *)d->model; } argv[n++] = "--max-bytes"; - argv[n++] = maxbuf; + argv[n++] = "0"; argv[n++] = "--autonomous"; if (remote) ; /* the remote host has its own keys */ @@ -346,12 +370,29 @@ exec_delegate(const struct del_ctx *c, const struct sp_delegate *d, } argv[n] = NULL; + /* + * env=NAME=VALUE from the delegate line, last so it beats a key from the + * environment scan: the line in the file is the more specific instruction. + * Remotely there is no environment to inherit, so it goes in front of the + * command as `env 'NAME=VALUE' ...`. + */ + if (!remote) + sp_config_apply_env((const char (*)[SP_CONFIG_ENV_LEN])d->env, + d->nenv); + if (remote) { struct sp_buf line; char *sshv[8]; + size_t e; if (sp_buf_init(&line) != 0) _exit(127); + if (d->nenv > 0 && sp_buf_puts(&line, "env ") != 0) + _exit(127); + for (e = 0; e < d->nenv; e++) + if (shell_quote(&line, d->env[e]) != 0 || + sp_buf_puts(&line, " ") != 0) + _exit(127); for (i = 0; i < n; i++) { if ((i > 0 && sp_buf_puts(&line, " ") != 0) || shell_quote(&line, argv[i]) != 0) @@ -405,31 +446,21 @@ run_child(const struct del_ctx *c, const struct sp_delegate *d, struct pollfd pfd; char chunk[4096]; ssize_t got; - int done = 0; - while (!done) { + for (;;) { pfd.fd = fds[0]; pfd.events = POLLIN; - if (poll(&pfd, 1, DELEGATE_TIMEOUT_MS) <= 0) { + if (poll(&pfd, 1, (int)delegate_timeout_ms(c->cfg)) <= 0) { (void)kill(child, SIGKILL); (void)waitpid(child, NULL, 0); close(fds[0]); - sp_buf_printf(err, "delegate: '%s' timed out", - d->id); + sp_buf_printf(err, sp_td("delegate.timeout", + "delegate: '%s' timed out"), d->id); return -1; } got = read(fds[0], chunk, sizeof(chunk)); if (got <= 0) break; - if (out->len + (size_t)got > DELEGATE_MAX_BYTES) { - size_t room = DELEGATE_MAX_BYTES - out->len; - - if (room > 0) - (void)sp_buf_add(out, chunk, room); - sp_buf_puts(out, "\n[delegate output truncated]\n"); - done = 1; - break; - } if (sp_buf_add(out, chunk, (size_t)got) != 0) break; } @@ -438,10 +469,10 @@ run_child(const struct del_ctx *c, const struct sp_delegate *d, int st = 0; (void)waitpid(child, &st, 0); - if (done || (WIFEXITED(st) && WEXITSTATUS(st) != 0)) { + if (WIFEXITED(st) && WEXITSTATUS(st) != 0) { sp_buf_printf(err, "delegate: '%s' exited %d", d->id, WIFEXITED(st) ? WEXITSTATUS(st) : -1); - return done ? 0 : -1; + return -1; } } } @@ -454,6 +485,198 @@ run_child(const struct del_ctx *c, const struct sp_delegate *d, * and a limit nobody checks is a comment. */ static int running[SP_CONFIG_MAX_DELEGATES]; +static struct del_ctx ctx; +static pthread_mutex_t del_lock; +static pthread_once_t del_lock_once = PTHREAD_ONCE_INIT; +static void del_lock_init(void){ pthread_mutexattr_t a; pthread_mutexattr_init(&a); pthread_mutexattr_settype(&a, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&del_lock,&a); pthread_mutexattr_destroy(&a); } +#define DEL_LOCK() do{ pthread_once(&del_lock_once, del_lock_init); pthread_mutex_lock(&del_lock);}while(0) +#define DEL_UNLOCK() pthread_mutex_unlock(&del_lock) + +/* ---- durable job records (submit/poll/resume-ready) ----------------------- */ +static long now_ms(void); + +static void +ensure_dir(const char *path) +{ + if (path && *path) mkdir(path, 0755); +} + +static void +jobs_dir(const struct del_ctx *c, char *out, size_t cap) +{ + const char *sd = c ? sp_host_session_dir(c->host) : NULL; + if (!sd || !*sd) { if (cap) out[0]='\0'; return; } + snprintf(out, cap, "%s/jobs", sd); +} + +static void +job_path(const struct del_ctx *c, const char *id, char *out, size_t cap) +{ + char jd[600]; + jobs_dir(c, jd, sizeof(jd)); + if (!jd[0]) { if (cap) out[0]='\0'; return; } + snprintf(out, cap, "%s/%s.json", jd, id); +} + +static void +gen_job_id(char *out, size_t cap) +{ + static unsigned seq; + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + snprintf(out, cap, "job-%ld-%d-%u", (long)ts.tv_sec, (int)getpid(), ++seq); +} + +static void +json_esc(struct sp_buf *b, const char *s) +{ + const unsigned char *p = (const unsigned char *)(s ? s : ""); + while (*p) { + if (*p == '"' || *p == '\\') { sp_buf_add(b, "\\", 1); sp_buf_add(b, (const char *)p, 1); } + else if (*p == '\n') sp_buf_puts(b, "\\n"); + else if (*p == '\r') sp_buf_puts(b, "\\r"); + else if (*p == '\t') sp_buf_puts(b, "\\t"); + else if (*p < 0x20) sp_buf_printf(b, "\\u%04x", *p); + else sp_buf_add(b, (const char *)p, 1); + p++; + } +} + +struct jobrec { + char id[64], state[32], tool[32], delegate_id[96], remote_id[128], plan_task_id[32]; + char next_poll_at[64], run_after[64]; + long started_ms, ended_ms; + int status, attempts, pid; + struct sp_buf task, result, err; +}; + +static void +jobrec_init(struct jobrec *j) +{ + memset(j, 0, sizeof(*j)); + j->status = -1; j->pid = -1; + sp_buf_init(&j->task); sp_buf_init(&j->result); sp_buf_init(&j->err); +} +static void +jobrec_free(struct jobrec *j) +{ + sp_buf_free(&j->task); sp_buf_free(&j->result); sp_buf_free(&j->err); +} + +static void +write_sidecar(const char *base, const char *ext, const struct sp_buf *b) +{ + char path[760], tmp[780]; + FILE *fp; + if (!base || !*base || !b || !b->p || b->len == 0) return; + snprintf(path, sizeof(path), "%s.%s", base, ext); + snprintf(tmp, sizeof(tmp), "%s.tmp", path); + fp = fopen(tmp, "w"); + if (!fp) return; + fwrite(b->p, 1, b->len, fp); + fclose(fp); + rename(tmp, path); +} + +static void +read_sidecar(const char *base, const char *ext, struct sp_buf *out) +{ + char path[760], buf[4096]; + FILE *fp; + size_t n; + if (!base || !*base) return; + snprintf(path, sizeof(path), "%s.%s", base, ext); + fp = fopen(path, "r"); + if (!fp) return; + while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) + sp_buf_add(out, buf, n); + fclose(fp); +} + +static void +jobrec_write(const struct del_ctx *c, struct jobrec *j) +{ + char jd[600], path[700], tmp[720], base[700]; + struct sp_buf b; + FILE *fp; + if (!c) return; + jobs_dir(c, jd, sizeof(jd)); if (!jd[0]) return; + ensure_dir(jd); + job_path(c, j->id, path, sizeof(path)); if (!path[0]) return; + snprintf(base, sizeof(base), "%s/%s", jd, j->id); + snprintf(tmp, sizeof(tmp), "%s.tmp", path); + if (sp_buf_init(&b) != 0) return; + sp_buf_puts(&b, "{\n"); + sp_buf_printf(&b, " \"id\":\"%s\",\n", j->id); + sp_buf_printf(&b, " \"state\":\"%s\",\n", j->state[0]?j->state:"unknown"); + sp_buf_printf(&b, " \"tool\":\"%s\",\n", j->tool); + sp_buf_printf(&b, " \"delegate\":\""); json_esc(&b, j->delegate_id); sp_buf_puts(&b, "\",\n"); + sp_buf_printf(&b, " \"remote_id\":\""); json_esc(&b, j->remote_id); sp_buf_puts(&b, "\",\n"); + sp_buf_printf(&b, " \"plan_task_id\":\""); json_esc(&b, j->plan_task_id); sp_buf_puts(&b, "\",\n"); + sp_buf_printf(&b, " \"pid\":%d,\n \"status\":%d,\n \"attempts\":%d,\n", j->pid, j->status, j->attempts); + sp_buf_printf(&b, " \"started_ms\":%ld,\n \"ended_ms\":%ld,\n", j->started_ms, j->ended_ms); + sp_buf_printf(&b, " \"next_poll_at\":\"%s\",\n \"run_after\":\"%s\",\n", j->next_poll_at, j->run_after); + sp_buf_puts(&b, " \"task\":\""); json_esc(&b, j->task.p?j->task.p:""); sp_buf_puts(&b, "\",\n"); + sp_buf_printf(&b, " \"has_result\":%s,\n \"has_error\":%s\n", (j->result.len>0?"true":"false"), (j->err.len>0?"true":"false")); + sp_buf_puts(&b, "}\n"); + fp = fopen(tmp, "w"); + if (fp) { fputs(b.p?b.p:"{}", fp); fclose(fp); rename(tmp, path); } + else unlink(tmp); + sp_buf_free(&b); + if (j->task.len > 0) write_sidecar(base, "task", &j->task); + if (j->result.len > 0) write_sidecar(base, "result", &j->result); + if (j->err.len > 0) write_sidecar(base, "error", &j->err); +} + +static const char * +jget(const char *s, const char *key, char *out, size_t cap) +{ + char pat[96]; const char *p, *q; size_t n; + out[0]='\0'; + snprintf(pat, sizeof(pat), "\"%s\"", key); + p = s ? strstr(s, pat) : NULL; if(!p) return out; + p = strchr(p+strlen(pat), ':'); if(!p) return out; + while (*p && *p!='\"' && *p!='-' && (*p<'0'||*p>'9') && *p!='t'&&*p!='f'&&*p!='n') p++; + if (*p=='\"') { p++; q=strchr(p,'\"'); if(!q) return out; n=(size_t)(q-p); if(n>=cap)n=cap-1; memcpy(out,p,n); out[n]='\0'; } + else { n=strcspn(p,", \t\r\n}"); if(n>=cap)n=cap-1; memcpy(out,p,n); out[n]='\0'; } + return out; +} + +static int +jobrec_read(const struct del_ctx *c, const char *id, struct jobrec *j) +{ + char path[700], buf[8192], jd[600], base[700]; FILE *fp; size_t n; char v[128]; + job_path(c,id,path,sizeof(path)); if(!path[0]) return -1; + fp=fopen(path,"r"); if(!fp) return -1; + n=fread(buf,1,sizeof(buf)-1,fp); fclose(fp); buf[n]='\0'; + jobrec_init(j); + jget(buf,"id",j->id,sizeof(j->id)); + jget(buf,"state",j->state,sizeof(j->state)); + jget(buf,"tool",j->tool,sizeof(j->tool)); + jget(buf,"delegate",j->delegate_id,sizeof(j->delegate_id)); + jget(buf,"remote_id",j->remote_id,sizeof(j->remote_id)); + jget(buf,"plan_task_id",j->plan_task_id,sizeof(j->plan_task_id)); + jget(buf,"next_poll_at",j->next_poll_at,sizeof(j->next_poll_at)); + jget(buf,"run_after",j->run_after,sizeof(j->run_after)); + jget(buf,"pid",v,sizeof(v)); j->pid=atoi(v); + jget(buf,"status",v,sizeof(v)); j->status=(int)strtol(v,NULL,10); + jget(buf,"attempts",v,sizeof(v)); j->attempts=atoi(v); + jget(buf,"started_ms",v,sizeof(v)); j->started_ms=strtol(v,NULL,10); + jget(buf,"ended_ms",v,sizeof(v)); j->ended_ms=strtol(v,NULL,10); + jobs_dir(c,jd,sizeof(jd)); snprintf(base,sizeof(base),"%s/%s",jd,id); + read_sidecar(base,"task",&j->task); + if (j->task.len == 0) { jget(buf,"task",v,sizeof(v)); if(v[0]) sp_buf_puts(&j->task,v); } + read_sidecar(base,"result",&j->result); + read_sidecar(base,"error",&j->err); + return 0; +} + + + +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); +static void link_plan_quota(struct del_ctx *c, const char *plan_task_id, const char *run_after, const char *job_id); static int tool_delegate(const char *args, struct sp_buf *out, void *ctx) @@ -469,17 +692,19 @@ tool_delegate(const char *args, struct sp_buf *out, void *ctx) return -1; task = NULL; wanted = NULL; + char plan_task_id[32] = {0}; if (args != NULL && args[0] == '{') { mcp_json *v = mcp_parse(args); if (v != NULL) { const char *t = mcp_arg_string(v, "task"); const char *g = mcp_arg_string(v, "tags"); - - if (t != NULL) - (void)sp_buf_puts(&keep, t); - if (g != NULL) - (void)sp_buf_puts(&tbuf, g); + const char *dn = mcp_arg_string(v, "delegate"); + const char *pt = mcp_arg_string(v, "plan_task_id"); + if (t != NULL) (void)sp_buf_puts(&keep, t); + if (g != NULL && *g) (void)sp_buf_puts(&tbuf, g); + else if (dn != NULL && *dn) (void)sp_buf_puts(&tbuf, dn); + if (pt && *pt) snprintf(plan_task_id, sizeof(plan_task_id), "%.31s", pt); mcp_json_free(v); task = keep.p; wanted = tbuf.p; @@ -498,7 +723,11 @@ tool_delegate(const char *args, struct sp_buf *out, void *ctx) return sp_buf_puts(out, "error: no delegate configured " "(add a 'delegate = ...' line to the config)"); } - d = choose(c->cfg, task, wanted, &score, why, sizeof(why)); + { + const struct sp_delegate *ex = (wanted && *wanted) ? find_delegate(c->cfg, wanted) : NULL; + if (ex) { d = ex; score = ex->prio; snprintf(why,sizeof(why),"explicit delegate '%s'", ex->id); } + else d = choose(c->cfg, task, wanted, &score, why, sizeof(why)); + } if (d == NULL) { sp_buf_free(&keep); sp_buf_free(&tbuf); @@ -510,70 +739,122 @@ tool_delegate(const char *args, struct sp_buf *out, void *ctx) sp_buf_free(&tbuf); return -1; } - sp_buf_printf(out, "[delegate %s, score %d, prio %d%s%s]\n", d->id, score, - d->prio, why[0] != '\0' ? ": " : "", why); { - size_t slot = (size_t)(d - c->cfg->delegate); + struct jobrec jr; + jobrec_init(&jr); + gen_job_id(jr.id, sizeof(jr.id)); + snprintf(jr.state, sizeof(jr.state), "running"); + snprintf(jr.tool, sizeof(jr.tool), "delegate"); + snprintf(jr.delegate_id, sizeof(jr.delegate_id), "%s", d->id); + if (plan_task_id[0]) snprintf(jr.plan_task_id, sizeof(jr.plan_task_id), "%s", plan_task_id); + sp_buf_puts(&jr.task, task); + jr.started_ms = now_ms(); + jr.attempts = 1; + sp_buf_printf(out, "[delegate %s, job %s, score %d, prio %d%s%s]\n", + d->id, jr.id, score, d->prio, why[0] != '\0' ? ": " : "", why); + jobrec_write(c, &jr); + { + size_t slot = (size_t)(d - c->cfg->delegate); + DEL_LOCK(); + if (slot < SP_CONFIG_MAX_DELEGATES && + running[slot] >= d->max_parallel) { + DEL_UNLOCK(); + snprintf(jr.state, sizeof(jr.state), "failed"); + sp_buf_puts(&jr.err, "delegate busy (max_parallel)"); + jr.ended_ms = now_ms(); + jobrec_write(c, &jr); + sp_buf_printf(out, "error: delegate '%s' is busy " + "(max_parallel %d)\n", d->id, d->max_parallel); + jobrec_free(&jr); + sp_buf_free(&reply); + sp_buf_free(&err); + sp_buf_free(&keep); + sp_buf_free(&tbuf); + return 0; + } + if (slot < SP_CONFIG_MAX_DELEGATES) + running[slot]++; + DEL_UNLOCK(); + } + /* + * A delegate is work someone else does while we wait: it belongs in the task + * panel with its own clock, so 'who is still running' is a fact on screen and + * not a guess. + */ + { + char label[80], detail[160]; - if (slot < SP_CONFIG_MAX_DELEGATES && - running[slot] >= d->max_parallel) { - sp_buf_printf(out, "error: delegate '%s' is busy " - "(max_parallel %d)\n", d->id, d->max_parallel); + snprintf(label, sizeof(label), "delegate:%s", d->id); + 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) { + 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(); + if (err.p) sp_buf_puts(&jr.err, err.p); + { + long ra = 0; + if (looks_quota_wait(err.p, &ra)) { + snprintf(jr.state, sizeof(jr.state), "waiting_quota"); + if (ra>0) { snprintf(jr.run_after,sizeof(jr.run_after),"%ld",ra); snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",ra); } + else snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+3600); + jobrec_write(c, &jr); + link_plan_quota(c, jr.plan_task_id, jr.run_after[0]?jr.run_after:jr.next_poll_at, jr.id); + sp_buf_printf(out, "quota: %s\n[job %s: waiting_quota run_after=%s, auto-scheduled]\n", err.p?err.p:"quota", jr.id, jr.run_after); + } else if (looks_transient(err.p)) { + snprintf(jr.state, sizeof(jr.state), "waiting_poll"); + snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+60); + jobrec_write(c, &jr); + sp_buf_printf(out, "error (transient): %s\n[job %s: waiting_poll, retry with delegate_retry]\n", err.p?err.p:"failed", jr.id); + } else { + snprintf(jr.state, sizeof(jr.state), "failed"); + jobrec_write(c, &jr); + sp_buf_printf(out, "error: %s\n[job %s: failed]\n", err.p?err.p:"failed", jr.id); + } + } + jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); sp_buf_free(&keep); sp_buf_free(&tbuf); return 0; } - if (slot < SP_CONFIG_MAX_DELEGATES) - running[slot]++; - } - /* - * A delegate is work someone else does while we wait: it belongs in the task - * panel with its own clock, so 'who is still running' is a fact on screen and - * not a guess. - */ - { - char label[80], detail[160]; + { + size_t slot = (size_t)(d - c->cfg->delegate); - snprintf(label, sizeof(label), "delegate:%s", d->id); - 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) { - sp_host_task_end(c->host, task_id, 1, 0); - size_t slot = (size_t)(d - c->cfg->delegate); - - if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] > 0) - running[slot]--; - sp_buf_printf(out, "error: %s\n", err.p != NULL ? err.p : "failed"); + DEL_LOCK(); if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] > 0) running[slot]--; DEL_UNLOCK(); + } + sp_host_task_end(c->host, task_id, 0, + reply.p != NULL ? strlen(reply.p) / 4 : 0); + snprintf(jr.state, sizeof(jr.state), "done"); + jr.status = 0; + jr.ended_ms = now_ms(); + if (reply.p != NULL) { + struct sp_buf ans; + if (sp_buf_init(&ans) == 0) { + copy_answer(&ans, &reply); + if (ans.p) sp_buf_puts(&jr.result, ans.p); + sp_buf_free(&ans); + } + copy_answer(out, &reply); + } else { + sp_buf_puts(out, "(no answer)\n"); + sp_buf_puts(&jr.result, "(no answer)\n"); + } + sp_buf_printf(out, "[job %s: done, poll with delegate_result]\n", jr.id); + jobrec_write(c, &jr); + jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); sp_buf_free(&keep); sp_buf_free(&tbuf); return 0; } - { - size_t slot = (size_t)(d - c->cfg->delegate); - - if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] > 0) - running[slot]--; - } - /* - * Closed here, after the answer is in hand, so duration and tokens in the - * panel are the ones the call actually cost. - */ - sp_host_task_end(c->host, task_id, 0, - reply.p != NULL ? strlen(reply.p) / 4 : 0); - if (reply.p != NULL) - copy_answer(out, &reply); - else - sp_buf_puts(out, "(no answer)\n"); - sp_buf_free(&reply); - sp_buf_free(&err); - sp_buf_free(&keep); - sp_buf_free(&tbuf); - return 0; } /* @@ -581,6 +862,7 @@ tool_delegate(const char *args, struct sp_buf *out, void *ctx) * task, and why. A pick nobody can explain is a pick nobody can correct. */ + /* ---- several delegates at once ------------------------------------------- */ #define PAR_MAX_TASKS 8 @@ -671,6 +953,8 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) { struct del_ctx *c = ctx; struct job jobs[PAR_MAX_TASKS]; + struct jobrec jrec[PAR_MAX_TASKS]; + char jids[PAR_MAX_TASKS][64]; size_t njobs = 0, i, running_now = 0; mcp_json *v; const mcp_json *tasks; @@ -692,6 +976,8 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) } memset(jobs, 0, sizeof(jobs)); + memset(jrec, 0, sizeof(jrec)); + memset(jids, 0, sizeof(jids)); for (i = 0; i < PAR_MAX_TASKS; i++) { const mcp_json *t = mcp_array_at(tasks, i); const char *task; @@ -722,16 +1008,37 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) } } jobs[njobs].d = d; - if (sp_buf_init(&jobs[njobs].out) != 0) + jobrec_init(&jrec[njobs]); + gen_job_id(jrec[njobs].id, sizeof(jrec[njobs].id)); + snprintf(jids[njobs], sizeof(jids[njobs]), "%s", jrec[njobs].id); + if (sp_buf_init(&jobs[njobs].out) != 0) { + jobrec_free(&jrec[njobs]); break; + } if (spawn_job(c, d, task, &jobs[njobs], &err) != 0) { + snprintf(jrec[njobs].state, sizeof(jrec[njobs].state), "failed"); + snprintf(jrec[njobs].tool, sizeof(jrec[njobs].tool), "delegate_parallel"); + snprintf(jrec[njobs].delegate_id, sizeof(jrec[njobs].delegate_id), "%s", d->id); + sp_buf_puts(&jrec[njobs].task, task); + if (err.p) sp_buf_puts(&jrec[njobs].err, err.p); + jrec[njobs].ended_ms = now_ms(); + jobrec_write(c, &jrec[njobs]); sp_buf_free(&jobs[njobs].out); + jobrec_free(&jrec[njobs]); continue; } snprintf(jobs[njobs].task, sizeof(jobs[njobs].task), "%s", task); jobs[njobs].start_ms = now_ms(); jobs[njobs].end_ms = 0; jobs[njobs].status = -1; + snprintf(jrec[njobs].state, sizeof(jrec[njobs].state), "running"); + snprintf(jrec[njobs].tool, sizeof(jrec[njobs].tool), "delegate_parallel"); + snprintf(jrec[njobs].delegate_id, sizeof(jrec[njobs].delegate_id), "%s", d->id); + sp_buf_puts(&jrec[njobs].task, task); + jrec[njobs].started_ms = jobs[njobs].start_ms; + jrec[njobs].pid = (int)jobs[njobs].pid; + jrec[njobs].attempts = 1; + jobrec_write(c, &jrec[njobs]); njobs++; running_now++; } @@ -761,8 +1068,9 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) ready = poll(pfd, (nfds_t)nfds, 1000); if (ready < 0 && errno != EINTR) break; - if (now_ms() - start > DELEGATE_TIMEOUT_MS) { - sp_buf_puts(out, "[parallel: timeout, killing the rest]\n"); + if (now_ms() - start > delegate_timeout_ms(c->cfg)) { + sp_buf_puts(out, sp_td("delegate.parallel_timeout", + "[parallel: timeout, killing the rest]\n")); break; /* the loop below kills and reaps */ } if (ready <= 0) @@ -784,7 +1092,7 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) got = read(jobs[i].fd, chunk, sizeof(chunk)); if (got > 0) { if (jobs[i].out.len + (size_t)got <= - DELEGATE_MAX_BYTES) + DELEGATE_MAX_BYTES_CAP) (void)sp_buf_add(&jobs[i].out, chunk, (size_t)got); continue; @@ -804,6 +1112,18 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) jobs[i].fd = -1; jobs[i].done = 1; running_now--; + { + struct sp_buf ans; + snprintf(jrec[i].state, sizeof(jrec[i].state), jobs[i].status==0?"done":"failed"); + jrec[i].status = jobs[i].status; + jrec[i].ended_ms = jobs[i].end_ms; + if (sp_buf_init(&ans)==0) { + copy_answer(&ans, &jobs[i].out); + if (ans.p) sp_buf_puts(&jrec[i].result, ans.p); + sp_buf_free(&ans); + } + jobrec_write(c, &jrec[i]); + } } } } @@ -827,6 +1147,11 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) jobs[i].done = 1; jobs[i].end_ms = now_ms(); jobs[i].status = -1; + snprintf(jrec[i].state, sizeof(jrec[i].state), "interrupted"); + jrec[i].status = -1; + jrec[i].ended_ms = jobs[i].end_ms; + sp_buf_puts(&jrec[i].err, "timeout or interrupted"); + jobrec_write(c, &jrec[i]); } /* @@ -841,8 +1166,8 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) long took = jobs[i].end_ms > 0 ? jobs[i].end_ms - jobs[i].start_ms : 0; - sp_buf_printf(out, "\n## task %zu | model %s | score %d | %ld ms | " - "exit %d | %zu B%s%s\n", i + 1, jobs[i].d->id, + sp_buf_printf(out, "\n## task %zu | job %s | model %s | score %d | %ld ms | " + "exit %d | %zu B%s%s\n", i + 1, jids[i], jobs[i].d->id, jobs[i].score, took, jobs[i].status, jobs[i].out.len, jobs[i].why[0] != '\0' ? " | " : "", jobs[i].why); @@ -852,6 +1177,7 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) else sp_buf_puts(out, "(no answer)\n"); sp_buf_free(&jobs[i].out); + jobrec_free(&jrec[i]); } { size_t k; @@ -918,11 +1244,499 @@ sp_delegate_choose(const struct sp_config *cfg, const char *task, return 0; } + +static int +tool_delegate_jobs(const char *args, struct sp_buf *out, void *ctx) +{ + struct del_ctx *c = ctx; + char jd[600]; + DIR *dp; + struct dirent *de; + int n = 0; + (void)args; + jobs_dir(c, jd, sizeof(jd)); + if (!jd[0]) return sp_buf_puts(out, "error: no session dir for jobs"); + dp = opendir(jd); + if (!dp) return sp_buf_puts(out, "(no delegate jobs)\n"); + sp_buf_puts(out, "delegate jobs (durable, pollable):\n"); + while ((de = readdir(dp)) != NULL) { + char *dot, id[128], v[128], buf[4096], path[1024]; + FILE *fp; size_t nr; + if (de->d_name[0] == '.') continue; + dot = strrchr(de->d_name, '.'); + if (!dot || strcmp(dot, ".json") != 0) continue; + snprintf(id, sizeof(id), "%.*s", (int)(dot - de->d_name), de->d_name); + snprintf(path, sizeof(path), "%s/%.255s", jd, de->d_name); + fp = fopen(path, "r"); if (!fp) continue; + nr = fread(buf, 1, sizeof(buf)-1, fp); fclose(fp); buf[nr]='\0'; + jget(buf,"state",v,sizeof(v)); sp_buf_printf(out, " %s state=%s", id, v[0]?v:"?"); + jget(buf,"delegate",v,sizeof(v)); if(v[0]) sp_buf_printf(out, " delegate=%s", v); + jget(buf,"status",v,sizeof(v)); sp_buf_printf(out, " exit=%s", v[0]?v:"-"); + jget(buf,"started_ms",v,sizeof(v)); if(v[0]) sp_buf_printf(out, " started_ms=%s", v); + jget(buf,"ended_ms",v,sizeof(v)); if(v[0]) sp_buf_printf(out, " ended_ms=%s", v); + jget(buf,"task",v,sizeof(v)); if(v[0]) sp_buf_printf(out, " task=%.80s", v); + sp_buf_puts(out, "\n"); + n++; + if (n >= 100) break; + } + closedir(dp); + if (n == 0) sp_buf_puts(out, " (none)\n"); + sp_buf_puts(out, "use delegate_result {\"id\":\"...\"} to poll full result/state\n"); + return 0; +} + +static int +tool_delegate_result(const char *args, struct sp_buf *out, void *ctx) +{ + struct del_ctx *c = ctx; + struct sp_buf keep; + struct jobrec jr; + const char *id; + if (sp_buf_init(&keep) != 0) return -1; + id = json_str(args, "id", &keep); + if (!id || !*id) id = json_str(args, "job_id", &keep); + if (!id || !*id) { + /* maybe plain string */ + if (args && args[0] && args[0] != '{') { sp_buf_puts(&keep, args); id = keep.p; } + } + if (!id || !*id) { + sp_buf_free(&keep); + return sp_buf_puts(out, "error: 'id' (or job_id) is required"); + } + if (jobrec_read(c, id, &jr) != 0) { + sp_buf_printf(out, "error: job not found: %s\n", id); + sp_buf_free(&keep); + return 0; + } + sp_buf_printf(out, "job %s\n state=%s tool=%s delegate=%s\n", jr.id, jr.state, jr.tool, jr.delegate_id); + sp_buf_printf(out, " exit=%d attempts=%d pid=%d\n", jr.status, jr.attempts, jr.pid); + sp_buf_printf(out, " started_ms=%ld ended_ms=%ld\n", jr.started_ms, jr.ended_ms); + if (jr.remote_id[0]) sp_buf_printf(out, " remote_id=%s\n", jr.remote_id); + if (jr.next_poll_at[0]) sp_buf_printf(out, " next_poll_at=%s\n", jr.next_poll_at); + if (jr.run_after[0]) sp_buf_printf(out, " run_after=%s\n", jr.run_after); + if (jr.task.p && jr.task.len) sp_buf_printf(out, " task: %s\n", jr.task.p); + if (jr.err.p && jr.err.len) sp_buf_printf(out, " error:\n%s\n", jr.err.p); + if (jr.result.p && jr.result.len) sp_buf_printf(out, " result:\n%s\n", jr.result.p); + else if (strcmp(jr.state, "running")==0 || strcmp(jr.state,"polling")==0 || strcmp(jr.state,"waiting_poll")==0) + sp_buf_puts(out, " (no result yet; poll again later)\n"); + jobrec_free(&jr); + sp_buf_free(&keep); + return 0; +} + + + +static int +looks_transient(const char *e) +{ + if (!e) return 0; + return strstr(e,"timeout")||strstr(e,"Timeout")||strstr(e,"connect")|| + strstr(e,"Connection")||strstr(e,"ssh:")||strstr(e,"network")|| + strstr(e,"unreachable")||strstr(e,"reset")||strstr(e,"temporar"); +} +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; +} + + +static const struct sp_delegate * +find_delegate(const struct sp_config *cfg, const char *id) +{ + size_t i; + if (!cfg || !id) return NULL; + for (i = 0; i < cfg->ndelegates; i++) + if (strcmp(cfg->delegate[i].id, id) == 0) + return &cfg->delegate[i]; + return NULL; +} + +static int +job_due(const struct jobrec *j, long now) +{ + long ra = 0, np = 0; + if (!j) return 0; + if (strcmp(j->state,"waiting_quota")!=0 && strcmp(j->state,"waiting_poll")!=0 && strcmp(j->state,"queued")!=0) + return 0; + if (j->run_after[0]) ra = strtol(j->run_after, NULL, 10); + if (j->next_poll_at[0] && j->next_poll_at[0] != '+') np = strtol(j->next_poll_at, NULL, 10); + if (ra > 0 && now < ra) return 0; + if (np > 0 && now < np) return 0; + return 1; +} + +static int +tool_delegate_due(const char *args, struct sp_buf *out, void *ctx) +{ + struct del_ctx *c = ctx; + char jd[600]; + DIR *dp; struct dirent *de; + long now = (long)time(NULL); + int n = 0; + (void)args; + jobs_dir(c, jd, sizeof(jd)); + if (!jd[0]) return sp_buf_puts(out, "error: no session dir for jobs"); + dp = opendir(jd); + if (!dp) return sp_buf_puts(out, "(no jobs dir)\n"); + sp_buf_puts(out, "due delegate jobs (scheduler view):\n"); + while ((de = readdir(dp)) != NULL) { + char *dot, id[128], path[1024], buf[4096]; + FILE *fp; size_t nr; struct jobrec jr; + if (de->d_name[0]=='.') continue; + dot=strrchr(de->d_name,'.'); if(!dot||strcmp(dot,".json")!=0) continue; + snprintf(id,sizeof(id),"%.*s",(int)(dot-de->d_name),de->d_name); + snprintf(path,sizeof(path),"%s/%.255s",jd,de->d_name); + fp=fopen(path,"r"); if(!fp) continue; + nr=fread(buf,1,sizeof(buf)-1,fp); fclose(fp); buf[nr]='\0'; + jobrec_init(&jr); + jget(buf,"id",jr.id,sizeof(jr.id)); if(!jr.id[0]) snprintf(jr.id,sizeof(jr.id),"%.63s",id); + jget(buf,"state",jr.state,sizeof(jr.state)); + jget(buf,"run_after",jr.run_after,sizeof(jr.run_after)); + jget(buf,"next_poll_at",jr.next_poll_at,sizeof(jr.next_poll_at)); + jget(buf,"delegate",jr.delegate_id,sizeof(jr.delegate_id)); + if (job_due(&jr, now)) { + sp_buf_printf(out, " %s state=%s delegate=%s run_after=%s next_poll_at=%s\n", + jr.id, jr.state, jr.delegate_id, jr.run_after, jr.next_poll_at); + n++; + } + jobrec_free(&jr); + if (n>=100) break; + } + closedir(dp); + if (n==0) sp_buf_puts(out, " (none due now)\n"); + else sp_buf_puts(out, "retry with delegate_retry {\"id\":\"...\"}\n"); + return 0; +} + + + +int +sp_delegate_tick(struct sp_buf *out) +{ + struct del_ctx *c = &ctx; + DEL_LOCK(); + char jd[600]; + DIR *dp; struct dirent *de; + long now = (long)time(NULL); + char due_id[64] = {0}; + int found = 0; + + jobs_dir(c, jd, sizeof(jd)); + if (!jd[0] || !c->cfg) { + if (out) sp_buf_puts(out, "scheduler: no session/delegate config"); + DEL_UNLOCK(); return 0; + } + dp = opendir(jd); + if (!dp) { + if (out) sp_buf_puts(out, "scheduler: no jobs"); + DEL_UNLOCK(); return 0; + } + /* pick first due job (prefer waiting_quota then waiting_poll/queued) */ + while ((de = readdir(dp)) != NULL) { + char *dot, id[128], path[1024], buf[4096]; + FILE *fp; size_t nr; struct jobrec jr; + if (de->d_name[0]=='.') continue; + dot=strrchr(de->d_name,'.'); if(!dot||strcmp(dot,".json")!=0) continue; + snprintf(id,sizeof(id),"%.*s",(int)(dot-de->d_name),de->d_name); + snprintf(path,sizeof(path),"%s/%.255s",jd,de->d_name); + fp=fopen(path,"r"); if(!fp) continue; + nr=fread(buf,1,sizeof(buf)-1,fp); fclose(fp); buf[nr]='\0'; + jobrec_init(&jr); + jget(buf,"id",jr.id,sizeof(jr.id)); if(!jr.id[0]) snprintf(jr.id,sizeof(jr.id),"%.63s",id); + jget(buf,"state",jr.state,sizeof(jr.state)); + jget(buf,"run_after",jr.run_after,sizeof(jr.run_after)); + jget(buf,"next_poll_at",jr.next_poll_at,sizeof(jr.next_poll_at)); + if (job_due(&jr, now)) { + snprintf(due_id, sizeof(due_id), "%.63s", jr.id[0]?jr.id:id); + found = 1; + jobrec_free(&jr); + break; + } + jobrec_free(&jr); + } + closedir(dp); + if (!found) { + if (out) sp_buf_puts(out, "scheduler: none due"); + DEL_UNLOCK(); return 0; + } + if (out) sp_buf_printf(out, "scheduler: retrying %s\n", due_id); + { int rc = sp_delegate_retry_job(due_id, 0, out); DEL_UNLOCK(); return rc; } +} + + +static void +link_plan_quota(struct del_ctx *c, const char *plan_task_id, const char *run_after, const char *job_id) +{ + struct sp_buf out, args; + if (!c || !c->host || !plan_task_id || !*plan_task_id) return; + if (sp_buf_init(&out)!=0 || sp_buf_init(&args)!=0) return; + sp_buf_printf(&args, "wait %s %s job:%s", plan_task_id, + (run_after && *run_after) ? run_after : "+3600", job_id ? job_id : ""); + (void)sp_host_command(c->host, "tasks", args.p ? args.p : "", &out); + sp_buf_free(&out); sp_buf_free(&args); +} + +int +sp_delegate_retry_job(const char *id, int force, struct sp_buf *out) +{ + struct del_ctx *c = &ctx; + struct sp_buf reply, err; + const struct sp_delegate *d; + struct jobrec jr; + int task_id = -1; + long now = (long)time(NULL); + + if (!id || !*id) return sp_buf_puts(out, "error: 'id' required"); + if (sp_buf_init(&reply)!=0 || sp_buf_init(&err)!=0) return -1; + if (jobrec_read(c,id,&jr)!=0) { + sp_buf_printf(out,"error: job not found: %s\n", id); + sp_buf_free(&reply); sp_buf_free(&err); return 0; + } + if (strcmp(jr.state,"done")==0 && !force) { + sp_buf_printf(out,"job %s already done (use force=1 to rerun)\n", jr.id); + jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); return 0; + } + if (!force && !job_due(&jr, now) && strcmp(jr.state,"failed")!=0) { + sp_buf_printf(out,"job %s not due yet (state=%s run_after=%s next_poll_at=%s); use force=1\n", + jr.id, jr.state, jr.run_after, jr.next_poll_at); + jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); return 0; + } + if (jr.delegate_id[0]=='\0' || jr.task.len==0) { + sp_buf_puts(out,"error: job missing delegate/task (cannot retry)\n"); + jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); return 0; + } + d = find_delegate(c->cfg, jr.delegate_id); + if (!d) { + sp_buf_printf(out,"error: delegate '%s' not configured\n", jr.delegate_id); + snprintf(jr.state,sizeof(jr.state),"failed"); sp_buf_puts(&jr.err,"delegate not configured"); + jr.ended_ms=now_ms(); jobrec_write(c,&jr); + jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); return 0; + } + { + size_t slot = (size_t)(d - c->cfg->delegate); + DEL_LOCK(); + if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] >= d->max_parallel) { + DEL_UNLOCK(); + snprintf(jr.state,sizeof(jr.state),"waiting_poll"); + snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+30); + jobrec_write(c,&jr); + sp_buf_printf(out,"job %s: delegate busy, requeued waiting_poll\n", jr.id); + jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); return 0; + } + if (slot < SP_CONFIG_MAX_DELEGATES) running[slot]++; + DEL_UNLOCK(); + } + jr.attempts++; + snprintf(jr.state,sizeof(jr.state),"running"); + jr.started_ms=now_ms(); jr.ended_ms=0; jr.run_after[0]='\0'; jr.next_poll_at[0]='\0'; + sp_buf_clear(&jr.result); sp_buf_clear(&jr.err); + jobrec_write(c,&jr); + { + char label[80], detail[160]; + snprintf(label,sizeof(label),"delegate:%s",d->id); + snprintf(detail,sizeof(detail),"retry %.120s", jr.task.p?jr.task.p:""); + 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) { + 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(); + if (err.p) sp_buf_puts(&jr.err,err.p); + { + long ra=0; + if (looks_quota_wait(err.p,&ra)) { + snprintf(jr.state,sizeof(jr.state),"waiting_quota"); + if(ra>0){snprintf(jr.run_after,sizeof(jr.run_after),"%ld",ra); snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",ra);} + else snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+3600); + link_plan_quota(c, jr.plan_task_id, jr.run_after[0]?jr.run_after:jr.next_poll_at, jr.id); + } else if (looks_transient(err.p)) { + snprintf(jr.state,sizeof(jr.state),"waiting_poll"); + snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+60); + } else snprintf(jr.state,sizeof(jr.state),"failed"); + } + jobrec_write(c,&jr); + sp_buf_printf(out,"state=%s: %s\n", jr.state, err.p?err.p:"failed"); + } else { + struct sp_buf ans; + { size_t slot=(size_t)(d-c->cfg->delegate); DEL_LOCK(); if(slot0) running[slot]--; DEL_UNLOCK(); } + sp_host_task_end(c->host,task_id,0,reply.p?strlen(reply.p)/4:0); + snprintf(jr.state,sizeof(jr.state),"done"); jr.status=0; jr.ended_ms=now_ms(); + if (sp_buf_init(&ans)==0) { copy_answer(&ans,&reply); if(ans.p) sp_buf_puts(&jr.result,ans.p); copy_answer(out,&reply); sp_buf_free(&ans); } + else copy_answer(out,&reply); + sp_buf_puts(out,"\nstate=done\n"); + jobrec_write(c,&jr); + } + jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); + return 0; +} + +static int +tool_delegate_retry(const char *args, struct sp_buf *out, void *ctx) +{ + struct sp_buf keep; + const char *id, *force_s; + int force = 0; + (void)ctx; + if (sp_buf_init(&keep)!=0) return -1; + id = json_str(args,"id",&keep); + if (!id||!*id) id = json_str(args,"job_id",&keep); + force_s = json_str(args,"force",&keep); + force = (force_s && (strcmp(force_s,"1")==0||strcmp(force_s,"true")==0)); + if (!id||!*id) { sp_buf_free(&keep); return sp_buf_puts(out,"error: 'id' required"); } + { + int rc = sp_delegate_retry_job(id, force, out); + sp_buf_free(&keep); + return rc; + } +} + + +static int +tool_delegate_submit(const char *args, struct sp_buf *out, void *ctx) +{ + struct del_ctx *c = ctx; + struct sp_buf keep, tbuf, reply, err; + const char *task, *wanted; + const struct sp_delegate *d; + char why[192] = ""; + char plan_task_id[32] = {0}; + int score = 0, task_id = -1; + + if (sp_buf_init(&keep) != 0 || sp_buf_init(&tbuf) != 0) + return -1; + task = NULL; + wanted = NULL; + if (args != NULL && args[0] == '{') { + mcp_json *v = mcp_parse(args); + if (v != NULL) { + const char *t = mcp_arg_string(v, "task"); + const char *g = mcp_arg_string(v, "tags"); + const char *dname = mcp_arg_string(v, "delegate"); + const char *ptid = mcp_arg_string(v, "plan_task_id"); + if (t != NULL) (void)sp_buf_puts(&keep, t); + if (g != NULL && *g) (void)sp_buf_puts(&tbuf, g); + else if (dname != NULL && *dname) (void)sp_buf_puts(&tbuf, dname); + if (ptid && *ptid) snprintf(plan_task_id, sizeof(plan_task_id), "%.31s", ptid); + mcp_json_free(v); + task = keep.p; wanted = tbuf.p; + } + } else + task = args; + if (task == NULL || *task == '\0') { + sp_buf_free(&keep); sp_buf_free(&tbuf); + return sp_buf_puts(out, "error: 'task' is required"); + } + if (c->cfg->ndelegates == 0) { + sp_buf_free(&keep); sp_buf_free(&tbuf); + return sp_buf_puts(out, "error: no delegate configured"); + } + { + const struct sp_delegate *ex = (wanted && *wanted) ? find_delegate(c->cfg, wanted) : NULL; + if (ex) { d = ex; score = ex->prio; snprintf(why,sizeof(why),"explicit delegate '%s'", ex->id); } + else d = choose(c->cfg, task, wanted, &score, why, sizeof(why)); + } + if (d == NULL) { + sp_buf_free(&keep); sp_buf_free(&tbuf); + return sp_buf_puts(out, "error: no delegate matches this task"); + } + if (sp_buf_init(&reply) != 0 || sp_buf_init(&err) != 0) { + sp_buf_free(&keep); sp_buf_free(&tbuf); return -1; + } + { + struct jobrec jr; + jobrec_init(&jr); + gen_job_id(jr.id, sizeof(jr.id)); + snprintf(jr.state, sizeof(jr.state), "submitted"); + snprintf(jr.tool, sizeof(jr.tool), "delegate_submit"); + if (plan_task_id[0]) snprintf(jr.plan_task_id, sizeof(jr.plan_task_id), "%s", plan_task_id); + snprintf(jr.delegate_id, sizeof(jr.delegate_id), "%s", d->id); + sp_buf_puts(&jr.task, task); + jr.started_ms = now_ms(); + jr.attempts = 1; + /* durable job exists before attempt (submit contract) */ + jobrec_write(c, &jr); + sp_buf_printf(out, "[delegate_submit job %s -> %s, score %d%s%s]\n", + jr.id, d->id, score, why[0]?" : ":"", why); + { + size_t slot = (size_t)(d - c->cfg->delegate); + DEL_LOCK(); + if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] >= d->max_parallel) { + DEL_UNLOCK(); + snprintf(jr.state, sizeof(jr.state), "waiting_poll"); + snprintf(jr.next_poll_at, sizeof(jr.next_poll_at), "%ld", (long)time(NULL)+60); + sp_buf_puts(&jr.err, "delegate busy (max_parallel), queued for poll/retry"); + jr.ended_ms = now_ms(); + jobrec_write(c, &jr); + sp_buf_printf(out, "state=waiting_poll (busy). poll: delegate_result {\"id\":\"%s\"}\n", jr.id); + jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); sp_buf_free(&keep); sp_buf_free(&tbuf); + return 0; + } + if (slot < SP_CONFIG_MAX_DELEGATES) running[slot]++; + DEL_UNLOCK(); + } + { + char label[80], detail[160]; + snprintf(label, sizeof(label), "delegate:%s", d->id); + snprintf(detail, sizeof(detail), "%.140s", task); + task_id = sp_host_task_begin(c->host, label, detail); + } + snprintf(jr.state, sizeof(jr.state), "running"); + jobrec_write(c, &jr); + if (run_child(c, d, task, &reply, &err) != 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(); + { + long ra = 0; + if (err.p) sp_buf_puts(&jr.err, err.p); + if (looks_quota_wait(err.p, &ra)) { + snprintf(jr.state, sizeof(jr.state), "waiting_quota"); + if (ra > 0) snprintf(jr.run_after, sizeof(jr.run_after), "%ld", ra); + if (ra>0) snprintf(jr.next_poll_at, sizeof(jr.next_poll_at), "%ld", ra); else snprintf(jr.next_poll_at, sizeof(jr.next_poll_at), "%ld", (long)time(NULL)+3600); + sp_buf_printf(out, "state=waiting_quota (run_after=%ld): %s\nauto-schedulable, poll: delegate_result {\"id\":\"%s\"}\n", + ra, err.p?err.p:"quota", jr.id); + } else if (looks_transient(err.p)) { + snprintf(jr.state, sizeof(jr.state), "waiting_poll"); + snprintf(jr.next_poll_at, sizeof(jr.next_poll_at), "%ld", (long)time(NULL)+60); + sp_buf_printf(out, "state=waiting_poll (transient): %s\npoll later: delegate_result {\"id\":\"%s\"}\n", + err.p?err.p:"failed", jr.id); + } else { + snprintf(jr.state, sizeof(jr.state), "failed"); + sp_buf_printf(out, "state=failed: %s\njob: %s (delegate_result)\n", err.p?err.p:"failed", jr.id); + } + } + jobrec_write(c, &jr); + jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); sp_buf_free(&keep); sp_buf_free(&tbuf); + return 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(); } + sp_host_task_end(c->host, task_id, 0, reply.p?strlen(reply.p)/4:0); + snprintf(jr.state, sizeof(jr.state), "done"); jr.status=0; jr.ended_ms=now_ms(); + if (reply.p) { + struct sp_buf ans; if(sp_buf_init(&ans)==0){ copy_answer(&ans,&reply); if(ans.p) sp_buf_puts(&jr.result,ans.p); sp_buf_free(&ans); } + copy_answer(out,&reply); + } else sp_buf_puts(out,"(no answer)\n"); + sp_buf_printf(out, "\nstate=done job=%s (poll anytime: delegate_result)\n", jr.id); + jobrec_write(c,&jr); jobrec_free(&jr); + sp_buf_free(&reply); sp_buf_free(&err); sp_buf_free(&keep); sp_buf_free(&tbuf); + return 0; + } +} + + int sp_delegate_register(struct sp_registry *r, const struct sp_config *cfg, struct sp_host *host) { - static struct del_ctx ctx; struct sp_tool t; ssize_t n; @@ -976,5 +1790,57 @@ sp_delegate_register(struct sp_registry *r, const struct sp_config *cfg, t.auth = SP_AUTH_DESTRUCTIVE; t.run = tool_delegate_parallel; t.ctx = &ctx; + if (sp_registry_add(r, &t) != 0) + return -1; + + memset(&t, 0, sizeof(t)); + t.name = "delegate_due"; + t.description = "List durable delegation jobs due for retry/poll now (waiting_quota/waiting_poll/queued with run_after/next_poll_at reached). Scheduler view."; + t.params = "{}"; + t.auth = SP_AUTH_READ; + t.run = tool_delegate_due; + t.ctx = &ctx; + if (sp_registry_add(r, &t) != 0) + return -1; + + memset(&t, 0, sizeof(t)); + t.name = "delegate_retry"; + t.description = "Retry a durable delegation job by id (resumes/re-executes when due or force=1). Updates job state/result; quota/transient failures become waiting_quota/waiting_poll with next_poll_at."; + t.params = "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"},\"force\":{\"type\":\"string\",\"description\":\"1 to retry even if not due\"}},\"required\":[\"id\"]}"; + t.auth = SP_AUTH_DESTRUCTIVE; + t.run = tool_delegate_retry; + t.ctx = &ctx; + if (sp_registry_add(r, &t) != 0) + return -1; + + memset(&t, 0, sizeof(t)); + t.name = "delegate_submit"; + t.description = "Submit a delegation as a durable job (submit+poll model): records the job, attempts execution, and returns a job id. On transient/connect failure the job is marked waiting_poll (resumable by a poller/worker); poll state/result with delegate_result."; + t.params = "{\"type\":\"object\",\"properties\":{" + "\"task\":{\"type\":\"string\",\"description\":\"what to do, self-contained\"}," + "\"tags\":{\"type\":\"string\",\"description\":\"what kind of work, e.g. code or chat\"}},\"required\":[\"task\"]}"; + t.auth = SP_AUTH_DESTRUCTIVE; + t.run = tool_delegate_submit; + t.ctx = &ctx; + if (sp_registry_add(r, &t) != 0) + return -1; + + memset(&t, 0, sizeof(t)); + t.name = "delegate_jobs"; + t.description = "List durable delegation jobs (submit/poll): id, state, delegate, exit, times. Jobs persist in the session so results can be polled later."; + t.params = "{}"; + t.auth = SP_AUTH_READ; + t.run = tool_delegate_jobs; + t.ctx = &ctx; + if (sp_registry_add(r, &t) != 0) + return -1; + + memset(&t, 0, sizeof(t)); + t.name = "delegate_result"; + t.description = "Poll a durable delegation job by id and return its state/result/error. Works after completion and across later polling (resumable job record)."; + t.params = "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"job id from delegate/delegate_submit/delegate_jobs\"}},\"required\":[\"id\"]}"; + t.auth = SP_AUTH_READ; + t.run = tool_delegate_result; + t.ctx = &ctx; return sp_registry_add(r, &t); } diff --git a/src/main.c b/src/main.c index 8727e4c..e47f247 100644 --- a/src/main.c +++ b/src/main.c @@ -9,7 +9,6 @@ */ #include #include -#include #include #include #include @@ -26,6 +25,7 @@ #include "mcpserver.h" #include "interview.h" #include "ack.h" +#include "swarm.h" #include "splinter_plugin.h" #include "theme.h" #include "ui.h" @@ -64,7 +64,7 @@ usage(FILE *f) "SPLINTER_MCP_TOKEN\n" " --mcp-listen-port N MCP port, default 8098\n" " --autonomous run mutating tools without asking\n" - " --steps N tool rounds per turn (default 8)\n" + " --steps N tool rounds per turn (default 150)\n" " --session DIR session directory (default ~/.splinter)\n" " --session-id ID session id (default sess-