/* * splinter -- delegation to other models. * * Copyright (c) 2026 Konrad Lother * SPDX-License-Identifier: BSD-3-Clause * * The harness can hand work to another model. Which one is decided here, in * code, from the tags and the description configured for each delegate - not by * guessing and not by asking a model to pick itself a helper. * * delegate = coder | C99 und POSIX, kennt den Baum | tags=code,c99 | * endpoint=http://kontron.local:8080/v1 | * model=Qwen3.6-35B * * The child is splinter itself in one-shot mode: same tools, same rules, own * context. Its answer comes back as the observation, with the choice and the * reason in front of it, so a wrong pick is visible instead of mysterious. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "splinter.h" #include "splinter_plugin.h" #include "i18n.h" #include "mcp.h" #include "config.h" #include "usage.h" #include "providers.h" #include #include #include #define DELEGATE_TIMEOUT_MS_DEFAULT 900000 #define DELEGATE_MAX_BYTES_CAP (64u << 20) /* safety cap; buffers grow */ static long delegate_timeout_ms(const struct sp_config *cfg) { const char *e = getenv("SPLINTER_DELEGATE_TIMEOUT"); long s = 0; if (e != NULL && *e != '\0') s = strtol(e, NULL, 10); if (s <= 0 && cfg != NULL) s = cfg->delegate_timeout; if (s <= 0) return DELEGATE_TIMEOUT_MS_DEFAULT; return s * 1000; } struct del_ctx { const struct sp_config *cfg; struct sp_host *host; /* may be NULL: no task panel */ char self[512]; }; /* * What is actually available. The model cannot delegate well if it has to guess * which ids and tags exist, and guessing produces 'no delegate matches this task' * at the moment the work should start. * * Without probe=1 it lists the configuration. With probe=1 it also asks every * endpoint what models it serves (/v1/models), so 'the config says so' and 'the * server answers' are two different columns. */ /* the string value of one argument, without the whole JSON parser */ static const char * json_str(const char *args, const char *key, struct sp_buf *keep) { char pat[64]; const char *p, *start; size_t n; snprintf(pat, sizeof(pat), "\"%s\"", key); p = args != NULL ? strstr(args, pat) : NULL; if (p == NULL) return NULL; p = strchr(p + strlen(pat), ':'); if (p == NULL || (start = strchr(p, '"')) == NULL) return NULL; start++; n = strcspn(start, "\""); sp_buf_add(keep, start, n); return keep->p; } static void models_url(const char *endpoint, char *out, size_t len) { sp_endpoint_url(endpoint, "models", out, len); } static int tool_delegate_list(const char *args, struct sp_buf *out, void *ctx) { struct del_ctx *c = ctx; struct sp_buf keep; const char *probe_s; int probe = 0; size_t i; (void)c; if (sp_buf_init(&keep) != 0) return -1; probe_s = json_str(args, "probe", &keep); probe = probe_s != NULL && (strcmp(probe_s, "true") == 0 || strcmp(probe_s, "1") == 0); sp_buf_free(&keep); if (c->cfg->ndelegates == 0) { sp_buf_puts(out, "keine Delegates konfiguriert\n"); return 0; } for (i = 0; i < c->cfg->ndelegates; i++) { const struct sp_delegate *d = &c->cfg->delegate[i]; sp_buf_printf(out, "%s\n tags: %s\n kind: %s prio: %d\n", d->id, d->tags[0] != '\0' ? d->tags : "(keine)", d->kind[0] != '\0' ? d->kind : "openai", d->prio); { struct sp_usage u; char b[160]; sp_usage_get(d->id, d->req_limit, d->req_window, d->tok_limit, d->tok_window, &u); sp_usage_brief(&u, b, sizeof(b)); sp_buf_printf(out, " usage: %s\n", b); } sp_buf_printf(out, " model: %s\n", d->model[0] != '\0' ? d->model : "(cli)"); sp_buf_printf(out, " endpoint: %s%s%s\n", d->endpoint[0] != '\0' ? d->endpoint : "(cli)", d->host[0] != '\0' ? " auf " : "", d->host[0] != '\0' ? d->host : ""); sp_buf_printf(out, " wofuer: %s\n", d->about); if (probe && d->endpoint[0] != '\0') { char url[600], cmd[700]; FILE *fp; char line[512]; int seen = 0; models_url(d->endpoint, url, sizeof(url)); snprintf(cmd, sizeof(cmd), "curl -sS --max-time 8 '%s'", url); fp = popen(cmd, "r"); sp_buf_puts(out, " models: "); if (fp == NULL) { sp_buf_puts(out, "nicht erreichbar\n"); } else { while (fgets(line, sizeof(line), fp) != NULL) { const char *m = strstr(line, "\"id\""); if (m == NULL) continue; m = strchr(m, ':'); if (m == NULL) continue; m = strchr(m, '"'); if (m == NULL) continue; { const char *e = strchr(m + 1, '"'); size_t n = e != NULL ? (size_t)(e - m - 1) : 0; if (n > 0 && n < 80) { if (seen++) sp_buf_puts(out, ", "); sp_buf_printf(out, "%.*s", (int)n, m + 1); } } } (void)pclose(fp); if (!seen) sp_buf_puts(out, "(keine Modellliste)"); sp_buf_puts(out, "\n"); } } sp_buf_puts(out, "\n"); } return 0; } static void lower(char *dst, size_t cap, const char *src) { size_t i; for (i = 0; src[i] != '\0' && i + 1 < cap; i++) dst[i] = (char)tolower((unsigned char)src[i]); dst[i] = '\0'; } /* * Pick the delegate that fits the task. * * A requested tag outweighs a tag found in the task, which outweighs a word of * the description. Ties go to the earlier entry: predictable beats clever when * someone is reading the log at night. */ static const struct sp_delegate *find_delegate(const struct sp_config *cfg, const char *id); /* * How well a delegate fits a task. * * The first version asked "does the task contain the tag as text", which is * wrong in both directions: "cli" is inside "client", and "gross" never * matched the tag "big". Matching is by word now, with a small table of what * people write for a tag (German and English), and a few rules that are not * scores at all. * * requested tag (the model asked for it) +6 * a word of the task is the tag +3 * a word of the task starts with the tag +2 (codebase, reviewen) * a word of the task is a synonym of the tag +2 (gross -> big) * a word of the description is in the task +1 (at most +2, no filler) * * A tag counts once. Rules: a task that is private (privat, geheim, secret ...) * only goes to a delegate tagged "private" -- a score must never be able to * send it elsewhere. When nothing matches at all, the config's default takes * the task, if there is one, instead of an error. */ #define FIT_WORDS 96 #define FIT_WORDLEN 40 struct words { char w[FIT_WORDS][FIT_WORDLEN]; size_t n; }; static void split_words(struct words *ws, const char *text) { const unsigned char *p = (const unsigned char *)(text != NULL ? text : ""); ws->n = 0; while (*p != '\0' && ws->n < FIT_WORDS) { size_t k = 0; while (*p != '\0' && !isalnum(*p) && *p < 0x80) p++; while (*p != '\0' && (isalnum(*p) || *p >= 0x80)) { if (k + 1 < FIT_WORDLEN) ws->w[ws->n][k++] = (char)tolower(*p); p++; } if (k > 0) { ws->w[ws->n][k] = '\0'; ws->n++; } } } /* what people write for a tag; a synonym matches as the start of a word */ static const struct { const char *tag, *syn; } synonyms[] = { { "code", "programm,funktion,function,bug,fehler,compil,refactor,implement,skript,script,klasse" }, { "review", "pruef,prüf,audit,kontroll,durchsicht,begutacht" }, { "analyze", "analys,analyz,untersuch,bewert,diagnos,ursache,root" }, { "decide", "entscheid,entscheiden,decide,decision,abwaeg,abwäg,trade,empfehl,recommend,vergleich" }, { "plan", "planung,entwurf,entwirf,architektur,design,roadmap,strategie" }, { "big", "gross,groß,large,komplex,umfangreich,gesamt,monorepo,refactor,migrat" }, { "small", "klein,kurz,short,tiny,winzig" }, { "fast", "schnell,quick,eilig,zuegig" }, { "cheap", "billig,guenstig,günstig,sparsam" }, { "private", "privat,geheim,secret,vertraulich,confidential,intern" }, { "local", "lokal,offline" }, { "chat", "frage,plauder,erklaer,erkläre,explain" }, { "summary", "zusammenfass,summar,tldr" }, { "research", "recherch,investigat,untersuch" }, { "test", "pytest,unittest,testfall" }, { "doc", "dokumentation,documentation,readme,handbuch" }, }; static int synonym_hit(const char *tag, const char *word) { size_t i; for (i = 0; i < sizeof(synonyms) / sizeof(synonyms[0]); i++) { char list[256], *s, *save = NULL; if (strcmp(synonyms[i].tag, tag) != 0) continue; snprintf(list, sizeof(list), "%s", synonyms[i].syn); for (s = strtok_r(list, ",", &save); s != NULL; s = strtok_r(NULL, ",", &save)) if (strncmp(word, s, strlen(s)) == 0) return 1; } return 0; } /* 3 exact, 2 prefix or synonym, 0 none */ static int word_fit(const char *tag, const char *word) { size_t tl = strlen(tag); if (strcmp(word, tag) == 0) return 3; if (tl >= 4 && strncmp(word, tag, tl) == 0) return 2; if (synonym_hit(tag, word)) { /* "entscheide", "analysiere": said outright, as good as the tag */ static const char *const roles[] = { "analyze", "decide", "review", "plan", NULL }; size_t i; for (i = 0; roles[i] != NULL; i++) if (strcmp(tag, roles[i]) == 0) return 3; return 2; } return 0; } static int has_tag(const char *tags, const char *tag) { char buf[160], *t, *save = NULL; snprintf(buf, sizeof(buf), "%s", tags); for (t = strtok_r(buf, ", ", &save); t != NULL; t = strtok_r(NULL, ", ", &save)) { char l[64]; lower(l, sizeof(l), t); if (strcmp(l, tag) == 0) return 1; } return 0; } static int mentions(const struct words *ws, const char *tag) { size_t i; for (i = 0; i < ws->n; i++) if (word_fit(tag, ws->w[i]) > 0) return 1; return 0; } static int filler(const char *w) { static const char *const f[] = { "dieses", "diese", "dieser", "einen", "einer", "eines", "wenn", "wenn", "fuer", "ohne", "oder", "aber", "nicht", "kein", "keine", "mehr", "sehr", "gute", "guter", "gutes", "anderes", "andere", "anderen", "konto", "gleiche", "account", "with", "that", "this", "from", "have", "good", "best", "other", NULL }; size_t i; for (i = 0; f[i] != NULL; i++) if (strcmp(w, f[i]) == 0) return 1; return 0; } static const struct sp_delegate * choose(const struct sp_config *cfg, const char *task, const char *wanted, int *score_out, char *why, size_t whylen) { const struct sp_delegate *best = NULL; struct words *tw, *ww, *aw; int best_score = 0, private_task; double best_frac = 2; size_t i; if (score_out != NULL) *score_out = 0; if (whylen > 0) why[0] = '\0'; tw = calloc(3, sizeof(*tw)); if (tw == NULL) return NULL; ww = tw + 1; aw = tw + 2; split_words(tw, task); split_words(ww, wanted); private_task = mentions(tw, "private") || mentions(ww, "private"); for (i = 0; i < cfg->ndelegates; i++) { const struct sp_delegate *d = &cfg->delegate[i]; char tags[160], reason[192] = "", *t, *save = NULL; int score = 0; struct sp_usage u; size_t k, extra = 0; if (sp_cooldown_until(d->id) != 0) continue; /* benched: at its limit until the reset */ if (!sp_provider_has_key(d)) continue; /* its key variable is not set here */ sp_usage_get(d->id, d->req_limit, d->req_window, d->tok_limit, d->tok_window, &u); if (u.frac >= 1.0) continue; /* its own allowance is used up */ /* a private task is not a matter of score */ if (private_task && !has_tag(d->tags, "private")) continue; snprintf(tags, sizeof(tags), "%s", d->tags); for (t = strtok_r(tags, ",", &save); t != NULL; t = strtok_r(NULL, ",", &save)) { char tag[64]; int best_w = 0, req = 0, hit; const char *how = ""; lower(tag, sizeof(tag), t); while (*tag == ' ') memmove(tag, tag + 1, strlen(tag)); if (tag[0] == '\0') continue; for (k = 0; k < ww->n; k++) if (word_fit(tag, ww->w[k]) > 0) req = 1; for (k = 0; k < tw->n; k++) { hit = word_fit(tag, tw->w[k]); if (hit > best_w) best_w = hit; } if (req) { score += 6; snprintf(reason, sizeof(reason), "requested tag '%s'", tag); } else if (best_w > 0) { score += best_w; how = best_w == 3 ? "task mentions" : "task suggests"; if (reason[0] == '\0') snprintf(reason, sizeof(reason), "%s '%s'", how, tag); } } split_words(aw, d->about); for (k = 0; k < aw->n && extra < 2; k++) { size_t j; if (strlen(aw->w[k]) < 5 || filler(aw->w[k])) continue; for (j = 0; j < tw->n; j++) if (strcmp(aw->w[k], tw->w[j]) == 0) { extra++; if (reason[0] == '\0') snprintf(reason, sizeof(reason), "description matches '%s'", aw->w[k]); break; } } score += (int)extra; if (score > best_score || (score == best_score && best != NULL && (u.frac + 0.05 < best_frac || (u.frac <= best_frac + 0.05 && d->prio > best->prio)))) { best_score = score; best = d; best_frac = u.frac; snprintf(why, whylen, "%s", reason); if (u.frac >= 0) { size_t n = strlen(why); snprintf(why + n, whylen - n, "%s%.0f%% used", n > 0 ? ", " : "", u.frac * 100.0); } } } free(tw); /* nothing fits by tag: the config's default takes it, if it may */ if (best == NULL && cfg->default_id[0] != '\0') { const struct sp_delegate *dd = find_delegate(cfg, cfg->default_id); if (dd != NULL && sp_cooldown_until(dd->id) == 0 && (!private_task || has_tag(dd->tags, "private"))) { best = dd; snprintf(why, whylen, "no tag fits, default '%s'", cfg->default_id); } } if (best == NULL && private_task && whylen > 0) snprintf(why, whylen, "private task and no available delegate " "is tagged private"); /* * A member of a pool stands for the pool: the task fits the member's * tags, but the one to use is whichever the pool's strategy picks now. */ if (best != NULL) { const struct sp_pool *pool = sp_pool_of(cfg, best->id); if (pool != NULL) { const struct sp_delegate *m = sp_pool_pick(cfg, pool, NULL, best->tags, NULL); if (m != NULL && m != best) { size_t n = strlen(why); snprintf(why + n, whylen - n, "%spool %s: %s", n > 0 ? ", " : "", pool->id, m->id); best = m; } } } if (score_out != NULL) *score_out = best_score; return best; } /* * Append 's' to 'b' as one word for a POSIX shell: '...' with every ' written * as '\''. Inside single quotes nothing is special, so the word arrives as it * was - whatever the model put into the task. */ static int shell_quote(struct sp_buf *b, const char *s) { if (sp_buf_puts(b, "'") != 0) return -1; for (; *s != '\0'; s++) { if (*s == '\'') { if (sp_buf_puts(b, "'\\''") != 0) return -1; } else if (sp_buf_add(b, s, 1) != 0) return -1; } return sp_buf_puts(b, "'"); } /* * Where the child of a cli delegate finds the cli transport. The child is this * binary again in one-shot mode, and for a cli delegate it has to load * plugins/cli/cli.so. * * Deriving that path from /proc/self/exe alone assumed the binary sits in the * build tree. An installed splinter sits in $(PREFIX)/bin, 'make install' put * no plugins next to it, so the child loaded nothing, registered no 'cli' * transport and exited 2. The parent reported that 2 as the delegate's exit * code, which made a healthy CLI behind it look broken. * * Order: * $SPLINTER_CLI_PLUGIN explicit, used as given * /plugins/cli/cli.so running from the tree * /../lib/splinter/plugins/cli/cli.so installed layout * SPLINTER_PLUGIN_DIR/plugins/cli/cli.so the build tree, compiled in * Of the three derived ones the first readable file wins; when none exists the * first is returned, so the child's own error names the place that was * expected. */ void sp_delegate_cli_plugin(const char *self, char *out, size_t len) { char dir[512], cand[3][600]; const char *env = getenv("SPLINTER_CLI_PLUGIN"); const char *slash; size_t n = 0, i; if (env != NULL && *env != '\0') { snprintf(out, len, "%s", env); return; } snprintf(dir, sizeof(dir), "%s", self != NULL && *self != '\0' ? self : "splinter"); slash = strrchr(dir, '/'); if (slash != NULL) dir[slash - dir] = '\0'; else snprintf(dir, sizeof(dir), "."); snprintf(cand[n++], sizeof(cand[0]), "%s/plugins/cli/cli.so", dir); snprintf(cand[n++], sizeof(cand[0]), "%s/../lib/splinter/plugins/cli/cli.so", dir); #ifdef SPLINTER_PLUGIN_DIR snprintf(cand[n++], sizeof(cand[0]), "%s/plugins/cli/cli.so", SPLINTER_PLUGIN_DIR); #endif for (i = 0; i < n; i++) if (access(cand[i], R_OK) == 0) break; snprintf(out, len, "%s", cand[i < n ? i : 0]); } /* * The child side of every delegation, single or parallel: build the argument * vector and exec. It used to be written twice, and the two copies had drifted * apart - one ignored 'host' entirely, the other put "ssh" into argv[0] and then * exec'd splinter with it. * * Locally the argv goes straight to execv. Remotely ssh joins its arguments * into one command line for the remote shell, so each one is quoted on the way * and the task cannot become a command over there either. Keys stay home: the * remote host has its own. */ static void exec_delegate(const struct del_ctx *c, const struct sp_delegate *d, const char *task, const char *key_env) { char *argv[24]; int n = 0, i; int cli = strcmp(d->kind, "cli") == 0; int remote = d->host[0] != '\0'; char envname[96], plug[600], clisess[256] = ""; argv[n++] = (char *)c->self; argv[n++] = "--no-config"; argv[n++] = "-p"; argv[n++] = (char *)task; /* * A cli delegate is a program, not an endpoint: the child runs the cli * transport with the configured command, and the token travels in the * environment where the program expects it. */ if (cli) { sp_delegate_cli_plugin(c->self, plug, sizeof(plug)); { char cmd[600]; if (sp_cli_command(d, NULL, cmd, sizeof(cmd)) == 0) (void)setenv("SPLINTER_CLI_CMD", cmd, 1); } if (d->key[0] != '\0' && !remote) { const char *kenv = d->key_env[0] != '\0' ? d->key_env : "CLAUDE_CODE_OAUTH_TOKEN"; (void)setenv(kenv, d->key, 1); } argv[n++] = "--transport"; argv[n++] = "cli"; argv[n++] = "--plugin"; argv[n++] = plug; } else { /* * Anthropic is a built-in vendor shape, not a plugin: the child has * to be told, or it would speak OpenAI at the Messages API. */ if (strcmp(d->kind, "anthropic") == 0) { argv[n++] = "--kind"; argv[n++] = (char *)"anthropic"; } argv[n++] = "--endpoint"; argv[n++] = (char *)d->endpoint; argv[n++] = "--model"; argv[n++] = (char *)d->model; } argv[n++] = "--max-bytes"; argv[n++] = "0"; argv[n++] = "--autonomous"; if (remote) ; /* the remote host has its own keys */ else if (key_env != NULL) { argv[n++] = "--api-key-env"; argv[n++] = (char *)key_env; } else if (d->key[0] != '\0' && !cli) { /* the literal key goes through the environment, never argv */ snprintf(envname, sizeof(envname), "SPLINTER_DELEGATE_KEY_%ld", (long)getpid()); (void)setenv(envname, d->key, 1); argv[n++] = "--api-key-env"; argv[n++] = envname; } else if (!cli && d->nenv > 0) { /* * A provider whose token lives in its env block: the child inherits * the variable (applied just below), and has to be told its name or * it would read the default one and send no auth at all. */ const char *eq = strchr(d->env[0], '='); size_t len = eq != NULL ? (size_t)(eq - d->env[0]) : 0; if (len > 0 && len < sizeof(envname)) { memcpy(envname, d->env[0], len); envname[len] = '\0'; argv[n++] = "--api-key-env"; argv[n++] = envname; } } argv[n] = NULL; /* * env=NAME=VALUE from the delegate line, last so it beats a key from the * environment scan: the line in the file is the more specific instruction. * Remotely there is no environment to inherit, so it goes in front of the * command as `env 'NAME=VALUE' ...`. */ if (!remote) sp_config_apply_env((const char (*)[SP_CONFIG_ENV_LEN])d->env, d->nenv); /* * One cli session per (splinter session, delegate): consecutive calls to * claude0 continue claude0's conversation, claude1 keeps its own. */ { const char *ps = getenv("SPLINTER_CLI_SESSION"); if (cli && !remote) (void)setenv("SPLINTER_CLI_ID", d->id, 1); if (cli && ps != NULL && *ps != '\0') { snprintf(clisess, sizeof(clisess), "%s:%s", ps, d->id); if (!remote) (void)setenv("SPLINTER_CLI_SESSION", clisess, 1); } } if (remote) { struct sp_buf line; char *sshv[8]; size_t e; if (sp_buf_init(&line) != 0) _exit(127); if ((d->nenv > 0 || clisess[0] != '\0' || cli) && sp_buf_puts(&line, "env ") != 0) _exit(127); if (cli) { char kv[64]; snprintf(kv, sizeof(kv), "SPLINTER_CLI_ID=%s", d->id); if (shell_quote(&line, kv) != 0 || sp_buf_puts(&line, " ") != 0) _exit(127); } if (clisess[0] != '\0') { char kv[300]; snprintf(kv, sizeof(kv), "SPLINTER_CLI_SESSION=%s", clisess); if (shell_quote(&line, kv) != 0 || sp_buf_puts(&line, " ") != 0) _exit(127); } for (e = 0; e < d->nenv; e++) if (shell_quote(&line, d->env[e]) != 0 || sp_buf_puts(&line, " ") != 0) _exit(127); for (i = 0; i < n; i++) { if ((i > 0 && sp_buf_puts(&line, " ") != 0) || shell_quote(&line, argv[i]) != 0) _exit(127); } sshv[0] = "ssh"; sshv[1] = "-o"; sshv[2] = "BatchMode=yes"; sshv[3] = "--"; sshv[4] = (char *)d->host; sshv[5] = line.p; sshv[6] = NULL; execvp("ssh", sshv); _exit(127); } execv(c->self, argv); _exit(127); } /* Run the child and collect its answer. */ static void copy_answer(struct sp_buf *dst, const struct sp_buf *src); static int run_child(const struct del_ctx *c, const struct sp_delegate *d, const char *task, struct sp_buf *out, struct sp_buf *err) { int fds[2]; pid_t child; const char *key_env = d->key_env[0] != '\0' ? d->key_env : NULL; sp_usage_record(d->id, 0, 0); if (pipe(fds) != 0) { sp_buf_printf(err, "delegate: pipe: %s", strerror(errno)); return -1; } child = fork(); if (child < 0) { sp_buf_printf(err, "delegate: fork: %s", strerror(errno)); close(fds[0]); close(fds[1]); return -1; } if (child == 0) { (void)dup2(fds[1], STDOUT_FILENO); (void)dup2(fds[1], STDERR_FILENO); close(fds[0]); close(fds[1]); exec_delegate(c, d, task, key_env); } close(fds[1]); { struct pollfd pfd; char chunk[4096]; ssize_t got; for (;;) { pfd.fd = fds[0]; pfd.events = POLLIN; if (poll(&pfd, 1, (int)delegate_timeout_ms(c->cfg)) <= 0) { (void)kill(child, SIGKILL); (void)waitpid(child, NULL, 0); close(fds[0]); sp_buf_printf(err, sp_td("delegate.timeout", "delegate: '%s' timed out"), d->id); return -1; } got = read(fds[0], chunk, sizeof(chunk)); if (got <= 0) break; if (sp_buf_add(out, chunk, (size_t)got) != 0) break; } close(fds[0]); { int st = 0; (void)waitpid(child, &st, 0); /* * The child's own words go with the exit code: "exited 1" * alone hid every rate limit, and a limit nobody can read * cannot bench anyone. A child killed by a signal failed * too, it did not succeed quietly. */ if (!WIFEXITED(st) || WEXITSTATUS(st) != 0) { const char *tail = out->p != NULL ? out->p : ""; size_t tl = strlen(tail); if (tl > 400) tail += tl - 400; sp_buf_printf(err, "delegate: '%s' exited %d: %s", d->id, WIFEXITED(st) ? WEXITSTATUS(st) : -1, tail); return -1; } } } return 0; } /* * How many calls are running per delegate. The tool loop is sequential today, so * this is 0 or 1 - but the limit is what makes parallel delegation safe later, * and a limit nobody checks is a comment. */ static int running[SP_CONFIG_MAX_DELEGATES]; static struct del_ctx ctx; static pthread_mutex_t del_lock; static pthread_once_t del_lock_once = PTHREAD_ONCE_INIT; static void del_lock_init(void){ pthread_mutexattr_t a; pthread_mutexattr_init(&a); pthread_mutexattr_settype(&a, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&del_lock,&a); pthread_mutexattr_destroy(&a); } #define DEL_LOCK() do{ pthread_once(&del_lock_once, del_lock_init); pthread_mutex_lock(&del_lock);}while(0) #define DEL_UNLOCK() pthread_mutex_unlock(&del_lock) /* ---- durable job records (submit/poll/resume-ready) ----------------------- */ static long now_ms(void); static void ensure_dir(const char *path) { if (path && *path) mkdir(path, 0755); } static void jobs_dir(const struct del_ctx *c, char *out, size_t cap) { const char *sd = c ? sp_host_session_dir(c->host) : NULL; if (!sd || !*sd) { if (cap) out[0]='\0'; return; } snprintf(out, cap, "%s/jobs", sd); } static void job_path(const struct del_ctx *c, const char *id, char *out, size_t cap) { char jd[600]; jobs_dir(c, jd, sizeof(jd)); if (!jd[0]) { if (cap) out[0]='\0'; return; } snprintf(out, cap, "%s/%s.json", jd, id); } static void gen_job_id(char *out, size_t cap) { static unsigned seq; struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); snprintf(out, cap, "job-%ld-%d-%u", (long)ts.tv_sec, (int)getpid(), ++seq); } static void json_esc(struct sp_buf *b, const char *s) { const unsigned char *p = (const unsigned char *)(s ? s : ""); while (*p) { if (*p == '"' || *p == '\\') { sp_buf_add(b, "\\", 1); sp_buf_add(b, (const char *)p, 1); } else if (*p == '\n') sp_buf_puts(b, "\\n"); else if (*p == '\r') sp_buf_puts(b, "\\r"); else if (*p == '\t') sp_buf_puts(b, "\\t"); else if (*p < 0x20) sp_buf_printf(b, "\\u%04x", *p); else sp_buf_add(b, (const char *)p, 1); p++; } } struct jobrec { char id[64], state[32], tool[32], delegate_id[96], remote_id[128], plan_task_id[32]; char next_poll_at[64], run_after[64]; long started_ms, ended_ms; int status, attempts, pid; struct sp_buf task, result, err; }; static void jobrec_init(struct jobrec *j) { memset(j, 0, sizeof(*j)); j->status = -1; j->pid = -1; sp_buf_init(&j->task); sp_buf_init(&j->result); sp_buf_init(&j->err); } static void jobrec_free(struct jobrec *j) { sp_buf_free(&j->task); sp_buf_free(&j->result); sp_buf_free(&j->err); } static void write_sidecar(const char *base, const char *ext, const struct sp_buf *b) { char path[760], tmp[780]; FILE *fp; if (!base || !*base || !b || !b->p || b->len == 0) return; snprintf(path, sizeof(path), "%s.%s", base, ext); snprintf(tmp, sizeof(tmp), "%s.tmp", path); fp = fopen(tmp, "w"); if (!fp) return; fwrite(b->p, 1, b->len, fp); fclose(fp); rename(tmp, path); } static void read_sidecar(const char *base, const char *ext, struct sp_buf *out) { char path[760], buf[4096]; FILE *fp; size_t n; if (!base || !*base) return; snprintf(path, sizeof(path), "%s.%s", base, ext); fp = fopen(path, "r"); if (!fp) return; while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) sp_buf_add(out, buf, n); fclose(fp); } static void jobrec_write(const struct del_ctx *c, struct jobrec *j) { char jd[600], path[700], tmp[720], base[700]; struct sp_buf b; FILE *fp; if (!c) return; jobs_dir(c, jd, sizeof(jd)); if (!jd[0]) return; ensure_dir(jd); job_path(c, j->id, path, sizeof(path)); if (!path[0]) return; snprintf(base, sizeof(base), "%s/%s", jd, j->id); snprintf(tmp, sizeof(tmp), "%s.tmp", path); if (sp_buf_init(&b) != 0) return; sp_buf_puts(&b, "{\n"); sp_buf_printf(&b, " \"id\":\"%s\",\n", j->id); sp_buf_printf(&b, " \"state\":\"%s\",\n", j->state[0]?j->state:"unknown"); sp_buf_printf(&b, " \"tool\":\"%s\",\n", j->tool); sp_buf_printf(&b, " \"delegate\":\""); json_esc(&b, j->delegate_id); sp_buf_puts(&b, "\",\n"); sp_buf_printf(&b, " \"remote_id\":\""); json_esc(&b, j->remote_id); sp_buf_puts(&b, "\",\n"); sp_buf_printf(&b, " \"plan_task_id\":\""); json_esc(&b, j->plan_task_id); sp_buf_puts(&b, "\",\n"); sp_buf_printf(&b, " \"pid\":%d,\n \"status\":%d,\n \"attempts\":%d,\n", j->pid, j->status, j->attempts); sp_buf_printf(&b, " \"started_ms\":%ld,\n \"ended_ms\":%ld,\n", j->started_ms, j->ended_ms); sp_buf_printf(&b, " \"next_poll_at\":\"%s\",\n \"run_after\":\"%s\",\n", j->next_poll_at, j->run_after); sp_buf_puts(&b, " \"task\":\""); json_esc(&b, j->task.p?j->task.p:""); sp_buf_puts(&b, "\",\n"); sp_buf_printf(&b, " \"has_result\":%s,\n \"has_error\":%s\n", (j->result.len>0?"true":"false"), (j->err.len>0?"true":"false")); sp_buf_puts(&b, "}\n"); fp = fopen(tmp, "w"); if (fp) { fputs(b.p?b.p:"{}", fp); fclose(fp); rename(tmp, path); } else unlink(tmp); sp_buf_free(&b); if (j->task.len > 0) write_sidecar(base, "task", &j->task); if (j->result.len > 0) write_sidecar(base, "result", &j->result); if (j->err.len > 0) write_sidecar(base, "error", &j->err); } static const char * jget(const char *s, const char *key, char *out, size_t cap) { char pat[96]; const char *p, *q; size_t n; out[0]='\0'; snprintf(pat, sizeof(pat), "\"%s\"", key); p = s ? strstr(s, pat) : NULL; if(!p) return out; p = strchr(p+strlen(pat), ':'); if(!p) return out; while (*p && *p!='\"' && *p!='-' && (*p<'0'||*p>'9') && *p!='t'&&*p!='f'&&*p!='n') p++; if (*p=='\"') { p++; q=strchr(p,'\"'); if(!q) return out; n=(size_t)(q-p); if(n>=cap)n=cap-1; memcpy(out,p,n); out[n]='\0'; } else { n=strcspn(p,", \t\r\n}"); if(n>=cap)n=cap-1; memcpy(out,p,n); out[n]='\0'; } return out; } static int jobrec_read(const struct del_ctx *c, const char *id, struct jobrec *j) { char path[700], buf[8192], jd[600], base[700]; FILE *fp; size_t n; char v[128]; job_path(c,id,path,sizeof(path)); if(!path[0]) return -1; fp=fopen(path,"r"); if(!fp) return -1; n=fread(buf,1,sizeof(buf)-1,fp); fclose(fp); buf[n]='\0'; jobrec_init(j); jget(buf,"id",j->id,sizeof(j->id)); jget(buf,"state",j->state,sizeof(j->state)); jget(buf,"tool",j->tool,sizeof(j->tool)); jget(buf,"delegate",j->delegate_id,sizeof(j->delegate_id)); jget(buf,"remote_id",j->remote_id,sizeof(j->remote_id)); jget(buf,"plan_task_id",j->plan_task_id,sizeof(j->plan_task_id)); jget(buf,"next_poll_at",j->next_poll_at,sizeof(j->next_poll_at)); jget(buf,"run_after",j->run_after,sizeof(j->run_after)); jget(buf,"pid",v,sizeof(v)); j->pid=atoi(v); jget(buf,"status",v,sizeof(v)); j->status=(int)strtol(v,NULL,10); jget(buf,"attempts",v,sizeof(v)); j->attempts=atoi(v); jget(buf,"started_ms",v,sizeof(v)); j->started_ms=strtol(v,NULL,10); jget(buf,"ended_ms",v,sizeof(v)); j->ended_ms=strtol(v,NULL,10); jobs_dir(c,jd,sizeof(jd)); snprintf(base,sizeof(base),"%s/%s",jd,id); read_sidecar(base,"task",&j->task); if (j->task.len == 0) { jget(buf,"task",v,sizeof(v)); if(v[0]) sp_buf_puts(&j->task,v); } read_sidecar(base,"result",&j->result); read_sidecar(base,"error",&j->err); return 0; } /* * Cooldown. A delegate at its limit - claude's "You've hit your weekly limit * · resets 3am (Europe/Lisbon)", a 429, opencode's "usage limit reached" - is * benched until the reset it names, and choose() skips it. The bench is a file * per delegate (~/.splinter/cooldown/, the epoch it may come back), so * every splinter on the machine sees it, not only the one that got the 429. * When the reset cannot be read, an hour: asking again after that costs one * refused call, not a model turn. */ #define COOLDOWN_DEFAULT 3600 static void cooldown_path(const char *id, char *buf, size_t len) { const char *dir = getenv("SPLINTER_COOLDOWN_DIR"); const char *home = getenv("HOME"); if (dir != NULL && *dir != '\0') snprintf(buf, len, "%s/%s", dir, id); else snprintf(buf, len, "%s/.splinter/cooldown/%s", home != NULL ? home : "/tmp", id); } /* the epoch the delegate is benched until, 0 when it is free */ long sp_cooldown_until(const char *id) { char path[700]; FILE *f; long until = 0; cooldown_path(id, path, sizeof(path)); f = fopen(path, "r"); if (f == NULL) return 0; if (fscanf(f, "%ld", &until) != 1) until = 0; fclose(f); if (until <= (long)time(NULL)) { (void)unlink(path); return 0; } return until; } void sp_cooldown_set(const char *id, long until, const char *why) { char path[700], *slash; FILE *f; cooldown_path(id, path, sizeof(path)); slash = strrchr(path, '/'); if (slash != NULL) { *slash = '\0'; (void)mkdir(path, 0700); *slash = '/'; } f = fopen(path, "w"); if (f == NULL) return; fprintf(f, "%ld\n%.300s\n", until, why != NULL ? why : ""); fclose(f); } static int has_ci(const char *hay, const char *needle) { size_t n = strlen(needle); for (; *hay != '\0'; hay++) if (strncasecmp(hay, needle, n) == 0) return 1; return 0; } /* * "resets 3am (Europe/Lisbon)" -> the next 3am in Lisbon. The phrase goes to * date(1) as data: only letters, digits and a few separators survive, and the * whole argument is one quoted word. A time of day already past today means * tomorrow. */ static long parse_reset(const char *e) { const char *p, *q; char when[64] = "", tz[64] = "", arg[160], cmd[256]; size_t n = 0; long t = 0, now = (long)time(NULL); FILE *fp; struct sp_buf line; /* the old claude form: "...limit reached|1755000000" */ p = strchr(e, '|'); if (p != NULL && isdigit((unsigned char)p[1])) { t = strtol(p + 1, NULL, 10); if (t > now) return t; } p = strstr(e, "ready_at="); if (p != NULL && (t = strtol(p + 9, NULL, 10)) > now) return t; p = strstr(e, "resets "); if (p == NULL) p = strstr(e, "reset at "); if (p == NULL) return 0; p = strchr(p, ' ') + 1; if (strncmp(p, "at ", 3) == 0) p += 3; for (q = p; *q != '\0' && *q != '(' && *q != '\n' && *q != '.' && n + 1 < sizeof(when); q++) if (isalnum((unsigned char)*q) || *q == ' ' || *q == ':') when[n++] = *q; when[n] = '\0'; while (n > 0 && when[n - 1] == ' ') when[--n] = '\0'; if (*q == '(') { for (n = 0, q++; *q != '\0' && *q != ')' && n + 1 < sizeof(tz); q++) if (isalnum((unsigned char)*q) || *q == '/' || *q == '_' || *q == '-' || *q == '+') tz[n++] = *q; tz[n] = '\0'; } if (when[0] == '\0') return 0; if (tz[0] != '\0') snprintf(arg, sizeof(arg), "TZ=\"%s\" %s", tz, when); else snprintf(arg, sizeof(arg), "%s", when); if (sp_buf_init(&line) != 0) return 0; if (sp_buf_puts(&line, "date -d ") != 0 || shell_quote(&line, arg) != 0 || sp_buf_puts(&line, " +%s 2>/dev/null") != 0) { sp_buf_free(&line); return 0; } snprintf(cmd, sizeof(cmd), "%s", line.p); sp_buf_free(&line); fp = popen(cmd, "r"); if (fp == NULL) return 0; if (fscanf(fp, "%ld", &t) != 1) t = 0; (void)pclose(fp); if (t <= 0) return 0; if (t <= now) t += 86400; /* "3am" was this morning: it means tomorrow */ return t > now ? t : 0; } /* Is this error a limit, and until when? Returns 1 and sets *until. */ int sp_limit_parse(const char *e, long *until) { long t; *until = 0; if (e == NULL) return 0; if (!(strstr(e, "429") != NULL || has_ci(e, "rate limit") || has_ci(e, "rate_limit") || has_ci(e, "usage limit") || has_ci(e, "weekly limit") || has_ci(e, "daily limit") || has_ci(e, "hit your limit") || has_ci(e, "limit reached") || has_ci(e, "quota") || strstr(e, "WAIT_QUOTA") != NULL)) return 0; t = parse_reset(e); *until = t > 0 ? t : (long)time(NULL) + COOLDOWN_DEFAULT; return 1; } /* * Run d; if it is at its limit, bench it and give the task to the next * delegate that fits - same request, the benched one no longer competes. *dp * ends as the delegate that ran last, and the running[] slot moves with it so * the caller's decrement hits the right one. A busy fallback is not taken: the * limit error stands and the job waits as before. */ static int run_child_fb(const struct del_ctx *c, const struct sp_delegate **dp, const char *task, const char *wanted, struct sp_buf *reply, struct sp_buf *err, struct sp_buf *note) { const struct sp_delegate *d = *dp, *next; size_t tries; int rc; for (tries = 0; ; tries++) { char want[300], why[192]; long until; int score; size_t from, to; sp_buf_clear(reply); sp_buf_clear(err); if ((until = sp_cooldown_until(d->id)) != 0) { /* named explicitly, but benched: do not spend a call */ sp_buf_printf(err, "delegate '%s' at its limit (WAIT_QUOTA " "ready_at=%ld)", d->id, until); rc = -1; } else { rc = run_child(c, d, task, reply, err); if (rc == 0 || !sp_limit_parse(err->p, &until)) break; sp_cooldown_set(d->id, until, err->p); } { char when[32]; time_t tt = (time_t)until; struct tm tm; strftime(when, sizeof(when), "%Y-%m-%d %H:%M", localtime_r(&tt, &tm)); sp_buf_printf(note, "[%s at its limit, benched until %s]\n", d->id, when); } if (tries + 1 >= c->cfg->ndelegates) break; /* what was asked, plus what the benched one was good for */ snprintf(want, sizeof(want), "%s,%s", wanted != NULL ? wanted : "", d->tags); next = choose(c->cfg, task, want, &score, why, sizeof(why)); if (next == NULL || next == d) break; from = (size_t)(d - c->cfg->delegate); to = (size_t)(next - c->cfg->delegate); DEL_LOCK(); if (to < SP_CONFIG_MAX_DELEGATES && running[to] >= next->max_parallel) { DEL_UNLOCK(); break; } if (from < SP_CONFIG_MAX_DELEGATES && running[from] > 0) running[from]--; if (to < SP_CONFIG_MAX_DELEGATES) running[to]++; DEL_UNLOCK(); sp_buf_printf(note, "[falling back to %s]\n", next->id); d = next; *dp = d; } return rc; } static const struct sp_delegate *find_delegate(const struct sp_config *cfg, const char *id); static int looks_transient(const char *e); static int looks_quota_wait(const char *e, long *ready_at); static void link_plan_quota(struct del_ctx *c, const char *plan_task_id, const char *run_after, const char *job_id); static int tool_delegate(const char *args, struct sp_buf *out, void *ctx) { struct del_ctx *c = ctx; struct sp_buf keep, tbuf, reply, err; const char *task, *wanted; const struct sp_delegate *d; char why[192] = ""; int score = 0, task_id = -1; if (sp_buf_init(&keep) != 0 || sp_buf_init(&tbuf) != 0) return -1; task = NULL; wanted = NULL; char plan_task_id[32] = {0}; if (args != NULL && args[0] == '{') { mcp_json *v = mcp_parse(args); if (v != NULL) { const char *t = mcp_arg_string(v, "task"); const char *g = mcp_arg_string(v, "tags"); const char *dn = mcp_arg_string(v, "delegate"); const char *pt = mcp_arg_string(v, "plan_task_id"); if (t != NULL) (void)sp_buf_puts(&keep, t); if (g != NULL && *g) (void)sp_buf_puts(&tbuf, g); else if (dn != NULL && *dn) (void)sp_buf_puts(&tbuf, dn); if (pt && *pt) snprintf(plan_task_id, sizeof(plan_task_id), "%.31s", pt); mcp_json_free(v); task = keep.p; wanted = tbuf.p; } } else task = args; if (task == NULL || *task == '\0') { sp_buf_free(&keep); sp_buf_free(&tbuf); return sp_buf_puts(out, "error: 'task' is required"); } if (c->cfg->ndelegates == 0) { sp_buf_free(&keep); sp_buf_free(&tbuf); return sp_buf_puts(out, "error: no delegate configured " "(add a 'delegate = ...' line to the config)"); } { const struct sp_delegate *ex = (wanted && *wanted) ? find_delegate(c->cfg, wanted) : NULL; if (ex) { d = ex; score = ex->prio; snprintf(why,sizeof(why),"explicit delegate '%s'", ex->id); } else d = choose(c->cfg, task, wanted, &score, why, sizeof(why)); } if (d == NULL) { sp_buf_free(&keep); sp_buf_free(&tbuf); return sp_buf_puts(out, "error: no delegate matches this task"); } if (sp_buf_init(&reply) != 0 || sp_buf_init(&err) != 0) { sp_buf_free(&keep); sp_buf_free(&tbuf); return -1; } { struct jobrec jr; jobrec_init(&jr); gen_job_id(jr.id, sizeof(jr.id)); snprintf(jr.state, sizeof(jr.state), "running"); snprintf(jr.tool, sizeof(jr.tool), "delegate"); snprintf(jr.delegate_id, sizeof(jr.delegate_id), "%s", d->id); if (plan_task_id[0]) snprintf(jr.plan_task_id, sizeof(jr.plan_task_id), "%s", plan_task_id); sp_buf_puts(&jr.task, task); jr.started_ms = now_ms(); jr.attempts = 1; sp_buf_printf(out, "[delegate %s, job %s, score %d, prio %d%s%s]\n", d->id, jr.id, score, d->prio, why[0] != '\0' ? ": " : "", why); jobrec_write(c, &jr); { size_t slot = (size_t)(d - c->cfg->delegate); DEL_LOCK(); if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] >= d->max_parallel) { DEL_UNLOCK(); snprintf(jr.state, sizeof(jr.state), "failed"); sp_buf_puts(&jr.err, "delegate busy (max_parallel)"); jr.ended_ms = now_ms(); jobrec_write(c, &jr); sp_buf_printf(out, "error: delegate '%s' is busy " "(max_parallel %d)\n", d->id, d->max_parallel); jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); sp_buf_free(&keep); sp_buf_free(&tbuf); return 0; } if (slot < SP_CONFIG_MAX_DELEGATES) running[slot]++; DEL_UNLOCK(); } /* * A delegate is work someone else does while we wait: it belongs in the task * panel with its own clock, so 'who is still running' is a fact on screen and * not a guess. */ { char label[80], detail[160]; snprintf(label, sizeof(label), "delegate:%s", d->id); snprintf(detail, sizeof(detail), "%.140s", task); task_id = sp_host_task_begin(c->host, label, detail); } const struct sp_delegate *ran = d; int child_rc = run_child_fb(c, &ran, task, wanted, &reply, &err, out); if (ran != d) { d = ran; snprintf(jr.delegate_id, sizeof(jr.delegate_id), "%s", d->id); } if (child_rc != 0) { sp_host_task_end(c->host, task_id, 1, 0); { size_t slot = (size_t)(d - c->cfg->delegate); DEL_LOCK(); if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] > 0) running[slot]--; DEL_UNLOCK(); } jr.status = 1; jr.ended_ms = now_ms(); if (err.p) sp_buf_puts(&jr.err, err.p); { long ra = 0; if (looks_quota_wait(err.p, &ra)) { snprintf(jr.state, sizeof(jr.state), "waiting_quota"); if (ra>0) { snprintf(jr.run_after,sizeof(jr.run_after),"%ld",ra); snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",ra); } else snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+3600); jobrec_write(c, &jr); link_plan_quota(c, jr.plan_task_id, jr.run_after[0]?jr.run_after:jr.next_poll_at, jr.id); sp_buf_printf(out, "quota: %s\n[job %s: waiting_quota run_after=%s, auto-scheduled]\n", err.p?err.p:"quota", jr.id, jr.run_after); } else if (looks_transient(err.p)) { snprintf(jr.state, sizeof(jr.state), "waiting_poll"); snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+60); jobrec_write(c, &jr); sp_buf_printf(out, "error (transient): %s\n[job %s: waiting_poll, retry with delegate_retry]\n", err.p?err.p:"failed", jr.id); } else { snprintf(jr.state, sizeof(jr.state), "failed"); jobrec_write(c, &jr); sp_buf_printf(out, "error: %s\n[job %s: failed]\n", err.p?err.p:"failed", jr.id); } } jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); sp_buf_free(&keep); sp_buf_free(&tbuf); return 0; } { size_t slot = (size_t)(d - c->cfg->delegate); DEL_LOCK(); if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] > 0) running[slot]--; DEL_UNLOCK(); } sp_host_task_end(c->host, task_id, 0, reply.p != NULL ? strlen(reply.p) / 4 : 0); snprintf(jr.state, sizeof(jr.state), "done"); jr.status = 0; jr.ended_ms = now_ms(); if (reply.p != NULL) { struct sp_buf ans; if (sp_buf_init(&ans) == 0) { copy_answer(&ans, &reply); if (ans.p) sp_buf_puts(&jr.result, ans.p); sp_buf_free(&ans); } copy_answer(out, &reply); } else { sp_buf_puts(out, "(no answer)\n"); sp_buf_puts(&jr.result, "(no answer)\n"); } sp_buf_printf(out, "[job %s: done, poll with delegate_result]\n", jr.id); jobrec_write(c, &jr); jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); sp_buf_free(&keep); sp_buf_free(&tbuf); return 0; } } /* * The decision on its own, so it can be tested and shown: which delegate fits a * task, and why. A pick nobody can explain is a pick nobody can correct. */ /* ---- several delegates at once ------------------------------------------- */ #define PAR_MAX_TASKS 8 struct job { pid_t pid; int fd; struct sp_buf out; const struct sp_delegate *d; int score; char why[160]; char task[256]; char tags[128]; /* as asked, for a fallback's choice */ char note[256]; /* benched / fell back, for the header */ int done; long start_ms; long end_ms; int status; }; static long now_ms(void) { struct timespec ts; (void)clock_gettime(CLOCK_MONOTONIC, &ts); return (long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } /* Drop the child's own log lines; they are diagnostics, not an answer. */ static void copy_answer(struct sp_buf *dst, const struct sp_buf *src) { const char *p; if (src->p == NULL) return; for (p = src->p; *p != '\0'; ) { const char *nl = strchr(p, '\n'); size_t len = nl != NULL ? (size_t)(nl - p) : strlen(p); if (!(len >= 9 && strncmp(p, "splinter:", 9) == 0)) (void)sp_buf_add(dst, p, len + (nl != NULL ? 1 : 0)); if (nl == NULL) break; p = nl + 1; } } /* * Spawn without waiting: the same argv a single delegation builds, but the pipe * comes back to the caller so eight of them can run at the same time. */ static int spawn_job(const struct del_ctx *c, const struct sp_delegate *d, const char *task, struct job *j, struct sp_buf *err) { int fds[2]; pid_t child; if (pipe(fds) != 0) { sp_buf_printf(err, "delegate: pipe: %s", strerror(errno)); return -1; } child = fork(); if (child < 0) { sp_buf_printf(err, "delegate: fork: %s", strerror(errno)); close(fds[0]); close(fds[1]); return -1; } if (child == 0) { (void)dup2(fds[1], STDOUT_FILENO); (void)dup2(fds[1], STDERR_FILENO); close(fds[0]); close(fds[1]); exec_delegate(c, d, task, d->key_env[0] != '\0' ? d->key_env : NULL); } close(fds[1]); /* non-blocking, so a finished child is noticed at once */ (void)fcntl(fds[0], F_SETFL, fcntl(fds[0], F_GETFL, 0) | O_NONBLOCK); j->pid = child; j->fd = fds[0]; return 0; } /* * A parallel task whose delegate answered with its limit: bench that delegate * and start the same task in the same slot on the next one that fits, while * the others keep running. Not taken when the fallback is already at its * max_parallel among the running jobs - then the limit error stands. Returns 1 * when the task runs again. */ static int par_fallback(struct del_ctx *c, struct job *jobs, size_t njobs, size_t i, struct jobrec *jr, struct sp_buf *err) { struct job *j = &jobs[i]; const struct sp_delegate *next; char want[300], why[160], when[32]; long until; int score; size_t k, same = 0, nl; time_t tt; struct tm tm; if (j->out.p == NULL || !sp_limit_parse(j->out.p, &until)) return 0; sp_cooldown_set(j->d->id, until, j->out.p); tt = (time_t)until; strftime(when, sizeof(when), "%Y-%m-%d %H:%M", localtime_r(&tt, &tm)); nl = strlen(j->note); snprintf(j->note + nl, sizeof(j->note) - nl, "[%s at its limit, benched until %s]", j->d->id, when); snprintf(want, sizeof(want), "%s,%s", j->tags, j->d->tags); next = choose(c->cfg, jr->task.p != NULL ? jr->task.p : j->task, want, &score, why, sizeof(why)); if (next == NULL || next == j->d) return 0; for (k = 0; k < njobs; k++) if (k != i && !jobs[k].done && jobs[k].d == next) same++; if ((int)same >= next->max_parallel) { nl = strlen(j->note); snprintf(j->note + nl, sizeof(j->note) - nl, "[%s busy, no fallback]", next->id); return 0; } sp_buf_clear(err); if (spawn_job(c, next, jr->task.p != NULL ? jr->task.p : j->task, j, err) != 0) return 0; sp_buf_clear(&j->out); nl = strlen(j->note); snprintf(j->note + nl, sizeof(j->note) - nl, "[falling back to %s]", next->id); j->d = next; j->score = score; snprintf(j->why, sizeof(j->why), "%s", why); snprintf(jr->delegate_id, sizeof(jr->delegate_id), "%s", next->id); jr->pid = (int)j->pid; jr->attempts++; jobrec_write(c, jr); return 1; } static int tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx) { struct del_ctx *c = ctx; struct job jobs[PAR_MAX_TASKS]; struct jobrec jrec[PAR_MAX_TASKS]; char jids[PAR_MAX_TASKS][64]; size_t njobs = 0, i, running_now = 0; mcp_json *v; const mcp_json *tasks; long start; struct sp_buf err; if (c->cfg->ndelegates == 0) return sp_buf_puts(out, "error: no delegate configured"); if (sp_buf_init(&err) != 0) return -1; v = args != NULL && args[0] == '{' ? mcp_parse(args) : NULL; tasks = v != NULL ? mcp_arg(v, "tasks") : NULL; if (tasks == NULL) { if (v != NULL) mcp_json_free(v); sp_buf_free(&err); return sp_buf_puts(out, "error: 'tasks' is required"); } memset(jobs, 0, sizeof(jobs)); memset(jrec, 0, sizeof(jrec)); memset(jids, 0, sizeof(jids)); for (i = 0; i < PAR_MAX_TASKS; i++) { const mcp_json *t = mcp_array_at(tasks, i); const char *task; const char *tags; const struct sp_delegate *d; if (t == NULL) break; task = mcp_arg_string(t, "task"); tags = mcp_arg_string(t, "tags"); if (task == NULL || *task == '\0') continue; d = choose(c->cfg, task, tags, &jobs[njobs].score, jobs[njobs].why, sizeof(jobs[njobs].why)); if (d == NULL) continue; /* the same limit the single call honours */ { size_t k, same = 0; for (k = 0; k < njobs; k++) if (jobs[k].d == d) same++; if ((int)same >= d->max_parallel) { sp_buf_printf(out, "[%s at max_parallel %d, " "task skipped]\n", d->id, d->max_parallel); continue; } } jobs[njobs].d = d; snprintf(jobs[njobs].tags, sizeof(jobs[njobs].tags), "%s", tags != NULL ? tags : ""); jobrec_init(&jrec[njobs]); gen_job_id(jrec[njobs].id, sizeof(jrec[njobs].id)); snprintf(jids[njobs], sizeof(jids[njobs]), "%s", jrec[njobs].id); if (sp_buf_init(&jobs[njobs].out) != 0) { jobrec_free(&jrec[njobs]); break; } if (spawn_job(c, d, task, &jobs[njobs], &err) != 0) { snprintf(jrec[njobs].state, sizeof(jrec[njobs].state), "failed"); snprintf(jrec[njobs].tool, sizeof(jrec[njobs].tool), "delegate_parallel"); snprintf(jrec[njobs].delegate_id, sizeof(jrec[njobs].delegate_id), "%s", d->id); sp_buf_puts(&jrec[njobs].task, task); if (err.p) sp_buf_puts(&jrec[njobs].err, err.p); jrec[njobs].ended_ms = now_ms(); jobrec_write(c, &jrec[njobs]); sp_buf_free(&jobs[njobs].out); jobrec_free(&jrec[njobs]); continue; } snprintf(jobs[njobs].task, sizeof(jobs[njobs].task), "%s", task); jobs[njobs].start_ms = now_ms(); jobs[njobs].end_ms = 0; jobs[njobs].status = -1; snprintf(jrec[njobs].state, sizeof(jrec[njobs].state), "running"); snprintf(jrec[njobs].tool, sizeof(jrec[njobs].tool), "delegate_parallel"); snprintf(jrec[njobs].delegate_id, sizeof(jrec[njobs].delegate_id), "%s", d->id); sp_buf_puts(&jrec[njobs].task, task); jrec[njobs].started_ms = jobs[njobs].start_ms; jrec[njobs].pid = (int)jobs[njobs].pid; jrec[njobs].attempts = 1; jobrec_write(c, &jrec[njobs]); njobs++; running_now++; } if (v != NULL) mcp_json_free(v); if (njobs == 0) { sp_buf_free(&err); return sp_buf_puts(out, "error: no task could be started"); } /* collect: poll every pipe, nobody waits for the one in front of them */ start = now_ms(); while (running_now > 0) { struct pollfd pfd[PAR_MAX_TASKS]; int nfds = 0, ready; for (i = 0; i < njobs; i++) { if (jobs[i].done || jobs[i].fd < 0) continue; pfd[nfds].fd = jobs[i].fd; pfd[nfds].events = POLLIN; pfd[nfds].revents = 0; nfds++; } if (nfds == 0) break; ready = poll(pfd, (nfds_t)nfds, 1000); if (ready < 0 && errno != EINTR) break; if (now_ms() - start > delegate_timeout_ms(c->cfg)) { sp_buf_puts(out, sp_td("delegate.parallel_timeout", "[parallel: timeout, killing the rest]\n")); break; /* the loop below kills and reaps */ } if (ready <= 0) continue; /* * Drain everything that is there, then ask the kernel whether the * child is gone. Relying on POLLHUP alone left fast jobs marked * "done" only when the slow one finished - every task reported the * same duration, which is exactly the number the planner is supposed * to use to tell a fast model from a slow one. */ for (i = 0; i < njobs; i++) { char chunk[4096]; ssize_t got; if (jobs[i].done || jobs[i].fd < 0) continue; for (;;) { got = read(jobs[i].fd, chunk, sizeof(chunk)); if (got > 0) { if (jobs[i].out.len + (size_t)got <= DELEGATE_MAX_BYTES_CAP) (void)sp_buf_add(&jobs[i].out, chunk, (size_t)got); continue; } break; } { int st = 0; pid_t reaped = waitpid(jobs[i].pid, &st, WNOHANG); if (reaped != jobs[i].pid) continue; /* still running */ jobs[i].end_ms = now_ms(); jobs[i].status = WIFEXITED(st) ? WEXITSTATUS(st) : -1; close(jobs[i].fd); jobs[i].fd = -1; /* at its limit: same slot, next delegate */ if (jobs[i].status != 0 && par_fallback(c, jobs, njobs, i, &jrec[i], &err)) { jobs[i].end_ms = 0; continue; } jobs[i].done = 1; running_now--; { struct sp_buf ans; snprintf(jrec[i].state, sizeof(jrec[i].state), jobs[i].status==0?"done":"failed"); jrec[i].status = jobs[i].status; jrec[i].ended_ms = jobs[i].end_ms; if (sp_buf_init(&ans)==0) { copy_answer(&ans, &jobs[i].out); if (ans.p) sp_buf_puts(&jrec[i].result, ans.p); sp_buf_free(&ans); } jobrec_write(c, &jrec[i]); } } } } /* * Whatever is still running here was left by the timeout or by a poll() * error: kill it, close its pipe and reap it. Before, each timeout left * up to eight zombies and eight open fds behind, and the poll error path * left the children running. */ for (i = 0; i < njobs; i++) { if (jobs[i].done) continue; (void)kill(jobs[i].pid, SIGKILL); if (jobs[i].fd >= 0) { close(jobs[i].fd); jobs[i].fd = -1; } while (waitpid(jobs[i].pid, NULL, 0) < 0 && errno == EINTR) ; jobs[i].done = 1; jobs[i].end_ms = now_ms(); jobs[i].status = -1; snprintf(jrec[i].state, sizeof(jrec[i].state), "interrupted"); jrec[i].status = -1; jrec[i].ended_ms = jobs[i].end_ms; sp_buf_puts(&jrec[i].err, "timeout or interrupted"); jobrec_write(c, &jrec[i]); } /* * The planner needs to know who did what and how long it took - not just * a wall of answers. One header per task, then a summary with the totals * per model, so a slow or failing delegate is visible without reading * every word it produced. */ sp_buf_printf(out, "[parallel: %zu task(s), %ld ms wall]\n", njobs, now_ms() - start); for (i = 0; i < njobs; i++) { long took = jobs[i].end_ms > 0 ? jobs[i].end_ms - jobs[i].start_ms : 0; sp_buf_printf(out, "\n## task %zu | job %s | model %s | score %d | %ld ms | " "exit %d | %zu B%s%s\n", i + 1, jids[i], jobs[i].d->id, jobs[i].score, took, jobs[i].status, jobs[i].out.len, jobs[i].why[0] != '\0' ? " | " : "", jobs[i].why); if (jobs[i].note[0] != '\0') sp_buf_printf(out, "%s\n", jobs[i].note); sp_buf_printf(out, "> %s\n\n", jobs[i].task); if (jobs[i].out.p != NULL) copy_answer(out, &jobs[i].out); else sp_buf_puts(out, "(no answer)\n"); sp_buf_free(&jobs[i].out); jobrec_free(&jrec[i]); } { size_t k; sp_buf_puts(out, "\n## summary\n"); for (k = 0; k < njobs; k++) { size_t m, count = 0; long total = 0; /* one line per model, accumulated */ { size_t earlier = 0; for (m = 0; m < k; m++) if (jobs[m].d == jobs[k].d) earlier++; if (earlier > 0) continue; } for (m = 0; m < njobs; m++) { if (jobs[m].d != jobs[k].d) continue; count++; total += jobs[m].end_ms > 0 ? jobs[m].end_ms - jobs[m].start_ms : 0; } sp_buf_printf(out, "- %s: %zu task(s), %ld ms total\n", jobs[k].d->id, count, total); } } sp_buf_free(&err); return 0; } int sp_delegate_prio(const struct sp_config *cfg, const char *id) { size_t i; if (cfg == NULL || id == NULL) return 0; for (i = 0; i < cfg->ndelegates; i++) if (strcmp(cfg->delegate[i].id, id) == 0) return cfg->delegate[i].prio; return 0; } int sp_delegate_choose(const struct sp_config *cfg, const char *task, const char *tags, char *id, size_t cap, char *why, size_t whylen, int *score) { const struct sp_delegate *d; if (id != NULL && cap > 0) id[0] = '\0'; if (why != NULL && whylen > 0) why[0] = '\0'; d = choose(cfg, task, tags, score, why, whylen); if (d == NULL) return -1; if (id != NULL) snprintf(id, cap, "%s", d->id); return 0; } static int tool_delegate_jobs(const char *args, struct sp_buf *out, void *ctx) { struct del_ctx *c = ctx; char jd[600]; DIR *dp; struct dirent *de; int n = 0; (void)args; jobs_dir(c, jd, sizeof(jd)); if (!jd[0]) return sp_buf_puts(out, "error: no session dir for jobs"); dp = opendir(jd); if (!dp) return sp_buf_puts(out, "(no delegate jobs)\n"); sp_buf_puts(out, "delegate jobs (durable, pollable):\n"); while ((de = readdir(dp)) != NULL) { char *dot, id[128], v[128], buf[4096], path[1024]; FILE *fp; size_t nr; if (de->d_name[0] == '.') continue; dot = strrchr(de->d_name, '.'); if (!dot || strcmp(dot, ".json") != 0) continue; snprintf(id, sizeof(id), "%.*s", (int)(dot - de->d_name), de->d_name); snprintf(path, sizeof(path), "%s/%.255s", jd, de->d_name); fp = fopen(path, "r"); if (!fp) continue; nr = fread(buf, 1, sizeof(buf)-1, fp); fclose(fp); buf[nr]='\0'; jget(buf,"state",v,sizeof(v)); sp_buf_printf(out, " %s state=%s", id, v[0]?v:"?"); jget(buf,"delegate",v,sizeof(v)); if(v[0]) sp_buf_printf(out, " delegate=%s", v); jget(buf,"status",v,sizeof(v)); sp_buf_printf(out, " exit=%s", v[0]?v:"-"); jget(buf,"started_ms",v,sizeof(v)); if(v[0]) sp_buf_printf(out, " started_ms=%s", v); jget(buf,"ended_ms",v,sizeof(v)); if(v[0]) sp_buf_printf(out, " ended_ms=%s", v); jget(buf,"task",v,sizeof(v)); if(v[0]) sp_buf_printf(out, " task=%.80s", v); sp_buf_puts(out, "\n"); n++; if (n >= 100) break; } closedir(dp); if (n == 0) sp_buf_puts(out, " (none)\n"); sp_buf_puts(out, "use delegate_result {\"id\":\"...\"} to poll full result/state\n"); return 0; } static int tool_delegate_result(const char *args, struct sp_buf *out, void *ctx) { struct del_ctx *c = ctx; struct sp_buf keep; struct jobrec jr; const char *id; if (sp_buf_init(&keep) != 0) return -1; id = json_str(args, "id", &keep); if (!id || !*id) id = json_str(args, "job_id", &keep); if (!id || !*id) { /* maybe plain string */ if (args && args[0] && args[0] != '{') { sp_buf_puts(&keep, args); id = keep.p; } } if (!id || !*id) { sp_buf_free(&keep); return sp_buf_puts(out, "error: 'id' (or job_id) is required"); } if (jobrec_read(c, id, &jr) != 0) { sp_buf_printf(out, "error: job not found: %s\n", id); sp_buf_free(&keep); return 0; } sp_buf_printf(out, "job %s\n state=%s tool=%s delegate=%s\n", jr.id, jr.state, jr.tool, jr.delegate_id); sp_buf_printf(out, " exit=%d attempts=%d pid=%d\n", jr.status, jr.attempts, jr.pid); sp_buf_printf(out, " started_ms=%ld ended_ms=%ld\n", jr.started_ms, jr.ended_ms); if (jr.remote_id[0]) sp_buf_printf(out, " remote_id=%s\n", jr.remote_id); if (jr.next_poll_at[0]) sp_buf_printf(out, " next_poll_at=%s\n", jr.next_poll_at); if (jr.run_after[0]) sp_buf_printf(out, " run_after=%s\n", jr.run_after); if (jr.task.p && jr.task.len) sp_buf_printf(out, " task: %s\n", jr.task.p); if (jr.err.p && jr.err.len) sp_buf_printf(out, " error:\n%s\n", jr.err.p); if (jr.result.p && jr.result.len) sp_buf_printf(out, " result:\n%s\n", jr.result.p); else if (strcmp(jr.state, "running")==0 || strcmp(jr.state,"polling")==0 || strcmp(jr.state,"waiting_poll")==0) sp_buf_puts(out, " (no result yet; poll again later)\n"); jobrec_free(&jr); sp_buf_free(&keep); return 0; } static int looks_transient(const char *e) { if (!e) return 0; return strstr(e,"timeout")||strstr(e,"Timeout")||strstr(e,"connect")|| strstr(e,"Connection")||strstr(e,"ssh:")||strstr(e,"network")|| strstr(e,"unreachable")||strstr(e,"reset")||strstr(e,"temporar"); } static int looks_quota_wait(const char *e, long *ready_at) { long until = 0; int r = sp_limit_parse(e, &until); if (ready_at != NULL) *ready_at = r ? until : 0; return r; } static const struct sp_delegate * find_delegate(const struct sp_config *cfg, const char *id) { size_t i; const struct sp_pool *p; if (!cfg || !id) return NULL; for (i = 0; i < cfg->ndelegates; i++) if (strcmp(cfg->delegate[i].id, id) == 0) return &cfg->delegate[i]; /* a pool's name stands for the member the pool picks now */ if ((p = sp_pool_find(cfg, id)) != NULL) { const struct sp_delegate *m = sp_pool_pick(cfg, p, NULL, NULL, NULL); if (m != NULL) return m; for (i = 0; i < cfg->ndelegates; i++) if (strcmp(cfg->delegate[i].id, p->member[0]) == 0) return &cfg->delegate[i]; } return NULL; } static int job_due(const struct jobrec *j, long now) { long ra = 0, np = 0; if (!j) return 0; if (strcmp(j->state,"waiting_quota")!=0 && strcmp(j->state,"waiting_poll")!=0 && strcmp(j->state,"queued")!=0) return 0; if (j->run_after[0]) ra = strtol(j->run_after, NULL, 10); if (j->next_poll_at[0] && j->next_poll_at[0] != '+') np = strtol(j->next_poll_at, NULL, 10); if (ra > 0 && now < ra) return 0; if (np > 0 && now < np) return 0; return 1; } static int tool_delegate_due(const char *args, struct sp_buf *out, void *ctx) { struct del_ctx *c = ctx; char jd[600]; DIR *dp; struct dirent *de; long now = (long)time(NULL); int n = 0; (void)args; jobs_dir(c, jd, sizeof(jd)); if (!jd[0]) return sp_buf_puts(out, "error: no session dir for jobs"); dp = opendir(jd); if (!dp) return sp_buf_puts(out, "(no jobs dir)\n"); sp_buf_puts(out, "due delegate jobs (scheduler view):\n"); while ((de = readdir(dp)) != NULL) { char *dot, id[128], path[1024], buf[4096]; FILE *fp; size_t nr; struct jobrec jr; if (de->d_name[0]=='.') continue; dot=strrchr(de->d_name,'.'); if(!dot||strcmp(dot,".json")!=0) continue; snprintf(id,sizeof(id),"%.*s",(int)(dot-de->d_name),de->d_name); snprintf(path,sizeof(path),"%s/%.255s",jd,de->d_name); fp=fopen(path,"r"); if(!fp) continue; nr=fread(buf,1,sizeof(buf)-1,fp); fclose(fp); buf[nr]='\0'; jobrec_init(&jr); jget(buf,"id",jr.id,sizeof(jr.id)); if(!jr.id[0]) snprintf(jr.id,sizeof(jr.id),"%.63s",id); jget(buf,"state",jr.state,sizeof(jr.state)); jget(buf,"run_after",jr.run_after,sizeof(jr.run_after)); jget(buf,"next_poll_at",jr.next_poll_at,sizeof(jr.next_poll_at)); jget(buf,"delegate",jr.delegate_id,sizeof(jr.delegate_id)); if (job_due(&jr, now)) { sp_buf_printf(out, " %s state=%s delegate=%s run_after=%s next_poll_at=%s\n", jr.id, jr.state, jr.delegate_id, jr.run_after, jr.next_poll_at); n++; } jobrec_free(&jr); if (n>=100) break; } closedir(dp); if (n==0) sp_buf_puts(out, " (none due now)\n"); else sp_buf_puts(out, "retry with delegate_retry {\"id\":\"...\"}\n"); return 0; } int sp_delegate_tick(struct sp_buf *out) { struct del_ctx *c = &ctx; DEL_LOCK(); char jd[600]; DIR *dp; struct dirent *de; long now = (long)time(NULL); char due_id[64] = {0}; int found = 0; jobs_dir(c, jd, sizeof(jd)); if (!jd[0] || !c->cfg) { if (out) sp_buf_puts(out, "scheduler: no session/delegate config"); DEL_UNLOCK(); return 0; } dp = opendir(jd); if (!dp) { if (out) sp_buf_puts(out, "scheduler: no jobs"); DEL_UNLOCK(); return 0; } /* pick first due job (prefer waiting_quota then waiting_poll/queued) */ while ((de = readdir(dp)) != NULL) { char *dot, id[128], path[1024], buf[4096]; FILE *fp; size_t nr; struct jobrec jr; if (de->d_name[0]=='.') continue; dot=strrchr(de->d_name,'.'); if(!dot||strcmp(dot,".json")!=0) continue; snprintf(id,sizeof(id),"%.*s",(int)(dot-de->d_name),de->d_name); snprintf(path,sizeof(path),"%s/%.255s",jd,de->d_name); fp=fopen(path,"r"); if(!fp) continue; nr=fread(buf,1,sizeof(buf)-1,fp); fclose(fp); buf[nr]='\0'; jobrec_init(&jr); jget(buf,"id",jr.id,sizeof(jr.id)); if(!jr.id[0]) snprintf(jr.id,sizeof(jr.id),"%.63s",id); jget(buf,"state",jr.state,sizeof(jr.state)); jget(buf,"run_after",jr.run_after,sizeof(jr.run_after)); jget(buf,"next_poll_at",jr.next_poll_at,sizeof(jr.next_poll_at)); if (job_due(&jr, now)) { snprintf(due_id, sizeof(due_id), "%.63s", jr.id[0]?jr.id:id); found = 1; jobrec_free(&jr); break; } jobrec_free(&jr); } closedir(dp); if (!found) { if (out) sp_buf_puts(out, "scheduler: none due"); DEL_UNLOCK(); return 0; } if (out) sp_buf_printf(out, "scheduler: retrying %s\n", due_id); { int rc = sp_delegate_retry_job(due_id, 0, out); DEL_UNLOCK(); return rc; } } static void link_plan_quota(struct del_ctx *c, const char *plan_task_id, const char *run_after, const char *job_id) { struct sp_buf out, args; if (!c || !c->host || !plan_task_id || !*plan_task_id) return; if (sp_buf_init(&out)!=0 || sp_buf_init(&args)!=0) return; sp_buf_printf(&args, "wait %s %s job:%s", plan_task_id, (run_after && *run_after) ? run_after : "+3600", job_id ? job_id : ""); (void)sp_host_command(c->host, "tasks", args.p ? args.p : "", &out); sp_buf_free(&out); sp_buf_free(&args); } int sp_delegate_retry_job(const char *id, int force, struct sp_buf *out) { struct del_ctx *c = &ctx; struct sp_buf reply, err; const struct sp_delegate *d; struct jobrec jr; int task_id = -1; long now = (long)time(NULL); if (!id || !*id) return sp_buf_puts(out, "error: 'id' required"); if (sp_buf_init(&reply)!=0 || sp_buf_init(&err)!=0) return -1; if (jobrec_read(c,id,&jr)!=0) { sp_buf_printf(out,"error: job not found: %s\n", id); sp_buf_free(&reply); sp_buf_free(&err); return 0; } if (strcmp(jr.state,"done")==0 && !force) { sp_buf_printf(out,"job %s already done (use force=1 to rerun)\n", jr.id); jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); return 0; } if (!force && !job_due(&jr, now) && strcmp(jr.state,"failed")!=0) { sp_buf_printf(out,"job %s not due yet (state=%s run_after=%s next_poll_at=%s); use force=1\n", jr.id, jr.state, jr.run_after, jr.next_poll_at); jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); return 0; } if (jr.delegate_id[0]=='\0' || jr.task.len==0) { sp_buf_puts(out,"error: job missing delegate/task (cannot retry)\n"); jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); return 0; } d = find_delegate(c->cfg, jr.delegate_id); if (!d) { sp_buf_printf(out,"error: delegate '%s' not configured\n", jr.delegate_id); snprintf(jr.state,sizeof(jr.state),"failed"); sp_buf_puts(&jr.err,"delegate not configured"); jr.ended_ms=now_ms(); jobrec_write(c,&jr); jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); return 0; } { size_t slot = (size_t)(d - c->cfg->delegate); DEL_LOCK(); if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] >= d->max_parallel) { DEL_UNLOCK(); snprintf(jr.state,sizeof(jr.state),"waiting_poll"); snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+30); jobrec_write(c,&jr); sp_buf_printf(out,"job %s: delegate busy, requeued waiting_poll\n", jr.id); jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); return 0; } if (slot < SP_CONFIG_MAX_DELEGATES) running[slot]++; DEL_UNLOCK(); } jr.attempts++; snprintf(jr.state,sizeof(jr.state),"running"); jr.started_ms=now_ms(); jr.ended_ms=0; jr.run_after[0]='\0'; jr.next_poll_at[0]='\0'; sp_buf_clear(&jr.result); sp_buf_clear(&jr.err); jobrec_write(c,&jr); { char label[80], detail[160]; snprintf(label,sizeof(label),"delegate:%s",d->id); snprintf(detail,sizeof(detail),"retry %.120s", jr.task.p?jr.task.p:""); task_id = sp_host_task_begin(c->host,label,detail); } sp_buf_printf(out,"[retry job %s -> %s attempt %d]\n", jr.id, d->id, jr.attempts); const struct sp_delegate *ran = d; int child_rc = run_child_fb(c, &ran, jr.task.p?jr.task.p:"", NULL, &reply, &err, out); if (ran != d) { d = ran; snprintf(jr.delegate_id, sizeof(jr.delegate_id), "%s", d->id); } if (child_rc != 0) { sp_host_task_end(c->host,task_id,1,0); { size_t slot=(size_t)(d-c->cfg->delegate); DEL_LOCK(); if(slot0) running[slot]--; DEL_UNLOCK(); } jr.status=1; jr.ended_ms=now_ms(); if (err.p) sp_buf_puts(&jr.err,err.p); { long ra=0; if (looks_quota_wait(err.p,&ra)) { snprintf(jr.state,sizeof(jr.state),"waiting_quota"); if(ra>0){snprintf(jr.run_after,sizeof(jr.run_after),"%ld",ra); snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",ra);} else snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+3600); link_plan_quota(c, jr.plan_task_id, jr.run_after[0]?jr.run_after:jr.next_poll_at, jr.id); } else if (looks_transient(err.p)) { snprintf(jr.state,sizeof(jr.state),"waiting_poll"); snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+60); } else snprintf(jr.state,sizeof(jr.state),"failed"); } jobrec_write(c,&jr); sp_buf_printf(out,"state=%s: %s\n", jr.state, err.p?err.p:"failed"); } else { struct sp_buf ans; { size_t slot=(size_t)(d-c->cfg->delegate); DEL_LOCK(); if(slot0) running[slot]--; DEL_UNLOCK(); } sp_host_task_end(c->host,task_id,0,reply.p?strlen(reply.p)/4:0); snprintf(jr.state,sizeof(jr.state),"done"); jr.status=0; jr.ended_ms=now_ms(); if (sp_buf_init(&ans)==0) { copy_answer(&ans,&reply); if(ans.p) sp_buf_puts(&jr.result,ans.p); copy_answer(out,&reply); sp_buf_free(&ans); } else copy_answer(out,&reply); sp_buf_puts(out,"\nstate=done\n"); jobrec_write(c,&jr); } jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); return 0; } static int tool_delegate_retry(const char *args, struct sp_buf *out, void *ctx) { struct sp_buf keep, fkeep; const char *id, *force_s; int force = 0; (void)ctx; if (sp_buf_init(&keep)!=0 || sp_buf_init(&fkeep)!=0) return -1; id = json_str(args,"id",&keep); if (!id||!*id) id = json_str(args,"job_id",&keep); /* * force gets its own buffer: json_str appends, so parsing it into * 'keep' turned id "job-1" plus force "1" into "job-11". */ force_s = json_str(args,"force",&fkeep); force = (force_s && (strcmp(force_s,"1")==0||strcmp(force_s,"true")==0)); if (!id||!*id) { sp_buf_free(&keep); sp_buf_free(&fkeep); return sp_buf_puts(out,"error: 'id' required"); } { int rc = sp_delegate_retry_job(id, force, out); sp_buf_free(&keep); sp_buf_free(&fkeep); return rc; } } static int tool_delegate_submit(const char *args, struct sp_buf *out, void *ctx) { struct del_ctx *c = ctx; struct sp_buf keep, tbuf, reply, err; const char *task, *wanted; const struct sp_delegate *d; char why[192] = ""; char plan_task_id[32] = {0}; int score = 0, task_id = -1; if (sp_buf_init(&keep) != 0 || sp_buf_init(&tbuf) != 0) return -1; task = NULL; wanted = NULL; if (args != NULL && args[0] == '{') { mcp_json *v = mcp_parse(args); if (v != NULL) { const char *t = mcp_arg_string(v, "task"); const char *g = mcp_arg_string(v, "tags"); const char *dname = mcp_arg_string(v, "delegate"); const char *ptid = mcp_arg_string(v, "plan_task_id"); if (t != NULL) (void)sp_buf_puts(&keep, t); if (g != NULL && *g) (void)sp_buf_puts(&tbuf, g); else if (dname != NULL && *dname) (void)sp_buf_puts(&tbuf, dname); if (ptid && *ptid) snprintf(plan_task_id, sizeof(plan_task_id), "%.31s", ptid); mcp_json_free(v); task = keep.p; wanted = tbuf.p; } } else task = args; if (task == NULL || *task == '\0') { sp_buf_free(&keep); sp_buf_free(&tbuf); return sp_buf_puts(out, "error: 'task' is required"); } if (c->cfg->ndelegates == 0) { sp_buf_free(&keep); sp_buf_free(&tbuf); return sp_buf_puts(out, "error: no delegate configured"); } { const struct sp_delegate *ex = (wanted && *wanted) ? find_delegate(c->cfg, wanted) : NULL; if (ex) { d = ex; score = ex->prio; snprintf(why,sizeof(why),"explicit delegate '%s'", ex->id); } else d = choose(c->cfg, task, wanted, &score, why, sizeof(why)); } if (d == NULL) { sp_buf_free(&keep); sp_buf_free(&tbuf); return sp_buf_puts(out, "error: no delegate matches this task"); } if (sp_buf_init(&reply) != 0 || sp_buf_init(&err) != 0) { sp_buf_free(&keep); sp_buf_free(&tbuf); return -1; } { struct jobrec jr; jobrec_init(&jr); gen_job_id(jr.id, sizeof(jr.id)); snprintf(jr.state, sizeof(jr.state), "submitted"); snprintf(jr.tool, sizeof(jr.tool), "delegate_submit"); if (plan_task_id[0]) snprintf(jr.plan_task_id, sizeof(jr.plan_task_id), "%s", plan_task_id); snprintf(jr.delegate_id, sizeof(jr.delegate_id), "%s", d->id); sp_buf_puts(&jr.task, task); jr.started_ms = now_ms(); jr.attempts = 1; /* durable job exists before attempt (submit contract) */ jobrec_write(c, &jr); sp_buf_printf(out, "[delegate_submit job %s -> %s, score %d%s%s]\n", jr.id, d->id, score, why[0]?" : ":"", why); { size_t slot = (size_t)(d - c->cfg->delegate); DEL_LOCK(); if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] >= d->max_parallel) { DEL_UNLOCK(); snprintf(jr.state, sizeof(jr.state), "waiting_poll"); snprintf(jr.next_poll_at, sizeof(jr.next_poll_at), "%ld", (long)time(NULL)+60); sp_buf_puts(&jr.err, "delegate busy (max_parallel), queued for poll/retry"); jr.ended_ms = now_ms(); jobrec_write(c, &jr); sp_buf_printf(out, "state=waiting_poll (busy). poll: delegate_result {\"id\":\"%s\"}\n", jr.id); jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); sp_buf_free(&keep); sp_buf_free(&tbuf); return 0; } if (slot < SP_CONFIG_MAX_DELEGATES) running[slot]++; DEL_UNLOCK(); } { char label[80], detail[160]; snprintf(label, sizeof(label), "delegate:%s", d->id); snprintf(detail, sizeof(detail), "%.140s", task); task_id = sp_host_task_begin(c->host, label, detail); } snprintf(jr.state, sizeof(jr.state), "running"); jobrec_write(c, &jr); const struct sp_delegate *ran = d; int child_rc = run_child_fb(c, &ran, task, wanted, &reply, &err, out); if (ran != d) { d = ran; snprintf(jr.delegate_id, sizeof(jr.delegate_id), "%s", d->id); } if (child_rc != 0) { sp_host_task_end(c->host, task_id, 1, 0); { size_t slot = (size_t)(d - c->cfg->delegate); DEL_LOCK(); if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] > 0) running[slot]--; DEL_UNLOCK(); } jr.status = 1; jr.ended_ms = now_ms(); { long ra = 0; if (err.p) sp_buf_puts(&jr.err, err.p); if (looks_quota_wait(err.p, &ra)) { snprintf(jr.state, sizeof(jr.state), "waiting_quota"); if (ra > 0) snprintf(jr.run_after, sizeof(jr.run_after), "%ld", ra); if (ra>0) snprintf(jr.next_poll_at, sizeof(jr.next_poll_at), "%ld", ra); else snprintf(jr.next_poll_at, sizeof(jr.next_poll_at), "%ld", (long)time(NULL)+3600); sp_buf_printf(out, "state=waiting_quota (run_after=%ld): %s\nauto-schedulable, poll: delegate_result {\"id\":\"%s\"}\n", ra, err.p?err.p:"quota", jr.id); } else if (looks_transient(err.p)) { snprintf(jr.state, sizeof(jr.state), "waiting_poll"); snprintf(jr.next_poll_at, sizeof(jr.next_poll_at), "%ld", (long)time(NULL)+60); sp_buf_printf(out, "state=waiting_poll (transient): %s\npoll later: delegate_result {\"id\":\"%s\"}\n", err.p?err.p:"failed", jr.id); } else { snprintf(jr.state, sizeof(jr.state), "failed"); sp_buf_printf(out, "state=failed: %s\njob: %s (delegate_result)\n", err.p?err.p:"failed", jr.id); } } jobrec_write(c, &jr); jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); sp_buf_free(&keep); sp_buf_free(&tbuf); return 0; } { size_t slot = (size_t)(d - c->cfg->delegate); DEL_LOCK(); if (slot < SP_CONFIG_MAX_DELEGATES && running[slot] > 0) running[slot]--; DEL_UNLOCK(); } sp_host_task_end(c->host, task_id, 0, reply.p?strlen(reply.p)/4:0); snprintf(jr.state, sizeof(jr.state), "done"); jr.status=0; jr.ended_ms=now_ms(); if (reply.p) { struct sp_buf ans; if(sp_buf_init(&ans)==0){ copy_answer(&ans,&reply); if(ans.p) sp_buf_puts(&jr.result,ans.p); sp_buf_free(&ans); } copy_answer(out,&reply); } else sp_buf_puts(out,"(no answer)\n"); sp_buf_printf(out, "\nstate=done job=%s (poll anytime: delegate_result)\n", jr.id); jobrec_write(c,&jr); jobrec_free(&jr); sp_buf_free(&reply); sp_buf_free(&err); sp_buf_free(&keep); sp_buf_free(&tbuf); return 0; } } int sp_delegate_register(struct sp_registry *r, const struct sp_config *cfg, struct sp_host *host) { struct sp_tool t; ssize_t n; memset(&ctx, 0, sizeof(ctx)); ctx.cfg = cfg; ctx.host = host; /* delegates show up in the task panel */ n = readlink("/proc/self/exe", ctx.self, sizeof(ctx.self) - 1); if (n <= 0) snprintf(ctx.self, sizeof(ctx.self), "splinter"); else ctx.self[n] = '\0'; memset(&t, 0, sizeof(t)); t.name = "delegate"; t.description = "Hand a task to another configured model and return its " "answer. Use it for work another model does better or cheaper."; t.params = "{\"type\":\"object\",\"properties\":{" "\"task\":{\"type\":\"string\",\"description\":\"what to do, " "self-contained\"}," "\"tags\":{\"type\":\"string\",\"description\":\"what kind of work, " "e.g. code or chat\"}}," "\"required\":[\"task\"]}"; t.auth = SP_AUTH_DESTRUCTIVE; /* it runs a whole agent of its own */ t.run = tool_delegate; t.ctx = &ctx; if (sp_registry_add(r, &t) != 0) return -1; memset(&t, 0, sizeof(t)); t.name = "delegate_list"; t.description = "List the configured delegates: id, tags, model, endpoint. " "probe=1 also asks each endpoint which models it really serves."; t.params = "{\"type\":\"object\",\"properties\":{\"probe\":" "{\"type\":\"string\",\"description\":\"'1' to query the endpoints\"}}}"; t.auth = SP_AUTH_READ; t.run = tool_delegate_list; t.ctx = &ctx; if (sp_registry_add(r, &t) != 0) return -1; memset(&t, 0, sizeof(t)); t.name = "delegate_parallel"; t.description = "Hand several tasks to different models at the same time " "and collect the answers."; t.params = "{\"type\":\"object\",\"properties\":{\"tasks\":" "{\"type\":\"array\",\"items\":{\"type\":\"object\"," "\"properties\":{\"task\":{\"type\":\"string\"}," "\"tags\":{\"type\":\"string\"}},\"required\":[\"task\"]}}}," "\"required\":[\"tasks\"]}"; t.auth = SP_AUTH_DESTRUCTIVE; t.run = tool_delegate_parallel; t.ctx = &ctx; if (sp_registry_add(r, &t) != 0) return -1; memset(&t, 0, sizeof(t)); t.name = "delegate_due"; t.description = "List durable delegation jobs due for retry/poll now (waiting_quota/waiting_poll/queued with run_after/next_poll_at reached). Scheduler view."; t.params = "{}"; t.auth = SP_AUTH_READ; t.run = tool_delegate_due; t.ctx = &ctx; if (sp_registry_add(r, &t) != 0) return -1; memset(&t, 0, sizeof(t)); t.name = "delegate_retry"; t.description = "Retry a durable delegation job by id (resumes/re-executes when due or force=1). Updates job state/result; quota/transient failures become waiting_quota/waiting_poll with next_poll_at."; t.params = "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"},\"force\":{\"type\":\"string\",\"description\":\"1 to retry even if not due\"}},\"required\":[\"id\"]}"; t.auth = SP_AUTH_DESTRUCTIVE; t.run = tool_delegate_retry; t.ctx = &ctx; if (sp_registry_add(r, &t) != 0) return -1; memset(&t, 0, sizeof(t)); t.name = "delegate_submit"; t.description = "Submit a delegation as a durable job (submit+poll model): records the job, attempts execution, and returns a job id. On transient/connect failure the job is marked waiting_poll (resumable by a poller/worker); poll state/result with delegate_result."; t.params = "{\"type\":\"object\",\"properties\":{" "\"task\":{\"type\":\"string\",\"description\":\"what to do, self-contained\"}," "\"tags\":{\"type\":\"string\",\"description\":\"what kind of work, e.g. code or chat\"}},\"required\":[\"task\"]}"; t.auth = SP_AUTH_DESTRUCTIVE; t.run = tool_delegate_submit; t.ctx = &ctx; if (sp_registry_add(r, &t) != 0) return -1; memset(&t, 0, sizeof(t)); t.name = "delegate_jobs"; t.description = "List durable delegation jobs (submit/poll): id, state, delegate, exit, times. Jobs persist in the session so results can be polled later."; t.params = "{}"; t.auth = SP_AUTH_READ; t.run = tool_delegate_jobs; t.ctx = &ctx; if (sp_registry_add(r, &t) != 0) return -1; memset(&t, 0, sizeof(t)); t.name = "delegate_result"; t.description = "Poll a durable delegation job by id and return its state/result/error. Works after completion and across later polling (resumable job record)."; t.params = "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"job id from delegate/delegate_submit/delegate_jobs\"}},\"required\":[\"id\"]}"; t.auth = SP_AUTH_READ; t.run = tool_delegate_result; t.ctx = &ctx; return sp_registry_add(r, &t); }