diff --git a/Makefile b/Makefile index 3bdee64..f80c104 100644 --- a/Makefile +++ b/Makefile @@ -27,7 +27,7 @@ LIB = libsplinter.so LIBOBJ = src/backend/buf.o src/backend/tool.o src/backend/session.o src/backend/conv.o src/backend/transport.o \ src/backend/json.o src/backend/sse.o src/backend/openai.o src/backend/transport_openai.o \ src/backend/anthropic.o src/backend/transport_anthropic.o src/backend/builtin.o \ - src/backend/agent.o src/backend/theme.o src/backend/palettes.o src/backend/decomp.o src/backend/i18n.o src/backend/delegate.o src/backend/telegram.o src/backend/log.o src/backend/cmdscript.o src/backend/folder.o src/backend/interview.o src/backend/ack.o src/backend/mcpserver.o src/backend/skills.o src/backend/memory.o src/backend/prompt.o src/backend/config.o src/backend/plugin.o src/backend/curl.o src/backend/swarm.o src/backend/provstate.o src/backend/md.o src/backend/tgmd.o src/backend/b64.o src/backend/a2aserver.o src/backend/providers.o src/backend/usage.o src/backend/confblock.o src/backend/agents.o src/backend/engine.o src/backend/http.o src/backend/openai_server.o src/backend/catalogs.o + src/backend/agent.o src/backend/theme.o src/backend/palettes.o src/backend/decomp.o src/backend/i18n.o src/backend/delegate.o src/backend/telegram.o src/backend/log.o src/backend/cmdscript.o src/backend/folder.o src/backend/interview.o src/backend/ack.o src/backend/mcpserver.o src/backend/mcpsession.o src/backend/skills.o src/backend/memory.o src/backend/prompt.o src/backend/config.o src/backend/plugin.o src/backend/curl.o src/backend/swarm.o src/backend/provstate.o src/backend/md.o src/backend/tgmd.o src/backend/b64.o src/backend/a2aserver.o src/backend/providers.o src/backend/usage.o src/backend/confblock.o src/backend/agents.o src/backend/engine.o src/backend/http.o src/backend/openai_server.o src/backend/catalogs.o # buildinfo.o is separate: buildinfo.c is generated from the objects below. LIBOBJ_ALL = $(LIBOBJ) src/backend/buildinfo.o BIN = splinter @@ -45,10 +45,11 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \ plugins/a2a/a2a.so \ plugins/sysinfo/sysinfo.so \ plugins/tmux/tmux.so \ - plugins/junction/junction.so + plugins/junction/junction.so \ + plugins/self/self.so TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \ tests/test_transport tests/test_agent tests/test_openai \ - tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_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_planner tests/test_tmux tests/test_usage tests/test_agents tests/test_confblock tests/test_jobs tests/test_engine + tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_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_planner tests/test_tmux tests/test_usage tests/test_agents tests/test_confblock tests/test_jobs tests/test_engine tests/test_self RPATH = -Wl,-rpath,'$$ORIGIN' PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..' @@ -261,6 +262,8 @@ tests/test_engine: tests/test_engine.c $(LIB) $(CC) $(CFLAGS) -o $@ tests/test_engine.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_junction: tests/test_junction.c $(LIB) plugins/junction/junction.so $(CC) $(CFLAGS) -o $@ tests/test_junction.c -L. -lsplinter $(TEST_RPATH) $(LIBS) +tests/test_self: tests/test_self.c $(LIB) plugins/self/self.so + $(CC) $(CFLAGS) -o $@ tests/test_self.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_usage: tests/test_usage.c $(LIB) $(CC) $(CFLAGS) -o $@ tests/test_usage.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_tmux: tests/test_tmux.c $(LIB) $(PLUGIN) @@ -314,6 +317,7 @@ check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) tests/test_junction echo "== tests/test_gateway_openai.sh"; sh tests/test_gateway_openai.sh; \ echo "== tests/test_reconnect.sh"; sh tests/test_reconnect.sh; \ echo "== tests/test_junction.sh"; sh tests/test_junction.sh; \ + echo "== tests/test_mcpsession.sh"; sh tests/test_mcpsession.sh; \ echo "all tests passed" # The installed binary finds its own library through an rpath relative to itself @@ -378,3 +382,7 @@ plugins/sysinfo/sysinfo.so: plugins/sysinfo/sysinfo.c $(LIB) plugins/junction/junction.so: plugins/junction/junction.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/junction/junction.c -L. -lsplinter \ $(PLUGIN_RPATH) $(LIBS) + +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/README.md b/README.md index d5557ed..277bc2c 100644 --- a/README.md +++ b/README.md @@ -324,11 +324,10 @@ 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. -A stream that goes completely silent is treated as a hang, not as a slow -answer: curl is started with `--speed-limit 1 --speed-time 180` -(`SPLINTER_STREAM_STALL_S` overrides the seconds), so a provider that sends -nothing for that long is cut off and the retry runs. A provider that keeps -streaming - even slowly - is never interrupted by it. +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 +exactly those with "Less than 1 bytes/sec". The overall HTTP timeout is the +only limit. ## Colour, measured @@ -706,6 +705,28 @@ On 127.x it needs nothing; on any other address it refuses to start without splinter --mcp-server-listen 0.0.0.0 (echo "AUTH $(cat ~/.splinter/mcp.token)"; cat requests.jsonl) | nc host 8098 +Beside the file tools the server offers the session tools, so another agent can +work with splinter itself: + + splinter_sessions list the sessions (current marked) + splinter_state model, endpoint, profile, session, busy, tokens + splinter_models the selectors /model takes + splinter_agents the profiles + splinter_history the open session's user and assistant messages + splinter_say send a prompt, wait, return the answer + splinter_open switch to a session (id, new, last) + splinter_model switch the model (any /model selector) + splinter_agent switch the profile by name + splinter_steer type into the running turn + splinter_cancel cancel the running turn + splinter_approve answer a pending approval (allow true|false) + +`say` starts a real turn, so the server needs a provider: give it `-m` (or run +`--daemon --mcp-server-listen`, where the Telegram daemon and the MCP server +share one engine). A turn that parks on an approval is returned as the +question, not as a failure; `splinter_approve` answers it. The first line of +`splinter_say` is the answer, then the step and tool-call counts. + ## Tools Every tool declares its class, and the loop enforces it - never the model, never diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md index fd1151c..82ea788 100644 --- a/docs/PLUGINS.md +++ b/docs/PLUGINS.md @@ -273,6 +273,7 @@ health probe is failing. ``` junction deepseek-v4.1-flash +serving opencode-go1 route opencode-go0 opencode-go1 opencode-go2 @@ -280,9 +281,14 @@ ollama0-splinter 4/4 up ``` -The rule is chosen by exact model match, then glob (`*`, `?`), then -catch-all; rules with a `path` describe another route (`/v1/models`) and are -skipped. A target whose probe is down gets the `!`. +`serving` is the `X-Junction-Endpoint` of the **last real answer** - the +provider says which upstream actually served it, and the transport publishes +it (`sp_host_served_by`). That is not the route: junction may pick another +target per request, and a fallback can differ from every rule. `(no request +yet)` until the first answer. The route below is what the matching rule would +use; the rule is chosen by exact model match, then glob (`*`, `?`), then +catch-all, and rules with a `path` describe another route (`/v1/models`). A +target whose probe is down gets the `!`. Everything else is `/junction`, not the sidebar: uptime, MCP servers, queue, requests, endpoints with p95 and exhausted counts, the model count from @@ -301,6 +307,26 @@ printed: it carries the key. `interval` (milliseconds, default 5000) sets how often the tick asks; `models_interval` (default 60000) how often the model route is probed, because that one goes upstream and the other two do not. +## self + +What the session costs the machine, and what its children cost: + +``` +self +84M rss 3.2% cpu +18 thr 41 fd +kids 3 120M 1.4% cpu +io 12M r 300k w +``` + +The process itself from `/proc/self/status` (VmRSS, Threads), `/proc/self/fd` +(count) and `/proc/self/io` (bytes); the children from one pass over +`/proc//stat`, following the parent chain: `run` calls, MCP server +children, delegates, a CLI transport. CPU is the delta between two samples +(2 s by default, `interval` in ms), so it says what is happening now; IO is +cumulative for the session. `/self` and the `session_usage` tool print the +same numbers with the pid and the child count. + ## sysinfo RAM, CPU, swap and disk in one sidebar line: diff --git a/include/splinter.h b/include/splinter.h index 1604070..3010f1e 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -148,6 +148,12 @@ 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 */ + /* + * A router may say which upstream answered (junction sends + * X-Junction-Endpoint): the model a run is on is not always the + * endpoint that serves it. "" when the provider does not say. + */ + char served_by[128]; char *content; /* assistant text, may be "" */ struct sp_toolcall *calls; char *calls_json; /* the provider's own tool_calls array */ diff --git a/include/splinter_plugin.h b/include/splinter_plugin.h index 7d8c95a..6b4e77f 100644 --- a/include/splinter_plugin.h +++ b/include/splinter_plugin.h @@ -160,6 +160,13 @@ const struct sp_meter *sp_host_meter(struct sp_host *); */ const char *sp_host_model(struct sp_host *h); void sp_host_set_model(struct sp_host *h, const char *model); +/* + * The upstream that served the last model request, when the provider says + * (junction: X-Junction-Endpoint). The model is what was asked for; this is + * who answered, and a router may pick a different one per request. + */ +const char *sp_host_served_by(struct sp_host *h); +void sp_host_set_served_by(struct sp_host *h, const char *endpoint); 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/focus/focus.c b/plugins/focus/focus.c index bd5ecc4..a43e2c7 100644 --- a/plugins/focus/focus.c +++ b/plugins/focus/focus.c @@ -166,17 +166,23 @@ focus_session_sync(struct sp_host *h) static void focus_publish(struct sp_host *h) { - char line[sizeof(widget_text)]; + char line[sizeof(widget_text) + 160]; + char rec[96]; + unsigned n; int done; pthread_mutex_lock(&focus_lock); done = strcmp(goal_state, "succeeded") == 0; + n = reminders; if (goal[0] == '\0') line[0] = '\0'; /* no goal: the sidebar says nothing */ - else - snprintf(line, sizeof(line), "%s%.160s%s", + else { + snprintf(rec, sizeof(rec), sp_td("focus.widget_recap", + "recap %u, every %u turns"), n, every); + snprintf(line, sizeof(line), "%s%.160s%s\n%s", done ? "[done] " : "", goal, - strlen(goal) > 160 ? "..." : ""); + strlen(goal) > 160 ? "..." : "", rec); + } pthread_mutex_unlock(&focus_lock); (void)sp_host_widget_text(h, "focus", line); } @@ -374,6 +380,7 @@ focus_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, char text[GOAL_MAX + 800]; char rem[GOAL_MAX + 768]; char r[GOAL_MAX + 1]; + unsigned n; int complete; (void)budget; @@ -428,6 +435,8 @@ focus_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, snprintf(text, sizeof(text), "[focus] %s", rem); if (insert_before_user(conv, text) != 0) return -1; + (void)sp_host_status_msg(h, + sp_t("focus.note_goal")); focus_publish(h); return 1; } @@ -452,9 +461,16 @@ focus_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, pthread_mutex_lock(&focus_lock); last_reminder = turn; reminders++; - snprintf(widget_text, sizeof(widget_text), "%u reminders, every %u turns", - reminders, every); + n = reminders; pthread_mutex_unlock(&focus_lock); + { + char note[160]; + + snprintf(note, sizeof(note), sp_td("focus.note_recap", + "recap applied (turn %u, every %u turns)"), turn, every); + (void)sp_host_status_msg(h, note); + } + (void)n; focus_publish(h); return 1; } diff --git a/plugins/junction/junction.c b/plugins/junction/junction.c index 0d1f62d..b46fe28 100644 --- a/plugins/junction/junction.c +++ b/plugins/junction/junction.c @@ -83,6 +83,7 @@ struct jset { struct jep { char name[32]; int probe_ok, ok, fail, exhausted; + long last_ms; }; /* Everything the tick thread writes and the UI thread reads lives here. */ @@ -112,6 +113,12 @@ static struct { long p95_ms; unsigned models; char model[256]; /* the model this run is on */ + char served[128]; /* which target answered last */ + long served_ms; + time_t served_at; + int have_prev; + struct { char name[32]; int ok; } prev[40]; + size_t nprev; char route[256]; /* the rule targets, space separated */ char route_down[160]; /* targets whose probe failed */ unsigned route_up, route_n; @@ -543,6 +550,8 @@ read_status(const char *body) j.ep[j.nep].fail = mcp_arg_int(e, "fail", 0); j.ep[j.nep].exhausted = mcp_arg_int(e, "exhausted", 0) == 1; + j.ep[j.nep].last_ms = + (long)mcp_arg_int(e, "last_ms", -1); j.nep++; } } @@ -557,6 +566,51 @@ read_status(const char *body) snprintf(j.route, sizeof(j.route), "blocked by a rule"); } route_health(); + /* + * Streaming answers carry no X-Junction-Endpoint (only non-stream and + * /v1/models do), so the interface counter is the next best witness: + * the route target whose "ok" grew since the last sample answered. + * Our own /v1/models probe hits another endpoint and is ignored. + */ + if (j.route[0] != '\0') { + char copy[sizeof(j.route)], *tok, *save = NULL; + + snprintf(copy, sizeof(copy), "%s", j.route); + for (tok = strtok_r(copy, " ", &save); tok != NULL; + tok = strtok_r(NULL, " ", &save)) { + size_t k, e; + + for (e = 0; e < j.nep; e++) + if (strcmp(j.ep[e].name, tok) == 0) + break; + if (e == j.nep) + continue; + for (k = 0; k < j.nprev; k++) + if (strcmp(j.prev[k].name, tok) == 0) { + if (j.have_prev && + j.ep[e].ok > j.prev[k].ok) { + snprintf(j.served, + sizeof(j.served), "%s", tok); + j.served_ms = + j.ep[e].last_ms; + j.served_at = time(NULL); + } + break; + } + } + } + j.nprev = 0; + { + size_t e; + + for (e = 0; e < j.nep && j.nprev < 40; e++) { + snprintf(j.prev[j.nprev].name, + sizeof(j.prev[0].name), "%s", j.ep[e].name); + j.prev[j.nprev].ok = j.ep[e].ok; + j.nprev++; + } + } + j.have_prev = 1; j.mcp_ok = ok; j.mcp_total = total; j.exhausted = exhausted; @@ -645,6 +699,20 @@ compose(void) char d[32]; human_duration(j.uptime_s, d, sizeof(d)); + { + const char *header = sp_host_served_by(j.host); + time_t now = time(NULL); + + if (j.served[0] == '\0' || j.served_at == 0 || + now - j.served_at > 120) { + if (header != NULL && *header != '\0') { + snprintf(j.served, sizeof(j.served), "%s", + header); + j.served_ms = 0; + j.served_at = now; + } + } + } compose_stats(); if (!j.identity) { /* @@ -681,8 +749,18 @@ compose(void) size_t off; int first = 1; - off = (size_t)snprintf(j.widget, sizeof(j.widget), "%s\nroute ", - j.model[0] != '\0' ? j.model : "(model unknown)"); + char sbuf[160]; + + if (j.served[0] == '\0') + snprintf(sbuf, sizeof(sbuf), "(no request yet)"); + else if (j.served_ms > 0 && j.served_ms < 600000) + snprintf(sbuf, sizeof(sbuf), "%s %.1fs", j.served, + (double)j.served_ms / 1000.0); + else + snprintf(sbuf, sizeof(sbuf), "%s", j.served); + off = (size_t)snprintf(j.widget, sizeof(j.widget), + "%s\nserving %s\nroute ", + j.model[0] != '\0' ? j.model : "(model unknown)", sbuf); snprintf(copy, sizeof(copy), "%s", j.route); for (tok = strtok_r(copy, " ", &save); tok != NULL; tok = strtok_r(NULL, " ", &save)) { @@ -698,8 +776,9 @@ compose(void) } if (first) off = (size_t)snprintf(j.widget, sizeof(j.widget), - "%s\nroute (no rule matched)", - j.model[0] != '\0' ? j.model : "(model unknown)"); + "%s\nserving %s\nroute (no rule matched)", + j.model[0] != '\0' ? j.model : "(model unknown)", + sbuf); if (off < sizeof(j.widget)) snprintf(j.widget + off, sizeof(j.widget) - off, "\n%u/%u up", j.route_up, j.route_n); @@ -900,8 +979,10 @@ 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)"); - sp_buf_printf(out, " route: %s%s\n", j.route[0] != '\0' ? j.route : - "(no rule matched)", j.route[0] != '\0' ? "" : ""); + 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 : + "(no rule matched)"); sp_buf_printf(out, " route health: %u/%u up%s%s\n", j.route_up, j.route_n, j.route_down[0] != '\0' ? ", down: " : "", j.route_down); diff --git a/plugins/self/self.c b/plugins/self/self.c new file mode 100644 index 0000000..b1f1ac4 --- /dev/null +++ b/plugins/self/self.c @@ -0,0 +1,424 @@ +/* + * splinter -- self: what this session costs the machine. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * Every other widget talks about the world. This one talks about the process + * the operator is looking at: how much memory, CPU, threads and file + * descriptors splinter itself holds just by running, and how much its children + * (a run tool, an MCP server child, a delegate, a CLI transport) hold under it. + * + * self + * 84M rss 3.2% cpu + * 18 thr 41 fd + * kids 3 120M 1.4% cpu + * io 12M r 300k w + * + * The numbers come from /proc: /proc/self/status (VmRSS, Threads), /proc/self/fd + * (count), /proc/self/io (bytes), /proc//stat (utime/stime, rss, PPid). + * A child is any process whose parent chain reaches this pid; the walk is one + * pass over /proc per tick, which is cheap next to what a model request costs. + * + * CPU is the delta between two ticks, not a lifetime average, so the widget + * says "right now". IO is cumulative for the session; that is what "used" + * means here. + * + * plugin self { interval = 2000 } # ms between samples + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "splinter_plugin.h" + +#define SELF_KIDS_MAX 256 +#define SELF_LIST_MAX 12 +#define SELF_DEFAULT_MS 2000 + +struct kid { + int pid; + int ppid; + unsigned long rss_pages; + unsigned long long ticks; +}; + +struct sample { + unsigned long rss_kb; + int threads; + int fds; + double cpu_pct; + unsigned long io_read; + unsigned long io_write; + unsigned long long self_ticks; + double kids_cpu_pct; + unsigned long kids_rss_kb; + int kids; +}; + +static pthread_mutex_t self_lock = PTHREAD_MUTEX_INITIALIZER; +static struct sample now_s; +static char widget[512]; +static char detail[4096]; + +static long hz; +static unsigned long long prev_self_ticks; +static double prev_time; +static struct { int pid; unsigned long long ticks; } prev_kids[SELF_KIDS_MAX]; +static size_t prev_nkids; + +static double +mono_now(void) +{ + struct timespec ts; + + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9; +} + +/* one /proc//stat: ppid, resident pages and utime+stime in clock ticks */ +static int +read_stat(int pid, struct kid *out) +{ + char path[64], buf[2048], *p, *end; + FILE *f; + char state; + long ppid; + unsigned long pre[9]; /* pgrp .. cmajflt */ + unsigned long long utime, stime; + unsigned long post[9]; /* cutime .. rss */ + + snprintf(path, sizeof(path), "/proc/%d/stat", pid); + f = fopen(path, "r"); + if (f == NULL) + return -1; + if (fgets(buf, sizeof(buf), f) == NULL) { + fclose(f); + return -1; + } + fclose(f); + end = strrchr(buf, ')'); + if (end == NULL) + return -1; + p = end + 2; /* after "comm)": state ppid ... */ + if (sscanf(p, "%c %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu " + "%llu %llu %lu %lu %lu %lu %lu %lu %lu %lu %lu", + &state, &ppid, + &pre[0], &pre[1], &pre[2], &pre[3], &pre[4], &pre[5], &pre[6], + &pre[7], &pre[8], + &utime, &stime, + &post[0], &post[1], &post[2], &post[3], &post[4], &post[5], + &post[6], &post[7], &post[8]) != 22) + return -1; + (void)state; + out->pid = pid; + out->ppid = (int)ppid; + out->rss_pages = post[8]; /* the field named rss, in pages */ + out->ticks = utime + stime; + return 0; +} + +static void +read_self(struct sample *s) +{ + FILE *f; + char line[512]; + + s->rss_kb = 0; + s->threads = 0; + f = fopen("/proc/self/status", "r"); + if (f != NULL) { + while (fgets(line, sizeof(line), f) != NULL) { + unsigned long v; + + if (sscanf(line, "VmRSS: %lu kB", &v) == 1) + s->rss_kb = v; + else if (sscanf(line, "Threads: %lu", &v) == 1) + s->threads = (int)v; + } + fclose(f); + } + { + DIR *d = opendir("/proc/self/fd"); + int n = 0; + + if (d != NULL) { + struct dirent *e; + + while ((e = readdir(d)) != NULL) + if (e->d_name[0] != '.') + n++; + closedir(d); + } + s->fds = n; + } + f = fopen("/proc/self/io", "r"); + if (f != NULL) { + while (fgets(line, sizeof(line), f) != NULL) { + unsigned long v; + + if (sscanf(line, "read_bytes: %lu", &v) == 1) + s->io_read = v; + else if (sscanf(line, "write_bytes: %lu", &v) == 1) + s->io_write = v; + } + fclose(f); + } +} + +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)); + else if (kb >= 1024) + snprintf(buf, cap, "%.0fM", (double)kb / 1024.0); + else + snprintf(buf, cap, "%luk", 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)); + else if (b >= 1024UL * 1024UL) + snprintf(buf, cap, "%.1fM", (double)b / (1024.0 * 1024.0)); + else if (b >= 1024) + snprintf(buf, cap, "%.0fk", (double)b / 1024.0); + else + snprintf(buf, cap, "%luB", b); +} + +/* + * Who is under this process: one read of every /proc//stat, then include + * anything whose parent is already included until nothing changes. The tree is + * a few levels deep, so a handful of passes is enough. + */ +static void +scan_kids(struct sample *s) +{ + DIR *d; + struct kid v[SELF_KIDS_MAX]; + unsigned char in[SELF_KIDS_MAX]; + size_t n = 0, i, pass; + int self = (int)getpid(); + + d = opendir("/proc"); + if (d != NULL) { + struct dirent *e; + + while ((e = readdir(d)) != NULL && n < SELF_KIDS_MAX) { + char *end; + long pid = strtol(e->d_name, &end, 10); + + if (*end != '\0' || pid <= 0) + continue; + memset(&v[n], 0, sizeof(v[n])); + if (read_stat((int)pid, &v[n]) != 0) + continue; + in[n] = pid == self; + n++; + } + closedir(d); + } + for (pass = 0; pass < 8; pass++) { + int changed = 0; + + for (i = 0; i < n; i++) { + size_t j; + + if (in[i]) + continue; + for (j = 0; j < n; j++) + if (in[j] && v[j].pid == v[i].ppid) { + in[i] = 1; + changed = 1; + break; + } + } + if (!changed) + break; + } + s->kids = 0; + s->kids_rss_kb = 0; + s->kids_cpu_pct = 0; + { + double dt = prev_time > 0 ? mono_now() - prev_time : 0; + unsigned long long sum = 0; + + for (i = 0; i < n; i++) { + size_t pi2; + + if (!in[i] || v[i].pid == self) + continue; + s->kids++; + s->kids_rss_kb += v[i].rss_pages * + (unsigned long)(sysconf(_SC_PAGESIZE) / 1024); + for (pi2 = 0; pi2 < prev_nkids; pi2++) + if (prev_kids[pi2].pid == v[i].pid) { + sum += v[i].ticks - + prev_kids[pi2].ticks; + break; + } + } + if (dt > 0 && hz > 0) + s->kids_cpu_pct = (double)sum / (double)hz / dt * 100.0; + } + prev_nkids = 0; + for (i = 0; i < n && prev_nkids < SELF_KIDS_MAX; i++) + if (in[i] && v[i].pid != self) { + prev_kids[prev_nkids].pid = v[i].pid; + prev_kids[prev_nkids].ticks = v[i].ticks; + prev_nkids++; + } +} + +static void +sample(struct sample *s) +{ + struct kid self; + double now = mono_now(); + double dt = prev_time > 0 ? now - prev_time : 0; + + memset(s, 0, sizeof(*s)); + read_self(s); + if (read_stat((int)getpid(), &self) == 0) { + s->self_ticks = self.ticks; + if (dt > 0 && hz > 0 && prev_self_ticks > 0) + s->cpu_pct = (double)(self.ticks - prev_self_ticks) / + (double)hz / dt * 100.0; + prev_self_ticks = self.ticks; + } + scan_kids(s); + prev_time = now; +} + +static void +compose(struct sample *s) +{ + char rss[24], kids[24], r[24], w[24]; + + human(s->rss_kb, rss, sizeof(rss)); + 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); + + snprintf(detail, sizeof(detail), + "self: pid %d\n" + " rss: %s (%lu kB)\n" + " threads: %d\n" + " fds: %d\n" + " cpu: %.1f%%\n" + " io: %s read, %s written\n" + "children: %d process(es), %s rss, %.1f%% cpu\n", + (int)getpid(), rss, s->rss_kb, s->threads, s->fds, s->cpu_pct, + r, w, s->kids, kids, s->kids_cpu_pct); +} + +static int +self_tick(struct sp_host *h, const char *name, void *ctx) +{ + struct sample s; + + (void)ctx; + if (hz <= 0) + hz = sysconf(_SC_CLK_TCK); + sample(&s); + pthread_mutex_lock(&self_lock); + now_s = s; + compose(&s); + pthread_mutex_unlock(&self_lock); + return sp_host_widget_text(h, name, widget); +} + +static void +copy_detail(char *out, size_t cap) +{ + pthread_mutex_lock(&self_lock); + snprintf(out, cap, "%s", detail); + pthread_mutex_unlock(&self_lock); +} + +static int +self_tool(const char *args, struct sp_buf *out, void *ctx) +{ + char buf[sizeof(detail)]; + + (void)args; + (void)ctx; + copy_detail(buf, sizeof(buf)); + sp_buf_puts(out, buf); + return 0; +} + +static int +self_command(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx) +{ + char buf[sizeof(detail)]; + + (void)h; + (void)ctx; + if (args != NULL && *args != '\0') + return sp_buf_puts(out, "usage: /self"); + copy_detail(buf, sizeof(buf)); + sp_buf_puts(out, buf); + return 0; +} + +static int +self_init(struct sp_host *h) +{ + struct sp_widget w; + static const struct sp_status seg = { "self", NULL }; + static const struct sp_tool t = { + "session_usage", + "What this splinter process costs the machine: RSS, CPU, threads " + "and file descriptors of the session itself, and the same for " + "every child process under it.", + "{\"type\":\"object\",\"properties\":{}}", + SP_AUTH_READ, + self_tool, + NULL + }; + const char *iv; + + hz = sysconf(_SC_CLK_TCK); + memset(&w, 0, sizeof(w)); + w.name = "self"; + w.tick = self_tick; + iv = sp_host_plugin_config(h, "self", "interval"); + w.interval_ms = iv != NULL && atoi(iv) > 0 ? + (unsigned)atoi(iv) : SELF_DEFAULT_MS; + if (sp_host_add_widget(h, &w) != 0) + return -1; + if (sp_host_add_tool(h, &t) != 0) + return -1; + if (sp_host_add_command(h, "self", self_command, NULL) != 0) + return -1; + (void)seg; + return 0; +} + +static const struct sp_plugin self_plugin = { + SP_PLUGIN_ABI, "self", "1.0.0", self_init, NULL, NULL +}; + +const struct sp_plugin * +sp_plugin_describe(void) +{ + return &self_plugin; +} diff --git a/share/locale/de.msg b/share/locale/de.msg index 56d3c8d..8d084b8 100644 --- a/share/locale/de.msg +++ b/share/locale/de.msg @@ -58,6 +58,9 @@ focus.set = Ziel gesetzt: %s focus.none = kein Ziel gesetzt (/goal ) focus.status = Ziel: %s (%u Recaps, alle %u Turns) focus.status_done = Ziel: %s [succeeded] (%u Recaps, alle %u Turns) +focus.widget_recap = Recap %u, alle %u Turns +focus.note_goal = Ziel im Prompt +focus.note_recap = Recap angewandt (Turn %u, alle %u Turns) focus.succeeded = Ziel erreicht: %s cps.idle = Leerlauf (angewandt %lu, vorbereitet %lu) cps.plan = Plan bereit: schnitt %zu/%zu, %zu -> %zu B diff --git a/share/locale/en.msg b/share/locale/en.msg index 64eef28..4c0afba 100644 --- a/share/locale/en.msg +++ b/share/locale/en.msg @@ -57,6 +57,9 @@ focus.set = goal set: %s focus.none = no goal set (/goal ) focus.status = goal: %s (%u recaps, every %u turns) focus.status_done = goal: %s [succeeded] (%u recaps, every %u turns) +focus.widget_recap = recap %u, every %u turns +focus.note_goal = goal in the prompt +focus.note_recap = recap applied (turn %u, every %u turns) focus.succeeded = goal succeeded: %s cps.idle = idle (applied %lu, prepared %lu) cps.plan = plan ready: cut %zu/%zu, %zu -> %zu B diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg index a8abc68..40240ef 100644 --- a/share/locale/pt_BR.msg +++ b/share/locale/pt_BR.msg @@ -73,6 +73,9 @@ focus.set = objetivo definido: %s focus.none = nenhum objetivo definido (/goal ) focus.status = objetivo: %s (%u recaps, a cada %u turnos) focus.status_done = objetivo: %s [succeeded] (%u recaps, a cada %u turnos) +focus.widget_recap = recap %u, a cada %u turnos +focus.note_goal = objetivo no prompt +focus.note_recap = recap aplicado (turno %u, a cada %u turnos) focus.succeeded = objetivo alcancado: %s cps.idle = ocioso (aplicado %lu, preparado %lu) diff --git a/src/backend/agent.c b/src/backend/agent.c index 53d5d41..ce3ecba 100644 --- a/src/backend/agent.c +++ b/src/backend/agent.c @@ -498,6 +498,9 @@ 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->cfg->note != NULL) a->cfg->note(a->cfg->note_ctx, ""); return 0; diff --git a/src/backend/mcpserver.c b/src/backend/mcpserver.c index e6a9026..5dd604f 100644 --- a/src/backend/mcpserver.c +++ b/src/backend/mcpserver.c @@ -40,11 +40,32 @@ #include #include "splinter.h" +#include "splinter_engine.h" #include "mcp.h" #include "mcpserver.h" +#include "mcpsession.h" static volatile int mcp_stop; +/* + * What a connection works on. With an engine the registry is asked from it on + * every call (a session switch replaces the engine and with it the registry); + * without one the server serves the registry it was handed. + */ +struct srv { + struct sp_engine **eng; + const struct sp_engine_opts *opts; + const struct sp_registry *reg; +}; + +static const struct sp_registry * +srv_reg(const struct srv *s) +{ + if (s->eng != NULL && *s->eng != NULL) + return sp_engine_registry(*s->eng); + return s->reg; +} + static void on_signal(int sig) { @@ -132,21 +153,24 @@ reply_error(int fd, int id, int code, const char *message) } static void -reply_tools(int fd, int id, const struct sp_registry *reg) +reply_tools(int fd, int id, const struct srv *s) { struct sp_buf b; - size_t i, ntv; - const struct sp_tool *tv; + size_t i, ntv = 0; + const struct sp_tool *tv = NULL; + int first = 1; if (sp_buf_init(&b) != 0) return; sp_buf_puts(&b, "{\"tools\":["); - tv = sp_registry_tools(reg, &ntv); + if (srv_reg(s) != NULL) + tv = sp_registry_tools(srv_reg(s), &ntv); for (i = 0; i < ntv; i++) { const struct sp_tool *t = &tv[i]; - if (i > 0) + if (!first) sp_buf_puts(&b, ","); + first = 0; sp_buf_puts(&b, "{\"name\":\""); (void)sp_json_escape(&b, t->name); sp_buf_puts(&b, "\",\"description\":\""); @@ -157,20 +181,23 @@ reply_tools(int fd, int id, const struct sp_registry *reg) "{\"type\":\"object\",\"properties\":{}}"); sp_buf_puts(&b, "}"); } + sp_mcpsession_tools(&b, &first); sp_buf_puts(&b, "]}"); reply_ok(fd, id, b.p); sp_buf_free(&b); } static void -call_tool(int fd, int id, const struct sp_registry *reg, const char *line, +call_tool(int fd, int id, const struct srv *s, const char *line, int allow_mutate) { const struct sp_tool *t; - const char *name, *argstart; + const char *name, *argstart = NULL; + char namebuf[128]; struct sp_buf raw, out; mcp_json *v; size_t arglen = 0; + int mine; v = mcp_parse(line); if (v == NULL) { @@ -178,7 +205,6 @@ call_tool(int fd, int id, const struct sp_registry *reg, const char *line, return; } name = NULL; - argstart = NULL; { const mcp_json *params = mcp_arg(v, "params"); const mcp_json *args; @@ -194,18 +220,10 @@ call_tool(int fd, int id, const struct sp_registry *reg, const char *line, reply_error(fd, id, -32602, "params.name is required"); return; } - t = sp_registry_find(reg, name); - if (t == NULL) { - mcp_json_free(v); - reply_error(fd, id, -32601, "unknown tool"); - return; - } - if (t->auth != SP_AUTH_READ && !allow_mutate) { - mcp_json_free(v); - reply_error(fd, id, -32000, "tool needs authorization; start the " - "server with --autonomous to allow mutating calls"); - return; - } + /* the name lives in the parsed JSON: copy it before freeing that */ + snprintf(namebuf, sizeof(namebuf), "%s", name); + name = namebuf; + mine = sp_mcpsession_has(name); /* the arguments object, as text - tools parse their own arguments */ { const char *p = strstr(line, "\"arguments\""); @@ -224,13 +242,39 @@ call_tool(int fd, int id, const struct sp_registry *reg, const char *line, (void)sp_buf_add(&raw, argstart, arglen); else (void)sp_buf_puts(&raw, "{}"); - if (sp_buf_init(&out) != 0) { sp_buf_free(&raw); return; } - if (t->run(raw.p, &out, t->ctx) != 0) - sp_buf_puts(&out, "error: tool failed"); + if (mine) { + if (sp_mcpsession_auth(name) != SP_AUTH_READ && !allow_mutate) { + sp_buf_free(&raw); + sp_buf_free(&out); + reply_error(fd, id, -32000, "tool needs authorization; " + "start the server with --autonomous to allow " + "mutating calls"); + return; + } + (void)sp_mcpsession_call(name, raw.p, &out); + } else { + t = srv_reg(s) != NULL ? sp_registry_find(srv_reg(s), name) : NULL; + if (t == NULL) { + sp_buf_free(&raw); + sp_buf_free(&out); + reply_error(fd, id, -32601, "unknown tool"); + return; + } + if (t->auth != SP_AUTH_READ && !allow_mutate) { + sp_buf_free(&raw); + sp_buf_free(&out); + reply_error(fd, id, -32000, "tool needs authorization; " + "start the server with --autonomous to allow " + "mutating calls"); + return; + } + if (t->run(raw.p, &out, t->ctx) != 0) + sp_buf_puts(&out, "error: tool failed"); + } { struct sp_buf res; @@ -247,8 +291,7 @@ call_tool(int fd, int id, const struct sp_registry *reg, const char *line, } static void -handle_line(int fd, const struct sp_registry *reg, const char *line, - int allow_mutate) +handle_line(int fd, const struct srv *s, const char *line, int allow_mutate) { mcp_json *v; const char *method; @@ -278,12 +321,12 @@ handle_line(int fd, const struct sp_registry *reg, const char *line, } if (strcmp(method, "tools/list") == 0) { mcp_json_free(v); - reply_tools(fd, id, reg); + reply_tools(fd, id, s); return; } if (strcmp(method, "tools/call") == 0) { mcp_json_free(v); - call_tool(fd, id, reg, line, allow_mutate); + call_tool(fd, id, s, line, allow_mutate); return; } mcp_json_free(v); @@ -305,8 +348,7 @@ token_equal(const char *a, const char *b) } static void -serve_conn(int fd, const struct sp_registry *reg, int allow_mutate, - const char *token) +serve_conn(int fd, const struct srv *s, int allow_mutate, const char *token) { char line[16384]; size_t used = 0; @@ -342,7 +384,7 @@ serve_conn(int fd, const struct sp_registry *reg, int allow_mutate, } authed = 1; } else if (line[0] == '{') - handle_line(fd, reg, line, allow_mutate); + handle_line(fd, s, line, allow_mutate); len = (size_t)(nl - line) + 1; memmove(line, line + len, used - len + 1); used -= len; @@ -353,13 +395,24 @@ serve_conn(int fd, const struct sp_registry *reg, int allow_mutate, } int -sp_mcp_serve(const struct sp_registry *reg, const char *ip, int port, - int allow_mutate, struct sp_buf *err) +sp_mcp_serve(struct sp_engine **eng, const struct sp_engine_opts *opts, + const struct sp_registry *reg, const char *ip, int port, + int allow_mutate, int own_signals, struct sp_buf *err) { + struct srv srv; int s, one = 1; struct sockaddr_in addr; const char *token = getenv("SPLINTER_MCP_TOKEN"); + size_t ntools = reg != NULL ? reg->len : 0; + + memset(&srv, 0, sizeof(srv)); + srv.eng = eng; + srv.opts = opts; + srv.reg = reg; + sp_mcpsession_bind(eng, opts); + if (eng != NULL && *eng != NULL && srv_reg(&srv) != NULL) + ntools = srv_reg(&srv)->len; if (ip == NULL || *ip == '\0') ip = "127.0.0.1"; @@ -396,12 +449,15 @@ sp_mcp_serve(const struct sp_registry *reg, const char *ip, int port, close(s); return -1; } - (void)signal(SIGINT, on_signal); - (void)signal(SIGTERM, on_signal); + if (own_signals) { + (void)signal(SIGINT, on_signal); + (void)signal(SIGTERM, on_signal); + } /* a client that hangs up mid-reply is a closed connection, not our death */ (void)signal(SIGPIPE, SIG_IGN); - fprintf(stderr, "splinter: MCP server on %s:%d (%zu tools, %s, %s)\n", - ip, port, reg->len, allow_mutate ? "mutating allowed" : "read only", + fprintf(stderr, "splinter: MCP server on %s:%d (%zu tools + %d " + "session tools, %s, %s)\n", ip, port, ntools, 12, + allow_mutate ? "mutating allowed" : "read only", token != NULL ? "token required" : "loopback, no token"); while (!mcp_stop) { @@ -422,7 +478,7 @@ sp_mcp_serve(const struct sp_registry *reg, const char *ip, int port, (void)setsockopt(c, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); } - serve_conn(c, reg, allow_mutate, token); + serve_conn(c, &srv, allow_mutate, token); close(c); } close(s); diff --git a/src/backend/mcpserver.h b/src/backend/mcpserver.h index 0810828..4906c25 100644 --- a/src/backend/mcpserver.h +++ b/src/backend/mcpserver.h @@ -9,7 +9,16 @@ #include "splinter.h" -int sp_mcp_serve(const struct sp_registry *, const char *ip, int port, - int allow_mutate, struct sp_buf *err); +struct sp_engine; +struct sp_engine_opts; + +/* + * eng/opts make the session tools work; NULL eng serves the registry only. + * own_signals: 0 when the caller already has SIGINT/SIGTERM handlers (the + * daemon runs the MCP server in a thread). + */ +int sp_mcp_serve(struct sp_engine **eng, const struct sp_engine_opts *opts, + const struct sp_registry *, const char *ip, int port, + int allow_mutate, int own_signals, struct sp_buf *err); #endif /* SPLINTER_MCPSERVER_H */ diff --git a/src/backend/mcpsession.c b/src/backend/mcpsession.c new file mode 100644 index 0000000..b45d59e --- /dev/null +++ b/src/backend/mcpsession.c @@ -0,0 +1,597 @@ +/* + * splinter -- the session tools of the MCP server. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * The file tools the MCP server exposes are the ones any MCP client already + * has. What only splinter can answer is its own sessions: which exist, what + * they said, what the model is, and how to put a prompt in and get the answer + * back. That is this file. + * + * splinter_sessions list the sessions of this state directory + * splinter_state model, profile, session, busy, counters + * splinter_models the selectors /model takes + * splinter_history the open session's user and assistant messages + * splinter_agents the profiles + * splinter_say submit a prompt, wait, return the answer + * splinter_open switch to another session (or "new") + * splinter_model switch the model (an ordinary /model selector) + * splinter_agent switch the profile by name + * splinter_steer type into the running turn + * splinter_cancel cancel the running turn + * splinter_approve answer a pending approval + * + * A turn that parks on an approval is not an error: splinter_say returns the + * question and leaves the turn waiting, and splinter_approve answers it. The + * server is one connection at a time, so there is at most one such turn. + * + * Authorization goes through the same gate as the file tools: reads are + * always served, anything that starts a turn or changes a session needs + * --autonomous on the server. + */ +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "splinter_engine.h" +#include "mcp.h" +#include "mcpsession.h" + +static struct sp_engine **session_eng; +static const struct sp_engine_opts *session_opts; + +#define SAY_TIMEOUT_S 3600 +#define SAY_ANSWER_MAX (256 * 1024) +#define HIST_TEXT_MAX 600 + +void +sp_mcpsession_bind(struct sp_engine **eng, const struct sp_engine_opts *opts) +{ + session_eng = eng; + session_opts = opts; +} + +static const char * +arg_string(const char *args, const char *key, char *out, size_t cap) +{ + mcp_json *v; + const char *s; + + out[0] = '\0'; + if (args == NULL || *args == '\0') + return out; + v = mcp_parse(args); + if (v == NULL) + return out; + s = mcp_arg_string(v, key); + if (s != NULL) + snprintf(out, cap, "%s", s); + mcp_json_free(v); + return out; +} + +static int +arg_int(const char *args, const char *key, int dflt) +{ + mcp_json *v; + int n = dflt; + + if (args == NULL || *args == '\0') + return dflt; + v = mcp_parse(args); + if (v == NULL) + return dflt; + n = mcp_arg_int(v, key, dflt); + mcp_json_free(v); + return n; +} + +static int +arg_bool(const char *args, const char *key, int dflt) +{ + mcp_json *v; + int n = dflt; + + if (args == NULL || *args == '\0') + return dflt; + v = mcp_parse(args); + if (v == NULL) + return dflt; + n = mcp_arg_bool(v, key, dflt); + mcp_json_free(v); + return n; +} + +/* ---- the tools ---- */ + +static const struct { + const char *name; + int auth; + const char *description; + const char *schema; +} tools[] = { + { "splinter_sessions", SP_AUTH_READ, + "List the splinter sessions in this state directory: id, title, " + "mtime, size, and which one is open.", + "{\"type\":\"object\",\"properties\":{}}" }, + { "splinter_state", SP_AUTH_READ, + "The running splinter: model, endpoint, profile, session, directory, " + "busy/waiting, tokens, context use and the last turn.", + "{\"type\":\"object\",\"properties\":{}}" }, + { "splinter_models", SP_AUTH_READ, + "The selectors /model takes (providers, then pools), with the current " + "one marked.", + "{\"type\":\"object\",\"properties\":{}}" }, + { "splinter_agents", SP_AUTH_READ, + "The agent profiles of this run, with the active one marked.", + "{\"type\":\"object\",\"properties\":{}}" }, + { "splinter_history", SP_AUTH_READ, + "The open session's user and assistant messages, oldest first.", + "{\"type\":\"object\",\"properties\":{\"limit\":{\"type\":\"integer\"," + "\"description\":\"how many messages, default 20, max 100\"}}}" }, + { "splinter_say", SP_AUTH_MUTATE, + "Send a prompt to the open session and wait for the answer. Returns " + "the answer; if the turn waits for an approval, returns the question " + "and leaves the turn parked (call splinter_approve).", + "{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"," + "\"description\":\"the prompt\"}},\"required\":[\"text\"]}" }, + { "splinter_open", SP_AUTH_MUTATE, + "Switch splinter to another session: a session id, \"new\" for a fresh " + "one, or \"last\" for the newest.", + "{\"type\":\"object\",\"properties\":{\"session\":{\"type\":\"string\"," + "\"description\":\"session id, new or last\"}}," + "\"required\":[\"session\"]}" }, + { "splinter_model", SP_AUTH_MUTATE, + "Switch the model: a provider id, a pool id, provider/model, or a " + "model name the provider serves (the same selector /model takes).", + "{\"type\":\"object\",\"properties\":{\"model\":{\"type\":\"string\"," + "\"description\":\"what goes after /model\"}},\"required\":[\"model\"]}" }, + { "splinter_agent", SP_AUTH_MUTATE, + "Switch the agent profile by name.", + "{\"type\":\"object\",\"properties\":{\"agent\":{\"type\":\"string\"," + "\"description\":\"profile name\"}},\"required\":[\"agent\"]}" }, + { "splinter_steer", SP_AUTH_MUTATE, + "Type into the running turn; the loop picks it up at the next step " + "boundary.", + "{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"," + "\"description\":\"the steering text\"}},\"required\":[\"text\"]}" }, + { "splinter_cancel", SP_AUTH_MUTATE, + "Cancel the running turn.", "{\"type\":\"object\",\"properties\":{}}" }, + { "splinter_approve", SP_AUTH_MUTATE, + "Answer a pending approval: allow true runs the tool, false denies it " + "(the denial becomes the observation the model sees).", + "{\"type\":\"object\",\"properties\":{\"allow\":{\"type\":\"boolean\"}}," + "\"required\":[\"allow\"]}" } +}; + +int +sp_mcpsession_has(const char *name) +{ + size_t i; + + for (i = 0; i < sizeof(tools) / sizeof(tools[0]); i++) + if (strcmp(tools[i].name, name) == 0) + return 1; + return 0; +} + +int +sp_mcpsession_auth(const char *name) +{ + size_t i; + + for (i = 0; i < sizeof(tools) / sizeof(tools[0]); i++) + if (strcmp(tools[i].name, name) == 0) + return tools[i].auth; + return SP_AUTH_READ; +} + +/* the JSON entries for tools/list, each prefixed with a comma when !first */ +void +sp_mcpsession_tools(struct sp_buf *b, int *first) +{ + size_t i; + + for (i = 0; i < sizeof(tools) / sizeof(tools[0]); i++) { + if (!*first) + sp_buf_puts(b, ","); + *first = 0; + sp_buf_puts(b, "{\"name\":\""); + (void)sp_json_escape(b, tools[i].name); + sp_buf_puts(b, "\",\"description\":\""); + (void)sp_json_escape(b, tools[i].description); + sp_buf_puts(b, "\",\"inputSchema\":"); + sp_buf_puts(b, tools[i].schema); + sp_buf_puts(b, "}"); + } +} + +/* ---- the handlers ---- */ + +static int +tool_sessions(struct sp_buf *out) +{ + struct sp_session_brief v[200]; + const char *cur; + int n, i; + const char *dir; + + dir = sp_engine_state_dir(*session_eng); + cur = sp_engine_session_id(*session_eng); + n = sp_session_list(dir, v, 200); + if (n < 0) + n = 0; + for (i = 0; i < n; i++) { + char when[32] = ""; + time_t t = (time_t)v[i].mtime; + struct tm tm; + + if (localtime_r(&t, &tm) != NULL) + strftime(when, sizeof(when), "%Y-%m-%d %H:%M", &tm); + sp_buf_printf(out, "%c %s %-28s %7zu %s\n", + strcmp(v[i].id, cur) == 0 ? '*' : ' ', when, v[i].id, + v[i].bytes, v[i].title); + } + if (n == 0) + sp_buf_puts(out, "no sessions yet\n"); + return 0; +} + +static int +tool_state(struct sp_buf *out) +{ + struct sp_engine_state st; + + if (sp_engine_state(*session_eng, &st) != 0) { + sp_buf_puts(out, "error: no engine"); + return 0; + } + sp_buf_printf(out, "model: %s\n", st.model); + sp_buf_printf(out, "endpoint: %s\n", st.endpoint); + sp_buf_printf(out, "agent: %s\n", st.agent); + sp_buf_printf(out, "session: %s\n", st.session); + sp_buf_printf(out, "dir: %s\n", st.dir); + sp_buf_printf(out, "busy: %s%s\n", st.busy ? "yes" : "no", + st.waiting ? " (waiting for an approval)" : ""); + sp_buf_printf(out, "tokens: %zu in / %zu out\n", st.tokens_in, + st.tokens_out); + sp_buf_printf(out, "ctx: %zu/%zu", st.ctx_used, st.ctx_max); + if (st.ctx_max > 0) + sp_buf_printf(out, " (%u%%)", + (unsigned)(100.0 * (double)st.ctx_used / (double)st.ctx_max)); + sp_buf_puts(out, "\n"); + sp_buf_printf(out, "last turn: %zu ms, %zu steps, %zu calls\n", + st.last_ms, st.last_steps, st.last_calls); + return 0; +} + +static int +tool_models(struct sp_buf *out) +{ + struct sp_model_choice v[SP_MODEL_CHOICES]; + size_t n, i; + + n = sp_engine_models(*session_eng, v, SP_MODEL_CHOICES); + for (i = 0; i < n; i++) + sp_buf_printf(out, "%c %-16s %s\n", v[i].current ? '*' : ' ', + v[i].sel, v[i].label); + if (n == 0) + sp_buf_puts(out, "no models configured\n"); + return 0; +} + +static int +tool_agents(struct sp_buf *out) +{ + int n, i, cur; + + n = sp_engine_agents(*session_eng); + cur = sp_engine_agent_cur(*session_eng); + for (i = 0; i < n; i++) + sp_buf_printf(out, "%c %s\n", i == cur ? '*' : ' ', + sp_engine_agent_name(*session_eng, i)); + return 0; +} + +static int +tool_history(const char *args, struct sp_buf *out) +{ + const struct sp_conv *conv = sp_engine_conv(*session_eng); + int limit = arg_int(args, "limit", 20); + size_t i, from; + + if (limit <= 0) + limit = 20; + if (limit > 100) + limit = 100; + if (conv == NULL) { + sp_buf_puts(out, "no conversation"); + return 0; + } + from = conv->n > (size_t)limit ? conv->n - (size_t)limit : 0; + for (i = from; i < conv->n; i++) { + const struct sp_msg *m = &conv->v[i]; + char text[HIST_TEXT_MAX + 1]; + + if (m->role == NULL || m->content == NULL) + continue; + if (strcmp(m->role, "user") != 0 && + strcmp(m->role, "assistant") != 0) + continue; + snprintf(text, sizeof(text), "%s", m->content); + sp_buf_printf(out, "[%s] %s\n", m->role, text); + } + return 0; +} + +/* drain the events of a turn; returns 0 while it is still running */ +static int +collect(struct sp_engine *e, char *answer, size_t cap, int *known, + size_t *steps, size_t *calls) +{ + struct sp_event ev; + + while (sp_engine_poll(e, &ev)) { + switch (ev.kind) { + case SP_EV_TURN_END: + if (ev.a != NULL) + snprintf(answer, cap, "%s", ev.a); + if (ev.b != NULL && ev.n != 0) + snprintf(answer, cap, "error: %s", ev.b); + *known = 1; + break; + case SP_EV_STEP: + (*steps)++; + break; + case SP_EV_TOOL: + (*calls)++; + break; + default: + break; + } + sp_engine_event_free(&ev); + } + return 0; +} + +static int +tool_say(const char *args, struct sp_buf *out) +{ + struct sp_engine *e = *session_eng; + char text[8192], answer[SAY_ANSWER_MAX]; + char nm[64] = "", ar[512] = ""; + size_t steps = 0, calls = 0; + int known = 0, auth = SP_AUTH_READ; + time_t deadline; + + arg_string(args, "text", text, sizeof(text)); + if (text[0] == '\0') { + sp_buf_puts(out, "error: 'text' is required"); + return 0; + } + if (sp_engine_busy(e)) { + sp_buf_puts(out, "error: a turn is already running " + "(splinter_steer or splinter_cancel)"); + return 0; + } + answer[0] = '\0'; + if (sp_engine_submit(e, text) != 0) { + sp_buf_puts(out, "error: cannot start the turn"); + return 0; + } + deadline = time(NULL) + SAY_TIMEOUT_S; + for (;;) { + struct sp_engine_state st; + + collect(e, answer, sizeof(answer), &known, &steps, &calls); + if (!sp_engine_busy(e)) + break; + if (sp_engine_state(e, &st) == 0 && st.waiting && + sp_engine_approval(e, nm, sizeof(nm), &auth, ar, + sizeof(ar))) { + sp_buf_printf(out, "approval required: %s %s (%s)\n" + "call splinter_approve {\"allow\":true} or " + "{\"allow\":false}\n", nm, ar, + auth == SP_AUTH_DESTRUCTIVE ? "destructive" : + auth == SP_AUTH_MUTATE ? "mutate" : "read"); + return 0; + } + if (time(NULL) > deadline) { + (void)sp_engine_cancel(e); + sp_buf_puts(out, "error: the turn did not finish in " + "time and was cancelled"); + return 0; + } + { + struct timespec ts = { 0, 50 * 1000 * 1000L }; + + nanosleep(&ts, NULL); + } + } + (void)sp_engine_wait(e); + if (known) + sp_buf_printf(out, "%s\n\n[%zu steps, %zu tool calls]\n", + answer[0] != '\0' ? answer : "(empty answer)", steps, calls); + else + sp_buf_puts(out, "error: the turn ended without an answer\n"); + return 0; +} + +static int +tool_open(const char *args, struct sp_buf *out) +{ + char id[128]; + struct sp_buf err; + int rc; + + arg_string(args, "session", id, sizeof(id)); + if (id[0] == '\0') { + sp_buf_puts(out, "error: 'session' is required"); + return 0; + } + if (session_opts == NULL) { + sp_buf_puts(out, "error: this server has no engine options; " + "sessions cannot be switched"); + return 0; + } + if (sp_buf_init(&err) != 0) + return -1; + rc = sp_engine_switch(session_eng, session_opts, id, &err); + if (rc != 0) + sp_buf_printf(out, "error: %s\n", + err.p != NULL ? err.p : "cannot open the session"); + else { + struct sp_engine_state st; + + if (sp_engine_state(*session_eng, &st) == 0) + sp_buf_printf(out, "opened: %s\nmodel: %s\nagent: %s\n", + st.session, st.model, st.agent); + else + sp_buf_puts(out, "opened\n"); + } + sp_buf_free(&err); + return 0; +} + +static int +tool_model(const char *args, struct sp_buf *out) +{ + char sel[300], line[340]; + struct sp_buf reply; + int kind; + + arg_string(args, "model", sel, sizeof(sel)); + if (sel[0] == '\0') { + sp_buf_puts(out, "error: 'model' is required " + "(splinter_models lists the selectors)"); + return 0; + } + if (sp_engine_busy(*session_eng)) { + sp_buf_puts(out, "error: a turn is running; wait or cancel it"); + return 0; + } + snprintf(line, sizeof(line), "/model %s", sel); + if (sp_buf_init(&reply) != 0) + return -1; + kind = sp_engine_input(*session_eng, line, &reply); + if (kind != SP_INPUT_HANDLED) { + sp_buf_puts(out, "error: /model started a turn?"); + sp_buf_free(&reply); + return 0; + } + sp_buf_printf(out, "%s", reply.p != NULL ? reply.p : ""); + sp_buf_free(&reply); + return 0; +} + +static int +tool_agent(const char *args, struct sp_buf *out) +{ + char name[64]; + int n, i, cur; + + arg_string(args, "agent", name, sizeof(name)); + if (name[0] == '\0') { + sp_buf_puts(out, "error: 'agent' is required"); + return 0; + } + if (sp_engine_busy(*session_eng)) { + sp_buf_puts(out, "error: a turn is running; wait or cancel it"); + return 0; + } + n = sp_engine_agents(*session_eng); + cur = sp_engine_agent_cur(*session_eng); + for (i = 0; i < n; i++) + if (strcmp(sp_engine_agent_name(*session_eng, i), name) == 0) { + if (sp_engine_agent_switch(*session_eng, i) != 0) { + sp_buf_puts(out, "error: cannot switch the agent"); + return 0; + } + sp_buf_printf(out, "agent: %s\n", name); + return 0; + } + sp_buf_printf(out, "error: no agent '%s' (active is %s)\n", name, + cur >= 0 ? sp_engine_agent_name(*session_eng, cur) : "?"); + return 0; +} + +static int +tool_steer(const char *args, struct sp_buf *out) +{ + char text[4096]; + + arg_string(args, "text", text, sizeof(text)); + if (text[0] == '\0') { + sp_buf_puts(out, "error: 'text' is required"); + return 0; + } + if (sp_engine_steer(*session_eng, text) != 0) { + sp_buf_puts(out, "error: no turn is running"); + return 0; + } + sp_buf_puts(out, "queued: the loop picks it up at the next step\n"); + return 0; +} + +static int +tool_cancel(struct sp_buf *out) +{ + if (!sp_engine_busy(*session_eng)) { + sp_buf_puts(out, "no turn is running"); + return 0; + } + (void)sp_engine_cancel(*session_eng); + sp_buf_puts(out, "cancel requested\n"); + return 0; +} + +static int +tool_approve(const char *args, struct sp_buf *out) +{ + int allow = arg_bool(args, "allow", 0); + + if (sp_engine_approve(*session_eng, allow) != 0) { + sp_buf_puts(out, "error: no approval is pending"); + return 0; + } + sp_buf_printf(out, "%s\n", allow ? "approved" : "denied"); + return 0; +} + +int +sp_mcpsession_call(const char *name, const char *args, struct sp_buf *out) +{ + if (session_eng == NULL || *session_eng == NULL) { + sp_buf_puts(out, "error: this MCP server has no splinter engine"); + return 1; + } + if (strcmp(name, "splinter_sessions") == 0) + return tool_sessions(out), 1; + if (strcmp(name, "splinter_state") == 0) + return tool_state(out), 1; + if (strcmp(name, "splinter_models") == 0) + return tool_models(out), 1; + if (strcmp(name, "splinter_agents") == 0) + return tool_agents(out), 1; + if (strcmp(name, "splinter_history") == 0) + return tool_history(args, out), 1; + if (strcmp(name, "splinter_say") == 0) + return tool_say(args, out), 1; + if (strcmp(name, "splinter_open") == 0) + return tool_open(args, out), 1; + if (strcmp(name, "splinter_model") == 0) + return tool_model(args, out), 1; + if (strcmp(name, "splinter_agent") == 0) + return tool_agent(args, out), 1; + if (strcmp(name, "splinter_steer") == 0) + return tool_steer(args, out), 1; + if (strcmp(name, "splinter_cancel") == 0) + return tool_cancel(out), 1; + if (strcmp(name, "splinter_approve") == 0) + return tool_approve(args, out), 1; + return 0; +} diff --git a/src/backend/mcpsession.h b/src/backend/mcpsession.h new file mode 100644 index 0000000..1d2b451 --- /dev/null +++ b/src/backend/mcpsession.h @@ -0,0 +1,31 @@ +/* + * splinter -- the MCP server's session tools. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + */ +#ifndef SPLINTER_MCPSESSION_H +#define SPLINTER_MCPSESSION_H + +#include + +struct sp_buf; +struct sp_engine; +struct sp_engine_opts; + +/* The engine a connection works on; NULL means "file tools only". */ +void sp_mcpsession_bind(struct sp_engine **eng, + const struct sp_engine_opts *opts); + +/* 1 when the name is one of ours, and its authorization class. */ +int sp_mcpsession_has(const char *name); +int sp_mcpsession_auth(const char *name); + +/* tools/list entries, comma-prefixed unless *first is still 1 */ +void sp_mcpsession_tools(struct sp_buf *b, int *first); + +/* 1 when handled (out filled), 0 when the name is not ours. */ +int sp_mcpsession_call(const char *name, const char *args, + struct sp_buf *out); + +#endif /* SPLINTER_MCPSESSION_H */ diff --git a/src/backend/plugin.c b/src/backend/plugin.c index 7510787..c4235e6 100644 --- a/src/backend/plugin.c +++ b/src/backend/plugin.c @@ -83,6 +83,7 @@ struct sp_host { size_t failed; unsigned turns; char model[256]; /* what the run is on */ + char served_by[128]; /* who answered the last request */ /* loaded plugins, in load order, so shutdown() runs in reverse */ const struct sp_plugin *loaded[MAX_PLUGINS]; size_t nloaded; @@ -513,6 +514,30 @@ sp_host_set_model(struct sp_host *h, const char *model) pthread_mutex_unlock(&h->lock); } +const char * +sp_host_served_by(struct sp_host *h) +{ + static __thread char copy[128]; + + if (h == NULL) + return ""; + pthread_mutex_lock(&h->lock); + snprintf(copy, sizeof(copy), "%s", h->served_by); + pthread_mutex_unlock(&h->lock); + return copy; +} + +void +sp_host_set_served_by(struct sp_host *h, const char *endpoint) +{ + if (h == NULL) + return; + pthread_mutex_lock(&h->lock); + snprintf(h->served_by, sizeof(h->served_by), "%s", + endpoint != NULL ? endpoint : ""); + pthread_mutex_unlock(&h->lock); +} + struct sp_registry * sp_host_registry(struct sp_host *h) { diff --git a/src/backend/transport_anthropic.c b/src/backend/transport_anthropic.c index 4ac56c5..128ccf6 100644 --- a/src/backend/transport_anthropic.c +++ b/src/backend/transport_anthropic.c @@ -134,6 +134,36 @@ parse_status_file(const char *path, long *status, long *retry_after) return have ? 0 : -1; } +/* the router's answer: which upstream served this request */ +static void +parse_served_by(const char *path, char *out, size_t cap) +{ + FILE *f; + char line[1024]; + size_t nl = strlen("X-Junction-Endpoint"); + + out[0] = '\0'; + if (path == NULL || *path == '\0') + return; + f = fopen(path, "r"); + if (f == NULL) + return; + while (fgets(line, sizeof(line), f) != NULL) { + char *p = line; + + if (strncasecmp(p, "X-Junction-Endpoint", nl) != 0 || + p[nl] != ':') + continue; + p += nl + 1; + while (*p == ' ' || *p == '\t') + p++; + p[strcspn(p, "\r\n")] = '\0'; + snprintf(out, cap, "%.*s", cap > 0 ? (int)cap - 1 : 0, p); + break; + } + fclose(f); +} + /* the provider's own sentence, so a limit shows a reason and not just a code */ static void provider_error(const char *body, struct sp_buf *err) @@ -170,21 +200,14 @@ as_curl(const struct as_ctx *c, const char *body_path, int stream, args[n++] = "-sS"; args[n++] = "-A"; args[n++] = "splinter/" SP_VERSION; - if (stream) { - /* - * A stream that goes completely silent is a hang, not a slow - * answer: a provider can stream for minutes, but no byte at all - * for SPLINTER_STREAM_STALL_S (default 180) means nobody will - * answer. curl ends the transfer with 28, the agent retries. - */ - const char *stall = getenv("SPLINTER_STREAM_STALL_S"); - + /* + * A stream may be silent for minutes while a router waits for a slow + * upstream; a rate guard here cut exactly those streams + * ("Less than 1 bytes/sec") although keepalives were still arriving. + * The overall -m timeout stays the only limit. + */ + if (stream) args[n++] = "-N"; - args[n++] = "--speed-limit"; - args[n++] = "1"; - args[n++] = "--speed-time"; - args[n++] = stall != NULL && atoi(stall) > 0 ? stall : "180"; - } args[n++] = "-m"; args[n++] = tmo; args[n++] = "-X"; @@ -344,6 +367,7 @@ as_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, fclose(p); (void)waitpid(child, NULL, 0); (void)parse_status_file(hdr_path, &status, &retry_after); + parse_served_by(hdr_path, out->served_by, sizeof(out->served_by)); out->retry_after_s = retry_after; sp_log_wire(sp_log_dir(), "response", raw.p != NULL ? raw.p : "", raw.len); @@ -512,6 +536,7 @@ as_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, (void)waitpid(child, &st, 0); } (void)parse_status_file(hdr_path, &status, &retry_after); + parse_served_by(hdr_path, out->served_by, sizeof(out->served_by)); out->retry_after_s = retry_after; finish_request(path, hdr_path); if (status != 0 && (status < 200 || status > 299)) { diff --git a/src/backend/transport_openai.c b/src/backend/transport_openai.c index 9ce0a55..55bb06f 100644 --- a/src/backend/transport_openai.c +++ b/src/backend/transport_openai.c @@ -156,21 +156,14 @@ openai_curl(const struct openai_ctx *c, const char *body_path, int stream, args[n++] = "-sS"; args[n++] = "-A"; args[n++] = ua; - if (stream) { - /* - * A stream that goes completely silent is a hang, not a slow - * answer: a provider can stream for minutes, but no byte at all - * for SPLINTER_STREAM_STALL_S (default 180) means nobody will - * answer. curl ends the transfer with 28, the agent retries. - */ - const char *stall = getenv("SPLINTER_STREAM_STALL_S"); - + /* + * A stream may be silent for minutes while a router waits for a slow + * upstream; a rate guard here cut exactly those streams + * ("Less than 1 bytes/sec") although keepalives were still arriving. + * The overall -m timeout stays the only limit. + */ + if (stream) args[n++] = "-N"; - args[n++] = "--speed-limit"; - args[n++] = "1"; - args[n++] = "--speed-time"; - args[n++] = stall != NULL && atoi(stall) > 0 ? stall : "180"; - } args[n++] = "-m"; args[n++] = tmo; args[n++] = "-X"; @@ -250,6 +243,35 @@ temp_template(char *dst, size_t cap, const char *name) } +/* the value of one response header ("X-Junction-Endpoint: opencode-go1") */ +static void +parse_header_value(const char *path, const char *name, char *out, size_t cap) +{ + FILE *f; + char line[1024]; + size_t nl = strlen(name); + + out[0] = '\0'; + if (path == NULL || *path == '\0') + return; + f = fopen(path, "r"); + if (f == NULL) + return; + while (fgets(line, sizeof(line), f)) { + char *p = line; + + if (strncasecmp(p, name, nl) != 0 || p[nl] != ':') + continue; + p += nl + 1; + while (*p == ' ' || *p == '\t') + p++; + p[strcspn(p, "\r\n")] = '\0'; + snprintf(out, cap, "%.*s", cap > 0 ? (int)cap - 1 : 0, p); + break; + } + fclose(f); +} + static long parse_retry_after_file(const char *path) { @@ -368,6 +390,8 @@ openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, *nl = '\0'; if (hdr_path[0]) { 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)); unlink(hdr_path); hdr_path[0] = '\0'; } @@ -403,7 +427,7 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, struct openai_ctx *c = ctx; struct sp_buf body, cmd, tail, delta; struct sp_sse *sse; - char path[512]; + char path[512], hdr_path[512]; FILE *p; pid_t child = -1; int fd, rc = -1; @@ -429,6 +453,17 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, } temp_template(path, sizeof(path), "sse"); + hdr_path[0] = '\0'; + { + int hfd; + + temp_template(hdr_path, sizeof(hdr_path), "shdr"); + hfd = mkstemp(hdr_path); + if (hfd < 0) + hdr_path[0] = '\0'; + else + close(hfd); + } fd = mkstemp(path); if (fd < 0) { sp_buf_printf(err, sp_td("openai.mkstemp", "openai: mkstemp: %s"), @@ -446,7 +481,8 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, goto out; } - p = openai_curl(c, path, 1, &child, err, NULL); + p = openai_curl(c, path, 1, &child, err, + hdr_path[0] != '\0' ? hdr_path : NULL); if (p == NULL) { unlink(path); goto out; @@ -612,6 +648,11 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out, } rc = 0; out: + if (hdr_path[0] != '\0') { + parse_header_value(hdr_path, "X-Junction-Endpoint", + out->served_by, sizeof(out->served_by)); + unlink(hdr_path); + } sp_sse_free(sse); sp_buf_free(&body); sp_buf_free(&cmd); diff --git a/src/frontend/curses.c b/src/frontend/curses.c index d87aff5..24ce3b7 100644 --- a/src/frontend/curses.c +++ b/src/frontend/curses.c @@ -2500,7 +2500,16 @@ static void drain_events(struct ui_state *s, struct turn_view *v) { struct sp_event ev; + struct sp_host *host = s->be->host(s->be->ctx); + char msg[1024]; + /* + * Plugin notes ("recap applied", "goal in the prompt") are host status + * messages, not engine events. Draining them here makes them visible + * while the turn runs, not only when the prompt comes back. + */ + while (host != NULL && sp_host_status_take(host, msg, sizeof(msg))) + add_entry(s, "splinter", msg); while (s->be->poll(s->be->ctx, &ev)) { switch (ev.kind) { case SP_EV_STREAM: diff --git a/src/frontend/protocol.c b/src/frontend/protocol.c index 7cc3296..24a6949 100644 --- a/src/frontend/protocol.c +++ b/src/frontend/protocol.c @@ -30,6 +30,7 @@ #include "splinter.h" #include "splinter_engine.h" +#include "splinter_plugin.h" #include "mcp.h" #include "i18n.h" #include "protocol.h" @@ -323,6 +324,21 @@ drain_to_client(struct client *c, struct sp_engine *eng) { struct sp_event ev; + { + struct sp_host *host = sp_engine_host(eng); + char msg[1024]; + struct sp_event note; + + while (host != NULL && + sp_host_status_take(host, msg, sizeof(msg))) { + memset(¬e, 0, sizeof(note)); + note.kind = SP_EV_ENTRY; + note.a = (char *)"splinter"; + note.b = msg; + if (send_event(c, eng, ¬e) != 0) + return -1; + } + } while (sp_engine_poll(eng, &ev)) { int rc = send_event(c, eng, &ev); diff --git a/src/main.c b/src/main.c index b04bd28..68c80f9 100644 --- a/src/main.c +++ b/src/main.c @@ -9,6 +9,7 @@ */ #include #include +#include #include #include #include @@ -1090,7 +1091,33 @@ daemon_lock(const char *dir, struct sp_buf *err) return fd; } -/* --daemon: answer on Telegram until SIGINT */ +/* + * The MCP server beside the Telegram daemon: its own thread, no signal + * handlers (the daemon's stay), no session switching (the daemon holds the + * engine and its agent). + */ +struct mcp_bg { + struct sp_engine **eng; + const char *ip; + int port; + int allow_mutate; +}; + +static void * +mcp_bg_thread(void *arg) +{ + struct mcp_bg *bg = arg; + struct sp_buf err; + + if (sp_buf_init(&err) == 0) { + (void)sp_mcp_serve(bg->eng, NULL, NULL, bg->ip, bg->port, + bg->allow_mutate, 0, &err); + sp_buf_free(&err); + } + free(bg); + return NULL; +} + /* --daemon: answer on Telegram until SIGINT */ static int run_daemon(struct sp_engine *eng, struct sp_buf *err) @@ -1391,7 +1418,12 @@ main(int argc, char **argv) eo.session_id = o.sessid; eo.resume = o.resume; eo.continue_last = o.continue_here; - eo.no_transport = o.mcp_ip != NULL || o.delegate != NULL; + /* + * The MCP server is tools-only unless a model is given (or the daemon + * owns the engine): the session tools need a transport to run a turn. + */ + eo.no_transport = (o.mcp_ip != NULL && !o.daemon && + o.endpoint == NULL && o.model == NULL) || o.delegate != NULL; /* the fleet belongs to the curses chat, not to a served engine */ eo.swarm = o.chat && !o.serve && !o.daemon && o.a2a_ip == NULL && o.mcp_ip == NULL && o.delegate == NULL; @@ -1443,12 +1475,43 @@ main(int argc, char **argv) err.len > 0 ? err.p : "A2A server failed"); rc = rc == 0 ? 0 : 1; } else if (o.mcp_ip != NULL) { - rc = sp_mcp_serve(sp_engine_registry(eng), o.mcp_ip, - o.mcp_port, cfg.autonomous == 1, &err); - if (rc != 0) - fprintf(stderr, "splinter: %s\n", - err.len > 0 ? err.p : "MCP server failed"); - rc = rc == 0 ? 0 : 1; + if (o.daemon) { + /* + * The daemon answers on Telegram; the MCP server runs + * beside it on its own thread. Session switching is not + * available here (the daemon holds the engine), but the + * session tools - list, history, say, model, steer, + * cancel, approve - are. + */ + struct mcp_bg *bg = calloc(1, sizeof(*bg)); + pthread_t th; + + if (bg == NULL) { + fprintf(stderr, "splinter: out of memory\n"); + rc = 3; + goto done; + } + bg->eng = ŋ + bg->ip = o.mcp_ip; + bg->port = o.mcp_port; + bg->allow_mutate = cfg.autonomous == 1; + if (pthread_create(&th, NULL, mcp_bg_thread, bg) != 0) { + fprintf(stderr, "splinter: cannot start the MCP " + "server thread\n"); + free(bg); + rc = 3; + goto done; + } + rc = run_daemon(eng, &err); + /* the process exit ends the MCP thread with it */ + } else { + rc = sp_mcp_serve(&eng, &eo, sp_engine_registry(eng), + o.mcp_ip, o.mcp_port, cfg.autonomous == 1, 1, &err); + if (rc != 0) + fprintf(stderr, "splinter: %s\n", + err.len > 0 ? err.p : "MCP server failed"); + rc = rc == 0 ? 0 : 1; + } } else if (o.openai_ip != NULL) { struct sp_gateway_opts go; diff --git a/tests/test_focus.c b/tests/test_focus.c index 6b869b9..3faa604 100644 --- a/tests/test_focus.c +++ b/tests/test_focus.c @@ -90,12 +90,29 @@ main(void) CHECK(strstr(conv.v[conv.n - 1].content, "erster turn") != NULL); CHECK(strstr(conv.v[conv.n - 2].content, "Ship the config file") != NULL); CHECK(strstr(conv.v[conv.n - 2].content, "GOAL_COMPLETE") != NULL); + { + char msg[256]; - /* turn 2: the reminder appears, once */ + msg[0] = '\0'; + CHECK(sp_host_status_take(host, msg, sizeof(msg)) == 1); + CHECK(strstr(msg, "goal in the prompt") != NULL); + } + + /* turn 2: the reminder appears, once, and says so */ CHECK(sp_conv_push(&conv, "user", NULL, "zweiter turn") == 0); sp_host_turn(host); CHECK(sp_host_compact(host, &conv, 1) == 1); CHECK(count_focus(&conv) == 2); + { + char msg[256], snap[1024]; + + msg[0] = '\0'; + CHECK(sp_host_status_take(host, msg, sizeof(msg)) == 1); + CHECK(strstr(msg, "recap applied") != NULL); + snap[0] = '\0'; + sp_host_widget_snapshot(host, snap, sizeof(snap)); + CHECK(strstr(snap, "recap 1, every 2 turns") != NULL); + } CHECK(strstr(conv.v[conv.n - 1].content, "zweiter turn") != NULL); { size_t i; diff --git a/tests/test_junction.c b/tests/test_junction.c index 1ca4aa2..26a43c0 100644 --- a/tests/test_junction.c +++ b/tests/test_junction.c @@ -104,7 +104,7 @@ main(int argc, char **argv) * "b!"), and the counters are not repeated here - they are /junction's * business. */ - CHECK(strstr(snap, "m\nroute a\nb!\n1/2 up") != NULL); + CHECK(strstr(snap, "m\nserving (no request yet)\nroute a\nb!\n1/2 up") != NULL); CHECK(strstr(snap, "mcp 4/5") == NULL); CHECK(strstr(snap, "models 3") == NULL); CHECK(strstr(snap, "endpoint=") == NULL); @@ -136,6 +136,7 @@ main(int argc, char **argv) CHECK(strstr(out.p, "statistics: endpoint=") == NULL); CHECK(strstr(out.p, "probe-ms=12") != NULL); CHECK(strstr(out.p, "model: m") != NULL); + CHECK(strstr(out.p, "serving: (no request yet)") != NULL); CHECK(strstr(out.p, "route: a b") != NULL); CHECK(strstr(out.p, "route health: 1/2 up, down: b") != NULL); CHECK(strstr(out.p, "not the session's") != NULL); diff --git a/tests/test_mcpsession.sh b/tests/test_mcpsession.sh new file mode 100755 index 0000000..01a47de --- /dev/null +++ b/tests/test_mcpsession.sh @@ -0,0 +1,87 @@ +#!/bin/sh +# The MCP server's session tools, over a real socket. +# +# A script transport stands in for the model ("answer hello"), so no network is +# touched: tools/list must offer the session tools, and say/history/sessions/ +# models must round-trip through the engine. +set -e +cd "$(dirname "$0")/.." + +D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-mcps-XXXXXX") || exit 1 +port=$((21000 + ($$ % 20000))) +pid= +cleanup() { [ -n "$pid" ] && kill "$pid" 2>/dev/null; rm -rf "$D"; } +trap cleanup EXIT INT TERM + +mkdir -p "$D/home" +echo "answer hello" > "$D/replies" +HOME=$D/home ./splinter --no-config --autonomous --model m \ + --script "$D/replies" --mcp-server-listen 127.0.0.1 \ + --mcp-listen-port "$port" > "$D/srv.out" 2>&1 & +pid=$! + +i=0 +while [ $i -lt 50 ]; do + if python3 - "$port" <<'PY' +import socket, sys +s = socket.socket(); s.settimeout(0.2) +try: + s.connect(("127.0.0.1", int(sys.argv[1]))) +except OSError: + sys.exit(1) +finally: + s.close() +PY + then + break + fi + i=$((i + 1)); sleep 0.1 +done + +python3 - "$port" <<'PY' +import json, socket, sys + +s = socket.create_connection(("127.0.0.1", int(sys.argv[1])), 5) +f = s.makefile("rw", encoding="utf-8") + +def req(i, method, params=None): + o = {"jsonrpc": "2.0", "id": i, "method": method} + if params is not None: + o["params"] = params + f.write(json.dumps(o) + "\n"); f.flush() + return json.loads(f.readline()) + +def call(i, name, args): + r = req(i, "tools/call", {"name": name, "arguments": args}) + if "error" in r: + print("error:", r["error"], file=sys.stderr); sys.exit(1) + return r["result"]["content"][0]["text"] + +init = req(1, "initialize", {}) +assert init["result"]["serverInfo"]["name"] == "splinter", init +tools = [t["name"] for t in req(2, "tools/list")["result"]["tools"]] +for want in ("splinter_sessions", "splinter_state", "splinter_models", + "splinter_history", "splinter_say", "splinter_steer", + "splinter_cancel", "splinter_approve"): + assert want in tools, (want, tools) + +state = call(3, "splinter_state", {}) +assert "model: m" in state, state +assert "session: sess-" in state, state + +say = call(4, "splinter_say", {"text": "hi"}) +assert "hello" in say, say + +hist = call(5, "splinter_history", {"limit": 10}) +assert "[user] hi" in hist and "[assistant] hello" in hist, hist + +sessions = call(6, "splinter_sessions", {}) +assert "sess-" in sessions and "*" in sessions, sessions + +models = call(7, "splinter_models", {}) +assert "main" in models, models + +cancel = call(8, "splinter_cancel", {}) +assert "no turn is running" in cancel, cancel +print("test_mcpsession: ok") +PY diff --git a/tests/test_secrets.c b/tests/test_secrets.c index c017921..ae3175b 100644 --- a/tests/test_secrets.c +++ b/tests/test_secrets.c @@ -219,7 +219,7 @@ test_mcp(void) CHECK(sp_buf_init(&err) == 0); unsetenv("SPLINTER_MCP_TOKEN"); - CHECK(sp_mcp_serve(&r, "0.0.0.0", port, 0, &err) != 0); + CHECK(sp_mcp_serve(NULL, NULL, &r, "0.0.0.0", port, 0, 1, &err) != 0); CHECK(strstr(err.p, "SPLINTER_MCP_TOKEN") != NULL); setenv("SPLINTER_MCP_TOKEN", "richtig", 1); @@ -228,7 +228,7 @@ test_mcp(void) struct sp_buf e; (void)sp_buf_init(&e); - _exit(sp_mcp_serve(&r, "127.0.0.1", port, 0, &e) == 0 ? 0 : 1); + _exit(sp_mcp_serve(NULL, NULL, &r, "127.0.0.1", port, 0, 1, &e) == 0 ? 0 : 1); } CHECK(srv > 0); diff --git a/tests/test_self.c b/tests/test_self.c new file mode 100644 index 0000000..9ba80db --- /dev/null +++ b/tests/test_self.c @@ -0,0 +1,77 @@ +/* + * splinter -- the self plugin: the session's own resource use. + * + * The numbers come from /proc, so the test proves the shape and that both the + * widget and /self answer; the exact values belong to the machine. + */ +#include +#include +#include + +#include "splinter.h" +#include "splinter_plugin.h" + +static int failures; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ +} while (0) + +static void +nap_ms(long ms) +{ + struct timespec ts; + + ts.tv_sec = ms / 1000; + ts.tv_nsec = (ms % 1000) * 1000000L; + nanosleep(&ts, NULL); +} + +int +main(void) +{ + struct sp_registry reg; + struct sp_agent ag; + struct sp_host *host; + struct sp_buf err, out; + char snap[2048]; + + memset(®, 0, sizeof(reg)); + memset(&ag, 0, sizeof(ag)); + if (sp_buf_init(&err) != 0 || sp_buf_init(&out) != 0) + return 1; + host = sp_host_new(®, &ag, NULL); + CHECK(host != NULL); + CHECK(sp_plugin_load(host, "plugins/self/self.so", &err) == 0); + CHECK(sp_registry_find(®, "session_usage") != NULL); + + /* the widget samples on its first tick and every two seconds */ + nap_ms(2400); + 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); + + /* /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, "threads:") != NULL); + CHECK(strstr(out.p, "children:") != NULL); + CHECK(strstr(out.p, "cpu:") != NULL); + + sp_host_free(host); + sp_buf_free(&err); + sp_buf_free(&out); + sp_registry_free(®); + + if (failures == 0) + printf("test_self: ok\n"); + return failures == 0 ? 0 : 1; +}