diff --git a/README.md b/README.md index f80b015..2f75302 100644 --- a/README.md +++ b/README.md @@ -320,9 +320,10 @@ A request that fails before anything was streamed is tried again three times, five seconds apart; a broken connection, a missing status, a 5xx and a stream that carried no answer qualify, a 401 or 404 does not. After the first streamed chunk the retry stops, because printing the same answer twice is worse than -reporting the provider's error. The wait is visible: the prompt line says -`retrying in 5 s: ...` until the next attempt answers, so a pause does not look -like a hang. Ctrl-C during a wait ends it at once. +reporting the provider's error. The wait is visible where the failure happened: +a status row `retrying in 5 s: ...` joins the transcript below the call, so a +pause does not look like a hang and nothing is printed into the input line. +Ctrl-C during a wait ends it at once. A stream is never cut for being slow: a router may wait minutes for an upstream without sending anything but keepalive lines, and a byte-per-second guard cut @@ -389,10 +390,13 @@ The turn runs on its own thread, so the keyboard stays live. Every tool call is one row in the transcript, in the words of the call itself - `>> Run echo a` - because "it did something" is not information. The reasoning is inserted before those rows: it came first, and the log should read in the order things -happened. While it runs, the input line is only `12s steer> ` and what is -typed, and the status line above it stays visible: the call belongs in the -transcript, and in the prompt it was a second copy that pushed the steer hint -off the right edge. A steer is picked up at the +happened. While it runs, the input line is only `steer> ` and what is typed, +and the status line above it carries the elapsed seconds as its first meter: +the call belongs in the transcript, and in the prompt it was a second copy that +pushed the steer hint off the right edge. Nothing else is written into the +input line or the status bar; an error is a transcript row below the row that +caused it, and a backend request that failed before any answer is retried (the +status row says so). A steer is picked up at the next step boundary; in a single-step turn it becomes the next message instead of being dropped. Curses is only ever touched by the UI thread. @@ -534,7 +538,10 @@ message, and a piece Telegram refuses to parse is sent as plain text instead. `SPLINTER_TG_MARKDOWN=0` turns the rendering off. `/compact [tokens]` runs the compactors now (default target: `compact_target`, -else 8000 tokens) and reports messages/bytes before and after. With +else 8000 tokens) and reports messages/bytes before and after. The `lcm` +widget in the sidebar keeps the running numbers (context, compactions, +messages cut, last cut in messages and bytes, trimmed tool outputs), and the +status line carries a `compact N` segment. With `compact_threshold` set, the harness compacts automatically once the last request was larger than that: the conversation is cut to `compact_target` before the next turn, so the context never grows without bound. Compaction @@ -543,20 +550,33 @@ threshold is the knob that trades cache hits for a smaller context. What was dropped stays in the session log, and the `recall` tool searches it: the model can look an earlier turn up instead of guessing. +`/cost` reports what the session has cost: provider-reported dollars (if the +provider puts `cost` in its usage object), tokens, and the cache share of the +last request. It splits turns into `judged` and `plain`, because a judged model +is an upstream alias that runs a judge first: the provider's usage object +carries only the final answer, so the judge's own tokens and dollars are not in +these numbers. What is measurable is the difference in latency and reported +tokens per turn. The sidebar's cost segment prefers the reported dollars over +list-price arithmetic. + `/new` (or `/reset`) starts a fresh conversation and a fresh session file; the old one stays on disk, and the system prompt is put back. `/model` lists the models the config names (the main endpoint, every delegate with a model, every exit) as buttons and points the running transport at the -one you press. The choice is written to `.d/90-model.conf` as -`default = PROVIDER[/MODEL]`, so the next start uses it too; picking `main` -deletes that file. `/model ` keeps the endpoint and takes another model -from it. `/model probe` asks every endpoint -`/v1/models` and offers what it really serves. +one you press. The choice is written to the session's sidecar +(`.model`) and comes back when that session is opened again, so one +conversation can sit on a different model without changing what a new one +starts on. `/model ` keeps the endpoint and takes another model from it. +`/model probe` asks the configured endpoints `/v1/models` and lists what they +really serve. In the curses chat, `/model` alone opens a picker: Up/Down move, typing filters -by provider or model, Enter takes the highlighted selector, Esc cancels. It is -the same list the clients get from the `models` protocol command, so `--attach` +by provider or model, Enter takes the highlighted selector, Esc cancels. After +the configured list appears, the picker asks the endpoint this session is on +what it serves and adds those models, so a router's whole menu is selectable +and not only the one alias in the config. It is the same list the clients get +from the `models` protocol command (with `probe`), so `--attach` has it too, and the actual switch is still the ordinary `/model ` command. @@ -680,7 +700,7 @@ conversation and puts it on screen. It continues that session id rather than opening a fresh one beside it - the first version did the latter, which looked like a resume and was none. The agent profile comes back too: the engine keeps the session's profile in `.agent`, so a session left in plan resumes -in plan. +in plan; the model it was left on is in `.model` and comes back too. ## MCP @@ -758,9 +778,12 @@ the prompt. - `edit` (mutate): replaces exactly one occurrence; a non-unique `old` is an 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 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. + Its own process group, stdin `/dev/null`, an environment without splinter's + API keys and tokens, so `run env` cannot hand them to the model. It is killed + after `SPLINTER_RUN_TIMEOUT` seconds (default 600, or `run_timeout` in the + config) **without output**: every line on stdout or stderr resets the window, + and the process itself is checked before it is extended, so a long build that + reports progress is not killed for being long. - `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 d512b09..66ad139 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -451,7 +451,7 @@ session_dir = /home/lotherk/.splinter ``` transport = cli cli_cmd = claude -p -cli_timeout = 1800 +cli_timeout = 1800 # seconds of silence, not a wall clock plugin = cli theme = Xresources ``` @@ -513,11 +513,12 @@ and stand for `http://127.0.0.1:11434/v1` and `OPENCODE_GO_API_KEY`). `/model` offers the models the config names and switches the transport; the -choice is written to `.d/90-model.conf` as -`default = PROVIDER[/MODEL]`, so the next start has it. The provider block -supplies kind, endpoint and key variable; the drop-in only names the choice. -Picking `main` deletes that file and the configuration speaks again. -`/model probe` asks each endpoint `/v1/models` and lists what it really serves; +choice is written to the session's sidecar (`.model`) as a selector, +so reopening that session brings the model back without changing what a new +session starts on. The provider block supplies kind, endpoint and key variable; +the sidecar only names the choice. `/model probe` asks each endpoint +`/v1/models` and lists what it really serves; the picker in the curses chat +also asks the endpoint the session is on and adds those models to its list. `/model ` takes another model from the current endpoint. With a plugin `transport` nothing is written — that program picks the model. diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md index 1e8ecda..edd5ca5 100644 --- a/docs/PLUGINS.md +++ b/docs/PLUGINS.md @@ -165,6 +165,21 @@ turn. No second model is called, so a run stays reproducible and costs nothing extra. `plugin lcm { keep = 6; tool_trim = 8192 }` sets the verbatim tail and the byte cap per old observation; `tool_trim = 0` turns the trim off. +What it did is visible while it runs - the counters are the compactor's own, not +a second estimate: + +``` +lcm: ctx 12.3k/32k +compacted 3 cut 41 msgs +last 60->22 msgs 180.2k->44.1k B +tools trimmed 7 +``` + +The first line is the context the last request carried against the window; then +the number of compactions and how many messages they removed in total; how the +last cut looked in messages and bytes; and how many old tool outputs were +trimmed. `/status` gets one segment, `compact 3`, next to the other meters. + **cps** — continuous parallel compression. The expensive part (deciding what would go) is computed on the widget's worker thread from an *index* of the conversation — role, size, and 64 bytes of head per message, copied under a @@ -201,7 +216,9 @@ 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 1800 (or `cli_timeout` in the config) +- `SPLINTER_CLI_TIMEOUT` — seconds of silence before the program is killed, + default 1800 (or `cli_timeout` in the config); output on stdout or stderr + resets the window, so a long answer that keeps printing is not cut off - `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`; diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 06a4aad..f3299fa 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -161,9 +161,12 @@ curses front end, plugin commands and `commands/` programs included. The list `/model` takes, for a picker: `"ev":"models"` with `"items":[{"sel":"junction","label":"junction qwen3.6-35b","current":true},...]`. `sel` is what goes after `/model `, `label` is what the picker shows, and -`current` marks the model the run is on. It is the configuration (providers, -then pools), not a network probe, so it answers at once; `/model ` -through `input` does the switch. +`current` marks the model the run is on. Without an argument it is the +configuration (providers, then pools), so it answers at once. With +`{"cmd":"models","probe":"true"}` the endpoint this session is on is also asked +`/v1/models` and its models are appended, as `provider/model` selectors; that +is a network call and may take a few seconds. `/model ` through +`input` does the switch and stores the choice in the session. ### `{"cmd":"ping"}` / `{"cmd":"quit"}` diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 1921bf3..c508ba6 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -83,8 +83,9 @@ Stream. (`test_gateway.sh`, `test_ui.sh`); `/connect` auch im TUI - **Modelle wechseln und Provider anlegen**: `/model` liest die konfigurierten Modelle (Haupt-Endpoint, Delegates, Exits), haengt den Transport um, merkt - die Wahl in `90-model.conf` und fragt per `/model probe` die Endpoints nach - `/v1/models`; das TUI kann dasselbe. `/connect` schreibt eine validierte + die Wahl in `.model` und fragt per `/model probe` die Endpoints nach + `/v1/models`; das TUI zeigt im Picker auch die Modelle des Endpoints, auf dem + die Sitzung gerade laeuft. `/connect` schreibt eine validierte `delegate`-Zeile in den Drop-in neben der benutzten Konfiguration, prueft sie mit einem Test-Turn und registriert sie im laufenden Prozess (`test_providers`, `test_gateway.sh`, `test_ui.sh`) diff --git a/include/splinter.h b/include/splinter.h index fff8290..7e42cb9 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -148,6 +148,7 @@ struct sp_reply { long tokens_cached; /* prompt tokens the provider served * from its cache, 0 unknown */ long retry_after_s; /* parsed Retry-After header, 0 unknown */ + double cost; /* provider-reported cost, USD; 0 unknown */ /* * A router may say which upstream answered (junction sends * X-Junction-Endpoint): the model a run is on is not always the @@ -372,6 +373,7 @@ struct sp_agent_stats { size_t steps; size_t tokens_in; size_t tokens_out; + double cost; /* provider-reported, USD */ size_t last_in; /* the last request's prompt, for the meter */ size_t last_cached; /* of which the provider had cached */ size_t compactions; diff --git a/include/splinter_engine.h b/include/splinter_engine.h index ec637e7..be170b8 100644 --- a/include/splinter_engine.h +++ b/include/splinter_engine.h @@ -112,6 +112,7 @@ struct sp_engine_state { char dir[512]; char theme[48]; /* set by the front end, for /status */ size_t tokens_in, tokens_out; + double cost; /* provider-reported, USD */ size_t ctx_used; /* prompt tokens of the last request */ size_t ctx_max; /* context window, 0 = unknown */ size_t cached; /* of ctx_used, served from the provider cache */ @@ -134,6 +135,13 @@ int sp_engine_state(struct sp_engine *, struct sp_engine_state *); */ size_t sp_engine_models(struct sp_engine *, struct sp_model_choice *, size_t max); +/* + * The models the endpoint this session is on reports at /v1/models, as + * selectors /model accepts. This talks to the network; the picker asks for it + * after the configured list is already on screen. + */ +size_t sp_engine_served_models(struct sp_engine *, struct sp_model_choice *, + size_t max); /* -------------------------------------------------------------- lifecycle */ diff --git a/plugins/cli/cli.c b/plugins/cli/cli.c index d60b8b1..07d4d39 100644 --- a/plugins/cli/cli.c +++ b/plugins/cli/cli.c @@ -254,9 +254,23 @@ ci_contains(const char *hay, const char *needle) return 0; } +/* the idle window in seconds; 0 or less means no limit */ +static long +cli_timeout_s(const struct cli_cfg *c) +{ + char *end = NULL; + long n; + + if (c == NULL || c->timeout[0] == '\0') + return 0; + n = strtol(c->timeout, &end, 10); + return n > 0 ? n : 0; +} + /* - * Build the shell line: timeout, the command with placeholders expanded, the - * session arguments, stdin and stderr redirection. + * Build the shell line: the command with placeholders expanded, the session + * arguments, stdin and stderr redirection. The timeout is not a `timeout` + * wrapper here: the read loop owns it so output can move the deadline. */ static int build_cmd(const struct cli_cfg *c, const char *path, const char *prompt, @@ -273,8 +287,6 @@ build_cmd(const struct cli_cfg *c, const char *path, const char *prompt, (sp_buf_puts(cmd, ". ") != 0 || sh_word(cmd, envfile) != 0 || sp_buf_puts(cmd, " && ") != 0)) return -1; - if (sp_buf_printf(cmd, "timeout %s ", c->timeout) != 0) - return -1; while (*p != '\0') { if (strncmp(p, "{file}", 6) == 0) { if (sh_word(cmd, path) != 0) @@ -315,22 +327,30 @@ build_cmd(const struct cli_cfg *c, const char *path, const char *prompt, * turn could only end when the program decided to. `claude -p` under its * 30-minute timeout therefore held Ctrl-C hostage: the UI set the flag, joined * the worker, and the worker was still blocked reading a pipe. The child gets - * its own process group (the shell, `timeout`, and the program under it), and - * the read loop polls it, so a cancellation kills the whole tree. + * its own process group (the shell and the program under it), and the read + * loop polls it, so a cancellation kills the whole tree. + * + * The timeout is an idle window, not a wall clock: every byte on stdout or + * stderr moves it forward, and the process itself is asked whether it is still + * there. A long answer that keeps typing is work, not a hang. */ static int -run_cmd(const char *line, const char *errpath, struct sp_buf *raw, - char *errtext, size_t errcap, int *status, struct sp_buf *err) +run_cmd(const char *line, const char *errpath, long timeout_s, + struct sp_buf *raw, char *errtext, size_t errcap, int *status, + struct sp_buf *err) { const volatile int *cancel = sp_cancel_flag(); char chunk[4096]; FILE *ef; - int fds[2], st = 0, rc = 0; + int fds[2], st = 0, rc = 0, timed_out = 0, reaped = 0; pid_t child; size_t en = 0; + time_t last_out; + long errseen = 0; sp_buf_clear(raw); *status = 0; + last_out = time(NULL); if (pipe(fds) != 0) { sp_buf_printf(err, "cli: pipe: %s", strerror(errno)); return -1; @@ -359,7 +379,9 @@ run_cmd(const char *line, const char *errpath, struct sp_buf *raw, close(fds[1]); for (;;) { struct pollfd pfd; + struct stat es; ssize_t got; + time_t now; int pr; if (cancel != NULL && *cancel) { @@ -368,6 +390,18 @@ run_cmd(const char *line, const char *errpath, struct sp_buf *raw, rc = -1; break; } + now = time(NULL); + /* stderr goes to a file: its growth is output too */ + if (errpath[0] != '\0' && stat(errpath, &es) == 0 && + (long)es.st_size > errseen) { + errseen = (long)es.st_size; + last_out = now; + } + if (timeout_s > 0 && now - last_out >= timeout_s) { + (void)kill(-child, SIGKILL); + timed_out = 1; + break; + } pfd.fd = fds[0]; pfd.events = POLLIN; pfd.revents = 0; @@ -402,10 +436,28 @@ run_cmd(const char *line, const char *errpath, struct sp_buf *raw, rc = -1; break; } + /* + * Output keeps the program alive only if the program is still + * there: a closed child can leave bytes in the pipe. + */ + if (!reaped) { + pid_t r; + + do { + r = waitpid(child, &st, WNOHANG); + } while (r < 0 && errno == EINTR); + if (r == child) + reaped = 1; + } + if (!reaped) + last_out = time(NULL); } close(fds[0]); - (void)waitpid(child, &st, 0); - *status = st; + if (!reaped) + while (waitpid(child, &st, 0) < 0 && errno == EINTR) + ; + /* the caller reports 124 as the cli's own timeout */ + *status = timed_out ? (124 << 8) : st; ef = fopen(errpath, "r"); if (ef != NULL) { en = fread(errtext, 1, errcap - 1, ef); @@ -532,8 +584,8 @@ cli_send_one(struct cli_cfg *c, const struct sp_conv *conv, } if (build_cmd(c, path, body.p != NULL ? body.p : "", key, uuid, extra, errpath, envfile, &cmd) != 0 || - run_cmd(cmd.p, errpath, &raw, errtext, sizeof(errtext), &status, - err) != 0) { + run_cmd(cmd.p, errpath, cli_timeout_s(c), &raw, errtext, + sizeof(errtext), &status, err) != 0) { unlink(path); goto fail; } @@ -550,8 +602,8 @@ cli_send_one(struct cli_cfg *c, const struct sp_conv *conv, resume ? "--resume" : "--session-id", uuid); if (build_cmd(c, path, body.p != NULL ? body.p : "", key, uuid, extra, errpath, envfile, &cmd) != 0 || - run_cmd(cmd.p, errpath, &raw, errtext, sizeof(errtext), - &status, err) != 0) { + run_cmd(cmd.p, errpath, cli_timeout_s(c), &raw, + errtext, sizeof(errtext), &status, err) != 0) { unlink(path); goto fail; } diff --git a/plugins/junction/junction.c b/plugins/junction/junction.c index b46fe28..e7c3f1a 100644 --- a/plugins/junction/junction.c +++ b/plugins/junction/junction.c @@ -979,6 +979,9 @@ snapshot_text(struct sp_buf *out) sp_buf_printf(out, " models: %u\n", j.models); sp_buf_printf(out, " model: %s\n", j.model[0] != '\0' ? j.model : "(unknown)"); + if (strstr(j.model, "judged") != NULL) + sp_buf_puts(out, " judged: yes (judge calls are upstream; the " + "provider's usage carries only the final answer)\n"); sp_buf_printf(out, " serving: %s\n", j.served[0] != '\0' ? j.served : "(no request yet)"); sp_buf_printf(out, " route: %s\n", j.route[0] != '\0' ? j.route : diff --git a/plugins/lcm/lcm.c b/plugins/lcm/lcm.c index 9515cc2..93f3381 100644 --- a/plugins/lcm/lcm.c +++ b/plugins/lcm/lcm.c @@ -16,6 +16,7 @@ * writes the summary) is a different plugin, not a flag on this one. */ #include +#include #include #include #include @@ -31,6 +32,14 @@ static size_t keep_tail = KEEP_TAIL; static size_t tool_trim = TOOL_TRIM; +/* what the widget and the status segment show; written by the compactor */ +static pthread_mutex_t lcm_lock = PTHREAD_MUTEX_INITIALIZER; +static unsigned compactions; +static size_t dropped_total; +static unsigned trimmed_total; +static size_t last_msgs_from, last_msgs_to; +static size_t last_bytes_from, last_bytes_to; + static int is_role(const struct sp_msg *m, const char *role) { @@ -111,6 +120,7 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, unsigned turn) { size_t bytes, i, drop, first, keep_from; + size_t msgs_before, bytes_before; char preview[PREVIEW + 1]; char summary[512]; size_t n_user = 0, n_asst = 0, n_tool = 0; @@ -126,6 +136,8 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, if (budget == 0) return 0; /* no byte budget: nothing to do */ bytes = sp_conv_bytes(conv); + msgs_before = conv->n; + bytes_before = bytes; if (bytes <= budget) return 0; /* fits: nothing to do */ @@ -147,9 +159,20 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, */ trimmed = trim_tools(conv, first, keep_from, tool_trim); if (trimmed > 0) { + pthread_mutex_lock(&lcm_lock); + trimmed_total += (unsigned)trimmed; + pthread_mutex_unlock(&lcm_lock); bytes = sp_conv_bytes(conv); - if (bytes <= budget) + if (bytes <= budget) { + pthread_mutex_lock(&lcm_lock); + compactions++; + dropped_total += 0; + last_msgs_from = last_msgs_to = conv->n; + last_bytes_from = bytes_before; + last_bytes_to = bytes; + pthread_mutex_unlock(&lcm_lock); return 1; + } } /* * The newest user message is the task being answered. A long tool loop @@ -222,6 +245,16 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, if (sp_conv_insert(conv, first + 1, &m) != 0) goto fail; } + { + pthread_mutex_lock(&lcm_lock); + compactions++; + dropped_total += drop; + last_msgs_from = msgs_before; + last_msgs_to = conv->n; + last_bytes_from = bytes_before; + last_bytes_to = sp_conv_bytes(conv); + pthread_mutex_unlock(&lcm_lock); + } free(pin_content); free(pin_name); return 1; @@ -319,6 +352,70 @@ static const struct sp_tool recall_tool = { static const struct sp_compactor lcm = { "lcm", lcm_compact }; +/* "12.3k" for a token count, "842" below a thousand */ +static void +human(size_t n, char *buf, size_t cap) +{ + if (n >= 1000000) + snprintf(buf, cap, "%.1fM", (double)n / 1e6); + else if (n >= 1000) + snprintf(buf, cap, "%.1fk", (double)n / 1e3); + else + snprintf(buf, cap, "%zu", n); +} + +/* + * What compaction did, in the sidebar: the context the last request carried, + * how often lcm cut, and how the last cut looked. The counters are the + * compactor's own, not a second estimate. + */ +static int +lcm_tick(struct sp_host *h, const char *name, void *ctx) +{ + struct sp_meter m; + char used[24], max[24], text[512]; + unsigned c; + size_t dropped, from, to; + unsigned trimmed; + size_t bf, bt; + + (void)ctx; + sp_host_meter_get(h, &m); + pthread_mutex_lock(&lcm_lock); + c = compactions; + dropped = dropped_total; + trimmed = trimmed_total; + from = last_msgs_from; + to = last_msgs_to; + bf = last_bytes_from; + bt = last_bytes_to; + pthread_mutex_unlock(&lcm_lock); + human(m.ctx_used, used, sizeof(used)); + if (m.ctx_max > 0) + human(m.ctx_max, max, sizeof(max)); + else + snprintf(max, sizeof(max), "?"); + snprintf(text, sizeof(text), + "ctx %s/%s\n" + "compacted %u cut %zu msgs\n" + "last %zu->%zu msgs %zu->%zu B\n" + "tools trimmed %u", + used, max, c, dropped, from, to, bf, bt, trimmed); + return sp_host_widget_text(h, name, text); +} + +static void +lcm_status(struct sp_host *h, char *buf, size_t len) +{ + unsigned c; + + (void)h; + pthread_mutex_lock(&lcm_lock); + c = compactions; + pthread_mutex_unlock(&lcm_lock); + snprintf(buf, len, "compact %u", c); +} + static int lcm_init(struct sp_host *h) { @@ -331,9 +428,18 @@ lcm_init(struct sp_host *h) v = sp_host_plugin_config(h, "lcm", "tool_trim"); if (v != NULL && atoi(v) >= 0) tool_trim = (size_t)atoi(v); + static const struct sp_widget w = { + "lcm", lcm_tick, NULL, NULL, 2000 + }; + static const struct sp_status seg = { "compact", lcm_status }; + rt.ctx = h; if (sp_host_add_compactor(h, &lcm) != 0) return -1; + if (sp_host_add_widget(h, &w) != 0) + return -1; + if (sp_host_add_status(h, &seg) != 0) + return -1; return sp_host_add_tool(h, &rt); } diff --git a/plugins/status/status.c b/plugins/status/status.c index 2e4d2e0..5065220 100644 --- a/plugins/status/status.c +++ b/plugins/status/status.c @@ -9,8 +9,9 @@ * clock: 17:20:01 | ctx 12.3k/32k [|||||||...] | 41 tok/s | 1.2k tok | $0.0042 * * The segments go to sp_host_add_status(): /status shows them in the - * transcript and the Telegram gateway sends them with its replies. The chat has - * no status bar - the prompt carries the running time and the tool. + * transcript and the Telegram gateway sends them with its replies. The chat's + * status bar draws its own meters (context, cache, speed, the running turn); + * the segments are not squeezed onto that line. * * The numbers come from the harness (struct sp_meter), never from the plugin * counting for itself: two counters that disagree are worse than none. @@ -125,15 +126,18 @@ render_cost(struct sp_host *h, char *buf, size_t len) const struct sp_meter *m = &mm; sp_host_meter_get(h, &mm); + /* + * A provider that reports a cost is believed over our own arithmetic: + * a router may bill differently than its list price. + */ + if (m->cost > 0) { + snprintf(buf, len, "$%.4f", m->cost); + return; + } if (price_in == 0 && price_out == 0) { buf[0] = '\0'; return; } - /* - * The price belongs to the model, the tokens belong to the harness: the - * product is computed here so a price change needs no rebuild of anything - * else. - */ snprintf(buf, len, "$%.4f", (double)m->tok_in * price_in / 1e6 + (double)m->tok_out * price_out / 1e6); diff --git a/share/locale/de.msg b/share/locale/de.msg index 8ee52fd..f9064db 100644 --- a/share/locale/de.msg +++ b/share/locale/de.msg @@ -21,7 +21,9 @@ ui.steer_failed = Steuerung nicht angenommen (kein Turn laeuft) ui.model_title = Modell ui.model_filter = filter: ui.model_hint = tippen filtert Pfeile bewegen Enter waehlt Esc bricht ab +ui.status_turn = %lds ui.model_empty = keine Modelle konfiguriert +ui.model_probing = frage den Endpoint, was er anbietet ... ui.model_none = kein Treffer sidebar.session = Sitzung diff --git a/share/locale/en.msg b/share/locale/en.msg index 3511de1..3ab232c 100644 --- a/share/locale/en.msg +++ b/share/locale/en.msg @@ -20,7 +20,9 @@ ui.steer_failed = steering not accepted (no turn is running) ui.model_title = model ui.model_filter = filter: ui.model_hint = type to filter Up/Down move Enter selects Esc cancels +ui.status_turn = %lds ui.model_empty = no models configured +ui.model_probing = asking the endpoint what it serves ... ui.model_none = no match sidebar.session = session diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg index 9db1108..a3d7807 100644 --- a/share/locale/pt_BR.msg +++ b/share/locale/pt_BR.msg @@ -21,7 +21,9 @@ ui.steer_failed = direcionamento nao aceito (nenhum turno em andamento) ui.model_title = modelo ui.model_filter = filtro: ui.model_hint = digite para filtrar setas movem Enter escolhe Esc cancela +ui.status_turn = %lds ui.model_empty = nenhum modelo configurado +ui.model_probing = perguntando ao endpoint o que ele serve ... ui.model_none = nenhum resultado ui.prompt_mark = > ui.steer_mark = direcionar> diff --git a/src/backend/agent.c b/src/backend/agent.c index 60bf6c1..c9fbe0f 100644 --- a/src/backend/agent.c +++ b/src/backend/agent.c @@ -722,6 +722,8 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, reply.tokens_in : 0); a->stats.tokens_out += (size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0); + if (reply.cost > 0) + a->stats.cost += reply.cost; /* * Some providers do not report usage on a tool-call step. A zero * there is "unknown", not "the context became empty": keep the diff --git a/src/backend/builtin.c b/src/backend/builtin.c index 5369738..36ecc9d 100644 --- a/src/backend/builtin.c +++ b/src/backend/builtin.c @@ -133,9 +133,11 @@ extern char **environ; * Run a shell command for the model. * * fork/exec instead of popen(), for three reasons popen cannot give: - * - a timeout: the child gets its own process group, and when it outlives - * SPLINTER_RUN_TIMEOUT (default 300 s) the whole group is killed - a - * 'sleep 1000' or an editor waiting for input no longer holds the agent; + * - a timeout: the child gets its own process group, and when it stays + * silent for SPLINTER_RUN_TIMEOUT (default 600 s) the whole group is + * killed - a 'sleep 1000' or an editor waiting for input no longer holds + * the agent. Every chunk the command prints moves the deadline: a build + * that reports progress is working, not hung; * - stdin is /dev/null: a command that reads input used to read the curses * terminal, stealing the operator's keystrokes; * - the environment is filtered: see secret_env above. @@ -150,6 +152,7 @@ tool_run(const char *args, struct sp_buf *out, void *ctx) char **envp; size_t total = 0, n, i, j; int fds[2], status = 0, timeout_s, timed_out = 0, cut = 0; + int reaped = 0; pid_t child; time_t end; @@ -243,18 +246,35 @@ tool_run(const char *args, struct sp_buf *out, void *ctx) if (sp_buf_add(out, chunk, (size_t)got) != 0) break; total += (size_t)got; + /* + * The command said something, so it is working: give it + * another full window. Ask the process, not the pipe - a + * closed child can still have bytes buffered here. + */ + if (!reaped) { + pid_t r; + + do { + r = waitpid(child, &status, WNOHANG); + } while (r < 0 && errno == EINTR); + if (r == child) + reaped = 1; + } + if (!reaped) + end = time(NULL) + timeout_s; } if (timed_out || cut) (void)kill(-child, SIGKILL); close(fds[0]); - while (waitpid(child, &status, 0) < 0 && errno == EINTR) - ; + if (!reaped) + while (waitpid(child, &status, 0) < 0 && errno == EINTR) + ; sp_buf_free(&keep); if (cut) sp_buf_puts(out, "\n[output truncated at 1 MiB]"); if (timed_out) - return sp_buf_printf(out, "\n[timed out after %d s, killed]", - timeout_s); + return sp_buf_printf(out, + "\n[timed out: no output for %d s, killed]", timeout_s); if (WIFEXITED(status)) return sp_buf_printf(out, "\n[exit status %d]", WEXITSTATUS(status)); diff --git a/src/backend/confblock.c b/src/backend/confblock.c index fd659c9..412d2fc 100644 --- a/src/backend/confblock.c +++ b/src/backend/confblock.c @@ -74,7 +74,8 @@ static void skip(struct cb *c, int nl) { for (;;) { - if (*c->p == ' ' || *c->p == '\t' || *c->p == '\r') + if (*c->p == ' ' || *c->p == '\t' || *c->p == '\r' || + *c->p == ';') c->p++; else if (*c->p == '\n' && nl) { c->line++; @@ -152,7 +153,8 @@ scalar(struct cb *c) } else { while (*c->p != '\0' && !isspace((unsigned char)*c->p) && *c->p != '#' && *c->p != ',' && *c->p != ']' && - *c->p != '}' && *c->p != '[' && *c->p != '{') { + *c->p != '}' && *c->p != '[' && *c->p != '{' && + *c->p != ';') { tmp[n] = *c->p++; if (n + 1 < sizeof(tmp)) n++; diff --git a/src/backend/engine.c b/src/backend/engine.c index e31a240..ce2cd16 100644 --- a/src/backend/engine.c +++ b/src/backend/engine.c @@ -121,6 +121,14 @@ struct sp_engine { /* the last turn, for the sidebar and /status */ size_t last_ms, last_steps, last_calls; size_t turn_out0; /* tokens_out when the turn began */ + size_t turn_in0; /* tokens_in when the turn began */ + double turn_cost0; /* cost when the turn began */ + struct { + unsigned turns; + unsigned long ms; + size_t in, out; + double cost; + } judged, plain; /* the two kinds, for /cost */ size_t last_turn_out; /* output tokens it produced */ struct timespec turn_t0; /* @@ -223,6 +231,7 @@ sp_engine_state(struct sp_engine *e, struct sp_engine_state *st) pthread_mutex_lock(&e->lock); st->tokens_in = e->snapshot.tokens_in; st->tokens_out = e->snapshot.tokens_out; + st->cost = e->snapshot.cost; st->ctx_used = e->snapshot.last_in; st->cached = e->snapshot.last_cached; st->turn_tokens_out = e->running && e->snapshot.tokens_out >= @@ -291,6 +300,78 @@ sp_engine_models(struct sp_engine *e, struct sp_model_choice *v, size_t max) return sp_provider_choices(e->conf, e->cur_model, v, max); } +/* + * The endpoint says what it really serves; the configured model may be one of + * several aliases or not listed at all. Only the provider the session is on is + * asked: /model with no argument must open at once, and one GET is enough to + * show the rest of that endpoint's menu. + */ +size_t +sp_engine_served_models(struct sp_engine *e, struct sp_model_choice *v, + size_t max) +{ + struct sp_provider p; + struct sp_buf ids, perr; + const char *act; + char *m, *save = NULL; + size_t i, n = 0, np; + + if (e == NULL || e->conf == NULL || v == NULL || max == 0 || + e->cur_endpoint[0] == '\0') + return 0; + memset(&p, 0, sizeof(p)); + act = sp_usage_active(); + np = sp_provider_count(e->conf); + for (i = 0; i < np; i++) { + struct sp_provider q; + + if (sp_provider_at(e->conf, i, &q) != 0) + continue; + if ((act != NULL && *act != '\0' && + strcmp(q.id, act) == 0) || + strcmp(q.endpoint, e->cur_endpoint) == 0) { + p = q; + break; + } + } + if (p.id[0] == '\0') { + /* --endpoint/--model without a provider block */ + snprintf(p.id, sizeof(p.id), "%s", + act != NULL && *act != '\0' ? act : "main"); + snprintf(p.kind, sizeof(p.kind), "%s", e->conf->kind); + snprintf(p.endpoint, sizeof(p.endpoint), "%s", e->cur_endpoint); + snprintf(p.model, sizeof(p.model), "%s", e->cur_model); + snprintf(p.key_env, sizeof(p.key_env), "%s", e->conf->key_env); + } + if (p.endpoint[0] == '\0' || strcmp(p.kind, "cli") == 0) + return 0; + if (sp_buf_init(&ids) != 0) + return 0; + if (sp_buf_init(&perr) != 0) { + sp_buf_free(&ids); + return 0; + } + if (sp_provider_served(&p, &ids, &perr) == 0 && ids.p != NULL) { + for (m = strtok_r(ids.p, "\n", &save); + m != NULL && n < max; m = strtok_r(NULL, "\n", &save)) { + if (*m == '\0' || strcmp(m, p.model) == 0) + continue; + if (p.main || strcmp(p.id, "main") == 0) + snprintf(v[n].sel, sizeof(v[n].sel), "%s", m); + else + snprintf(v[n].sel, sizeof(v[n].sel), "%s/%s", + p.id, m); + snprintf(v[n].label, sizeof(v[n].label), "%s %s", + p.id, m); + v[n].current = strcmp(m, e->cur_model) == 0; + n++; + } + } + sp_buf_free(&ids); + sp_buf_free(&perr); + return n; +} + /* /.agent: the profile a session was left in */ static void profile_path(struct sp_engine *e, char *buf, size_t cap) @@ -315,6 +396,94 @@ profile_save(struct sp_engine *e) (void)chmod(path, 0600); } +/* /.model: the model /model chose in this session */ +static void +session_model_path(struct sp_engine *e, char *buf, size_t cap) +{ + snprintf(buf, cap, "%s/%s.model", e->sess.dir, e->sess.id); +} + +static int +session_model_save(struct sp_engine *e, const char *sel, char *err, + size_t errcap) +{ + char path[800], tmp[820]; + FILE *f; + + if (e == NULL || sel == NULL || *sel == '\0') + return -1; + session_model_path(e, path, sizeof(path)); + snprintf(tmp, sizeof(tmp), "%s.tmp", path); + f = fopen(tmp, "w"); + if (f == NULL) { + if (err != NULL && errcap > 0) + snprintf(err, errcap, "%s", strerror(errno)); + return -1; + } + (void)fchmod(fileno(f), 0600); + fprintf(f, "%s\n", sel); + if (fclose(f) != 0 || rename(tmp, path) != 0) { + if (err != NULL && errcap > 0) + snprintf(err, errcap, "%s", strerror(errno)); + (void)unlink(tmp); + return -1; + } + return 0; +} + +static int +session_model_read(struct sp_engine *e, char *buf, size_t cap) +{ + char path[800], line[320]; + FILE *f; + size_t n; + + if (e == NULL || e->sess.dir[0] == '\0' || buf == NULL || cap == 0) + return -1; + session_model_path(e, path, sizeof(path)); + f = fopen(path, "r"); + if (f == NULL) + return -1; + if (fgets(line, sizeof(line), f) == NULL) { + fclose(f); + return -1; + } + fclose(f); + line[strcspn(line, "\r\n")] = '\0'; + n = strlen(line); + if (n == 0 || n >= cap) + return -1; + memcpy(buf, line, n + 1); + return 0; +} + +/* the selector that puts this engine back on the model it is on now */ +static void +current_model_selector(struct sp_engine *e, char *buf, size_t cap) +{ + const char *act = sp_usage_active(); + + if (act != NULL && *act != '\0' && strcmp(act, "main") != 0) + snprintf(buf, cap, "%s/%s", act, e->cur_model); + else + snprintf(buf, cap, "%s", e->cur_model); +} + +/* the transcript note after a successful /model: saved in this session */ +static void +session_model_note(struct sp_engine *e, const char *sel, struct sp_buf *out, + const char *model, const char *provider) +{ + char err[128]; + + err[0] = '\0'; + if (session_model_save(e, sel, err, sizeof(err)) != 0) + sp_buf_printf(out, sp_t("model.save_failed"), model, provider, + err[0] != '\0' ? err : "?"); + else + sp_buf_printf(out, sp_t("model.switched"), model, provider); +} + static int profile_load(struct sp_engine *e, char *buf, size_t cap) { @@ -932,6 +1101,8 @@ turn_thread(void *arg) sp_buf_clear(&e->err); pthread_mutex_lock(&e->lock); e->turn_out0 = e->ag.stats.tokens_out; + e->turn_in0 = e->ag.stats.tokens_in; + e->turn_cost0 = e->ag.stats.cost; pthread_mutex_unlock(&e->lock); rc = sp_agent_run(&e->ag, text, &e->answer, &e->err); if (e->have_swarm) @@ -1026,6 +1197,28 @@ turn_thread(void *arg) e->last_ms = ms; e->last_turn_out = e->ag.stats.tokens_out >= e->turn_out0 ? e->ag.stats.tokens_out - e->turn_out0 : 0; + { + struct sp_engine *ce = e; + int is_judged = strstr(ce->cur_model, "judged") != NULL; + size_t tin = ce->ag.stats.tokens_in >= ce->turn_in0 ? + ce->ag.stats.tokens_in - ce->turn_in0 : 0; + double c = ce->ag.stats.cost >= ce->turn_cost0 ? + ce->ag.stats.cost - ce->turn_cost0 : 0; + + if (is_judged) { + ce->judged.turns++; + ce->judged.ms += (unsigned long)ms; + ce->judged.in += tin; + ce->judged.out += ce->last_turn_out; + ce->judged.cost += c; + } else { + ce->plain.turns++; + ce->plain.ms += (unsigned long)ms; + ce->plain.in += tin; + ce->plain.out += ce->last_turn_out; + ce->plain.cost += c; + } + } e->last_steps = e->ag.stats.steps; e->last_calls = e->ag.stats.tool_calls; pthread_mutex_unlock(&e->lock); @@ -1522,7 +1715,7 @@ int sp_engine_command_names(struct sp_engine *e, char (*names)[64], int max) { static const char *builtin[] = { - "agent", "agents", "compact", "connect", "continue", "exit", "model", + "agent", "agents", "compact", "connect", "continue", "cost", "exit", "model", "new", "q", "quit", "rename", "reset", "resume", "rm", "status", "swarm", "usage", "widgets" }; @@ -1564,12 +1757,17 @@ sp_engine_command_names(struct sp_engine *e, char (*names)[64], int max) return n; } -/* /model: list, switch provider, pool or model; remember the choice */ +/* + * /model: list, switch provider, pool or model. The choice is written to the + * session's own sidecar, so reopening that conversation brings it back without + * changing what a new conversation starts on. 'probe' asks the configured + * endpoints which models they really serve. + */ static void cmd_model(struct sp_engine *e, const char *args, struct sp_buf *out) { struct sp_provider p; - struct sp_buf perr, serr; + struct sp_buf perr; size_t idx = 0, i, n; char poolname[40]; int is_pool = 0; @@ -1607,6 +1805,45 @@ cmd_model(struct sp_engine *e, const char *args, struct sp_buf *out) sp_buf_printf(out, " %s", e->conf->pool[i].member[j]); } + } else if (strcmp(args, "probe") == 0) { + size_t total = 0; + + n = sp_provider_count(e->conf); + for (i = 0; i < n; i++) { + struct sp_buf ids, perr2; + char *m, *save = NULL; + + if (sp_provider_at(e->conf, i, &p) != 0 || + p.endpoint[0] == '\0' || + strcmp(p.kind, "cli") == 0) + continue; + if (sp_buf_init(&ids) != 0) + break; + if (sp_buf_init(&perr2) != 0) { + sp_buf_free(&ids); + break; + } + if (sp_provider_served(&p, &ids, &perr2) == 0 && + ids.p != NULL) { + for (m = strtok_r(ids.p, "\n", &save); + m != NULL; m = strtok_r(NULL, "\n", &save)) { + if (*m == '\0') + continue; + if (p.main || + strcmp(p.id, "main") == 0) + sp_buf_printf(out, + "\n %s", m); + else + sp_buf_printf(out, + "\n %s/%s", p.id, m); + total++; + } + } + sp_buf_free(&ids); + sp_buf_free(&perr2); + } + if (total == 0) + sp_buf_puts(out, sp_t("model.probe_none")); } else if (is_pool) { struct sp_choice ch; @@ -1625,12 +1862,13 @@ cmd_model(struct sp_engine *e, const char *args, struct sp_buf *out) "%s", ch.d->endpoint); snprintf(e->cur_model, sizeof(e->cur_model), "%s", ch.model[0] != '\0' ? ch.model : ch.d->model); - sp_buf_printf(out, sp_t("model.pool"), poolname, + session_model_note(e, poolname, out, e->cur_model, ch.d->id); } sp_buf_free(&perr); } } else if (sp_provider_find(e->conf, args, &idx)) { + /* a provider id: its configured model, main included */ sp_buf_init(&perr); if (sp_provider_use(&e->ag, e->conf, idx, &perr) != 0) { sp_buf_printf(out, sp_t("model.failed"), @@ -1640,43 +1878,79 @@ cmd_model(struct sp_engine *e, const char *args, struct sp_buf *out) p.endpoint); snprintf(e->cur_model, sizeof(e->cur_model), "%s", p.model); - sp_buf_init(&serr); - sp_buf_printf(out, sp_provider_save_choice(e->conf, &p, - &serr) == 0 ? sp_t("model.saved") : - sp_t("model.switched"), p.model, p.id); - sp_buf_free(&serr); + session_model_note(e, p.id, out, p.model, p.id); } sp_buf_free(&perr); } else { - struct sp_provider chosen; - int ok; + struct sp_choice ch; - memset(&p, 0, sizeof(p)); - if (!sp_provider_find(e->conf, e->cur_model, &idx) || - sp_provider_at(e->conf, idx, &p) != 0) - (void)sp_provider_at(e->conf, 0, &p); - sp_buf_init(&perr); - ok = sp_provider_apply(&e->ag, p.kind, p.endpoint, args, - p.key_env, &perr) == 0; - if (ok) { - memset(&chosen, 0, sizeof(chosen)); - snprintf(chosen.id, sizeof(chosen.id), "%s", p.id); - snprintf(chosen.endpoint, sizeof(chosen.endpoint), "%s", - p.endpoint); - snprintf(chosen.model, sizeof(chosen.model), "%s", args); - snprintf(chosen.key_env, sizeof(chosen.key_env), "%s", - p.key_env); - snprintf(e->cur_model, sizeof(e->cur_model), "%s", args); - sp_buf_init(&serr); - sp_buf_printf(out, sp_provider_save_choice(e->conf, - &chosen, &serr) == 0 ? sp_t("model.saved") : - sp_t("model.switched"), args, p.id); - sp_buf_free(&serr); + memset(&ch, 0, sizeof(ch)); + if (sp_provider_choose(e->conf, args, &ch) == 0 && + ch.d != NULL) { + /* provider/model, or a model one provider owns */ + const char *model = ch.model[0] != '\0' ? + ch.model : ch.d->model; + char sel[320]; + + sp_buf_init(&perr); + if (sp_provider_apply(&e->ag, ch.d->kind, + ch.d->endpoint, model, ch.d->key_env, &perr) != 0) { + sp_buf_printf(out, sp_t("model.failed"), + perr.p != NULL ? perr.p : "?"); + } else { + sp_usage_set_active(ch.d->id); + snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), + "%s", ch.d->endpoint); + snprintf(e->cur_model, sizeof(e->cur_model), "%s", + model); + if (strcmp(ch.d->id, "main") == 0) + snprintf(sel, sizeof(sel), "%s", model); + else + snprintf(sel, sizeof(sel), "%s/%s", + ch.d->id, model); + session_model_note(e, sel, out, e->cur_model, + ch.d->id); + } + sp_buf_free(&perr); } else { - sp_buf_printf(out, sp_t("model.failed"), - perr.p != NULL ? perr.p : "?"); + /* + * A bare model the config does not own: it goes on the + * endpoint this session is already talking to. + */ + const char *act = sp_usage_active(); + char sel[320]; + int ok; + + memset(&p, 0, sizeof(p)); + if (act == NULL || *act == '\0' || + !sp_provider_find(e->conf, act, &idx)) + idx = 0; + if (sp_provider_at(e->conf, idx, &p) != 0) { + sp_buf_printf(out, sp_t("model.unknown"), + args); + } else { + sp_buf_init(&perr); + ok = sp_provider_apply(&e->ag, p.kind, + p.endpoint, args, p.key_env, &perr) == 0; + if (ok) { + snprintf(e->cur_model, + sizeof(e->cur_model), "%s", args); + if (p.main || + strcmp(p.id, "main") == 0) + snprintf(sel, sizeof(sel), "%s", + args); + else + snprintf(sel, sizeof(sel), + "%s/%s", p.id, args); + session_model_note(e, sel, out, args, + p.id); + } else { + sp_buf_printf(out, sp_t("model.failed"), + perr.p != NULL ? perr.p : "?"); + } + sp_buf_free(&perr); + } } - sp_buf_free(&perr); } if (e->host != NULL) sp_host_set_model(e->host, e->cur_model); @@ -1717,6 +1991,13 @@ cmd_new(struct sp_engine *e, struct sp_buf *out) (void)sp_log_open(e->sess.dir, e->sess.id); sp_logf("session", "started: %s", e->sess.id); profile_save(e); + { + char sel[320]; + + current_model_selector(e, sel, sizeof(sel)); + if (sel[0] != '\0') + (void)session_model_save(e, sel, NULL, 0); + } ev_push(e, SP_EV_CLEAR, 0, NULL, NULL); sp_buf_printf(out, sp_t("session.new"), e->sess.id); } @@ -1968,6 +2249,61 @@ cmd_agents(struct sp_engine *e, struct sp_buf *out) sp_buf_puts(out, sp_t("agent.help")); } +/* + * What the session has cost so far and what the provider told us about it. + * judge calls happen upstream; the usage object only carries the final answer, + * so this reports what is measurable and says where it stops. + */ +static void +cmd_cost(struct sp_engine *e, struct sp_buf *out) +{ + struct sp_agent_stats st = e->snapshot; + unsigned cachepct = 0; + + if (st.last_in > 0 && st.last_cached > 0) + cachepct = (unsigned)(100.0 * (double)st.last_cached / + (double)st.last_in); + sp_buf_printf(out, "cost: $%.4f reported, %zu in / %zu out, " + "last ctx %u%% cached\n", st.cost, st.tokens_in, st.tokens_out, + cachepct); + sp_buf_printf(out, "average: $%.5f/turn, %zu ms/turn, %zu calls\n", + e->judged.turns + e->plain.turns > 0 ? + st.cost / (double)(e->judged.turns + e->plain.turns) : 0.0, + e->judged.turns + e->plain.turns > 0 ? + (e->judged.ms + e->plain.ms) / (e->judged.turns + e->plain.turns) : 0, + st.tool_calls); + if (e->judged.turns > 0 || e->plain.turns > 0) { + sp_buf_printf(out, "judged: %u turns, %.0f ms/turn, " + "%.0f tok/turn, $%.5f/turn\n", e->judged.turns, + e->judged.turns ? (double)e->judged.ms / e->judged.turns : 0, + e->judged.turns ? (double)(e->judged.in + e->judged.out) / + e->judged.turns : 0, + e->judged.turns ? e->judged.cost / e->judged.turns : 0); + sp_buf_printf(out, "plain: %u turns, %.0f ms/turn, " + "%.0f tok/turn, $%.5f/turn\n", e->plain.turns, + e->plain.turns ? (double)e->plain.ms / e->plain.turns : 0, + e->plain.turns ? (double)(e->plain.in + e->plain.out) / + e->plain.turns : 0, + e->plain.turns ? e->plain.cost / e->plain.turns : 0); + if (e->judged.turns > 0 && e->plain.turns > 0) + sp_buf_printf(out, "delta: %+.0f ms, %+.0f tok, " + "%+.5f $/turn (judged - plain)\n", + (double)e->judged.ms / e->judged.turns - + (double)e->plain.ms / e->plain.turns, + (double)(e->judged.in + e->judged.out) / + e->judged.turns - + (double)(e->plain.in + e->plain.out) / + e->plain.turns, + (e->judged.cost / e->judged.turns) - + (e->plain.cost / e->plain.turns)); + } + if (strstr(e->cur_model, "judged") != NULL) + sp_buf_puts(out, "note: judge calls happen upstream; the " + "provider's usage carries only the final answer, so they " + "are not in $ or tokens above - only latency and the " + "reported tokens are measurable\n"); +} + int sp_engine_input(struct sp_engine *e, const char *line, struct sp_buf *out) { @@ -2058,6 +2394,10 @@ sp_engine_input(struct sp_engine *e, const char *line, struct sp_buf *out) ev_push(e, SP_EV_STATE, 0, NULL, NULL); return SP_INPUT_HANDLED; } + if (strcmp(name, "cost") == 0) { + cmd_cost(e, out); + return SP_INPUT_HANDLED; + } if (strcmp(name, "status") == 0) { cmd_status(e, out); return SP_INPUT_HANDLED; @@ -2402,13 +2742,21 @@ int sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o, struct sp_buf *err) { + struct sp_engine_opts local; struct sp_engine *e; - char cwd[700]; + char cwd[700], saved[320], saved_model[320]; int start = -1, code = -1; if (out == NULL || o == NULL || o->conf == NULL || o->base == NULL) return -1; *out = NULL; + /* + * The model a session was left on wins over the configuration when the + * session comes back: a choice made with /model belongs to the + * conversation, not to every later start. + */ + local = *o; + o = &local; e = calloc(1, sizeof(*e)); if (e == NULL) { sp_buf_puts(err, sp_t("err.oom")); @@ -2455,6 +2803,35 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o, } if (open_session(e, o, err, &code) != 0) goto fail; + if (session_model_read(e, saved, sizeof(saved)) == 0) { + struct sp_choice ch; + + memset(&ch, 0, sizeof(ch)); + if (sp_provider_choose(e->conf, saved, &ch) == 0 && + ch.d != NULL) { + local.endpoint = ch.d->endpoint; + snprintf(saved_model, sizeof(saved_model), "%s", + ch.model[0] != '\0' ? ch.model : ch.d->model); + local.model = saved_model; + local.kind = ch.d->kind; + local.key_env = ch.d->key_env; + sp_usage_set_active(ch.d->id); + } else if (strchr(saved, '/') == NULL) { + /* a model of the endpoint the run was configured with */ + snprintf(saved_model, sizeof(saved_model), "%s", saved); + local.model = saved_model; + } else { + sp_logf("session", "saved model '%s' is gone; " + "using the default", saved); + saved[0] = '\0'; + } + if (saved[0] != '\0') { + snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), "%s", + local.endpoint != NULL ? local.endpoint : ""); + snprintf(e->cur_model, sizeof(e->cur_model), "%.255s", + local.model != NULL ? local.model : ""); + } + } e->ag.sess = &e->sess; sp_logf("session", "started: %s", e->sess.id); if (load_plugins(e, o, err) != 0) @@ -2481,7 +2858,8 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o, snprintf(e->conf->endpoint, sizeof(e->conf->endpoint), "%s", o->endpoint); if (e->conf->model[0] == '\0' && o->model != NULL) - snprintf(e->conf->model, sizeof(e->conf->model), "%s", o->model); + snprintf(e->conf->model, sizeof(e->conf->model), "%.255s", + o->model); if (setup_conversation(e, o, err) != 0) goto fail; e->ag.reg = &e->reg; diff --git a/src/backend/openai.c b/src/backend/openai.c index 6834ea6..fd0b5ed 100644 --- a/src/backend/openai.c +++ b/src/backend/openai.c @@ -270,6 +270,14 @@ sp_openai_reply(const char *json, struct sp_reply *out, struct sp_buf *err) out->tokens_out = pout; if (cached >= 0) out->tokens_cached = cached; + { + double c = mcp_arg_num(usage, "cost", -1); + + if (c < 0) + c = mcp_arg_num(usage, "cost_usd", -1); + if (c >= 0) + out->cost = c; + } } } diff --git a/src/backend/providers.c b/src/backend/providers.c index ad8863b..d4e2029 100644 --- a/src/backend/providers.c +++ b/src/backend/providers.c @@ -303,7 +303,8 @@ http_get(const char *url, const char *const *headers, struct sp_buf *out, snprintf(tbuf, sizeof(tbuf), "%d", PROVIDER_GET_TIMEOUT_S); snprintf(cbuf, sizeof(cbuf), "%d", PROVIDER_CONNECT_TIMEOUT_S); - args[n++] = "-sS"; + /* -s, not -sS: a probe can fail while curses owns the terminal */ + args[n++] = "-s"; args[n++] = "--connect-timeout"; args[n++] = cbuf; args[n++] = "-m"; diff --git a/src/backend/sse.c b/src/backend/sse.c index 84c4f83..692f5f6 100644 --- a/src/backend/sse.c +++ b/src/backend/sse.c @@ -40,6 +40,7 @@ struct sp_sse { long tokens_in; long tokens_out; long tokens_cached; + double cost; }; #define PENDING_MAX (1u << 20) /* a huge "object" is not a kept promise */ @@ -256,6 +257,14 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out, s->tokens_out = out; if (cached >= 0) s->tokens_cached = cached; + { + double c = mcp_arg_num(usage, "cost", -1); + + if (c < 0) + c = mcp_arg_num(usage, "cost_usd", -1); + if (c >= 0) + s->cost = c; + } } } @@ -379,6 +388,7 @@ sp_sse_finish(struct sp_sse *s, struct sp_reply *out, struct sp_buf *err) out->tokens_in = s->tokens_in; out->tokens_out = s->tokens_out; out->tokens_cached = s->tokens_cached; + out->cost = s->cost; out->content = strdup(s->content.p != NULL ? s->content.p : ""); if (out->content == NULL) return -1; diff --git a/src/frontend/curses.c b/src/frontend/curses.c index 24ce3b7..9f70d1b 100644 --- a/src/frontend/curses.c +++ b/src/frontend/curses.c @@ -19,9 +19,9 @@ * | | session | * | | directory | * +---------------------------------+------------+ - * | ctx 1290/131072 [|| ] 1% | cache 62% | t/s | + * | 12s | ctx 1290/131072 [|| ] 1% | cache 62% | t/s | * +----------------------------------------------+ - * | build> prompt, or "12s tool steer>" | + * | build> prompt, or "steer> " while a turn runs| * +----------------------------------------------+ * * Only the UI thread ever calls into curses. The engine runs a turn on a @@ -113,8 +113,11 @@ struct ui_state { size_t gen; /* history changed since painted */ size_t painted; /* the generation last drawn */ long last_ms; + long turn_ms; /* the running turn, for the status bar */ + int turn_running; size_t tokens_in; size_t tokens_out; + double cost; size_t ctx_used; /* prompt tokens of the last request */ size_t ctx_max; /* its context window, 0 = unknown */ size_t ctx_cached; /* of ctx_used, served from cache */ @@ -198,6 +201,7 @@ sync_state(struct ui_state *s) return; s->tokens_in = st.tokens_in; s->tokens_out = st.tokens_out; + s->cost = st.cost; s->ctx_used = st.ctx_used; s->ctx_max = st.ctx_max; if (ctxmax != NULL && *ctxmax != '\0') @@ -1042,6 +1046,36 @@ sidebar_heading(int *y, int cols, const char *text) wattron(ui_side, COLOR_PAIR(PAIR_SIDE)); } +/* a plugin block's title: bold, underlined, italic where the terminal has it */ +static void +sidebar_widget_heading(int *y, int cols, const char *text) +{ + int attr = COLOR_PAIR(PAIR_SIDE) | A_BOLD | A_UNDERLINE; + +#ifdef A_ITALIC + attr |= A_ITALIC; +#endif + wattron(ui_side, attr); + mvwaddnstr(ui_side, *y, 0, text, cols - 1); + wattrset(ui_side, COLOR_PAIR(PAIR_SIDE)); + (*y)++; +} + +/* the line between two plugin blocks; '-' because this curses' ACS is broken */ +static void +sidebar_rule(int *y, int cols) +{ + int i, w = cols > 1 ? cols - 1 : 1; + + if (*y >= getmaxy(ui_side) - 2) + return; + wattron(ui_side, COLOR_PAIR(PAIR_DIM)); + for (i = 0; i < w; i++) + mvwaddch(ui_side, *y, i, '-'); + wattrset(ui_side, COLOR_PAIR(PAIR_SIDE)); + (*y)++; +} + /* * Wrap 'text' into the sidebar from row *y, at most 'maxrows' rows. The * first row of a widget is its title line: bold, so a plugin block reads as a @@ -1224,6 +1258,7 @@ draw_sidebar(struct ui_state *s, const char *id, const char *dir, if (host != NULL && sp_host_widget_count(host) > 0) { char snap[1024], *line, *save = NULL; char cont_name[48] = ""; + int first_widget = 1; sp_host_widget_snapshot(host, snap, sizeof(snap)); for (line = strtok_r(snap, "\n", &save); line != NULL; @@ -1260,11 +1295,16 @@ draw_sidebar(struct ui_state *s, const char *id, const char *dir, } if (*text == '\0' || y >= getmaxy(ui_side) - 2) continue; - /* one blank row between widgets, not between their rows */ - if (cont_name[0] != '\0' && y < getmaxy(ui_side) - 2) - y++; + /* + * A rule between the plugin blocks, not between their + * rows: the sidebar has to read as separate reports. + */ + if (!first_widget && cont_name[0] != '\0' && + y < getmaxy(ui_side) - 2) + sidebar_rule(&y, cols); + first_widget = 0; snprintf(key, sizeof(key), "widget.%s", name); - sidebar_heading(&y, cols, sp_td(key, name)); + sidebar_widget_heading(&y, cols, sp_td(key, name)); side_text(&y, cols, text, 8, 1); snprintf(cont_name, sizeof(cont_name), "%s", name); } @@ -1337,6 +1377,7 @@ set_ui_fields(struct sp_meter *m, void *ctx) m->cached = s->ctx_cached; m->tok_in = s->tokens_in; m->tok_out = s->tokens_out; + m->cost = s->cost; if (s->last_ms > 0 && s->turn_out > 0) m->tps = (long)((double)s->turn_out * 1000.0 / (double)s->last_ms); @@ -1368,6 +1409,11 @@ draw_statusbar(struct ui_state *s) return; werase(ui_status); wattrset(ui_status, COLOR_PAIR(PAIR_STATUS)); + if (s->turn_running) { + n += (size_t)snprintf(line + n, sizeof(line) - n, + sp_td("ui.status_turn", "%lds"), s->turn_ms / 1000); + n += (size_t)snprintf(line + n, sizeof(line) - n, " | "); + } if (max > 0) { int bw = 16, filled, pct; @@ -1852,11 +1898,23 @@ model_picker(const struct ui_backend *be, char *sel, size_t cap) return -1; memset(&list, 0, sizeof(list)); filter[0] = '\0'; - be->models(be->ctx, pick_add, &list); - nmatch = pick_match(&list, filter, match); win = pick_window(&w, &h); if (win == NULL) return -1; + /* the configured list is instant; the endpoint may take a moment */ + be->models(be->ctx, pick_add, &list); + if (be->served != NULL) { + werase(win); + wattrset(win, COLOR_PAIR(PAIR_STATUS) | A_BOLD); + mvwhline(win, 0, 0, ' ', w); + mvwaddnstr(win, 0, 1, sp_t("ui.model_title"), w - 2); + wattrset(win, COLOR_PAIR(PAIR_MAIN)); + mvwaddnstr(win, 3, 2, sp_t("ui.model_probing"), w - 4); + wnoutrefresh(win); + doupdate(); + be->served(be->ctx, pick_add, &list); + } + nmatch = pick_match(&list, filter, match); for (;;) { int changed = 0; int listh = h - 4; @@ -2400,9 +2458,6 @@ struct turn_view { struct sp_buf live; /* the step's answer so far */ char line[1024]; /* steering text being typed */ size_t llen; - char note[600]; /* a usage-limit wait, or "" */ - char steer[160]; /* "steering queued (n)", or "" */ - unsigned steers; /* how many went out this turn */ int rc; int got_end; }; @@ -2488,8 +2543,6 @@ finalize_turn(struct ui_state *s, struct turn_view *v, int rc, const char *answe v->ans.id = v->ans.off = v->ans.shown = 0; sp_buf_clear(&v->thinkbuf); sp_buf_clear(&v->live); - v->note[0] = '\0'; - v->steer[0] = '\0'; } /* @@ -2536,7 +2589,6 @@ drain_events(struct ui_state *s, struct turn_view *v) seg_show(s, &v->ans, "agent", ev.b); v->think.id = v->think.off = v->think.shown = 0; v->ans.id = v->ans.off = v->ans.shown = 0; - v->steer[0] = '\0'; sp_buf_clear(&v->thinkbuf); sp_buf_clear(&v->live); break; @@ -2556,8 +2608,14 @@ drain_events(struct ui_state *s, struct turn_view *v) add_entry(s, "observation", ev.b); break; case SP_EV_NOTE: - snprintf(v->note, sizeof(v->note), "%s", - ev.a != NULL ? ev.a : ""); + /* + * A backend note (a retry, a usage-limit wait) is a + * status message and belongs below the row that caused + * it, not in the input line or the status bar. The + * retry itself is the agent's job. + */ + if (ev.a != NULL && ev.a[0] != '\0') + add_entry(s, "splinter", ev.a); break; case SP_EV_ENTRY: add_entry(s, ev.a, ev.b); @@ -2590,57 +2648,35 @@ drain_events(struct ui_state *s, struct turn_view *v) } /* - * The steering line: elapsed seconds, an engine note (a usage-limit wait), the - * steer confirmation, then "steer>" and what is typed. One row, never wrapped. - * Called every tick and, without a history repaint, after every key: typing - * must not wait for the next 100 ms frame. + * The steering line: the steer mark and what is typed, nothing else. It is one + * row and never wraps. Called every tick and, without a history repaint, after + * every key: typing must not wait for the next 100 ms frame. The running time + * is a meter and lives in the status bar; notes from the backend are transcript + * rows, so nothing but the input appears here. */ static void turn_draw_input(struct ui_state *s, struct turn_view *v) { - struct timespec now; - long ms; - int w, used; + int w, used; + char steer[32]; - clock_gettime(CLOCK_MONOTONIC, &now); - ms = (long)((now.tv_sec - v->t0.tv_sec) * 1000 + - (now.tv_nsec - v->t0.tv_nsec) / 1000000); - s->last_ms = ms; + (void)s; werase(ui_input); w = getmaxx(ui_input) - 1; + snprintf(steer, sizeof(steer), "%s", + sp_td("ui.steer_mark", "steer> ")); + /* a catalogue entry without the trailing space must not glue the + * typed text to the mark: steer>x reads like a syntax error */ { - /* - * No status bar: the input line leads with how long the turn - * has been running and the steer prompt. The notes are the - * exception - a usage-limit wait and a queued steer say so - * here, because that is where the operator is looking. - */ - char note[900], mark[1000], steer[32], extra[200]; + size_t sl = strlen(steer); - snprintf(steer, sizeof(steer), "%s", - sp_td("ui.steer_mark", "steer> ")); - /* a catalogue entry without the trailing space must not glue the - * typed text to the mark: steer>x reads like a syntax error */ - { - size_t sl = strlen(steer); - - if (sl > 0 && steer[sl - 1] != ' ' && - sl + 1 < sizeof(steer)) { - steer[sl] = ' '; - steer[sl + 1] = '\0'; - } + if (sl > 0 && steer[sl - 1] != ' ' && sl + 1 < sizeof(steer)) { + steer[sl] = ' '; + steer[sl + 1] = '\0'; } - extra[0] = '\0'; - if (v->steer[0] != '\0') - snprintf(extra, sizeof(extra), " %s", v->steer); - snprintf(note, sizeof(note), "%lds%s%.500s%s", ms / 1000, - v->note[0] != '\0' ? " " : "", v->note, extra); - cut_line(note, w > (int)strlen(steer) + 2 ? - (size_t)w - strlen(steer) - 2 : 0); - snprintf(mark, sizeof(mark), "%s %s", note, steer); - mvwaddnstr(ui_input, 0, 0, mark, w); - used = (int)strlen(mark); } + mvwaddnstr(ui_input, 0, 0, steer, w); + used = (int)strlen(steer); if (used < w) ui_add_text(ui_input, v->line, w - used - 1); wclrtoeol(ui_input); @@ -2675,6 +2711,13 @@ turn_paint(struct ui_state *s, struct turn_view *v) swarm_poll(sw); update_meter(s, s->be->host(s->be->ctx)); + { + struct timespec now; + + clock_gettime(CLOCK_MONOTONIC, &now); + s->turn_ms = (long)((now.tv_sec - v->t0.tv_sec) * 1000 + + (now.tv_nsec - v->t0.tv_nsec) / 1000000); + } draw_statusbar(s); turn_draw_input(s, v); } @@ -2766,16 +2809,9 @@ turn_key(struct ui_state *s, struct turn_view *v, int c) char line[600]; if (s->be->steer(s->be->ctx, v->line) == 0) { - /* - * Say it twice: in the transcript, where the - * steer is a message to the model, and in the - * input line, which stays visible while the - * answer streams. - */ - v->steers++; - snprintf(v->steer, sizeof(v->steer), - "%s (%u)", sp_t("ui.steering_queued"), - v->steers); + /* the transcript is where a steer is a + * message to the model, and where it stays + * readable while the answer streams */ snprintf(line, sizeof(line), sp_t("ui.steer_queued_line"), v->line); cut_line(line, 240); @@ -2821,6 +2857,8 @@ ui_turn(struct ui_state *s, const char *text) return -1; } wtimeout(ui_input, 100); + s->turn_running = 1; + s->turn_ms = 0; for (;;) { int c; @@ -2848,14 +2886,13 @@ ui_turn(struct ui_state *s, const char *text) */ if (cancelled) { wtimeout(ui_input, 100); + /* the operator sees why the screen stays, in the transcript */ + add_entry(s, "splinter", sp_t("ui.cancelling")); while (s->be->busy(s->be->ctx)) { int c2; drain_events(s, &v); - werase(ui_input); - mvwaddstr(ui_input, 0, 0, sp_t("ui.cancelling")); - wclrtoeol(ui_input); - wrefresh(ui_input); + turn_draw_input(s, &v); c2 = wgetch(ui_input); if (c2 == 3 || c2 == 4) { endwin(); @@ -2868,6 +2905,7 @@ ui_turn(struct ui_state *s, const char *text) drain_events(s, &v); (void)s->be->wait(s->be->ctx); wtimeout(ui_input, -1); + s->turn_running = 0; sync_state(s); /* * The answers were added when their turn events arrived. What is left diff --git a/src/frontend/protocol.c b/src/frontend/protocol.c index 24a6949..95f8a43 100644 --- a/src/frontend/protocol.c +++ b/src/frontend/protocol.c @@ -485,9 +485,13 @@ send_sessions(struct client *c, struct proto *p) return rc; } -/* what a /model picker may offer; no network, the configuration is the list */ +/* + * What a /model picker may offer: the configuration, and with probe the + * endpoint this session is on says it serves as well. Probe is a network call; + * the picker asks for the configured list first and this after it is visible. + */ static int -send_models(struct client *c, struct proto *p) +send_models(struct client *c, struct proto *p, int probe) { struct sp_model_choice v[SP_MODEL_CHOICES]; size_t n, i; @@ -495,6 +499,9 @@ send_models(struct client *c, struct proto *p) int rc; n = sp_engine_models(p->eng, v, SP_MODEL_CHOICES); + if (probe) + n += sp_engine_served_models(p->eng, v + n, + SP_MODEL_CHOICES - n); if (sp_buf_init(&b) != 0) return -1; ev_start(&b, "models"); @@ -705,7 +712,7 @@ handle_line(struct client *c, struct proto *p, const char *line) } else if (strcmp(cmd, "sessions") == 0) { (void)send_sessions(c, p); } else if (strcmp(cmd, "models") == 0) { - (void)send_models(c, p); + (void)send_models(c, p, mcp_arg_bool(v, "probe", 0)); } else if (strcmp(cmd, "open") == 0) { (void)proto_open(c, p, mcp_arg_string(v, "session"), mcp_arg_bool(v, "new", 0)); diff --git a/src/frontend/ui_backend.h b/src/frontend/ui_backend.h index ddd8cbd..0d2d7e2 100644 --- a/src/frontend/ui_backend.h +++ b/src/frontend/ui_backend.h @@ -63,6 +63,13 @@ struct ui_backend { int (*models)(void *ctx, void (*cb)(void *cbctx, const char *sel, const char *label, int current), void *cbctx); + /* + * The same for the models the serving endpoint reports it has. Network; + * NULL when the backend cannot ask (then the picker stays config-only). + */ + int (*served)(void *ctx, + void (*cb)(void *cbctx, const char *sel, const char *label, + int current), void *cbctx); /* the sessions in this backend's directory; cb per entry */ int (*sessions)(void *ctx, void (*cb)(void *cbctx, const char *id, const char *title, diff --git a/src/frontend/ui_local.c b/src/frontend/ui_local.c index 16052b9..09dacf9 100644 --- a/src/frontend/ui_local.c +++ b/src/frontend/ui_local.c @@ -157,6 +157,19 @@ loc_models(void *ctx, void (*cb)(void *, const char *, const char *, int), return (int)n; } +static int +loc_served(void *ctx, void (*cb)(void *, const char *, const char *, int), + void *cbctx) +{ + struct sp_model_choice v[SP_MODEL_CHOICES]; + size_t n, i; + + n = sp_engine_served_models(ENG(ctx), v, SP_MODEL_CHOICES); + for (i = 0; i < n; i++) + cb(cbctx, v[i].sel, v[i].label, v[i].current); + return (int)n; +} + static int loc_history(void *ctx, void (*cb)(void *, const char *, const char *), void *cbctx) @@ -257,6 +270,7 @@ static const struct ui_backend local = { .agent_switch = loc_agent_switch, .command_names = loc_command_names, .models = loc_models, + .served = loc_served, .sessions = loc_sessions, .open_session = loc_open_session, .history = loc_history, diff --git a/src/frontend/ui_remote.c b/src/frontend/ui_remote.c index 0d2f2ec..de78ad2 100644 --- a/src/frontend/ui_remote.c +++ b/src/frontend/ui_remote.c @@ -712,20 +712,21 @@ rem_command_names(void *ctx, char (*names)[64], int max) /* * The picker's list from the server: `models` answers one event with every - * selector. Other events that arrive while we wait (state, busy) still go - * through dispatch, so nothing is lost. + * selector; probe also asks the serving endpoint. Other events that arrive + * while we wait (state, busy) still go through dispatch, so nothing is lost. */ static int -rem_models(void *ctx, void (*cb)(void *, const char *, const char *, int), - void *cbctx) +rem_models_probe(void *ctx, + void (*cb)(void *, const char *, const char *, int), void *cbctx, int probe) { struct rem *r = ctx; long deadline; int n = 0; - if (r->fd < 0 || send_cmd(r, "models", NULL, NULL) != 0) + if (r->fd < 0 || send_cmd(r, "models", probe ? "probe" : NULL, + probe ? "true" : NULL) != 0) return 0; - deadline = now_ms() + 5000; + deadline = now_ms() + (probe ? 15000 : 5000); while (now_ms() < deadline) { mcp_json *v; const char *ev; @@ -760,6 +761,20 @@ rem_models(void *ctx, void (*cb)(void *, const char *, const char *, int), return n; } +static int +rem_models(void *ctx, void (*cb)(void *, const char *, const char *, int), + void *cbctx) +{ + return rem_models_probe(ctx, cb, cbctx, 0); +} + +static int +rem_served(void *ctx, void (*cb)(void *, const char *, const char *, int), + void *cbctx) +{ + return rem_models_probe(ctx, cb, cbctx, 1); +} + static void emit_history(struct rem *r) { @@ -1104,6 +1119,7 @@ sp_ui_backend_remote(const char *socket_path, struct sp_buf *err) be.agent_switch = rem_agent_switch; be.command_names = rem_command_names; be.models = rem_models; + be.served = rem_served; be.sessions = rem_sessions; be.open_session = rem_open_session; be.take_steer = rem_take_steer; diff --git a/tests/fake_telegram.py b/tests/fake_telegram.py index 525e67f..037f52f 100644 --- a/tests/fake_telegram.py +++ b/tests/fake_telegram.py @@ -16,6 +16,7 @@ next_uid = [2] sent = [] TARGET = sys.argv[2] ANSWER = sys.argv[4] if len(sys.argv) > 4 else "ok" +FAILS = [2] # "wiederholen": the first two calls answer HTTP 500 def add_update(text, frm=7): @@ -153,12 +154,24 @@ class H(http.server.BaseHTTPRequestHandler): last_user = m.get("content") or "" break answer = "ok" + if "wiederholen" in last_user and FAILS[0] > 0: + # a provider that is briefly broken: the harness must retry and + # put the reason in the transcript, not in the input line + FAILS[0] -= 1 + self.send_response(500) + self.send_header("Content-Length", "0") + self.end_headers() + return if "INTERVIEW_COMPLETE" in system: # the model-driven interview: a summary and the marker; the # gateway strips it and writes USER.txt answer = "Testprofil: mag C99.\nINTERVIEW_COMPLETE" chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] + elif "wiederholen" in last_user: + answer = "antwort nach dem retry" + chunks = [{"choices": [{"delta": {"content": answer}}]}, + {"choices": [{"delta": {}, "finish_reason": "stop"}]}] elif "single word ok" in last_user: # /connect's test turn answer = "ok" diff --git a/tests/test_cli.c b/tests/test_cli.c index 6d306d6..73a8c7e 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -126,7 +126,7 @@ main(void) { struct sp_registry reg; struct sp_agent ag; - struct sp_host *host, *host2, *host3; + struct sp_host *host, *host2, *host3, *host4, *host5; struct sp_buf err; struct sp_reply rep; @@ -172,6 +172,30 @@ main(void) CHECK(strstr(err.p, "kaputt") != NULL); sp_reply_free(&rep); + /* + * The timeout is an idle window: a program that keeps printing is + * working, and the window moves with every line. One that says nothing + * for the whole window is still killed and reported. + */ + setenv("SPLINTER_CLI_TIMEOUT", "2", 1); + host4 = host_for(®, &ag, "sh -c 'for i in 1 2 3 4 5 6; do " + "echo tick; sleep 0.5; done; echo fertig'", &err); + CHECK(host4 != NULL); + sp_buf_clear(&err); + memset(&rep, 0, sizeof(rep)); + CHECK(one_turn(host4, "hallo", &rep, &err) == 0); + CHECK(rep.content != NULL && strstr(rep.content, "fertig") != NULL); + sp_reply_free(&rep); + + host5 = host_for(®, &ag, "sleep 10", &err); + CHECK(host5 != NULL); + sp_buf_clear(&err); + memset(&rep, 0, sizeof(rep)); + CHECK(one_turn(host5, "hallo", &rep, &err) == -1); + CHECK(strstr(err.p, "timed out") != NULL); + sp_reply_free(&rep); + unsetenv("SPLINTER_CLI_TIMEOUT"); + /* * Ctrl-C while the program runs. This is the freeze: the transport used * popen() and read the pipe with no way to stop it, so a `claude -p` turn diff --git a/tests/test_compactor.c b/tests/test_compactor.c index fa669f3..e046a6a 100644 --- a/tests/test_compactor.c +++ b/tests/test_compactor.c @@ -270,6 +270,24 @@ main(void) CHECK(compactions >= 1); CHECK(failed == 0); + /* + * The sidebar shows those numbers, not an estimate: the widget is the + * compactor's own counter, and the status line carries one segment. + */ + nap_ms(2200); /* the widget ticks every two seconds */ + { + char snap[2048]; + + CHECK(sp_host_widget_snapshot(host, snap, sizeof(snap)) > 0); + CHECK(strstr(snap, "lcm: ctx ") != NULL); + CHECK(strstr(snap, "compacted ") != NULL); + CHECK(strstr(snap, "cut ") != NULL); + CHECK(strstr(snap, "tools trimmed ") != NULL); + snap[0] = '\0'; + CHECK(sp_host_status_text(host, snap, sizeof(snap)) > 0); + CHECK(strstr(snap, "compact ") != NULL); + } + /* * ---- lcm never leaves a tool result without its call ---- * system, user, then [assistant+tool_calls, tool, tool] x 4, then a user: diff --git a/tests/test_confblock.c b/tests/test_confblock.c index a89e540..f54b0fd 100644 --- a/tests/test_confblock.c +++ b/tests/test_confblock.c @@ -149,7 +149,7 @@ main(void) " tags = [a, b]\n" " opts { depth = 3 }\n" "}\n" - "plugin tmux { }\n" + "plugin tmux { keep = 6; tool_trim = 8192 }\n" "plugin off { enabled = false\n x = 1 }\n" "plugin mine {\n" " path = ~/my/plugin.so\n" @@ -183,6 +183,11 @@ main(void) CHECK(sp_config_plugin_value(c, "mine", "path") == NULL); CHECK(sp_config_plugin_value(c, "off", "x") == NULL); CHECK(sp_config_plugin_value(c, "lcm", "nope") == NULL); + /* one line, ';' between the settings: both are their own key */ + CHECK(sp_config_plugin_value(c, "tmux", "keep") != NULL && + strcmp(sp_config_plugin_value(c, "tmux", "keep"), "6") == 0); + CHECK(sp_config_plugin_value(c, "tmux", "tool_trim") != NULL && + strcmp(sp_config_plugin_value(c, "tmux", "tool_trim"), "8192") == 0); /* plugin mcp { server ... } is what mcp ID { } was */ CHECK(c->nmcp == 2); CHECK(c->nmcp == 2 && strcmp(c->mcp[0].id, "junction") == 0 && diff --git a/tests/test_engine.c b/tests/test_engine.c index a5d0df0..ea88012 100644 --- a/tests/test_engine.c +++ b/tests/test_engine.c @@ -194,6 +194,12 @@ main(void) CHECK(contains(mv[1].label, "pool")); } + kind = sp_engine_input(eng, "/cost", &out); + CHECK(kind == SP_INPUT_HANDLED); + CHECK(contains(out.p, "cost:")); + CHECK(contains(out.p, "judged:")); + sp_buf_clear(&out); + kind = sp_engine_input(eng, "/status", &out); CHECK(kind == SP_INPUT_HANDLED); CHECK(contains(out.p, "session sess-engine")); @@ -244,6 +250,35 @@ main(void) sp_buf_clear(&out); } + /* + * /model belongs to the session: the selector is written to the + * session's sidecar and comes back when the session is reopened. + */ + kind = sp_engine_input(eng, "/model test-model-2", &out); + CHECK(kind == SP_INPUT_HANDLED); + CHECK(contains(out.p, "test-model-2")); + { + char mp[800], line[320]; + FILE *mf; + + snprintf(mp, sizeof(mp), "%s/%s.model", path, + sp_engine_session_id(eng)); + mf = fopen(mp, "r"); + CHECK(mf != NULL); + if (mf != NULL) { + CHECK(fgets(line, sizeof(line), mf) != NULL); + CHECK(contains(line, "test-model-2")); + fclose(mf); + } + } + sp_buf_clear(&out); + + /* the endpoint answers nothing here; the command still answers */ + kind = sp_engine_input(eng, "/model probe", &out); + CHECK(kind == SP_INPUT_HANDLED); + CHECK(out.p != NULL && out.p[0] != '\0'); + sp_buf_clear(&out); + /* a shell line is an entry event, not a reply */ kind = sp_engine_input(eng, "!echo shell-out", &out); CHECK(kind == SP_INPUT_HANDLED); @@ -286,6 +321,12 @@ main(void) opts.resume = 1; opts.agent = NULL; CHECK(sp_engine_open(&eng2, &opts, &err) == 0); + { + struct sp_engine_state st; + + CHECK(sp_engine_state(eng2, &st) == 0); + CHECK(strcmp(st.model, "test-model-2") == 0); + } n2 = sp_engine_agents(eng2); for (i = 0; i < n2; i++) if (strcmp(sp_engine_agent_name(eng2, i), "plan") == 0) diff --git a/tests/test_secrets.c b/tests/test_secrets.c index 1f454ba..2b3bf2e 100644 --- a/tests/test_secrets.c +++ b/tests/test_secrets.c @@ -99,6 +99,16 @@ test_run(void) run_tool(&r, "run", "{\"command\":\"sleep 30 & sleep 30\"}", &out); CHECK(strstr(out.p, "timed out") != NULL); CHECK(time(NULL) - t0 < 10); + + /* + * Output is life: the same one-second window is reset by every line, + * so a command that keeps talking runs past it and finishes. + */ + run_tool(&r, "run", + "{\"command\":\"for i in 1 2 3 4 5; do echo tick; " + "sleep 0.4; done; echo fertig\"}", &out); + CHECK(strstr(out.p, "fertig") != NULL); + CHECK(strstr(out.p, "timed out") == NULL); unsetenv("SPLINTER_RUN_TIMEOUT"); sp_buf_free(&out); diff --git a/tests/test_ui.sh b/tests/test_ui.sh index ea934b0..954daa7 100755 --- a/tests/test_ui.sh +++ b/tests/test_ui.sh @@ -61,7 +61,7 @@ done_turn() { # wait until the turn label is gone done return 1 } -start() { # a fresh fake model and a fresh UI +start() { # a fresh fake model and a fresh UI ($2: retry wait in ms) [ -n "$F" ] && kill "$F" 2>/dev/null killserver P=$((20000 + ($$ + $1) % 30000)) @@ -80,8 +80,9 @@ start() { # a fresh fake model and a fresh UI cat "$D/fake.out" 2>/dev/null exit 1 fi + RW=${2:+SPLINTER_RETRY_WAIT_MS=$2} tmux new-session -d -s $S -x 110 -y 30 "HOME=$D/home SPLINTER_LOCALE=en \ - SPLINTER_CTX_MAX=131072 \ + $RW SPLINTER_CTX_MAX=131072 \ ./splinter --no-config --endpoint http://127.0.0.1:$P/v1/chat/completions \ --model m --chat 2>/dev/null; echo \$? > $D/rc" shows 'Enter sends' @@ -146,6 +147,13 @@ tmux resize-window -t $S -x 70 -y 20; sleep 1 check shows '^build>' check test "$(quit_code)" = 0 +# ---- an API failure is a status row, then a retry ---- +start 1 100 +typed 'bitte wiederholen'; key Enter +check shows 'retrying in' +check shows 'antwort nach dem retry' +check test "$(quit_code)" = 0 + start 1 typed 'schreib die datei'; key Enter check shows 'changes files' @@ -170,6 +178,9 @@ check shows 'Enter sends' sleep 1 typed 'tu was'; key Enter check shows 'steer>' +# the elapsed seconds are the first meter in the status bar, not part of +# the prompt; the prompt line is only "steer> " and what was typed +check shows 's | ctx' sleep 0.5 key C-c check shows 'cancelled'