From 489c5da26a8c0f6f128e797500c02d70e9ffd95e Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 8 Nov 2026 20:50:33 +0000 Subject: [PATCH] fixes from the review, second round: mcp client, kids rules, plugin life, ui Each change has a test that fails against the code before it. Also note: 8900d7f ("telegram: refuse to start without a token") swept in work of this round that its message does not describe - an OLLAMA_KEY no longer overwrites the key of the operator's last exit (config.c), parallel delegates are killed and reaped after a timeout (delegate.c), lcm/cps never leave a tool result without its call, cps keeps working past 256 messages, Telegram ids are parsed as 64 bit, and 'run' also hides SPLINTER_OLLAMA_KEY_* and SPLINTER_MCP_TOKEN. MCP client (plugins/mcp) - fgets into char[16384] split every longer reply into unparseable pieces; a big tools/list or file read never arrived. A reply sharing one write with a notification sat in stdio's buffer, invisible to poll(). Lines are now buffered on the fd (up to 16 MiB). An error is the top-level "error" member, not the text "error" anywhere in the line. test_mcpclient. kids - Rules were matched against the raw JSON, so "run ls*" never matched. They now see the command, path or url. A 'run' command that can chain, substitute or redirect is never whitelisted. The glob is linear instead of exponential. test_kids, which also covers the approval-command quoting and the domain checks from the first round. Plugin life (src/plugin.c, ABI 2) - An init() that failed kept what it had registered (tools, gate, widget threads); it is now rolled back. shutdown() was never called; the host calls it, newest plugin first, after the widget threads have stopped. - A widget slot is filled before it is counted, and the count is read under the lock, so tick threads never see a half-made slot. - SP_PLUGIN_ABI is 2: struct sp_gate grew block_turn while the ABI stayed 1. test_lifecycle, with tests/plugin_lifecycle.so. UI - Ctrl-C and Ctrl-D cancel under the lock and wake a turn waiting for approval (it waited forever); Ctrl-D cancelled nothing before the join. - A steer the turn already took is not sent again as the next message. - KEY_RESIZE re-cuts the windows; Ctrl-L repaints instead of sending the half-typed line; key codes above 255 are not typed into the input. - Markdown attributes went to stdscr while the text went to ui_hist: bold and code never showed. They now build on the line's role colour. Checked in tmux: UTF-8 input, resize to 70x20, Ctrl-L, Ctrl-D, bold. Telegram - Replies are split on UTF-8 boundaries; a cut umlaut made Telegram refuse the chunk and the rest of the answer was lost. Build - Seven plugins linked with an undefined $(PLUGIN_LDFLAGS): no rpath, no LIBS. All eleven now carry $ORIGIN/../..; objects depend on the interface headers. Seen, not changed: sp_session_append fsyncs every line; under disk load an answer appears up to 15 s late. Not a deadlock, and the same before this round. make check: 26 test binaries, green, also under ASan/UBSan. Co-Authored-By: Claude Opus 5.5 --- Makefile | 37 +++++++--- README.md | 4 +- include/splinter_plugin.h | 8 +- plugins/kids/kids.c | 71 +++++++++++++++--- plugins/mcp/mcp.c | 149 +++++++++++++++++++++++++------------- src/plugin.c | 127 +++++++++++++++++++++++++++----- src/telegram.c | 13 +++- src/ui.c | 114 ++++++++++++++++++++++++----- tests/plugin_lifecycle.c | 63 ++++++++++++++++ tests/test_kids.c | 124 +++++++++++++++++++++++++++++++ tests/test_lifecycle.c | 75 +++++++++++++++++++ tests/test_mcpclient.c | 107 +++++++++++++++++++++++++++ 12 files changed, 782 insertions(+), 110 deletions(-) create mode 100644 tests/plugin_lifecycle.c create mode 100644 tests/test_kids.c create mode 100644 tests/test_lifecycle.c create mode 100644 tests/test_mcpclient.c diff --git a/Makefile b/Makefile index 31caec3..0d524e5 100644 --- a/Makefile +++ b/Makefile @@ -32,7 +32,7 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \ plugins/kids/kids.so plugins/status/status.so plugins/tasks/tasks.so TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \ tests/test_transport tests/test_agent tests/test_openai \ - tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_cli tests/test_compactor tests/test_secrets + tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_cli tests/test_compactor tests/test_secrets tests/test_mcpclient tests/test_kids tests/test_lifecycle RPATH = -Wl,-rpath,'$$ORIGIN' PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..' @@ -71,22 +71,22 @@ plugins/cli/cli.so: plugins/cli/cli.c $(LIB) plugins/ring/ring.so: plugins/ring/ring.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/ring/ring.c -L. -lsplinter \ - -Iinclude -Isrc -Ivendor/libmcp $(PLUGIN_LDFLAGS) + $(PLUGIN_RPATH) $(LIBS) plugins/kids/kids.so: plugins/kids/kids.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/kids/kids.c -L. -lsplinter \ - -Iinclude -Isrc -Ivendor/libmcp $(PLUGIN_LDFLAGS) + $(PLUGIN_RPATH) $(LIBS) plugins/tasks/tasks.so: plugins/tasks/tasks.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/tasks/tasks.c -L. -lsplinter \ - -Iinclude -Isrc -Ivendor/libmcp $(PLUGIN_LDFLAGS) + $(PLUGIN_RPATH) $(LIBS) plugins/status/status.so: plugins/status/status.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/status/status.c -L. -lsplinter \ - -Iinclude -Isrc -Ivendor/libmcp $(PLUGIN_LDFLAGS) + $(PLUGIN_RPATH) $(LIBS) plugins/reminder/reminder.so: plugins/reminder/reminder.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/reminder/reminder.c -L. -lsplinter \ - -Iinclude -Isrc -Ivendor/libmcp $(PLUGIN_LDFLAGS) + $(PLUGIN_RPATH) $(LIBS) plugins/mcp/mcp.so: plugins/mcp/mcp.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/mcp/mcp.c -L. -lsplinter \ - -Iinclude -Isrc -Ivendor/libmcp $(PLUGIN_LDFLAGS) + $(PLUGIN_RPATH) $(LIBS) plugins/focus/focus.so: plugins/focus/focus.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/focus/focus.c -L. -lsplinter \ $(PLUGIN_RPATH) $(LIBS) @@ -98,6 +98,14 @@ plugins/cps/cps.so: plugins/cps/cps.c $(LIB) .c.o: $(CC) $(CFLAGS) -c -o $@ $< +# POSIX make has no automatic dependencies. Rather than a list that is wrong +# the day somebody adds an #include, every object depends on the headers that +# make up the interface: a change there rebuilds everything that could see it. +HDRS = include/splinter.h include/splinter_plugin.h src/config.h src/ack.h \ + src/curl.h src/log.h src/i18n.h +$(LIBOBJ) $(BINOBJ): $(HDRS) +$(PLUGIN): $(HDRS) + src/agent.o: include/splinter.h src/buf.o: include/splinter.h src/tool.o: include/splinter.h @@ -159,8 +167,7 @@ tests/test_delegate: tests/test_delegate.c $(LIB) tests/test_builtin: tests/test_builtin.c $(LIB) $(CC) $(CFLAGS) -o $@ tests/test_builtin.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_ack: tests/test_ack.c $(LIB) - $(CC) $(CFLAGS) -o $@ tests/test_ack.c -L. -lsplinter \ - -Iinclude -Isrc $(PLUGIN_LDFLAGS) + $(CC) $(CFLAGS) -o $@ tests/test_ack.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_i18n: tests/test_i18n.c $(LIB) $(CC) $(CFLAGS) -o $@ tests/test_i18n.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_ascii: tests/test_ascii.c $(LIB) $(BINOBJ) @@ -177,6 +184,15 @@ tests/test_compactor: tests/test_compactor.c $(LIB) $(PLUGIN) $(CC) $(CFLAGS) -o $@ tests/test_compactor.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_secrets: tests/test_secrets.c $(LIB) $(PLUGIN) $(CC) $(CFLAGS) -o $@ tests/test_secrets.c -L. -lsplinter $(TEST_RPATH) $(LIBS) +tests/test_mcpclient: tests/test_mcpclient.c $(LIB) $(PLUGIN) + $(CC) $(CFLAGS) -o $@ tests/test_mcpclient.c -L. -lsplinter $(TEST_RPATH) $(LIBS) +tests/test_kids: tests/test_kids.c $(LIB) $(PLUGIN) + $(CC) $(CFLAGS) -o $@ tests/test_kids.c -L. -lsplinter $(TEST_RPATH) $(LIBS) +tests/plugin_lifecycle.so: tests/plugin_lifecycle.c $(LIB) $(HDRS) + $(CC) $(CFLAGS) -shared -o $@ tests/plugin_lifecycle.c -L. -lsplinter \ + $(TEST_RPATH) $(LIBS) +tests/test_lifecycle: tests/test_lifecycle.c $(LIB) tests/plugin_lifecycle.so + $(CC) $(CFLAGS) -o $@ tests/test_lifecycle.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_plugin: tests/test_plugin.c $(LIB) $(PLUGIN) $(CC) $(CFLAGS) -o $@ tests/test_plugin.c -L. -lsplinter $(TEST_RPATH) $(LIBS) @@ -198,7 +214,8 @@ install: all @echo "installed $(DESTDIR)$(PREFIX)/bin/splinter" clean: - rm -f $(BIN) $(LIB) $(LIBOBJ) $(BINOBJ) $(PLUGIN) $(TESTS) + rm -f $(BIN) $(LIB) $(LIBOBJ) $(BINOBJ) $(PLUGIN) $(TESTS) \ + tests/plugin_lifecycle.so .PHONY: all check curses install clean diff --git a/README.md b/README.md index bf81d2f..4e085df 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ the screen, a sidebar on one quarter, plugins that can put tools and widgets into both. make # libsplinter.so, the binary, the plugins - make check # thirteen test binaries + make check # every test binary (26), no network, no model splinter # starts the chat from ~/.config/splinter/config @@ -65,7 +65,7 @@ transport replays replies. src/builtin.c echo (read) and run (destructive) src/agent.c the loop src/main.c CLI - tests/ five test binaries, run by `make check` + tests/ the test binaries, run by `make check` docs/splinter.1 manual page src/www/index.html HTML 4.01 static page diff --git a/include/splinter_plugin.h b/include/splinter_plugin.h index 0278797..f01db79 100644 --- a/include/splinter_plugin.h +++ b/include/splinter_plugin.h @@ -31,7 +31,13 @@ #include "splinter.h" -#define SP_PLUGIN_ABI 1u +/* + * Raise this whenever a struct a plugin hands to the host changes shape. It + * stayed 1 while struct sp_gate gained block_turn: a gate built against the old + * header would have had the host read past its struct and call what it found. + * 2: sp_gate.block_turn, sp_task_ops, sp_status, commands and transports. + */ +#define SP_PLUGIN_ABI 2u struct sp_host; diff --git a/plugins/kids/kids.c b/plugins/kids/kids.c index 74ebfd4..0459726 100644 --- a/plugins/kids/kids.c +++ b/plugins/kids/kids.c @@ -137,17 +137,31 @@ quota_left(void) return used_seconds < (long)daily_minutes * 60; } +/* + * '*' matches any run of characters. Iterative, remembering only the last star: + * the recursive version backtracked exponentially on model-written arguments. + */ static int glob_match(const char *pattern, const char *text) { - if (*pattern == '\0') - return *text == '\0'; - if (*pattern == '*') - return glob_match(pattern + 1, text) || - (*text != '\0' && glob_match(pattern, text + 1)); - if (*text == '\0') - return 0; - return *pattern == *text && glob_match(pattern + 1, text + 1); + const char *star = NULL, *resume = NULL; + + while (*text != '\0') { + if (*pattern == '*') { + star = pattern++; + resume = text; + } else if (*pattern == *text) { + pattern++; + text++; + } else if (star != NULL) { + pattern = star + 1; + text = ++resume; + } else + return 0; + } + while (*pattern == '*') + pattern++; + return *pattern == '\0'; } static void @@ -194,16 +208,51 @@ load_rules(void) fclose(f); } +/* + * What a rule is matched against: the argument that says what the call does - + * the command of 'run', else a path or a URL - not the raw JSON. Against the + * JSON ('{"command":"ls"}') a rule like "run ls*" never matched at all, and + * only "*" rules ever had an effect. + */ +static void +rule_subject(const char *tool, const char *args, char *buf, size_t len) +{ + static const char *keys[] = { "command", "path", "url", NULL }; + mcp_json *v; + size_t k; + + snprintf(buf, len, "%s", args != NULL ? args : ""); + if (args == NULL || args[0] != '{' || (v = mcp_parse(args)) == NULL) + return; + for (k = strcmp(tool, "run") == 0 ? 0 : 1; keys[k] != NULL; k++) { + const char *val = mcp_arg_string(v, keys[k]); + + if (val != NULL) { + snprintf(buf, len, "%s", val); + break; + } + } + mcp_json_free(v); +} + static int whitelisted(const char *tool, const char *args) { - size_t i; + char subject[1024]; + size_t i; + rule_subject(tool, args, subject, sizeof(subject)); + /* + * "run ls*" is meant to allow ls, not "ls; anything". A shell command + * that can chain, substitute or redirect is never on the list: a parent + * decides it. + */ + if (strcmp(tool, "run") == 0 && strpbrk(subject, ";&|`$<>\n\r(") != NULL) + return 0; for (i = 0; i < nrules; i++) { if (strcmp(rules[i].tool, tool) != 0 && strcmp(rules[i].tool, "*")) continue; - if (glob_match(rules[i].pattern, - args != NULL ? args : "")) + if (glob_match(rules[i].pattern, subject)) return 1; } return 0; diff --git a/plugins/mcp/mcp.c b/plugins/mcp/mcp.c index 4aa20d3..b2d1103 100644 --- a/plugins/mcp/mcp.c +++ b/plugins/mcp/mcp.c @@ -38,7 +38,8 @@ struct server { pid_t pid; FILE *to; /* our writes become the server's stdin */ - FILE *from; + int from; /* its stdout, read without stdio */ + struct sp_buf in; /* bytes read but not yet a whole line */ int next_id; int dead; }; @@ -88,13 +89,62 @@ slice_object(const char *at, size_t *lenp) return NULL; } +#define RPC_MAX_LINE (16u * 1024 * 1024) + +/* + * The next line from the server, without its newline. 1 a line, 0 timeout, + * -1 the pipe is gone or the line is beyond RPC_MAX_LINE. + * + * fgets() into a char[16384] split every longer reply - a tools/list of a big + * server, a file read - into pieces that do not parse; the client then waited + * for an answer it had already received in parts. And poll() on the fd of a + * stdio stream does not see what stdio has already buffered: two messages in + * one write left the second one unseen until the timeout. So the bytes are + * buffered here, where poll() and the buffer agree. + */ +static int +read_line(struct sp_buf *line, int timeout_ms) +{ + for (;;) { + char *nl = srv.in.p != NULL ? + memchr(srv.in.p, '\n', srv.in.len) : NULL; + char chunk[65536]; + ssize_t got; + struct pollfd pfd; + + if (nl != NULL) { + size_t n = (size_t)(nl - srv.in.p); + + sp_buf_clear(line); + if (sp_buf_add(line, srv.in.p, n) != 0) + return -1; + memmove(srv.in.p, nl + 1, srv.in.len - n - 1); + srv.in.len -= n + 1; + srv.in.p[srv.in.len] = '\0'; + return 1; + } + if (srv.in.len > RPC_MAX_LINE) + return -1; + pfd.fd = srv.from; + pfd.events = POLLIN; + if (poll(&pfd, 1, timeout_ms) <= 0) + return 0; + got = read(srv.from, chunk, sizeof(chunk)); + if (got < 0 && errno == EINTR) + continue; + if (got <= 0) + return -1; + if (sp_buf_add(&srv.in, chunk, (size_t)got) != 0) + return -1; + } +} + /* One JSON-RPC round trip on the pipe. Result is the raw reply line. */ static char * rpc(const char *method, const char *params, struct sp_buf *err) { - struct pollfd pfd; - char line[16384]; - int id = ++srv.next_id; + struct sp_buf line; + int id = ++srv.next_id, rc; if (srv.dead) return NULL; @@ -105,59 +155,58 @@ rpc(const char *method, const char *params, struct sp_buf *err) fprintf(srv.to, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"method\":\"%s\"}\n", id, method); fflush(srv.to); + if (sp_buf_init(&line) != 0) + return NULL; for (;;) { - pfd.fd = fileno(srv.from); - pfd.events = POLLIN; - if (poll(&pfd, 1, RPC_TIMEOUT_MS) <= 0) { - sp_buf_printf(err, "mcp: no answer to %s", method); - return NULL; - } - if (fgets(line, sizeof(line), srv.from) == NULL) { - srv.dead = 1; - sp_buf_printf(err, "mcp: server closed the pipe during %s", - method); - return NULL; - } - { - /* - * Match the id by parsing it, not by looking for a substring: - * servers differ in whitespace ("id": 1 vs "id":1), and a raw - * strstr() then never matches - the client waits for a reply - * it already has. - */ - mcp_json *v = mcp_parse(line); - int rid = v != NULL ? - mcp_arg_int(v, "id", -1) : -1; + mcp_json *v; + const mcp_json *e; + int rid; + char *res; + rc = read_line(&line, RPC_TIMEOUT_MS); + if (rc == 0) { + sp_buf_printf(err, "mcp: no answer to %s", method); + sp_buf_free(&line); + return NULL; + } + if (rc < 0) { + srv.dead = 1; + sp_buf_printf(err, "mcp: server closed the pipe (or sent " + "a line over 16 MiB) during %s", method); + sp_buf_free(&line); + return NULL; + } + /* + * Match the id by parsing it, not by looking for a substring: + * servers differ in whitespace ("id": 1 vs "id":1), and a raw + * strstr() then never matches - the client waits for a reply it + * already has. + */ + v = mcp_parse(line.p); + rid = v != NULL ? mcp_arg_int(v, "id", -1) : -1; + if (rid != id) { if (v != NULL) mcp_json_free(v); - if (rid != id) - continue; /* notification or another reply */ + continue; /* notification or another reply */ } - if (strstr(line, "\"error\"") != NULL) { - struct sp_buf msg; + /* + * An error is the top-level "error" member, not the text "error" + * anywhere in the line - a file that contains it is a result. + */ + e = mcp_arg(v, "error"); + if (e != NULL) { + const char *m = mcp_arg_string(e, "message"); - if (sp_buf_init(&msg) == 0) { - mcp_json *v = mcp_parse(line); - - if (v != NULL) { - const mcp_json *e = mcp_arg(v, "error"); - - if (e != NULL && mcp_arg_string(e, - "message") != NULL) - sp_buf_printf(&msg, "%s", - mcp_arg_string(e, "message")); - mcp_json_free(v); - } - sp_buf_printf(err, "mcp: %s failed: %s", method, - msg.p != NULL ? msg.p : line); - sp_buf_free(&msg); - } else - sp_buf_printf(err, "mcp: %s failed", method); + sp_buf_printf(err, "mcp: %s failed: %s", method, + m != NULL ? m : line.p); + mcp_json_free(v); + sp_buf_free(&line); return NULL; } - return strdup(line); + mcp_json_free(v); + res = line.p; /* the caller frees it */ + return res; } } @@ -196,8 +245,8 @@ spawn(struct sp_buf *err) close(from[1]); srv.pid = child; srv.to = fdopen(to[1], "w"); - srv.from = fdopen(from[0], "r"); - if (srv.to == NULL || srv.from == NULL) { + srv.from = from[0]; + if (srv.to == NULL || sp_buf_init(&srv.in) != 0) { sp_buf_puts(err, "mcp: fdopen failed"); return -1; } diff --git a/src/plugin.c b/src/plugin.c index 04863a8..104f954 100644 --- a/src/plugin.c +++ b/src/plugin.c @@ -29,6 +29,7 @@ #define MAX_COMPACTORS 8 #define MAX_TRANSPORTS 8 #define MAX_COMMANDS 16 +#define MAX_PLUGINS 32 #define MAX_NOTE 2048 struct widget { @@ -77,6 +78,9 @@ struct sp_host { size_t compactions; size_t failed; unsigned turns; + /* loaded plugins, in load order, so shutdown() runs in reverse */ + const struct sp_plugin *loaded[MAX_PLUGINS]; + size_t nloaded; }; static void * @@ -140,7 +144,13 @@ sp_host_add_widget(struct sp_host *h, const struct sp_widget *w) if (strcmp(h->widgets[i].name, w->name) == 0) return -1; - slot = &h->widgets[h->nwidgets++]; + /* + * Fill the slot first, publish it last. nwidgets used to be counted up + * before the slot (and its mutex) existed, while tick threads of other + * widgets were already walking the table. + */ + slot = &h->widgets[h->nwidgets]; + memset(slot, 0, sizeof(*slot)); slot->host = h; snprintf(slot->name, sizeof(slot->name), "%s", w->name); slot->tick = w->tick; @@ -151,18 +161,24 @@ sp_host_add_widget(struct sp_host *h, const struct sp_widget *w) pthread_mutex_init(&slot->lock, NULL); snprintf(slot->text, sizeof(slot->text), "starting..."); + pthread_mutex_lock(&h->lock); + h->nwidgets++; + pthread_mutex_unlock(&h->lock); if (slot->tick != NULL) { /* * A worker gets the host pointer, but only the publish path is * thread-safe: sp_host_widget_text() and sp_host_note() take locks. * Everything else on the host belongs to the main thread. */ + slot->running = 1; if (pthread_create(&slot->thread, NULL, widget_thread, slot) != 0) { slot->running = 0; + pthread_mutex_lock(&h->lock); h->nwidgets--; + pthread_mutex_unlock(&h->lock); + pthread_mutex_destroy(&slot->lock); return -1; } - slot->running = 1; } return 0; } @@ -444,11 +460,15 @@ sp_host_turn(struct sp_host *h) int sp_host_widget_text(struct sp_host *h, const char *widget, const char *text) { - size_t i; + size_t i, n; if (h == NULL || widget == NULL || text == NULL) return -1; - for (i = 0; i < h->nwidgets; i++) { + /* called from tick threads: the count is read under the host lock */ + pthread_mutex_lock(&h->lock); + n = h->nwidgets; + pthread_mutex_unlock(&h->lock); + for (i = 0; i < n; i++) { struct widget *w = &h->widgets[i]; if (strcmp(w->name, widget) != 0) @@ -500,6 +520,61 @@ struct sp_plugin_handle { char path[512]; }; +/* how far each table was filled before a plugin's init() ran */ +struct host_mark { + size_t tools, widgets, compact, gate, status; + size_t transports, commands; + const struct sp_task_ops *taskops; +}; + +static void +mark(struct sp_host *h, struct host_mark *m) +{ + pthread_mutex_lock(&h->lock); + m->tools = h->reg != NULL ? h->reg->len : 0; + m->widgets = h->nwidgets; + m->compact = h->ncompact; + m->gate = h->ngate; + m->status = h->nstatus; + m->transports = h->ntransports; + m->commands = h->ncommands; + m->taskops = h->taskops; + pthread_mutex_unlock(&h->lock); +} + +static void +stop_widget(struct widget *w) +{ + if (w->running) { + pthread_mutex_lock(&w->lock); + w->stop = 1; + pthread_mutex_unlock(&w->lock); + pthread_join(w->thread, NULL); + w->running = 0; + } + pthread_mutex_destroy(&w->lock); +} + +static void +rollback(struct sp_host *h, const struct host_mark *m) +{ + size_t i; + + for (i = m->widgets; i < h->nwidgets; i++) + stop_widget(&h->widgets[i]); + pthread_mutex_lock(&h->lock); + h->nwidgets = m->widgets; + if (h->reg != NULL && h->reg->len > m->tools) + h->reg->len = m->tools; + h->ncompact = m->compact; + h->ngate = m->gate; + h->nstatus = m->status; + h->ntransports = m->transports; + h->ncommands = m->commands; + h->taskops = m->taskops; + pthread_mutex_unlock(&h->lock); +} + int sp_plugin_load(struct sp_host *h, const char *path, struct sp_buf *err) { @@ -543,10 +618,28 @@ sp_plugin_load(struct sp_host *h, const char *path, struct sp_buf *err) path, p->abi, SP_PLUGIN_ABI); return -1; } - if (p->init != NULL && p->init(h) != 0) { - sp_buf_printf(err, "plugin %s: init failed", path); + if (h->nloaded == MAX_PLUGINS) { + sp_buf_printf(err, "plugin %s: more than %d plugins", path, + MAX_PLUGINS); return -1; } + { + struct host_mark m; + + mark(h, &m); + if (p->init != NULL && p->init(h) != 0) { + /* + * "Never half-used": whatever init registered before + * it failed - tools, a gate, widget threads - goes + * again. A kids plugin whose gate stayed while its + * compactor did not was a policy nobody had chosen. + */ + rollback(h, &m); + sp_buf_printf(err, "plugin %s: init failed", path); + return -1; + } + } + h->loaded[h->nloaded++] = p; return 0; } } @@ -573,18 +666,16 @@ sp_host_free(struct sp_host *h) if (h == NULL) return; - for (i = 0; i < h->nwidgets; i++) { - struct widget *w = &h->widgets[i]; - - if (!w->running) - continue; - pthread_mutex_lock(&w->lock); - w->stop = 1; - pthread_mutex_unlock(&w->lock); - pthread_join(w->thread, NULL); - w->running = 0; - pthread_mutex_destroy(&w->lock); - } + /* the threads first: a tick must not run into a plugin that shut down */ + for (i = 0; i < h->nwidgets; i++) + stop_widget(&h->widgets[i]); + /* + * Then shutdown(), newest plugin first. It was declared in the ABI and + * never called: the MCP plugin's server process was never reaped. + */ + for (i = h->nloaded; i > 0; i--) + if (h->loaded[i - 1]->shutdown != NULL) + h->loaded[i - 1]->shutdown(h); pthread_mutex_destroy(&h->lock); free(h); } diff --git a/src/telegram.c b/src/telegram.c index b498ffe..036ebc0 100644 --- a/src/telegram.c +++ b/src/telegram.c @@ -186,8 +186,19 @@ send_message(const char *token, long chat_id, const char *text, do { size_t take = len - off; - if (take > TG_MAX_CHUNK) + if (take > TG_MAX_CHUNK) { take = TG_MAX_CHUNK; + /* + * Never inside a UTF-8 character: a cut umlaut is invalid + * UTF-8, Telegram refuses the chunk, and the rest of the + * answer was lost with it. Back up to a lead byte. + */ + while (take > 0 && + ((unsigned char)text[off + take] & 0xc0) == 0x80) + take--; + if (take == 0) + take = TG_MAX_CHUNK; /* not UTF-8 at all */ + } sp_buf_clear(&body); sp_buf_printf(&body, "{\"chat_id\":%ld,\"text\":\"", chat_id); { diff --git a/src/ui.c b/src/ui.c index f9bff6b..e14ff27 100644 --- a/src/ui.c +++ b/src/ui.c @@ -692,10 +692,20 @@ md_draw(int y, int cols, int maxrows, const char *text, const unsigned char *att { int row = 0, col = 0, x = 1; size_t i; + attr_t base; + short pair; + /* + * The role colour the caller set is the base; markdown adds to it. The + * attributes used to go to stdscr while the text went to ui_hist, so bold, + * italic and code never showed. + */ + (void)wattr_get(ui_hist, &base, &pair, NULL); + base &= ~A_COLOR; for (i = 0; text[i] != '\0' && row < maxrows; i++) { char out[8]; unsigned a = attr[i]; + attr_t at = base; if (text[i] == '\n') { row++; @@ -712,18 +722,16 @@ md_draw(int y, int cols, int maxrows, const char *text, const unsigned char *att } i += sp_ui_ascii_char(text + i, out, sizeof(out)) - 1; - attrset(COLOR_PAIR(PAIR_MAIN)); if (a & MD_BOLD) - attron(A_BOLD); + at |= A_BOLD; if (a & MD_ITALIC) - attron(A_UNDERLINE); - if (a & MD_CODE) - attron(COLOR_PAIR(PAIR_DIM)); + at |= A_UNDERLINE; + (void)wattr_set(ui_hist, at, (a & MD_CODE) ? PAIR_DIM : pair, NULL); mvwaddstr(ui_hist, y + row, x, out); - attrset(A_NORMAL); x += (int)strlen(out); col += (int)strlen(out); } + (void)wattr_set(ui_hist, base, pair, NULL); return row + 1; } @@ -855,6 +863,8 @@ draw_history(struct ui_state *s, int reserve) getyx(ui_hist, ny, nx); y = nx == 0 ? ny : ny + 1; free(render); + /* the role colour must not leak into the next entry */ + wattrset(ui_hist, A_NORMAL); continue; } wattrset(ui_hist, A_NORMAL); @@ -1177,6 +1187,28 @@ layout(void) scrollok(ui_status, FALSE); } +/* + * The terminal changed size: the windows were cut for the old one. layout() + * used to run once, so after a resize the four windows kept their old + * geometry and drew over each other. + */ +static void +relayout(int input_timeout_ms) +{ + if (ui_hist != NULL) + delwin(ui_hist); + if (ui_side != NULL) + delwin(ui_side); + if (ui_status != NULL) + delwin(ui_status); + if (ui_input != NULL) + delwin(ui_input); + ui_hist = ui_side = ui_status = ui_input = NULL; + layout(); + wtimeout(ui_input, input_timeout_ms); + clearok(curscr, TRUE); +} + int sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model, const char *theme_name, struct sp_host *host) @@ -1303,8 +1335,31 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model, s.quit = 1; break; } - if (ch == 12) - break; + /* + * Ctrl-L repaints, KEY_RESIZE re-cuts the windows. Ctrl-L + * used to break out of the loop - sending the half-typed + * line as if Enter had been pressed. + */ + if (ch == 12 || ch == KEY_RESIZE) { + if (ch == KEY_RESIZE) + relayout(500); + else + clearok(curscr, TRUE); + draw_history(&s, 0); + draw_sidebar(&s, ag->sess != NULL ? + ag->sess->id : NULL, + ag->sess != NULL ? ag->sess->dir : NULL, + host); + draw_status(&s); + input[len] = '\0'; + werase(ui_input); + mvwaddstr(ui_input, 0, 0, sp_t("ui.prompt_mark")); + ui_add_text(ui_input, input, + getmaxx(ui_input) - 3); + wnoutrefresh(ui_input); + doupdate(); + continue; + } if (ch == 3) { len = 0; werase(ui_input); @@ -1351,7 +1406,8 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model, } continue; } - if (ch >= 32 && ch != 127 && + /* key codes (arrows, F-keys) are not bytes of text */ + if (ch >= 32 && ch < 256 && ch != 127 && len < sizeof(input) - 2) { /* * Bytes, not wide chars: a UTF-8 sequence arrives @@ -1735,7 +1791,18 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model, doupdate(); continue; } - if (c == KEY_NPAGE || c == KEY_SF) { + if (c == KEY_RESIZE) { + relayout(100); + draw_history(&s, 0); + draw_sidebar(&s, ag->sess != NULL ? + ag->sess->id : NULL, + ag->sess != NULL ? ag->sess->dir : + NULL, host); + draw_status(&s); + doupdate(); + continue; + } + if (c == KEY_NPAGE || c == KEY_SF) { int step = (c == KEY_SF ? 1 : 10); s.scroll = s.scroll > (size_t)step ? @@ -1749,13 +1816,20 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model, doupdate(); continue; } - if (c == 3) { + /* + * Cancel under the lock and wake the turn: it may be + * asleep in approve_cb. Setting the flag alone left a + * turn that was waiting for a yes waiting forever, and + * Ctrl-D did not cancel at all before the join below. + */ + if (c == 3 || c == 4) { + pthread_mutex_lock(&tu.lock); tu.cancel = 1; + pthread_cond_broadcast(&tu.cond); + pthread_mutex_unlock(&tu.lock); cancelled = 1; - break; - } - if (c == 4) { - s.quit = 1; + if (c == 4) + s.quit = 1; break; } if (c == '\n' || c == '\r' || c == KEY_ENTER) { @@ -1784,7 +1858,7 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model, line[llen] = '\0'; continue; } - if (c >= 32 && c != 127 && + if (c >= 32 && c < 256 && c != 127 && llen < sizeof(line) - 2) { line[llen++] = (char)c; line[llen] = '\0'; @@ -1800,7 +1874,13 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model, */ sp_openai_set_cancel(NULL); ag->cfg = orig; - (void)cancelled; + /* + * A steer the turn took at a step boundary is already in + * the conversation. Only one it never reached becomes the + * next message - before, every steer was sent twice. + */ + if (!tu.have_steer || cancelled) + pending_steer[0] = '\0'; rc = tu.rc; sp_buf_clear(&answer); sp_buf_clear(&err); diff --git a/tests/plugin_lifecycle.c b/tests/plugin_lifecycle.c new file mode 100644 index 0000000..96bb11a --- /dev/null +++ b/tests/plugin_lifecycle.c @@ -0,0 +1,63 @@ +/* + * A plugin for tests/test_lifecycle: registers a tool and a ticking widget, + * then fails its init when SP_TEST_INIT_FAIL is set. Its shutdown() writes + * SP_TEST_SHUTDOWN_FILE, so the test can see that it ran. + */ +#include +#include + +#include "splinter.h" +#include "splinter_plugin.h" + +static int +lc_tool(const char *args, struct sp_buf *out, void *ctx) +{ + (void)args; + (void)ctx; + return sp_buf_puts(out, "lifecycle"); +} + +static int +lc_tick(struct sp_host *h, const char *name, void *ctx) +{ + (void)ctx; + return sp_host_widget_text(h, name, "tick"); +} + +static const struct sp_tool tool = { + "lifecycle_tool", "test", "{\"type\":\"object\"}", SP_AUTH_READ, lc_tool, + NULL +}; + +static const struct sp_widget widget = { "lifecycle", lc_tick, NULL, NULL, 50 }; + +static int +lc_init(struct sp_host *h) +{ + if (sp_host_add_tool(h, &tool) != 0 || sp_host_add_widget(h, &widget) != 0) + return -1; + return getenv("SP_TEST_INIT_FAIL") != NULL ? -1 : 0; +} + +static void +lc_shutdown(struct sp_host *h) +{ + const char *path = getenv("SP_TEST_SHUTDOWN_FILE"); + FILE *f; + + (void)h; + if (path != NULL && (f = fopen(path, "w")) != NULL) { + fputs("shut down\n", f); + fclose(f); + } +} + +static const struct sp_plugin plugin = { + SP_PLUGIN_ABI, "lifecycle", "1.0.0", lc_init, NULL, lc_shutdown +}; + +const struct sp_plugin * +sp_plugin_describe(void) +{ + return &plugin; +} diff --git a/tests/test_kids.c b/tests/test_kids.c new file mode 100644 index 0000000..d91b640 --- /dev/null +++ b/tests/test_kids.c @@ -0,0 +1,124 @@ +/* + * splinter -- kid mode's gate, against the ways it was found to open. + * + * - the whitelist was matched against the raw JSON, so "run ls*" never + * matched; and a working glob over a shell command would have allowed + * "ls; anything"; + * - the parent was asked through system("cmd 'Anfrage: '"), so a + * quote in the model's arguments ran a command before anybody answered; + * - the domain list took "allowed.org:x@evil.example" for allowed.org. + */ +#include +#include +#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 +put(const char *path, const char *text) +{ + FILE *f = fopen(path, "w"); + + CHECK(f != NULL); + if (f != NULL) { + fputs(text, f); + fclose(f); + } +} + +static int +gate(struct sp_host *h, const char *tool, int auth, const char *args) +{ + char reason[256] = ""; + + return sp_host_gate(h, tool, auth, args, reason, sizeof(reason)); +} + +int +main(void) +{ + char home[] = "/var/tmp/splinter-kids-XXXXXX"; + char path[700], mark[700], args[1200], cmd[800]; + struct sp_registry reg; + struct sp_agent ag; + struct sp_host *host; + struct sp_buf err; + struct stat st; + + CHECK(mkdtemp(home) != NULL); + snprintf(path, sizeof(path), "%s/.splinter", home); + (void)mkdir(path, 0700); + snprintf(path, sizeof(path), "%s/.splinter/kids", home); + (void)mkdir(path, 0700); + snprintf(path, sizeof(path), "%s/.splinter/kids/allow", home); + put(path, "run ls*\n"); + snprintf(path, sizeof(path), "%s/.splinter/kids/domains", home); + put(path, "allowed.org\n"); + snprintf(mark, sizeof(mark), "%s/pwned", home); + + (void)setenv("HOME", home, 1); + (void)unsetenv("SPLINTER_ACK_CHANNELS"); + (void)unsetenv("SPLINTER_ACK_DIR"); + (void)setenv("SPLINTER_KIDS_APPROVE_CMD", "exit 1", 1); /* parent says no */ + (void)setenv("SPLINTER_KIDS_TIMEOUT", "2", 1); + (void)setenv("SPLINTER_KIDS_SEARCH", "approve", 1); + + memset(®, 0, sizeof(reg)); + memset(&ag, 0, sizeof(ag)); + CHECK(sp_buf_init(&err) == 0); + host = sp_host_new(®, &ag, NULL); + CHECK(host != NULL); + if (host == NULL) + return 1; + CHECK(sp_plugin_load(host, "plugins/kids/kids.so", &err) == 0); + + /* ---- the whitelist sees the command, not the JSON ---- */ + CHECK(gate(host, "run", SP_AUTH_DESTRUCTIVE, + "{\"command\":\"ls -la\"}") == 1); + /* ---- and a command that chains is a parent's decision ---- */ + CHECK(gate(host, "run", SP_AUTH_DESTRUCTIVE, + "{\"command\":\"ls; rm -rf ~\"}") == 0); + CHECK(gate(host, "run", SP_AUTH_DESTRUCTIVE, + "{\"command\":\"ls $(rm -rf ~)\"}") == 0); + CHECK(gate(host, "run", SP_AUTH_DESTRUCTIVE, + "{\"command\":\"cat /etc/shadow\"}") == 0); + + /* ---- asking the parent does not run the model's text ---- */ + snprintf(args, sizeof(args), "{\"path\":\"x'; touch %s; echo '\"}", mark); + CHECK(gate(host, "write", SP_AUTH_MUTATE, args) == 0); + CHECK(stat(mark, &st) != 0); + + /* ---- the domain list names hosts, not user names ---- */ + CHECK(gate(host, "webfetch", SP_AUTH_MUTATE, + "{\"url\":\"https://allowed.org/page\"}") == 1); + CHECK(gate(host, "webfetch", SP_AUTH_MUTATE, + "{\"url\":\"https://allowed.org:x@evil.example/\"}") == 0); + CHECK(gate(host, "webfetch", SP_AUTH_MUTATE, + "{\"url\":\"https://allowed.org.evil.example/\"}") == 0); + /* two "url" keys: checked and fetched must be the same one */ + CHECK(gate(host, "webfetch", SP_AUTH_MUTATE, + "{\"url\":\"https://allowed.org/\",\"url\":\"https://evil.example/\"}") + == 0 || gate(host, "webfetch", SP_AUTH_MUTATE, + "{\"url\":\"https://evil.example/\",\"url\":\"https://allowed.org/\"}") + == 0); + + sp_host_free(host); + sp_buf_free(&err); + snprintf(cmd, sizeof(cmd), "rm -rf '%s'", home); + (void)system(cmd); + if (failures == 0) + printf("test_kids: ok\n"); + return failures == 0 ? 0 : 1; +} diff --git a/tests/test_lifecycle.c b/tests/test_lifecycle.c new file mode 100644 index 0000000..1bd365f --- /dev/null +++ b/tests/test_lifecycle.c @@ -0,0 +1,75 @@ +/* + * splinter -- a plugin's life: a failed init leaves nothing behind, and + * shutdown() is called when the host goes. + * + * Both were promised by the header and neither happened: an init that failed + * half-way kept its tools and its widget thread, and shutdown() was never + * called by anybody. + */ +#include +#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) + +int +main(void) +{ + struct sp_registry reg; + struct sp_agent ag; + struct sp_host *host; + struct sp_buf err; + char mark[] = "/var/tmp/splinter-lifecycle-XXXXXX"; + int fd; + + fd = mkstemp(mark); + CHECK(fd >= 0); + if (fd >= 0) + close(fd); + (void)unlink(mark); + (void)setenv("SP_TEST_SHUTDOWN_FILE", mark, 1); + CHECK(sp_buf_init(&err) == 0); + + /* ---- init fails after registering: nothing of it stays ---- */ + memset(®, 0, sizeof(reg)); + memset(&ag, 0, sizeof(ag)); + host = sp_host_new(®, &ag, NULL); + CHECK(host != NULL); + (void)setenv("SP_TEST_INIT_FAIL", "1", 1); + CHECK(sp_plugin_load(host, "tests/plugin_lifecycle.so", &err) != 0); + CHECK(sp_registry_find(®, "lifecycle_tool") == NULL); + CHECK(sp_host_widget_count(host) == 0); + sp_host_free(host); /* joins nothing, calls no shutdown */ + CHECK(access(mark, F_OK) != 0); + sp_registry_free(®); + + /* ---- init succeeds: the plugin is used, then shut down ---- */ + memset(®, 0, sizeof(reg)); + host = sp_host_new(®, &ag, NULL); + CHECK(host != NULL); + (void)unsetenv("SP_TEST_INIT_FAIL"); + sp_buf_clear(&err); + CHECK(sp_plugin_load(host, "tests/plugin_lifecycle.so", &err) == 0); + CHECK(sp_registry_find(®, "lifecycle_tool") != NULL); + CHECK(sp_host_widget_count(host) == 1); + sp_host_free(host); + CHECK(access(mark, F_OK) == 0); + (void)unlink(mark); + sp_registry_free(®); + + sp_buf_free(&err); + if (failures == 0) + printf("test_lifecycle: ok\n"); + return failures == 0 ? 0 : 1; +} diff --git a/tests/test_mcpclient.c b/tests/test_mcpclient.c new file mode 100644 index 0000000..612056b --- /dev/null +++ b/tests/test_mcpclient.c @@ -0,0 +1,107 @@ +/* + * splinter -- the MCP client plugin against a server that talks big. + * + * The failures it guards against, as they were found: a reply longer than the + * client's 16 KiB line buffer was split into pieces that never parsed, a reply + * that arrived in the same write as a notification sat unseen in stdio's + * buffer until the timeout, and a result that merely contained the text + * "error" was reported as a failed call. + */ +#include +#include +#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 const char *server_sh = + "#!/bin/sh\n" + "big() { head -c \"$1\" /dev/zero | tr '\\000' x; }\n" + "while IFS= read -r line; do\n" + " id=$(printf '%s' \"$line\" | sed -n 's/.*\"id\": *\\([0-9]*\\).*/\\1/p')\n" + " [ -n \"$id\" ] || continue\n" + " case \"$line\" in\n" + " *'\"initialize\"'*)\n" + " printf '{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\\n' \"$id\" ;;\n" + " *'\"tools/list\"'*)\n" + " d=$(big 40000)\n" + " printf '{\"jsonrpc\":\"2.0\",\"method\":\"notifications/x\"}\\n" + "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"tools\":[{\"name\":\"big\"," + "\"description\":\"%s\",\"inputSchema\":{\"type\":\"object\"," + "\"properties\":{}}}]}}\\n' \"$id\" \"$d\" ;;\n" + " *'\"tools/call\"'*)\n" + " t=$(big 100000)\n" + " printf '{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"content\":" + "[{\"type\":\"text\",\"text\":\"the word \\\\\"error\\\\\" then %s\"}]}}\\n'" + " \"$id\" \"$t\" ;;\n" + " *) printf '{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\\n' \"$id\" ;;\n" + " esac\n" + "done\n"; + +int +main(void) +{ + char dir[] = "/var/tmp/splinter-mcpc-XXXXXX"; + char path[600], cmd[700]; + struct sp_registry reg; + struct sp_agent ag; + struct sp_host *host; + struct sp_buf err, out; + const struct sp_tool *t; + FILE *f; + + CHECK(mkdtemp(dir) != NULL); + snprintf(path, sizeof(path), "%s/server.sh", dir); + f = fopen(path, "w"); + CHECK(f != NULL); + if (f == NULL) + return 1; + fputs(server_sh, f); + fclose(f); + (void)chmod(path, 0755); + (void)setenv("SPLINTER_MCP_CMD", path, 1); + + memset(®, 0, sizeof(reg)); + memset(&ag, 0, sizeof(ag)); + CHECK(sp_buf_init(&err) == 0); + CHECK(sp_buf_init(&out) == 0); + host = sp_host_new(®, &ag, NULL); + CHECK(host != NULL); + if (host == NULL) + return 1; + CHECK(sp_plugin_load(host, "plugins/mcp/mcp.so", &err) == 0); + if (err.len > 0) + fprintf(stderr, "load: %s\n", err.p); + + /* a 40 KiB tools/list, behind a notification in the same write */ + t = sp_registry_find(®, "mcp_big"); + CHECK(t != NULL); + if (t != NULL) { + CHECK(strlen(t->description) == 40000); + /* a 100 KiB result that says "error" is a result, not an error */ + CHECK(t->run("{}", &out, t->ctx) == 0); + CHECK(out.len > 100000); + CHECK(strstr(out.p, "the word \"error\" then xxx") != NULL); + CHECK(strncmp(out.p, "error:", 6) != 0); + } + + sp_host_free(host); + sp_buf_free(&out); + sp_buf_free(&err); + snprintf(cmd, sizeof(cmd), "rm -rf '%s'", dir); + (void)system(cmd); + if (failures == 0) + printf("test_mcpclient: ok\n"); + return failures == 0 ? 0 : 1; +}