/* * splinter -- plugin host: loading, tools, widgets, worker threads. * * Copyright (c) 2026 Konrad Lother * SPDX-License-Identifier: BSD-3-Clause * * Three rules keep this safe without a sandbox: * * 1. A plugin is only ever touched on the main thread, except its tick(), * which the host calls on a thread the host owns and can stop. * 2. Anything crossing from a worker thread to the UI goes through a copy * under a mutex. Workers never hold a pointer the UI can see. * 3. Nothing is dlclose()d while threads might still run. A stopped * widget's thread is joined first; the handle itself stays mapped for * the life of the process, which is the only honest option in C. */ #include #include #include #include #include #include #include #include "splinter.h" #include "splinter_plugin.h" #include "config.h" #define MAX_WIDGETS 32 #define MAX_COMPACTORS 8 #define MAX_STATUS 16 /* segments are cheap; sharing the cap hid a plugin */ #define MAX_TRANSPORTS 8 #define MAX_COMMANDS 16 #define MAX_PLUGINS 32 #define MAX_NOTE 2048 struct widget { struct sp_host *host; char name[64]; int (*tick)(struct sp_host *, const char *, void *); void (*draw)(struct sp_host *, const char *, void *); void *ctx; unsigned interval_ms; pthread_t thread; int running; int stop; char text[MAX_NOTE]; pthread_mutex_t lock; }; struct sp_host { struct sp_registry *reg; const void *conf; /* the loaded config, for plugins */ const char *session_dir; /* session directory, for persistence */ struct widget widgets[MAX_WIDGETS]; size_t nwidgets; char note[MAX_NOTE]; char msgs[16][200]; /* status lines for the chat */ size_t msg_head, msg_n; const struct sp_compactor *compact[MAX_COMPACTORS]; size_t ncompact; /* set by a plugin that is preparing a plan; lasts one call */ int compact_hold; const struct sp_gate *gate[MAX_COMPACTORS]; size_t ngate; const struct sp_status *status[MAX_STATUS]; size_t nstatus; struct sp_meter meter; const struct sp_task_ops *taskops; struct { char name[32]; struct sp_transport tr; } transports[MAX_TRANSPORTS]; size_t ntransports; struct { char name[32]; sp_cmd_fn fn; void *ctx; } commands[MAX_COMMANDS]; size_t ncommands; pthread_mutex_t lock; /* guards note and the registry */ struct sp_session_info *sess; struct sp_agent *agent; size_t compactions; size_t failed; unsigned turns; char model[256]; /* what the run is on */ char served_by[128]; /* who answered the last request */ struct sp_judge_next judge; /* X-Junction-Judge-Next-* */ char cache_mode[8]; /* X-Junction-Cache */ /* loaded plugins, in load order, so shutdown() runs in reverse */ const struct sp_plugin *loaded[MAX_PLUGINS]; size_t nloaded; /* quota/usage/burst policy hook (dispatches by provider/key_id) */ const struct sp_provider_ops *provider; }; static void * widget_thread(void *arg) { struct widget *w = arg; for (;;) { struct timespec ts; pthread_mutex_lock(&w->lock); if (w->stop) { pthread_mutex_unlock(&w->lock); break; } pthread_mutex_unlock(&w->lock); if (w->tick != NULL) (void)w->tick(w->host, w->name, w->ctx); if (w->interval_ms == 0) break; /* * Sleep in short steps and look at the stop flag between them: * one long sleep made the exit wait for a whole interval, since * sp_host_free() joins this thread. */ { unsigned long left = w->interval_ms; int stop = 0; while (left > 0 && !stop) { unsigned long step = left > 100 ? 100 : left; ts.tv_sec = 0; ts.tv_nsec = (long)step * 1000000L; nanosleep(&ts, NULL); left -= step; pthread_mutex_lock(&w->lock); stop = w->stop; pthread_mutex_unlock(&w->lock); } } } return NULL; } uint32_t sp_host_abi(struct sp_host *h) { (void)h; return SP_PLUGIN_ABI; } int sp_host_add_tool(struct sp_host *h, const struct sp_tool *t) { int rc; if (h == NULL || t == NULL || t->name == NULL || t->run == NULL) return -1; pthread_mutex_lock(&h->lock); rc = sp_registry_add(h->reg, t); pthread_mutex_unlock(&h->lock); return rc; } int sp_host_add_widget(struct sp_host *h, const struct sp_widget *w) { struct widget *slot; size_t i; if (h == NULL || w == NULL || w->name == NULL) return -1; if (h->nwidgets == MAX_WIDGETS) return -1; for (i = 0; i < h->nwidgets; i++) if (strcmp(h->widgets[i].name, w->name) == 0) return -1; /* * 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; slot->draw = w->draw; slot->ctx = w->ctx; slot->interval_ms = w->interval_ms; slot->stop = 0; 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; } } return 0; } int sp_host_add_compactor(struct sp_host *h, const struct sp_compactor *c) { if (h == NULL || c == NULL || c->name == NULL || c->compact == NULL) return -1; if (h->ncompact == MAX_COMPACTORS) return -1; h->compact[h->ncompact++] = c; return 0; } int sp_host_add_status(struct sp_host *h, const struct sp_status *s) { if (h == NULL || s == NULL || s->render == NULL || s->name == NULL) return -1; if (h->nstatus == MAX_STATUS) return -1; h->status[h->nstatus++] = s; return 0; } void sp_host_set_task_ops(struct sp_host *h, const struct sp_task_ops *ops) { if (h != NULL) h->taskops = ops; } int sp_host_task_begin(struct sp_host *h, const char *label, const char *detail) { if (h == NULL || h->taskops == NULL || h->taskops->begin == NULL) return -1; return h->taskops->begin(h, label, detail); } void sp_host_task_end(struct sp_host *h, int id, int status, size_t tokens) { if (h != NULL && h->taskops != NULL && h->taskops->end != NULL) h->taskops->end(h, id, status, tokens); } const struct sp_meter * sp_host_meter(struct sp_host *h) { static const struct sp_meter empty; return h != NULL ? &h->meter : ∅ } void sp_host_set_meter(struct sp_host *h, const struct sp_meter *m) { if (h == NULL || m == NULL) return; pthread_mutex_lock(&h->lock); h->meter = *m; pthread_mutex_unlock(&h->lock); } /* * The meter is written from the UI thread (tokens), from turn threads (tools * of the tasks plugin) and from widget threads. These two are the safe way: * a copy taken under the lock, and a change of only the fields the caller * owns, under the lock. */ void sp_host_meter_get(struct sp_host *h, struct sp_meter *out) { if (out == NULL) return; if (h == NULL) { memset(out, 0, sizeof(*out)); return; } pthread_mutex_lock(&h->lock); *out = h->meter; pthread_mutex_unlock(&h->lock); } void sp_host_meter_update(struct sp_host *h, void (*fn)(struct sp_meter *, void *), void *ctx) { if (h == NULL || fn == NULL) return; pthread_mutex_lock(&h->lock); fn(&h->meter, ctx); pthread_mutex_unlock(&h->lock); } size_t sp_host_status_text(struct sp_host *h, char *buf, size_t len) { size_t i, used = 0; if (h == NULL || buf == NULL || len == 0) return 0; buf[0] = '\0'; for (i = 0; i < h->nstatus; i++) { char piece[256]; int n; piece[0] = '\0'; h->status[i]->render(h, piece, sizeof(piece)); if (piece[0] == '\0') continue; n = snprintf(buf + used, len - used, "%s%s", used > 0 ? " | " : "", piece); if (n < 0 || (size_t)n >= len - used) break; used += (size_t)n; } return used; } int sp_host_add_gate(struct sp_host *h, const struct sp_gate *g) { if (h == NULL || g == NULL || g->check == NULL || g->name == NULL) return -1; if (h->ngate == MAX_COMPACTORS) return -1; h->gate[h->ngate++] = g; return 0; } /* * The first gate with an opinion wins. A denial carries its reason; allowing * skips the operator prompt, which is what a whitelist is for. */ int sp_host_turn_blocked(struct sp_host *h, char *msg, size_t len) { size_t i; if (h == NULL) return 0; for (i = 0; i < h->ngate; i++) if (h->gate[i]->block_turn != NULL && h->gate[i]->block_turn(h, msg, len)) return 1; return 0; } int sp_host_gate(struct sp_host *h, const char *tool, int auth, const char *args, char *reason, size_t reason_len) { size_t i; if (h == NULL) return -1; for (i = 0; i < h->ngate; i++) { int rc = h->gate[i]->check(h, tool, auth, args, reason, reason_len); if (rc >= 0) return rc; } return -1; } int sp_host_add_transport(struct sp_host *h, const char *name, struct sp_transport tr) { if (h == NULL || name == NULL || tr.send == NULL) return -1; if (h->ntransports == MAX_TRANSPORTS) return -1; if (sp_host_transport(h, name) != NULL) return -1; snprintf(h->transports[h->ntransports].name, sizeof(h->transports[h->ntransports].name), "%s", name); h->transports[h->ntransports].tr = tr; h->ntransports++; return 0; } struct sp_transport * sp_host_transport(struct sp_host *h, const char *name) { size_t i; if (h == NULL || name == NULL) return NULL; for (i = 0; i < h->ntransports; i++) if (strcmp(h->transports[i].name, name) == 0) return &h->transports[i].tr; return NULL; } int sp_host_add_command(struct sp_host *h, const char *name, sp_cmd_fn fn, void *ctx) { if (h == NULL || name == NULL || fn == NULL) return -1; if (h->ncommands == MAX_COMMANDS) return -1; snprintf(h->commands[h->ncommands].name, sizeof(h->commands[h->ncommands].name), "%s", name); h->commands[h->ncommands].fn = fn; h->commands[h->ncommands].ctx = ctx; h->ncommands++; return 0; } int sp_host_command(struct sp_host *h, const char *name, const char *args, struct sp_buf *out) { size_t i; int rc = -1; if (h == NULL || name == NULL) return -1; for (i = 0; i < h->ncommands; i++) { if (strcmp(h->commands[i].name, name) != 0) continue; rc = h->commands[i].fn(h, args != NULL ? args : "", out, h->commands[i].ctx); if (rc == 0) return 0; } sp_buf_printf(out, "unknown command: /%s", name); return -1; } size_t sp_host_command_help(struct sp_host *h, struct sp_buf *out) { size_t i; if (h == NULL) return 0; for (i = 0; i < h->ncommands; i++) (void)sp_buf_printf(out, "/%s ", h->commands[i].name); return h->ncommands; } /* * Run every compactor in registration order. A compactor that fails does not * stop the others and does not abort the turn: the failure is counted and the * loop carries on with whatever the conversation looks like now. */ int sp_host_compact(struct sp_host *h, struct sp_conv *conv, size_t budget) { size_t i; int changed = 0, rc; if (h == NULL || conv == NULL) return 0; /* * The plugins get their turn first, and the core is the backstop. * * The old rule was "any plugin compactor means the core stays out", and * it was wrong twice over. compact_threshold and compact_target are core * settings, so a configuration whose plugins happened to register one * made them dead - the operator set a limit and the conversation grew * past the window until the provider cut it (254k of 131k, 2026-11-21). * And most plugin "compactors" do not compact at all: focus and reminder * insert one message and return 0 or 1. A plugin that inserts a goal * reminder must not be the reason an oversized request goes out whole. * * So the core always gets a look, and decides for itself: core_compact() * returns 0 without touching anything when the conversation already fits * the budget. That is the check that separates "focus inserted a * reminder into a small conversation" (616 bytes under a 1-byte budget * in a test, every real turn under its real budget) from "lcm cut the * transcript in half". Only the second kind of turn gets a digest, and * then it comes after the plugin's own work, so that work is what * survives where it did something. */ for (i = 0; i < h->ncompact; i++) { rc = h->compact[i]->compact(h, conv, budget, (unsigned)h->turns); if (rc > 0) { changed = 1; h->compactions++; } else if (rc < 0) { h->failed++; } } /* * A plugin that answered "not yet, my plan is still being prepared" asked * for one round of room. Its next call applies the plan. Cutting the * conversation in between would invalidate that plan, which is the bug * this flag exists to prevent. */ if (h->compact_hold) { h->compact_hold = 0; return changed; } rc = sp_core_compactor()->compact(h, conv, budget, (unsigned)h->turns); if (rc > 0) { changed = 1; h->compactions++; } else if (rc < 0) { h->failed++; } return changed; } void sp_host_compactor_hold(struct sp_host *h) { if (h != NULL) h->compact_hold = 1; } size_t sp_host_compaction_stats(struct sp_host *h, size_t *compactions, size_t *failed, unsigned *turns) { if (compactions != NULL) *compactions = h != NULL ? h->compactions : 0; if (failed != NULL) *failed = h != NULL ? h->failed : 0; if (turns != NULL) *turns = h != NULL ? h->turns : 0; return h != NULL ? h->compactions : 0; } const char * sp_host_model(struct sp_host *h) { static __thread char copy[256]; if (h == NULL) return ""; pthread_mutex_lock(&h->lock); snprintf(copy, sizeof(copy), "%s", h->model); pthread_mutex_unlock(&h->lock); return copy; } void sp_host_set_model(struct sp_host *h, const char *model) { if (h == NULL) return; pthread_mutex_lock(&h->lock); snprintf(h->model, sizeof(h->model), "%s", model != NULL ? 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); } void sp_host_set_judge_next(struct sp_host *h, const struct sp_judge_next *j) { if (h == NULL) return; pthread_mutex_lock(&h->lock); if (j != NULL) h->judge = *j; else memset(&h->judge, 0, sizeof(h->judge)); pthread_mutex_unlock(&h->lock); } int sp_host_judge_next(struct sp_host *h, struct sp_judge_next *out) { int valid = 0; if (h == NULL || out == NULL) return 0; pthread_mutex_lock(&h->lock); *out = h->judge; valid = h->judge.valid; pthread_mutex_unlock(&h->lock); return valid; } struct sp_registry * sp_host_registry(struct sp_host *h) { return h != NULL ? h->reg : NULL; } const void * sp_host_config(struct sp_host *h) { return h != NULL ? h->conf : NULL; } void sp_host_set_config(struct sp_host *h, const void *conf) { if (h != NULL) h->conf = conf; } const char * sp_host_plugin_config(struct sp_host *h, const char *plugin, const char *key) { return sp_config_plugin_value(h != NULL ? h->conf : NULL, plugin, key); } const char * sp_host_plugin_config_at(struct sp_host *h, const char *plugin, size_t i, const char **key) { const struct sp_config *c = h != NULL ? h->conf : NULL; size_t k, seen = 0; if (c == NULL || plugin == NULL) return NULL; for (k = 0; k < c->nplugin_conf; k++) { if (strcmp(c->plugin_conf[k].plugin, plugin) != 0) continue; if (seen++ == i) { if (key != NULL) *key = c->plugin_conf[k].key; return c->plugin_conf[k].val; } } return NULL; } void sp_host_turn(struct sp_host *h) { if (h != NULL) h->turns++; } int sp_host_widget_text(struct sp_host *h, const char *widget, const char *text) { size_t i, n; if (h == NULL || widget == NULL || text == NULL) return -1; /* 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) continue; pthread_mutex_lock(&w->lock); snprintf(w->text, sizeof(w->text), "%s", text); pthread_mutex_unlock(&w->lock); return 0; } return -1; } int sp_host_note(struct sp_host *h, const char *text) { if (h == NULL || text == NULL) return -1; pthread_mutex_lock(&h->lock); snprintf(h->note, sizeof(h->note), "%s", text); pthread_mutex_unlock(&h->lock); return 0; } /* A status line for the chat, from any thread; the UI takes them one by one. */ int sp_host_status_msg(struct sp_host *h, const char *text) { if (h == NULL || text == NULL) return -1; pthread_mutex_lock(&h->lock); if (h->msg_n == 16) { /* the oldest goes */ h->msg_head = (h->msg_head + 1) % 16; h->msg_n--; } snprintf(h->msgs[(h->msg_head + h->msg_n) % 16], sizeof(h->msgs[0]), "%s", text); h->msg_n++; pthread_mutex_unlock(&h->lock); return 0; } int sp_host_status_take(struct sp_host *h, char *buf, size_t len) { int rc = 0; if (h == NULL || buf == NULL || len == 0) return 0; pthread_mutex_lock(&h->lock); if (h->msg_n > 0) { snprintf(buf, len, "%s", h->msgs[h->msg_head]); h->msg_head = (h->msg_head + 1) % 16; h->msg_n--; rc = 1; } pthread_mutex_unlock(&h->lock); return rc; } size_t sp_host_widget_snapshot(struct sp_host *h, char *buf, size_t len) { size_t i, used = 0; if (h == NULL || buf == NULL || len == 0) return 0; buf[0] = '\0'; for (i = 0; i < h->nwidgets; i++) { struct widget *w = &h->widgets[i]; int n; pthread_mutex_lock(&w->lock); n = snprintf(buf + used, len - used, "%s: %s\n", w->name, w->text); pthread_mutex_unlock(&w->lock); if (n < 0 || (size_t)n >= len - used) break; used += (size_t)n; } return used; } /* 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) { void *hd; const struct sp_plugin *(*describe)(void); if (h == NULL || path == NULL) return -1; hd = dlopen(path, RTLD_NOW | RTLD_LOCAL); if (hd == NULL) { sp_buf_printf(err, "plugin %s: %s", path, dlerror()); return -1; } { void *sym = dlsym(hd, "sp_plugin_describe"); if (sym == NULL) { sp_buf_printf(err, "plugin %s: no sp_plugin_describe()", path); /* the handle stays mapped: dlclose after a failed init is * how a half-initialised plugin takes the process with it */ return -1; } { union { void *p; const struct sp_plugin *(*f)(void); } cast; cast.p = sym; describe = cast.f; } } { const struct sp_plugin *p = describe(); if (p == NULL) { sp_buf_printf(err, "plugin %s: describe() returned NULL", path); return -1; } if (p->abi != SP_PLUGIN_ABI) { sp_buf_printf(err, "plugin %s: abi %u, host speaks %u", path, p->abi, SP_PLUGIN_ABI); return -1; } 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; } } struct sp_host * sp_host_new(struct sp_registry *reg, struct sp_agent *agent, struct sp_session_info *sess) { struct sp_host *h = calloc(1, sizeof(*h)); if (h == NULL) return NULL; h->reg = reg; h->agent = agent; h->sess = sess; h->session_dir = (sess != NULL) ? sess->dir : NULL; pthread_mutex_init(&h->lock, NULL); return h; } const char * sp_host_session_dir(struct sp_host *h) { return (h != NULL) ? h->session_dir : NULL; } const char * sp_host_session_id(struct sp_host *h) { return (h != NULL && h->sess != NULL) ? h->sess->id : NULL; } void sp_host_set_provider(struct sp_host *h, const struct sp_provider_ops *ops) { if (h != NULL) h->provider = ops; } enum sp_prov_decision sp_host_provider_preflight(struct sp_host *h, const char *provider, const char *key_id, struct sp_prov_result *out) { if (out != NULL) { memset(out, 0, sizeof(*out)); out->decision = SP_PROV_ADMIT; } if (h == NULL || h->provider == NULL || h->provider->preflight == NULL) return SP_PROV_ADMIT; (void)h->provider->preflight(h->provider->ctx, provider, key_id, out); return (out != NULL) ? out->decision : SP_PROV_ADMIT; } void sp_host_provider_account(struct sp_host *h, const char *provider, const char *key_id, long http_status, size_t tokens_in, size_t tokens_out) { if (h == NULL || h->provider == NULL || h->provider->account == NULL) return; h->provider->account(h->provider->ctx, provider, key_id, http_status, tokens_in, tokens_out); } void sp_host_free(struct sp_host *h) { size_t i; if (h == NULL) return; /* 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); } size_t sp_host_widget_count(struct sp_host *h) { return h != NULL ? h->nwidgets : 0; } const char * sp_host_cache_mode(struct sp_host *h) { static __thread char copy[8]; if (h == NULL) return ""; pthread_mutex_lock(&h->lock); snprintf(copy, sizeof(copy), "%s", h->cache_mode); pthread_mutex_unlock(&h->lock); return copy; } void sp_host_set_cache_mode(struct sp_host *h, const char *mode) { if (h == NULL) return; pthread_mutex_lock(&h->lock); snprintf(h->cache_mode, sizeof(h->cache_mode), "%s", mode != NULL ? mode : ""); pthread_mutex_unlock(&h->lock); }