/* * splinter -- background tasks. * * Copyright (c) 2026 Konrad Lother * SPDX-License-Identifier: BSD-3-Clause * * Some work should not hold the conversation. A build, a test run, a delegate on * another host: start it, keep talking, look at it later. * * Four at a time by default (SPLINTER_TASKS_MAX), because a machine that runs * twenty background shell commands at once is not doing the work faster, it is * only harder to read. A start beyond the limit is refused with the reason, not * queued into an invisible backlog. * * The tools: * * process_start command, label? -> id, starts at once * process_list -> id, state, seconds, bytes, label * process_result id -> output, exit status; fails while running * process_kill id -> stop it * * Tasks are shell commands, so starting one is destructive in the same sense that * `run` is: the gate and the approval path see it like any other change. */ #include #include #include #include #include #include #include #include #include #include #include #include "splinter.h" #include "mcp.h" #include "splinter_plugin.h" #define TASKS_MAX 16 struct task { int id; volatile int running; int status; /* exit status once finished */ char label[64]; char cmd[512]; struct sp_buf out; time_t started, ended; pid_t pid; pthread_t th; pthread_mutex_t lock; }; static struct task tasks[TASKS_MAX]; static int ntasks; static int next_id = 1; static unsigned max_parallel = 4; static pthread_mutex_t tasks_lock = PTHREAD_MUTEX_INITIALIZER; static int running_count(void) { int i, n = 0; pthread_mutex_lock(&tasks_lock); for (i = 0; i < ntasks; i++) if (tasks[i].running) n++; pthread_mutex_unlock(&tasks_lock); return n; } static void set_process_fields(struct sp_meter *m, void *ctx) { const unsigned *run = ctx; m->tasks_running = *run; m->tasks_max = max_parallel; } /* * Only the task fields, under the host's lock. A copy of the whole meter, * changed and written back, raced with the UI doing the same with the token * fields: whichever wrote last erased the other's update. */ static void publish_meter(struct sp_host *h) { unsigned run = (unsigned)running_count(); sp_host_meter_update(h, set_process_fields, &run); } static void refresh_widget(struct sp_host *h) { char text[1024]; size_t used = 0; int i; pthread_mutex_lock(&tasks_lock); for (i = 0; i < ntasks && used + 96 < sizeof(text); i++) { struct task *t = &tasks[i]; int n; /* * The sidebar is for what is happening now. A finished task * stays in process_list/process_result (its output is still there), * but it does not take a row of the sidebar forever. */ if (!t->running) continue; n = snprintf(text + used, sizeof(text) - used, "#%d %s %lds\n", t->id, t->label, (long)(time(NULL) - t->started)); if (n < 0 || (size_t)n >= sizeof(text) - used) break; used += (size_t)n; } pthread_mutex_unlock(&tasks_lock); if (used == 0) (void)sp_host_widget_text(h, "processes", ""); else (void)sp_host_widget_text(h, "processes", text); } extern char **environ; /* * The end of a task, under tasks_lock: that is the lock process_list, the widget * and running_count read 'running', 'status' and 'ended' under. They used to * be written under the task's own lock only - two locks guarding one field * guard nothing. */ static void process_finish(struct task *t, int status) { pthread_mutex_lock(&tasks_lock); t->status = status; t->ended = time(NULL); t->running = 0; pthread_mutex_unlock(&tasks_lock); } /* * Run the task in its own process group, so process_kill can stop the shell and * everything it started. popen() gave no pid: t->pid stayed 0, and * kill(-0, SIGTERM) is "every process in my group" - process_kill killed * splinter itself. stdin is /dev/null (a task must not read the terminal), and * the environment loses splinter's keys, as for the 'run' tool. */ static void * process_run(void *arg) { struct task *t = arg; char chunk[2048]; char **envp; ssize_t got; size_t n, i, j; int fds[2], st = 0; pid_t child; for (n = 0; environ != NULL && environ[n] != NULL; n++) ; envp = calloc(n + 1, sizeof(*envp)); if (envp == NULL || pipe(fds) != 0) { free(envp); pthread_mutex_lock(&t->lock); sp_buf_printf(&t->out, "error: %s", strerror(errno)); pthread_mutex_unlock(&t->lock); process_finish(t, 127); return NULL; } for (i = 0, j = 0; i < n; i++) if (!sp_secret_env_is(environ[i])) envp[j++] = environ[i]; envp[j] = NULL; child = fork(); if (child == 0) { int dn = open("/dev/null", O_RDONLY); (void)setpgid(0, 0); if (dn >= 0) { (void)dup2(dn, STDIN_FILENO); if (dn != STDIN_FILENO) close(dn); } (void)dup2(fds[1], STDOUT_FILENO); (void)dup2(fds[1], STDERR_FILENO); close(fds[0]); close(fds[1]); execle("/bin/sh", "sh", "-c", t->cmd, (char *)NULL, envp); _exit(127); } close(fds[1]); free(envp); if (child < 0) { close(fds[0]); pthread_mutex_lock(&t->lock); sp_buf_printf(&t->out, "error: fork: %s", strerror(errno)); pthread_mutex_unlock(&t->lock); process_finish(t, 127); return NULL; } (void)setpgid(child, child); pthread_mutex_lock(&tasks_lock); t->pid = child; pthread_mutex_unlock(&tasks_lock); for (;;) { got = read(fds[0], chunk, sizeof(chunk)); if (got < 0 && errno == EINTR) continue; if (got <= 0) break; pthread_mutex_lock(&t->lock); if (t->out.len < (1u << 20)) /* 1 MiB, stated */ (void)sp_buf_add(&t->out, chunk, (size_t)got); pthread_mutex_unlock(&t->lock); } close(fds[0]); while (waitpid(child, &st, 0) < 0 && errno == EINTR) ; pthread_mutex_lock(&tasks_lock); t->pid = 0; /* reaped: the id may be reused */ pthread_mutex_unlock(&tasks_lock); process_finish(t, st); return NULL; } static struct task * find(int id) { int i; for (i = 0; i < ntasks; i++) if (tasks[i].id == id) return &tasks[i]; return NULL; } /* * The value of an argument, with the parser the rest of splinter uses. The old * strstr() only matched "key":"..." - the schema declares 'id' an integer, so * {"id":3} came out empty and every process_kill said "no such task". */ static void arg_str(const char *args, const char *key, char *buf, size_t len) { mcp_json *v; const char *sv; buf[0] = '\0'; if (args == NULL || args[0] != '{' || (v = mcp_parse(args)) == NULL) return; sv = mcp_arg_string(v, key); if (sv != NULL) snprintf(buf, len, "%s", sv); else { int n = mcp_arg_int(v, key, INT_MIN); if (n != INT_MIN) snprintf(buf, len, "%d", n); } mcp_json_free(v); } static struct sp_host *host_ref; /* * Tasks someone else owns - a delegate on another host. They get an entry and a * clock, but no thread here: the harness closes them when the call returns. */ static int ops_begin(struct sp_host *h, const char *label, const char *detail) { struct task *t; int id; (void)detail; pthread_mutex_lock(&tasks_lock); if (ntasks == TASKS_MAX) { pthread_mutex_unlock(&tasks_lock); return -1; } t = &tasks[ntasks++]; memset(t, 0, sizeof(*t)); (void)pthread_mutex_init(&t->lock, NULL); t->id = next_id++; t->running = 1; t->started = time(NULL); snprintf(t->label, sizeof(t->label), "%.63s", label != NULL ? label : "?"); id = t->id; pthread_mutex_unlock(&tasks_lock); if (h != NULL) { publish_meter(h); refresh_widget(h); } return id; } static void ops_end(struct sp_host *h, int id, int status, size_t tokens) { struct task *t; if (id < 0) return; pthread_mutex_lock(&tasks_lock); t = find(id); if (t != NULL) { t->running = 0; t->status = status; t->ended = time(NULL); if (tokens > 0) (void)sp_buf_printf(&t->out, "[~%zu tokens]", tokens); } pthread_mutex_unlock(&tasks_lock); if (h != NULL) { publish_meter(h); refresh_widget(h); } } static const struct sp_task_ops task_ops = { ops_begin, ops_end }; static int tool_process_start(const char *args, struct sp_buf *out, void *ctx) { char cmd[600], label[80]; struct task *t; int id; (void)ctx; arg_str(args, "command", cmd, sizeof(cmd)); arg_str(args, "label", label, sizeof(label)); if (cmd[0] == '\0') return sp_buf_puts(out, "error: empty command"); if (label[0] == '\0') snprintf(label, sizeof(label), "%.40s", cmd); if (running_count() >= (int)max_parallel) return sp_buf_printf(out, "error: %u tasks already running " "(SPLINTER_TASKS_MAX) - finish or kill one first", max_parallel); pthread_mutex_lock(&tasks_lock); if (ntasks == TASKS_MAX) { pthread_mutex_unlock(&tasks_lock); return sp_buf_puts(out, "error: task table full"); } t = &tasks[ntasks++]; memset(t, 0, sizeof(*t)); t->id = next_id++; (void)pthread_mutex_init(&t->lock, NULL); snprintf(t->cmd, sizeof(t->cmd), "%.511s", cmd); snprintf(t->label, sizeof(t->label), "%.63s", label); t->started = time(NULL); t->running = 1; if (sp_buf_init(&t->out) != 0) { ntasks--; pthread_mutex_unlock(&tasks_lock); return sp_buf_puts(out, "error: no memory"); } id = t->id; if (pthread_create(&t->th, NULL, process_run, t) != 0) { t->running = 0; ntasks--; pthread_mutex_unlock(&tasks_lock); return sp_buf_puts(out, "error: cannot start thread"); } pthread_detach(t->th); pthread_mutex_unlock(&tasks_lock); if (host_ref != NULL) { publish_meter(host_ref); refresh_widget(host_ref); } return sp_buf_printf(out, "started #%d (%s) - %d/%u running", id, label, running_count(), max_parallel); } static int tool_process_list(const char *args, struct sp_buf *out, void *ctx) { int i, any = 0; (void)args; (void)ctx; pthread_mutex_lock(&tasks_lock); for (i = 0; i < ntasks; i++) { struct task *t = &tasks[i]; any = 1; if (t->running) sp_buf_printf(out, "#%d running %lds %zu B %s\n", t->id, (long)(time(NULL) - t->started), t->out.len, t->label); else sp_buf_printf(out, "#%d done %.2fs exit %d %zu B %s\n", t->id, difftime(t->ended, t->started), t->status, t->out.len, t->label); } pthread_mutex_unlock(&tasks_lock); if (!any) sp_buf_puts(out, "keine Tasks"); return 0; } static int tool_process_result(const char *args, struct sp_buf *out, void *ctx) { char num[32]; struct task *t; int id; (void)ctx; arg_str(args, "id", num, sizeof(num)); id = atoi(num); pthread_mutex_lock(&tasks_lock); t = find(id); if (t == NULL) { pthread_mutex_unlock(&tasks_lock); return sp_buf_puts(out, "error: no such task"); } if (t->running) { long secs = (long)(time(NULL) - t->started); pthread_mutex_unlock(&tasks_lock); return sp_buf_printf(out, "still running (%lds, %zu B so far)", secs, t->out.len); } pthread_mutex_lock(&t->lock); if (t->out.p != NULL) (void)sp_buf_add(out, t->out.p, t->out.len); pthread_mutex_unlock(&t->lock); sp_buf_printf(out, "\n[exit %d, %.1fs]", t->status, difftime(t->ended, t->started)); pthread_mutex_unlock(&tasks_lock); return 0; } static int tool_process_kill(const char *args, struct sp_buf *out, void *ctx) { char num[32]; struct task *t; int id; (void)ctx; arg_str(args, "id", num, sizeof(num)); id = atoi(num); pthread_mutex_lock(&tasks_lock); t = find(id); if (t == NULL) { pthread_mutex_unlock(&tasks_lock); return sp_buf_puts(out, "error: no such task"); } if (!t->running) { pthread_mutex_unlock(&tasks_lock); return sp_buf_puts(out, "already finished"); } /* * Only a task with a process group of its own. A task opened by * ops_begin (a delegate on another host) has none here, and a pid of 0 * or 1 would make kill(-pid) hit splinter's own group or everything. */ if (t->pid <= 1) { pthread_mutex_unlock(&tasks_lock); return sp_buf_puts(out, "error: this task has no local process " "to stop"); } (void)kill(-(t->pid), SIGTERM); pthread_mutex_unlock(&tasks_lock); return sp_buf_puts(out, "kill signal sent"); } static const struct sp_tool t_start = { "process_start", "Start a shell command in the background and return its id. Use it for " "builds, tests or long runs instead of blocking the conversation.", "{\"type\":\"object\",\"properties\":{\"command\":{\"type\":\"string\"}," "\"label\":{\"type\":\"string\",\"description\":\"short name\"}}," "\"required\":[\"command\"]}", SP_AUTH_DESTRUCTIVE, tool_process_start, NULL }; static const struct sp_tool t_list = { "process_list", "List background tasks: id, state, time, size, label.", "{\"type\":\"object\",\"properties\":{}}", SP_AUTH_READ, tool_process_list, NULL }; static const struct sp_tool t_result = { "process_result", "Output and exit status of a finished task.", "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}}," "\"required\":[\"id\"]}", SP_AUTH_READ, tool_process_result, NULL }; static const struct sp_tool t_kill = { "process_kill", "Stop a running task.", "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}}," "\"required\":[\"id\"]}", SP_AUTH_DESTRUCTIVE, tool_process_kill, NULL }; static int tasks_tick(struct sp_host *h, const char *name, void *ctx) { (void)name; (void)ctx; refresh_widget(h); publish_meter(h); return 0; } static const struct sp_widget widget = { "processes", /* name */ tasks_tick, /* tick */ NULL, /* draw */ NULL, /* ctx */ 1000 /* interval: a running task is interesting every second */ }; static int tasks_init(struct sp_host *h) { const char *m = getenv("SPLINTER_TASKS_MAX"); if (m != NULL && *m != '\0') { unsigned v = (unsigned)strtoul(m, NULL, 10); if (v > 0 && v <= TASKS_MAX) max_parallel = v; } host_ref = h; (void)sp_host_add_tool(h, &t_start); (void)sp_host_add_tool(h, &t_list); (void)sp_host_add_tool(h, &t_result); (void)sp_host_add_tool(h, &t_kill); (void)sp_host_add_widget(h, &widget); (void)sp_host_widget_text(h, "processes", ""); sp_host_set_task_ops(h, &task_ops); publish_meter(h); return 0; } static const struct sp_plugin plugin = { SP_PLUGIN_ABI, "tasks", "1.0", tasks_init, NULL, NULL }; const struct sp_plugin * sp_plugin_describe(void) { return &plugin; }