diff --git a/Makefile b/Makefile index ee2ba24..2a8d416 100644 --- a/Makefile +++ b/Makefile @@ -43,7 +43,8 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \ plugins/scheduler/scheduler.so \ plugins/a2a/a2a.so \ plugins/junction/junction.so \ - plugins/self/self.so + plugins/self/self.so \ + plugins/cache/cache.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_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_anthropic tests/test_cli tests/test_compactor tests/test_secrets tests/test_mcpclient tests/test_kids tests/test_lifecycle tests/test_md tests/test_tgmd tests/test_providers tests/test_b64 tests/test_pause tests/test_swarm tests/test_provstate tests/test_usage tests/test_agents tests/test_confblock tests/test_jobs tests/test_engine tests/test_self @@ -365,6 +366,10 @@ plugins/junction/junction.so: plugins/junction/junction.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/junction/junction.c -L. -lsplinter \ $(PLUGIN_RPATH) $(LIBS) +plugins/cache/cache.so: plugins/cache/cache.c $(LIB) + $(CC) $(CFLAGS) -shared -o $@ plugins/cache/cache.c -L. -lsplinter \ + $(PLUGIN_LDFLAGS) + plugins/self/self.so: plugins/self/self.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/self/self.c -L. -lsplinter \ $(PLUGIN_RPATH) $(LIBS) diff --git a/include/splinter.h b/include/splinter.h index 17bfbf3..ec42ba7 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -155,6 +155,17 @@ struct sp_reply { * endpoint that serves it. "" when the provider does not say. */ char served_by[128]; + /* + * X-Junction-Judge-Next-*: when and where the next judge step runs. + * valid is 0 when the provider sent none (not a judged rule). + */ + int judge_valid; + int judge_next, judge_in, judge_step, judge_every; + char judge_target[64]; + char judge_model[128]; + char judge_cache[8]; + char cache_mode[8]; /* X-Junction-Cache: off/5m/1h */ + char *content; /* assistant text, may be "" */ struct sp_toolcall *calls; char *calls_json; /* the provider's own tool_calls array */ @@ -373,6 +384,7 @@ struct sp_agent_stats { size_t steps; size_t tokens_in; size_t tokens_out; + size_t tokens_cached; /* prompt tokens served from cache, session */ 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 */ diff --git a/include/splinter_engine.h b/include/splinter_engine.h index be170b8..674cc6c 100644 --- a/include/splinter_engine.h +++ b/include/splinter_engine.h @@ -116,6 +116,7 @@ struct sp_engine_state { 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 */ + size_t cached_total; /* of tokens_in, the whole session */ size_t turn_tokens_out; /* output tokens of this/last turn */ size_t steps, calls, compactions; /* the session's counters */ size_t last_ms, last_steps, last_calls; /* the last turn */ diff --git a/include/splinter_plugin.h b/include/splinter_plugin.h index 6b4e77f..082c391 100644 --- a/include/splinter_plugin.h +++ b/include/splinter_plugin.h @@ -101,6 +101,7 @@ struct sp_meter { size_t tok_in; /* this session */ size_t tok_out; size_t cached; /* tokens the provider served from cache */ + size_t cached_total; /* the same for the whole session */ long tps; /* output tokens per second, last turn */ double cost; /* session cost, filled from the price config */ unsigned tasks_running; @@ -167,6 +168,26 @@ void sp_host_set_model(struct sp_host *h, const char *model); */ const char *sp_host_served_by(struct sp_host *h); void sp_host_set_served_by(struct sp_host *h, const char *endpoint); +/* + * The judge schedule of the last judged response (X-Junction-Judge-Next, + * -In, -Next-Step/Every/Target/Model/Cache). A plugin can say when the next + * escalation happens without calling the model itself. + */ +struct sp_judge_next { + int valid; + int next; /* counter value */ + int in; /* calls remaining */ + int step, every; /* the next judge's position in the chain */ + char target[64]; + char model[128]; + char cache[8]; +}; +void sp_host_set_judge_next(struct sp_host *, + const struct sp_judge_next *); +int sp_host_judge_next(struct sp_host *, struct sp_judge_next *); +/* X-Junction-Cache of the last response: off, 5m or 1h; "" when unknown */ +const char *sp_host_cache_mode(struct sp_host *); +void sp_host_set_cache_mode(struct sp_host *, const char *mode); 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 diff --git a/plugins/cache/cache.c b/plugins/cache/cache.c new file mode 100644 index 0000000..a919d6c --- /dev/null +++ b/plugins/cache/cache.c @@ -0,0 +1,347 @@ +/* + * splinter -- cache: what the prompt cache is doing, in the sidebar. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * Three caches meet in one turn: + * + * provider the prompt tokens the model server served from its own cache + * (usage.prompt_tokens_details.cached_tokens), last call and the + * whole session; + * junction the router's cache mode from X-Junction-Cache (off/5m/1h) and, + * when its /status answers, entries/hits/misses/bytes; + * local the same provider number seen from this machine - there is no + * second cache between splinter and the endpoint, so it is shown + * once, not invented twice. + * + * The widget says the last hit rate and the session hit rate, not a single + * number that hides which one it is. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "splinter_plugin.h" +#include "config.h" +#include "curl.h" +#include "mcp.h" + +#define CACHE_MS 3000 +#define CACHE_PROBE_MS 15000 + +struct jcache { + int valid; + long ttl_s, entries, bytes, hits, misses, joined; + time_t at; + char url[600]; +}; + +static struct { + struct sp_host *host; + pthread_mutex_t lock; + struct jcache j; + char widget[1024]; + char dbg[256]; +} c = { NULL, PTHREAD_MUTEX_INITIALIZER, { 0 }, "", "" }; + +/* "12.3k" for token counts; a cache line should fit one sidebar row */ +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); +} + +static void +human_bytes(long n, char *buf, size_t cap) +{ + if (n >= 1024L * 1024L * 1024L) + snprintf(buf, cap, "%.1f GB", (double)n / (1024.0 * 1024.0 * 1024.0)); + else if (n >= 1024L * 1024L) + snprintf(buf, cap, "%.1f MB", (double)n / (1024.0 * 1024.0)); + else if (n >= 1024L) + snprintf(buf, cap, "%.0f kB", (double)n / 1024.0); + else + snprintf(buf, cap, "%ld B", n); +} + +/* the junction status URL and header from the mcp server the config names */ +static void +resolve_junction(const struct sp_config *cfg, char *url, size_t urlcap, + char *hdr, size_t hdrcap) +{ + size_t i; + + url[0] = '\0'; + hdr[0] = '\0'; + if (cfg == NULL) + return; + for (i = 0; i < cfg->nmcp; i++) { + const struct sp_mcpserver *m = &cfg->mcp[i]; + + if (strcmp(m->id, "junction") != 0) + continue; + if (m->url[0] == '\0') + return; + snprintf(url, urlcap, "%s", m->url); + snprintf(hdr, hdrcap, "%s", m->header); + break; + } + if (url[0] == '\0') + return; + { + size_t n = strlen(url); + + if (n >= 4 && strcmp(url + n - 4, "/mcp") == 0) { + n -= 4; + url[n] = '\0'; + } + while (n > 0 && url[n - 1] == '/') + url[--n] = '\0'; + snprintf(url + n, urlcap - n, "/status"); + } +} + +/* one GET, body only; the widget thread may block for the 4 s timeout */ +static char * +get_body(const char *url, const char *header) +{ + static const char *const args[] = { "-s", "-m", "4", NULL }; + const char *hdrs[2]; + char chunk[4096]; + struct sp_buf err, body; + pid_t pid; + int fd, st = 0; + ssize_t got; + + hdrs[0] = header != NULL && *header != '\0' ? header : NULL; + hdrs[1] = NULL; + if (sp_buf_init(&err) != 0) + return NULL; + fd = sp_curl_start(args, url, hdrs, 1, &pid, &err); + if (fd < 0) { + sp_buf_free(&err); + return NULL; + } + if (sp_buf_init(&body) != 0) { + close(fd); + (void)waitpid(pid, &st, 0); + sp_buf_free(&err); + return NULL; + } + while ((got = read(fd, chunk, sizeof(chunk))) > 0) + if (sp_buf_add(&body, chunk, (size_t)got) != 0) + break; + close(fd); + while (waitpid(pid, &st, 0) < 0 && errno == EINTR) + ; + sp_buf_free(&err); + if (body.p == NULL) { + sp_buf_free(&body); + return NULL; + } + return body.p; +} + +static void +probe_junction(void) +{ + const struct sp_config *cfg; + char url[600], hdr[600], *body; + mcp_json *v; + const mcp_json *cache; + struct jcache j; + + cfg = sp_host_config(c.host); + resolve_junction(cfg, url, sizeof(url), hdr, sizeof(hdr)); + if (url[0] == '\0') + return; + body = get_body(url, hdr); + if (body == NULL) { + snprintf(c.dbg, sizeof(c.dbg), "no body from %s", url); + return; + } + v = mcp_parse(body); + if (v == NULL) { + snprintf(c.dbg, sizeof(c.dbg), "unparseable: %.120s", body); + free(body); + return; + } + cache = mcp_arg(v, "cache"); + if (cache == NULL) { + snprintf(c.dbg, sizeof(c.dbg), "no cache object: %.100s", body); + free(body); + mcp_json_free(v); + return; + } + free(body); + if (cache != NULL) { + memset(&j, 0, sizeof(j)); + j.valid = 1; + j.ttl_s = (long)mcp_arg_int(cache, "ttl_s", 0); + j.entries = (long)mcp_arg_int(cache, "entries", 0); + j.bytes = (long)mcp_arg_int(cache, "bytes", 0); + j.hits = (long)mcp_arg_int(cache, "hits", 0); + j.misses = (long)mcp_arg_int(cache, "misses", 0); + j.joined = (long)mcp_arg_int(cache, "joined", 0); + j.at = time(NULL); + snprintf(j.url, sizeof(j.url), "%s", url); + pthread_mutex_lock(&c.lock); + c.j = j; + pthread_mutex_unlock(&c.lock); + } + mcp_json_free(v); +} + +static int +cache_tick(struct sp_host *h, const char *name, void *ctx) +{ + struct sp_meter m; + struct jcache j; + char text[1024], last[24], ses[24], l[24], s[24]; + int lpct = 0, spct = 0; + time_t now = time(NULL); + int probe = 0; + + (void)ctx; + c.host = h; + sp_host_meter_get(h, &m); + pthread_mutex_lock(&c.lock); + j = c.j; + if (!j.valid || now - j.at >= CACHE_PROBE_MS / 1000) + probe = 1; + pthread_mutex_unlock(&c.lock); + if (probe) + probe_junction(); + pthread_mutex_lock(&c.lock); + j = c.j; + pthread_mutex_unlock(&c.lock); + + human(m.ctx_used, last, sizeof(last)); + human(m.tok_in, ses, sizeof(ses)); + if (m.ctx_used > 0) + lpct = (int)((m.cached * 100 + m.ctx_used / 2) / m.ctx_used); + if (m.tok_in > 0) + spct = (int)((m.cached_total * 100 + m.tok_in / 2) / m.tok_in); + snprintf(l, sizeof(l), "%zu", m.cached); + snprintf(s, sizeof(s), "%zu", m.cached_total); + + if (m.ctx_used == 0 && m.tok_in == 0) + snprintf(text, sizeof(text), + "prompt no request yet\n" + "junction %s", sp_host_cache_mode(h)[0] != '\0' ? + sp_host_cache_mode(h) : "unknown"); + else + snprintf(text, sizeof(text), + "prompt %d%% last | %d%% session\n" + "cached %s of %s last\n" + "session %s of %s tokens", + lpct, spct, l, last, s, ses); + if (j.valid) { + size_t off = strlen(text); + char b[24]; + + human_bytes(j.bytes, b, sizeof(b)); + snprintf(text + off, sizeof(text) - off, + "\njunction %s | %ld entries\n" + "junction %ld hits | %ld misses | %s", + sp_host_cache_mode(h)[0] != '\0' ? + sp_host_cache_mode(h) : "unknown", + j.entries, j.hits, j.misses, b); + } else { + size_t off = strlen(text); + + snprintf(text + off, sizeof(text) - off, + "\njunction %s | no stats", + sp_host_cache_mode(h)[0] != '\0' ? + sp_host_cache_mode(h) : "unknown"); + } + (void)sp_host_widget_text(h, name, text); + return 0; +} + +static int +cache_command(struct sp_host *h, const char *args, struct sp_buf *out, + void *ctx) +{ + struct sp_meter m; + struct jcache j; + char l[24], s[24], b[24]; + char curl[600], chdr[600]; + const struct sp_config *cfg; + int lpct = 0, spct = 0; + + (void)args; + (void)ctx; + c.host = h; + cfg = sp_host_config(h); + resolve_junction(cfg, curl, sizeof(curl), chdr, sizeof(chdr)); + sp_host_meter_get(h, &m); + pthread_mutex_lock(&c.lock); + j = c.j; + pthread_mutex_unlock(&c.lock); + if (m.ctx_used > 0) + lpct = (int)((m.cached * 100 + m.ctx_used / 2) / m.ctx_used); + if (m.tok_in > 0) + spct = (int)((m.cached_total * 100 + m.tok_in / 2) / m.tok_in); + human(m.ctx_used, l, sizeof(l)); + human(m.tok_in, s, sizeof(s)); + sp_buf_printf(out, "cache:\n"); + sp_buf_printf(out, " provider last: %zu of %s tokens (%d%%)\n", + m.cached, l, lpct); + sp_buf_printf(out, " provider session: %zu of %s tokens (%d%%)\n", + m.cached_total, s, spct); + sp_buf_printf(out, " junction mode: %s\n", + sp_host_cache_mode(h)[0] != '\0' ? sp_host_cache_mode(h) : "?"); + sp_buf_printf(out, " junction url: %s (mcp %zu)\n", + curl[0] != '\0' ? curl : "(not configured)", + cfg != NULL ? cfg->nmcp : 0); + if (j.valid) { + human_bytes(j.bytes, b, sizeof(b)); + sp_buf_printf(out, " junction: %ld entries, %ld hits, " + "%ld misses, %s, ttl %ld s, %ld joined\n", j.entries, + j.hits, j.misses, b, j.ttl_s, j.joined); + sp_buf_printf(out, " junction status: %s\n", j.url); + } else { + sp_buf_puts(out, " junction: no /status cache stats\n"); + if (c.dbg[0] != '\0') + sp_buf_printf(out, " probe: %s\n", c.dbg); + } + return 0; +} + +static const struct sp_widget w = { + "cache", cache_tick, NULL, NULL, CACHE_MS +}; + +static int +cache_init(struct sp_host *h) +{ + c.host = h; + if (sp_host_add_widget(h, &w) != 0) + return -1; + if (sp_host_add_command(h, "cache", cache_command, NULL) != 0) + return -1; + return 0; +} + +static const struct sp_plugin cache_plugin = { + SP_PLUGIN_ABI, "cache", "1.0.0", cache_init, NULL, NULL +}; + +const struct sp_plugin * +sp_plugin_describe(void) +{ + return &cache_plugin; +} diff --git a/plugins/junction/junction.c b/plugins/junction/junction.c index e7c3f1a..3bf076b 100644 --- a/plugins/junction/junction.c +++ b/plugins/junction/junction.c @@ -759,8 +759,35 @@ compose(void) else snprintf(sbuf, sizeof(sbuf), "%s", j.served); off = (size_t)snprintf(j.widget, sizeof(j.widget), - "%s\nserving %s\nroute ", + "%s\nserving %s\n", j.model[0] != '\0' ? j.model : "(model unknown)", sbuf); + { + struct sp_judge_next jn; + + if (sp_host_judge_next(j.host, &jn) && jn.valid) { + if (jn.in > 0) + off += (size_t)snprintf(j.widget + off, + sizeof(j.widget) - off, + "judge next in %d %s via %s " + "%d/%d cache %s\n", jn.in, + jn.model[0] != '\0' ? jn.model : "?", + jn.target[0] != '\0' ? jn.target : "?", + jn.step, jn.every, + jn.cache[0] != '\0' ? jn.cache : "?"); + else + off += (size_t)snprintf(j.widget + off, + sizeof(j.widget) - off, + "judge next now %s via %s " + "%d/%d cache %s\n", + jn.model[0] != '\0' ? jn.model : "?", + jn.target[0] != '\0' ? jn.target : "?", + jn.step, jn.every, + jn.cache[0] != '\0' ? jn.cache : "?"); + } + } + if (off < sizeof(j.widget)) + off += (size_t)snprintf(j.widget + off, + sizeof(j.widget) - off, "route "); snprintf(copy, sizeof(copy), "%s", j.route); for (tok = strtok_r(copy, " ", &save); tok != NULL; tok = strtok_r(NULL, " ", &save)) { @@ -984,6 +1011,20 @@ snapshot_text(struct sp_buf *out) "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)"); + { + struct sp_judge_next jn; + + if (sp_host_judge_next(j.host, &jn) && jn.valid) + sp_buf_printf(out, " judge next: in %d calls, " + "step %d/%d, %s via %s, cache %s (counter %d)\n", + jn.in, jn.step, jn.every, + jn.model[0] != '\0' ? jn.model : "?", + jn.target[0] != '\0' ? jn.target : "?", + jn.cache[0] != '\0' ? jn.cache : "?", + jn.next); + else + sp_buf_puts(out, " judge next: no headers\n"); + } sp_buf_printf(out, " route: %s\n", j.route[0] != '\0' ? j.route : "(no rule matched)"); sp_buf_printf(out, " route health: %u/%u up%s%s\n", j.route_up, diff --git a/plugins/self/self.c b/plugins/self/self.c index b1f1ac4..432ee39 100644 --- a/plugins/self/self.c +++ b/plugins/self/self.c @@ -176,24 +176,26 @@ static void human(unsigned long kb, char *buf, size_t cap) { if (kb >= 1024 * 1024) - snprintf(buf, cap, "%.1fG", (double)kb / (1024.0 * 1024.0)); + snprintf(buf, cap, "%.1f GB", + (double)kb / (1024.0 * 1024.0)); else if (kb >= 1024) - snprintf(buf, cap, "%.0fM", (double)kb / 1024.0); + snprintf(buf, cap, "%.0f MB", (double)kb / 1024.0); else - snprintf(buf, cap, "%luk", kb); + snprintf(buf, cap, "%lu kB", kb); } static void human_bytes(unsigned long b, char *buf, size_t cap) { if (b >= 1024UL * 1024UL * 1024UL) - snprintf(buf, cap, "%.1fG", (double)b / (1024.0 * 1024.0 * 1024.0)); + snprintf(buf, cap, "%.1f GB", + (double)b / (1024.0 * 1024.0 * 1024.0)); else if (b >= 1024UL * 1024UL) - snprintf(buf, cap, "%.1fM", (double)b / (1024.0 * 1024.0)); + snprintf(buf, cap, "%.1f MB", (double)b / (1024.0 * 1024.0)); else if (b >= 1024) - snprintf(buf, cap, "%.0fk", (double)b / 1024.0); + snprintf(buf, cap, "%.0f kB", (double)b / 1024.0); else - snprintf(buf, cap, "%luB", b); + snprintf(buf, cap, "%lu B", b); } /* @@ -309,19 +311,27 @@ compose(struct sample *s) human(s->kids_rss_kb, kids, sizeof(kids)); human_bytes(s->io_read, r, sizeof(r)); human_bytes(s->io_write, w, sizeof(w)); - snprintf(widget, sizeof(widget), - "%s rss %.1f%% cpu\n" - "%d thr %d fd\n" - "kids %d %s %.1f%% cpu\n" - "io %s r %s w", - rss, s->cpu_pct, s->threads, s->fds, s->kids, kids, - s->kids_cpu_pct, r, w); + if (s->kids == 0) + snprintf(widget, sizeof(widget), + "%s memory | %.1f%% cpu\n" + "%d threads | %d open files\n" + "no children\n" + "io %s read | %s written", + rss, s->cpu_pct, s->threads, s->fds, r, w); + else + snprintf(widget, sizeof(widget), + "%s memory | %.1f%% cpu\n" + "%d threads | %d open files\n" + "children %d | %s | %.1f%% cpu\n" + "io %s read | %s written", + rss, s->cpu_pct, s->threads, s->fds, s->kids, kids, + s->kids_cpu_pct, r, w); snprintf(detail, sizeof(detail), "self: pid %d\n" - " rss: %s (%lu kB)\n" + " memory (RSS): %s (%lu kB)\n" " threads: %d\n" - " fds: %d\n" + " open files: %d\n" " cpu: %.1f%%\n" " io: %s read, %s written\n" "children: %d process(es), %s rss, %.1f%% cpu\n", diff --git a/src/backend/agent.c b/src/backend/agent.c index f725605..8106710 100644 --- a/src/backend/agent.c +++ b/src/backend/agent.c @@ -506,9 +506,28 @@ agent_request(struct sp_agent *a, struct sp_conv *conv, struct sp_reply *reply, sent_rc = a->tr.send(a->tr.ctx, conv, reply, err); if (sent_rc == 0 && reply->status >= 200 && reply->status <= 299) { - if (a->host != NULL && reply->served_by[0] != '\0') - sp_host_set_served_by(a->host, - reply->served_by); + if (a->host != NULL) { + struct sp_judge_next jn; + + if (reply->served_by[0] != '\0') + sp_host_set_served_by(a->host, + reply->served_by); + memset(&jn, 0, sizeof(jn)); + jn.valid = reply->judge_valid; + jn.next = reply->judge_next; + jn.in = reply->judge_in; + jn.step = reply->judge_step; + jn.every = reply->judge_every; + snprintf(jn.target, sizeof(jn.target), "%s", + reply->judge_target); + snprintf(jn.model, sizeof(jn.model), "%s", + reply->judge_model); + snprintf(jn.cache, sizeof(jn.cache), "%s", + reply->judge_cache); + sp_host_set_judge_next(a->host, &jn); + sp_host_set_cache_mode(a->host, + reply->cache_mode); + } if (a->cfg->note != NULL) a->cfg->note(a->cfg->note_ctx, ""); return 0; @@ -741,6 +760,8 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, a->stats.last_cached = (size_t)(reply.tokens_cached > 0 ? reply.tokens_cached : 0); } + if (reply.tokens_cached > 0) + a->stats.tokens_cached += (size_t)reply.tokens_cached; 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), diff --git a/src/backend/engine.c b/src/backend/engine.c index 1867356..aed6782 100644 --- a/src/backend/engine.c +++ b/src/backend/engine.c @@ -242,6 +242,7 @@ sp_engine_state(struct sp_engine *e, struct sp_engine_state *st) st->cost = e->snapshot.cost; st->ctx_used = e->snapshot.last_in; st->cached = e->snapshot.last_cached; + st->cached_total = e->snapshot.tokens_cached; st->turn_tokens_out = e->running && e->snapshot.tokens_out >= e->turn_out0 ? e->snapshot.tokens_out - e->turn_out0 : (e->running ? 0 : e->last_turn_out); diff --git a/src/backend/plugin.c b/src/backend/plugin.c index 6cdade6..542704c 100644 --- a/src/backend/plugin.c +++ b/src/backend/plugin.c @@ -85,6 +85,8 @@ struct sp_host { unsigned turns; char model[256]; /* what the run is on */ char served_by[128]; /* who answered the last request */ + struct sp_judge_next judge; /* X-Junction-Judge-Next-* */ + char cache_mode[8]; /* X-Junction-Cache */ /* loaded plugins, in load order, so shutdown() runs in reverse */ const struct sp_plugin *loaded[MAX_PLUGINS]; size_t nloaded; @@ -539,6 +541,33 @@ sp_host_set_served_by(struct sp_host *h, const char *endpoint) pthread_mutex_unlock(&h->lock); } +void +sp_host_set_judge_next(struct sp_host *h, const struct sp_judge_next *j) +{ + if (h == NULL) + return; + pthread_mutex_lock(&h->lock); + if (j != NULL) + h->judge = *j; + else + memset(&h->judge, 0, sizeof(h->judge)); + pthread_mutex_unlock(&h->lock); +} + +int +sp_host_judge_next(struct sp_host *h, struct sp_judge_next *out) +{ + int valid = 0; + + if (h == NULL || out == NULL) + return 0; + pthread_mutex_lock(&h->lock); + *out = h->judge; + valid = h->judge.valid; + pthread_mutex_unlock(&h->lock); + return valid; +} + struct sp_registry * sp_host_registry(struct sp_host *h) { @@ -899,4 +928,28 @@ size_t sp_host_widget_count(struct sp_host *h) { return h != NULL ? h->nwidgets : 0; -} \ No newline at end of file +} + +const char * +sp_host_cache_mode(struct sp_host *h) +{ + static __thread char copy[8]; + + if (h == NULL) + return ""; + pthread_mutex_lock(&h->lock); + snprintf(copy, sizeof(copy), "%s", h->cache_mode); + pthread_mutex_unlock(&h->lock); + return copy; +} + +void +sp_host_set_cache_mode(struct sp_host *h, const char *mode) +{ + if (h == NULL) + return; + pthread_mutex_lock(&h->lock); + snprintf(h->cache_mode, sizeof(h->cache_mode), "%s", + mode != NULL ? mode : ""); + pthread_mutex_unlock(&h->lock); +} diff --git a/src/backend/sse.c b/src/backend/sse.c index 935b100..8e28ea8 100644 --- a/src/backend/sse.c +++ b/src/backend/sse.c @@ -252,7 +252,7 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out, msg = mcp_json_string(error); s->error_code = code != NULL ? (int)mcp_arg_int(error, "code", 0) : 0; - sp_buf_printf(err, "sse: %s", + sp_buf_printf(err, "provider error: %s", msg != NULL ? msg : "the endpoint sent an error"); mcp_json_free(v); return -1; diff --git a/src/backend/transport_openai.c b/src/backend/transport_openai.c index 43493eb..692db97 100644 --- a/src/backend/transport_openai.c +++ b/src/backend/transport_openai.c @@ -272,6 +272,46 @@ parse_header_value(const char *path, const char *name, char *out, size_t cap) fclose(f); } +/* + * X-Junction-Judge-Next-* says when the next escalation runs. These are only + * on judged responses; valid stays 0 otherwise, so the widget does not show a + * stale schedule after a switch to a plain model. + */ +static int +header_int(const char *path, const char *name) +{ + char v[32]; + + parse_header_value(path, name, v, sizeof(v)); + return v[0] != '\0' ? atoi(v) : 0; +} + +static void +parse_judge_headers(const char *path, struct sp_reply *out) +{ + char v[128]; + + /* the cache mode is on every routed response, judged or not */ + parse_header_value(path, "X-Junction-Cache", out->cache_mode, + sizeof(out->cache_mode)); + parse_header_value(path, "X-Junction-Judge-Next", v, sizeof(v)); + if (v[0] == '\0') { + out->judge_valid = 0; + return; + } + out->judge_valid = 1; + out->judge_next = atoi(v); + out->judge_in = header_int(path, "X-Junction-Judge-In"); + out->judge_step = header_int(path, "X-Junction-Judge-Next-Step"); + out->judge_every = header_int(path, "X-Junction-Judge-Next-Every"); + parse_header_value(path, "X-Junction-Judge-Next-Target", + out->judge_target, sizeof(out->judge_target)); + parse_header_value(path, "X-Junction-Judge-Next-Model", + out->judge_model, sizeof(out->judge_model)); + parse_header_value(path, "X-Junction-Judge-Next-Cache", + out->judge_cache, sizeof(out->judge_cache)); +} + static long parse_retry_after_file(const char *path) { @@ -392,6 +432,7 @@ openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, out->retry_after_s = parse_retry_after_file(hdr_path); parse_header_value(hdr_path, "X-Junction-Endpoint", out->served_by, sizeof(out->served_by)); + parse_judge_headers(hdr_path, out); unlink(hdr_path); hdr_path[0] = '\0'; } @@ -666,6 +707,7 @@ out: if (hdr_path[0] != '\0') { parse_header_value(hdr_path, "X-Junction-Endpoint", out->served_by, sizeof(out->served_by)); + parse_judge_headers(hdr_path, out); unlink(hdr_path); } sp_sse_free(sse); diff --git a/src/frontend/curses.c b/src/frontend/curses.c index 373258b..1712ad3 100644 --- a/src/frontend/curses.c +++ b/src/frontend/curses.c @@ -123,6 +123,7 @@ struct ui_state { 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 */ + size_t cached_total; /* of tokens_in, the session */ size_t turn_out; /* output tokens of this/last turn */ size_t last_steps; size_t last_calls; @@ -141,6 +142,7 @@ static WINDOW *ui_side; static WINDOW *ui_gap; /* the one column between chat and sidebar */ static WINDOW *ui_status; static WINDOW *ui_input; +static int ui_input_h = 1; /* rows the prompt box uses, 1..5 */ /* * The agent whose profile is active. The sidebar does not show it; with one * text field the prompt carries the name, so "build> " says what Tab did. @@ -211,6 +213,7 @@ sync_state(struct ui_state *s) if (ctxmax != NULL && *ctxmax != '\0') s->ctx_max = (size_t)strtoul(ctxmax, NULL, 10); s->ctx_cached = st.cached; + s->cached_total = st.cached_total; s->turn_out = st.turn_tokens_out; s->last_ms = st.last_ms; s->last_steps = st.last_steps; @@ -1380,6 +1383,7 @@ set_ui_fields(struct sp_meter *m, void *ctx) if (ctxmax != NULL && *ctxmax != '\0') m->ctx_max = (size_t)strtoul(ctxmax, NULL, 10); m->cached = s->ctx_cached; + m->cached_total = s->cached_total; m->tok_in = s->tokens_in; m->tok_out = s->tokens_out; m->cost = s->cost; @@ -1506,16 +1510,23 @@ hist_push(struct ui_state *s, const char *dir, const char *line) char path[600]; FILE *f; + char flat[1024]; + size_t i; + if (line == NULL || line[0] == '\0') return; + /* the history file is one line per entry: a multi-line prompt folds */ + for (i = 0; i + 1 < sizeof(flat) && line[i] != '\0'; i++) + flat[i] = line[i] == '\n' ? ' ' : line[i]; + flat[i] = '\0'; /* typing the same thing twice in a row is not two history entries */ - if (s->nhist > 0 && strcmp(s->hist[s->nhist - 1], line) == 0) + if (s->nhist > 0 && strcmp(s->hist[s->nhist - 1], flat) == 0) return; if (s->nhist == 128) { memmove(&s->hist[0], &s->hist[1], sizeof(s->hist[0]) * 127); s->nhist--; } - snprintf(s->hist[s->nhist], 1024, "%s", line); + snprintf(s->hist[s->nhist], 1024, "%s", flat); s->nhist++; s->hist_pos = -1; @@ -1525,7 +1536,7 @@ hist_push(struct ui_state *s, const char *dir, const char *line) f = fopen(path, "a"); if (f == NULL) return; - fprintf(f, "%s\n", line); + fprintf(f, "%s\n", flat); fclose(f); } @@ -1634,14 +1645,27 @@ add_entry(struct ui_state *s, const char *role, const char *text) static void layout(void) { - int rows, cols; + int rows, cols, in_h, chat_rows; getmaxyx(stdscr, rows, cols); /* * The conversation on three quarters, the sidebar on the last one, the - * input below both. The conversation starts at the top and grows - * downward; what was written stays where it is. + * input below both. The input grows to five rows for a long prompt; + * the conversation gives up the rows, never the other way around. */ + in_h = ui_input_h; + if (in_h < 1) + in_h = 1; + if (in_h > 5) + in_h = 5; + if (rows - 1 - in_h < 3) + in_h = rows > 4 ? rows - 4 : 1; + if (in_h < 1) + in_h = 1; + ui_input_h = in_h; + chat_rows = rows - 1 - in_h; + if (chat_rows < 2) + chat_rows = 2; { int side_w = cols / 4; int chat_w = cols - side_w - 1; @@ -1650,16 +1674,16 @@ layout(void) side_w = cols > 50 ? 18 : 0; if (side_w == 0) chat_w = cols; - ui_hist = newwin(rows - 2, chat_w, 0, 0); + ui_hist = newwin(chat_rows, chat_w, 0, 0); ui_side = side_w > 0 ? - newwin(rows - 2, side_w, 0, chat_w + 1) : NULL; + newwin(chat_rows, side_w, 0, chat_w + 1) : NULL; /* * The column between the two panes belongs to nobody. Left * alone it keeps the terminal's default colour, which on a * white theme is a black stripe down the middle. It is a * window with the page colour instead. */ - ui_gap = side_w > 0 ? newwin(rows - 2, 1, 0, chat_w) : NULL; + ui_gap = side_w > 0 ? newwin(chat_rows, 1, 0, chat_w) : NULL; } wbkgd(ui_hist, COLOR_PAIR(PAIR_MAIN)); if (ui_side != NULL) @@ -1669,9 +1693,9 @@ layout(void) werase(ui_gap); } /* the meter line sits above the input, like a status bar */ - ui_status = newwin(1, cols, rows - 2, 0); + ui_status = newwin(1, cols, chat_rows, 0); wbkgd(ui_status, COLOR_PAIR(PAIR_STATUS)); - ui_input = newwin(1, cols, rows - 1, 0); + ui_input = newwin(in_h, cols, chat_rows + 1, 0); wbkgd(ui_input, COLOR_PAIR(PAIR_INPUT)); keypad(ui_input, TRUE); /* a one-line window that may scroll is a screen that jumps */ @@ -1713,38 +1737,140 @@ redraw(struct ui_state *s, const struct ui_backend *be) doupdate(); } -/* the prompt line with what has been typed so far */ +/* xterm's modifyOtherKeys: makes Shift+Enter a distinct sequence */ static void -draw_prompt(const char *input) +modify_keys(int on) { - const char *mark = prompt_mark(); - char *ascii; - size_t n, avail, cap; - int w = getmaxx(ui_input); + fputs(on ? "\033[>4;2m" : "\033[>4;0m", stdout); + fflush(stdout); +} - werase(ui_input); - mvwaddstr(ui_input, 0, 0, mark); - /* - * The line is one row and never wraps: when the text is longer than the - * room, the end of it stays visible and the start scrolls out to the - * left. The last column stays empty -- writing into the bottom-right - * cell of a window that cannot scroll is an error in curses, and in - * this port a crash. - */ - avail = (size_t)(w - (int)strlen(mark) - 2); - if (input == NULL || w < 8 || avail < 1) +/* + * The prompt box with what has been typed so far. It wraps at the window + * width, grows to five rows and then keeps the line with the cursor visible; + * the last column stays empty (writing the bottom-right cell of a window that + * cannot scroll is an error in this curses port). + */ +static void +draw_prompt(struct ui_state *s, const char *input) +{ + const char *mark = prompt_mark(); + char *ascii; + size_t cap, i; + int cols, marklen, row, used, total, cur_row, cur_used; + int prefix, room, start, drawn = -1; + + cols = getmaxx(ui_input) - 1; + if (cols < 8) return; - cap = strlen(input) * 4 + 16; + marklen = (int)strlen(mark); + cap = (input != NULL ? strlen(input) : 0) * 4 + 16; ascii = malloc(cap); if (ascii == NULL) return; - if (sp_ui_ascii(input, ascii, cap) != 0) + if (input == NULL) + ascii[0] = '\0'; + else if (sp_ui_ascii(input, ascii, cap) != 0) snprintf(ascii, cap, "%s", input); - n = strlen(ascii); - if (n > avail) - waddnstr(ui_input, ascii + (n - avail), (int)avail); - else - waddnstr(ui_input, ascii, (int)n); + + /* first pass: how many rows, and where the cursor is */ + row = 0; + used = 0; + total = 1; + prefix = marklen; + for (i = 0; ascii[i] != '\0'; i++) { + if (ascii[i] == '\n') { + row++; + used = 0; + prefix = 2; + if (row + 1 > total) + total = row + 1; + continue; + } + room = cols - prefix; + if (room < 1) + room = 1; + if (used >= room) { + row++; + used = 0; + prefix = 2; + if (row + 1 > total) + total = row + 1; + } + used++; + } + cur_row = row; + cur_used = used; + if (total < 1) + total = 1; + { + int want = total > 5 ? 5 : total; + + if (want != ui_input_h) { + ui_input_h = want; + relayout(500); + draw_history(s); + s->painted = s->gen; + draw_sidebar(s, SESS_ID(s->be), SESS_DIR(s->be), + s->be->host(s->be->ctx)); + draw_statusbar(s); + } + } + werase(ui_input); + start = total > ui_input_h ? total - ui_input_h : 0; + row = 0; + used = 0; + prefix = marklen; + for (i = 0; ascii[i] != '\0'; i++) { + int dr; + + if (ascii[i] == '\n') { + row++; + used = 0; + prefix = 2; + continue; + } + room = cols - prefix; + if (room < 1) + room = 1; + if (used >= room) { + row++; + used = 0; + prefix = 2; + } + if (row < start) { + used++; + continue; + } + dr = row - start; + if (dr < ui_input_h) { + if (drawn != dr) { + mvwaddstr(ui_input, dr, 0, + row == 0 ? mark : " "); + drawn = dr; + } + mvwaddch(ui_input, dr, prefix + used, ascii[i]); + } + used++; + } + if (cur_row >= start && cur_row - start < ui_input_h && + drawn != cur_row - start) + mvwaddstr(ui_input, cur_row - start, 0, + cur_row == 0 ? mark : " "); + { + int cy = cur_row - start, cx = (cur_row == 0 ? marklen : 2) + + cur_used; + + if (cy < 0) + cy = 0; + if (cy >= ui_input_h) + cy = ui_input_h - 1; + if (cx >= getmaxx(ui_input) - 1) + cx = getmaxx(ui_input) - 2; + if (cx < 0) + cx = 0; + wmove(ui_input, cy, cx); + } free(ascii); } @@ -2013,7 +2139,7 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); wnoutrefresh(ui_input); } else - draw_prompt(input); + draw_prompt(s, input); wnoutrefresh(ui_input); doupdate(); wtimeout(ui_input, 500); @@ -2058,12 +2184,68 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); wnoutrefresh(ui_input); } else { - draw_prompt(input); + draw_prompt(s, input); wnoutrefresh(ui_input); } doupdate(); continue; } + if (ch == 27) { + char seq[16]; + int n = 0, c2, newline = 0; + + wtimeout(ui_input, 60); + c2 = wgetch(ui_input); + if (c2 == '\r' || c2 == '\n') { + newline = 1; /* Alt+Enter */ + } else if (c2 == '[') { + seq[n++] = (char)c2; + while (n < 15) { + c2 = wgetch(ui_input); + if (c2 == ERR) + break; + seq[n++] = (char)c2; + /* a CSI sequence ends at 0x40..0x7e */ + if (c2 >= '@' && c2 <= '~') + break; + } + seq[n] = '\0'; + if (strstr(seq, "[13;2u") != NULL || + strstr(seq, "[13;2~") != NULL || + strstr(seq, "[27;2;13~") != NULL) + newline = 1; + } else if (c2 != ERR) { + ungetch(c2); /* a lone ESC, not ours */ + } + wtimeout(ui_input, 500); + if (newline && !locked && len + 1 < cap) { + input[len++] = '\n'; + input[len] = '\0'; + draw_prompt(s, input); + wrefresh(ui_input); + } + continue; + } + if (ch == KEY_MOUSE) { + MEVENT me; + + if (getmouse(&me) == OK) { + if (me.bstate & BUTTON4_PRESSED) + s->scroll += 3; + else if (me.bstate & BUTTON5_PRESSED) + s->scroll = s->scroll > 3 ? + s->scroll - 3 : 0; + draw_history(s); + s->painted = s->gen; + draw_sidebar(s, SESS_ID(be), SESS_DIR(be), + host); + draw_statusbar(s); + draw_prompt(s, input); + wnoutrefresh(ui_input); + doupdate(); + } + continue; + } if (ch == '\n' || ch == '\r' || ch == KEY_ENTER) { if (locked) continue; break; @@ -2087,7 +2269,7 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, werase(ui_input); mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); } else - draw_prompt(input); + draw_prompt(s, input); wnoutrefresh(ui_input); doupdate(); continue; @@ -2096,7 +2278,7 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, if (locked) continue; len = 0; input[0] = '\0'; - draw_prompt(input); + draw_prompt(s, input); wrefresh(ui_input); continue; } @@ -2118,7 +2300,7 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, len = strlen(input); } input[len] = '\0'; - draw_prompt(input); + draw_prompt(s, input); wrefresh(ui_input); continue; } @@ -2134,7 +2316,7 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, werase(ui_input); mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); } else - draw_prompt(input); + draw_prompt(s, input); wnoutrefresh(ui_input); doupdate(); continue; @@ -2150,7 +2332,7 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, werase(ui_input); mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); } else - draw_prompt(input); + draw_prompt(s, input); wnoutrefresh(ui_input); doupdate(); continue; @@ -2163,7 +2345,7 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, len--; while (len > 0 && ((unsigned char)input[len] & 0xc0) == 0x80); input[len] = '\0'; - draw_prompt(input); + draw_prompt(s, input); wrefresh(ui_input); } continue; @@ -2186,7 +2368,7 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, draw_history(s); draw_sidebar(s, SESS_ID(be), SESS_DIR(be), host); draw_statusbar(s); - draw_prompt(input); + draw_prompt(s, input); wnoutrefresh(ui_input); doupdate(); continue; @@ -2244,7 +2426,7 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, } } } - draw_prompt(input); + draw_prompt(s, input); wnoutrefresh(ui_input); doupdate(); } @@ -2255,7 +2437,7 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, if (ch >= 32 && ch < 256 && len + 1 < cap) { input[len++] = (char)ch; input[len] = '\0'; - draw_prompt(input); + draw_prompt(s, input); wrefresh(ui_input); } } @@ -2869,6 +3051,22 @@ turn_key(struct ui_state *s, struct turn_view *v, int c) redraw(s, s->be); return 0; } + if (c == KEY_MOUSE) { + MEVENT me; + + if (getmouse(&me) == OK) { + if (me.bstate & BUTTON4_PRESSED) + s->scroll += 3; + else if (me.bstate & BUTTON5_PRESSED) + s->scroll = s->scroll > 3 ? s->scroll - 3 : 0; + draw_history(s); + s->painted = s->gen; + draw_sidebar(s, SESS_ID(s->be), SESS_DIR(s->be), + s->be->host(s->be->ctx)); + draw_statusbar(s); + } + return 0; + } /* * Cancel at the engine: it wakes a turn that is asleep in an approval * and the transports kill their child or curl when the flag is set. @@ -2933,6 +3131,10 @@ ui_turn(struct ui_state *s, const char *text) clock_gettime(CLOCK_MONOTONIC, &v.t0); sp_buf_init(&v.thinkbuf); sp_buf_init(&v.live); + if (ui_input_h != 1) { + ui_input_h = 1; + relayout(100); + } if (s->be->submit(s->be->ctx, text) != 0) { add_entry(s, "error", sp_t("err.thread")); sp_buf_free(&v.thinkbuf); @@ -2978,6 +3180,7 @@ ui_turn(struct ui_state *s, const char *text) turn_draw_input(s, &v); c2 = wgetch(ui_input); if (c2 == 3 || c2 == 4) { + modify_keys(0); endwin(); tmux_title_reset(); _exit(1); @@ -3069,8 +3272,12 @@ ui_start(struct ui_state *s, const struct ui_backend *be, raw(); noecho(); keypad(stdscr, TRUE); + modify_keys(1); + mousemask(ALL_MOUSE_EVENTS, NULL); + mouseinterval(0); curs_set(1); init_colors(&s->theme); + ui_input_h = 1; layout(); /* @@ -3229,6 +3436,7 @@ tmux_title_reset(void) static void tmux_signal(int sig) { + modify_keys(0); endwin(); tmux_title_reset(); signal(sig, SIG_DFL); @@ -3478,6 +3686,7 @@ sp_ui_run(const struct ui_backend *be, const char *theme_name) if (s.quit) break; } + modify_keys(0); endwin(); be->close(be->ctx); return 0; diff --git a/tests/test_self.c b/tests/test_self.c index 9ba80db..4a1f873 100644 --- a/tests/test_self.c +++ b/tests/test_self.c @@ -53,15 +53,15 @@ main(void) snap[0] = '\0'; CHECK(sp_host_widget_snapshot(host, snap, sizeof(snap)) > 0); CHECK(strstr(snap, "self: ") != NULL); - CHECK(strstr(snap, "rss") != NULL); - CHECK(strstr(snap, "thr") != NULL); - CHECK(strstr(snap, "fd") != NULL); - CHECK(strstr(snap, "kids") != NULL); + CHECK(strstr(snap, "memory") != NULL); + CHECK(strstr(snap, "threads") != NULL); + CHECK(strstr(snap, "open files") != NULL); + CHECK(strstr(snap, "children") != NULL); /* /self and the tool carry the same numbers, with the child count */ sp_buf_clear(&out); CHECK(sp_host_command(host, "self", "", &out) == 0); - CHECK(strstr(out.p, "rss:") != NULL); + CHECK(strstr(out.p, "memory (RSS):") != NULL); CHECK(strstr(out.p, "threads:") != NULL); CHECK(strstr(out.p, "children:") != NULL); CHECK(strstr(out.p, "cpu:") != NULL);