/* * splinter -- the turn loop. * * Copyright (c) 2026 Konrad Lother * SPDX-License-Identifier: BSD-3-Clause * * One turn: append the user message, ask the transport, run the tools it asks * for, repeat until it answers or the step limit is hit. The conversation * lives in sp_conv and survives the turn, so splinter is not an amnesiac * one-shot. * * Invariants, in this order, before any tool runs: * 1. the conversation fits the byte budget, otherwise the turn fails and * nothing is sent (never rely on the endpoint to truncate); * 2. the tool exists in the registry, otherwise the model is told so; * 3. the tool's authorization class is honoured; a denial is reported back * as the observation, not silently skipped. */ #include #include #include #include #include #include #include #include "splinter.h" #include "i18n.h" #include "splinter_plugin.h" #include "ack.h" #include "log.h" #include "usage.h" /* * The terminal as one more approval channel. It must be stoppable: when the * phone answers first, or the request times out, the agent goes on, and a * thread still sitting in fgets() would hold it until somebody pressed Enter. * So it polls the terminal together with a pipe, and a byte on the pipe ends it. */ struct ack_thread { int id; FILE *in; int stop; /* read end of the stop pipe */ }; struct quota_set_ctx { long status; long now; long retry_after_s; }; static void quota_set_fn(struct sp_prov_state *st, void *p) { struct quota_set_ctx *c = p; long ra = 0; if (c->retry_after_s > 0) ra = c->now + c->retry_after_s; else if (c->status == 429 || c->status == 402) ra = c->now + 60; else if (c->status == 529) ra = c->now + 120; if (ra > 0 && st->quota_ready_at < ra) st->quota_ready_at = ra; if (ra > 0) st->last_429_at = c->now; if (ra > 0) snprintf(st->note, sizeof(st->note), "quota %ld ready_at=%ld", c->status, ra); } static void quota_hint(const char *provider, const char *key_id, long status, long retry_after_s) { struct quota_set_ctx c; if (!provider||!*provider||!key_id||!*key_id) return; if (status!=429 && status!=402 && status!=529) return; c.status = status; c.now = (long)time(NULL); c.retry_after_s = retry_after_s; sp_provstate_update(provider, key_id, quota_set_fn, &c); } static void * ack_stdin_thread(void *arg) { struct ack_thread *at = arg; char line[64]; struct pollfd pfd[2]; pfd[0].fd = fileno(at->in); pfd[0].events = POLLIN; pfd[1].fd = at->stop; pfd[1].events = POLLIN; for (;;) { pfd[0].revents = pfd[1].revents = 0; if (poll(pfd, 2, -1) < 0) { if (errno == EINTR) continue; break; } if (pfd[1].revents != 0) break; /* answered elsewhere or expired */ if (pfd[0].revents != 0) { if (fgets(line, sizeof(line), at->in) != NULL) (void)sp_ack_answer(at->id, line[0] == 'y' || line[0] == 'Y', "terminal"); break; } } return NULL; } /* * Approval through the ack mechanism: the request becomes a file, the channels are * fired, and whoever answers first wins - the person at this terminal, a phone, or * a script. Without any channel configured this falls back to the plain prompt, so * nothing starts hanging that used to be synchronous. */ static int ack_approval(struct sp_agent *a, const struct sp_tool *t, const char *args) { const char *chans = getenv("SPLINTER_ACK_CHANNELS"); const char *ttl_s = getenv("SPLINTER_ACK_TTL"); struct sp_buf log; char who[64] = ""; int id, ttl, yes; pthread_t th; int th_started = 0; int stop[2] = { -1, -1 }; struct ack_thread at; if (chans == NULL || *chans == '\0') return -1; ttl = ttl_s != NULL && *ttl_s != '\0' ? atoi(ttl_s) : 120; if (ttl <= 0) ttl = 120; id = sp_ack_request(t->name, args, t->auth == SP_AUTH_MUTATE ? "mutate" : "destructive", ttl); if (id < 0) { /* fail closed, but say why: a silent "denied" sends people hunting */ fprintf(stderr, "splinter: cannot file an approval request in %s " "(missing, not yours, or writable by others): %s denied\n", sp_ack_dir() != NULL ? sp_ack_dir() : "(no ack dir)", t->name); return 0; } if (sp_buf_init(&log) == 0) { (void)sp_ack_notify(id, &log); if (log.p != NULL && *log.p != '\0') fprintf(stderr, "%s", log.p); sp_buf_free(&log); } if (a->cfg->approval_out != NULL) fprintf(a->cfg->approval_out, sp_td("ack.prompt", "approval %d: %s %s (%ds) - 'splinter --ack %d yes' or y/N " "here: "), id, t->name, args, ttl, id); else fprintf(stderr, sp_td("ack.pending", "approval %d: %s %s (%ds)\n"), id, t->name, args, ttl); if (a->cfg->approval_out != NULL) fflush(a->cfg->approval_out); /* the terminal is one more channel, not a special case */ if (a->cfg->approval_in != NULL && pipe(stop) == 0) { at.id = id; at.in = a->cfg->approval_in; at.stop = stop[0]; if (pthread_create(&th, NULL, ack_stdin_thread, &at) == 0) th_started = 1; } yes = sp_ack_wait(id, ttl, who, sizeof(who)); if (th_started) { (void)write(stop[1], "x", 1); (void)pthread_join(th, NULL); } if (stop[0] >= 0) { close(stop[0]); close(stop[1]); } if (yes && who[0] != '\0') fprintf(stderr, sp_td("ack.approved_by", "splinter: approved by %s\n"), who); return yes; } static int ask_operator(struct sp_agent *a, const struct sp_tool *t, const char *args) { char line[64]; int verdict; if (a->cfg->approve != NULL && a->cfg->approve_is_channel) return a->cfg->approve(a->cfg->approve_ctx, t->name, (int)t->auth, args); verdict = ack_approval(a, t, args); if (verdict >= 0) return verdict; if (a->cfg->approve != NULL) return a->cfg->approve(a->cfg->approve_ctx, t->name, (int)t->auth, args); if (a->cfg->approval_out != NULL) { fprintf(a->cfg->approval_out, "run %s (%s) %s? [y/N] ", t->name, t->auth == SP_AUTH_MUTATE ? "mutate" : "destructive", args); fflush(a->cfg->approval_out); } if (a->cfg->approval_in == NULL) return 0; /* fail closed */ if (fgets(line, sizeof(line), a->cfg->approval_in) == NULL) return 0; return (line[0] == 'y' || line[0] == 'Y'); } /* The observation is always written: an error is an observation too. */ /* * 0 = ran (obs is the observation), 1 = a person has to decide first (nothing * ran). have_decision/decision are used by a resume: the decision applies to * the pending calls instead of asking again. */ /* a name against a comma list of names; a trailing '*' is a prefix */ static int in_name_list(const char *list, const char *name) { char buf[512], *t, *save = NULL; snprintf(buf, sizeof(buf), "%s", list); for (t = strtok_r(buf, ", ", &save); t != NULL; t = strtok_r(NULL, ", ", &save)) { size_t n = strlen(t); if (n > 0 && t[n - 1] == '*') { if (strncmp(name, t, n - 1) == 0) return 1; } else if (strcmp(name, t) == 0) return 1; } return 0; } static int policy_allows(const struct sp_tool_policy *p, const struct sp_tool *t) { if (p == NULL) return 1; if (in_name_list(p->deny, t->name)) return 0; if (in_name_list(p->allow, t->name)) return 1; return p->max_auth < 0 || (int)t->auth <= p->max_auth; } static int run_one_call(struct sp_agent *a, const struct sp_toolcall *call, struct sp_buf *obs, int have_decision, int decision) { const struct sp_tool *t; int verdict; a->stats.tool_calls++; t = sp_registry_find(a->reg, call->name); if (t == NULL) { sp_buf_printf(obs, "error: unknown tool '%s'", call->name); return 0; } if (!policy_allows(a->policy, t)) { a->stats.denied++; sp_buf_printf(obs, "denied: '%s' is not available in the '%s' " "agent (%s); ask the user to switch agent (Tab) or use a " "tool that is allowed", t->name, a->policy->name, a->policy->max_auth == 0 ? "read-only" : "restricted"); return 0; } /* * A gate may decide before anybody else: a plugin's policy (kid mode, a * sandbox) can allow a call outright or refuse it with a reason. Only when * no gate has an opinion do the normal rules apply. */ if (a->host != NULL) { char reason[256]; verdict = sp_host_gate(a->host, t->name, (int)t->auth, call->args, reason, sizeof(reason)); if (verdict == 0) { a->stats.denied++; sp_buf_printf(obs, "denied: %s", reason[0] != '\0' ? reason : "by policy"); sp_logf("gate", "%s denied: %s", t->name, reason); return 0; } if (verdict == 1) { if (t->run(call->args, obs, t->ctx) != 0) sp_buf_printf(obs, "error: tool '%s' failed", call->name); return 0; } } if (t->auth != SP_AUTH_READ && !a->cfg->autonomous) { if (have_decision) verdict = decision ? 1 : 0; else { verdict = ask_operator(a, t, call->args); if (verdict == 2) return 1; /* pause; nothing has run */ } if (!verdict) { a->stats.denied++; sp_buf_puts(obs, "error: denied by operator"); return 0; } } if (t->run(call->args, obs, t->ctx) != 0) sp_buf_printf(obs, "error: tool '%s' failed", call->name); return 0; } /* run one call and add its observation; 1 means approval is still required */ static int run_one(struct sp_agent *a, struct sp_conv *conv, const struct sp_toolcall *call, int have_decision, int decision, struct sp_buf *obs, struct sp_buf *err) { struct sp_msg tm; int rc; sp_buf_clear(obs); sp_logf("tool", "%s %s", call->name, call->args != NULL ? call->args : ""); if (a->cfg->tool_begin != NULL) a->cfg->tool_begin(a->cfg->tool_begin_ctx, call->name, call->args); rc = run_one_call(a, call, obs, have_decision, decision); if (rc != 0) return rc; if (a->cfg->tool_end != NULL) a->cfg->tool_end(a->cfg->tool_end_ctx, call->name, obs->p != NULL ? obs->p : ""); sp_logf("observation", "%s", obs->p != NULL ? obs->p : ""); if (obs->p != NULL && strncmp(obs->p, "error", 5) == 0) sp_logf("tool failed", "%s: %s", call->name, obs->p); memset(&tm, 0, sizeof(tm)); tm.role = "tool"; tm.name = call->name; tm.call_id = call->id; tm.content = obs->p; if (sp_conv_add(conv, &tm) != 0) { sp_buf_puts(err, "agent: out of memory"); return -1; } if (a->sess != NULL && sp_session_append(a->sess, "observation", obs->p, err) != 0) return -1; return 0; } /* * The waiter for callers without a screen (-p, the daemon, the servers): say * when the run goes on and sleep until then. 'ctx' points at the longest wait * in seconds; a longer one fails the turn instead, so a limit that lifts next * week does not hold a process for a week. */ int sp_limit_wait_default(void *ctx, long until, const char *why) { const long *maxw = ctx; long now = (long)time(NULL), cap = maxw != NULL && *maxw > 0 ? *maxw : 12 * 3600; char when[32]; struct tm tm; time_t tt = (time_t)until; if (until - now > cap) return 0; strftime(when, sizeof(when), "%Y-%m-%d %H:%M", localtime_r(&tt, &tm)); fprintf(stderr, "splinter: usage limit reached (%.80s); continuing at %s\n", why != NULL ? why : "", when); while ((long)time(NULL) < until) sleep(1); return 1; } /* * A request ran into a usage limit. When the caller can wait, find out when the * limit lifts -- from the status and Retry-After, from "ready_at=", or from the * reset the provider named in its message -- bench the provider until then, * wait, and tell the loop to ask again. 0: not a limit, or not waiting. */ static int limit_retry(struct sp_agent *a, struct sp_buf *err, long status, long retry_after, long ready_at, int *tries) { long now = (long)time(NULL), until = 0; const char *e = err != NULL && err->p != NULL ? err->p : ""; if ((a->cfg->limit_wait == NULL && a->cfg->limit_switch == NULL) || *tries >= 50) return 0; if (ready_at > now) until = ready_at; else if (status == 429 || status == 402 || status == 529) until = now + (retry_after > 0 ? retry_after : (status == 529 ? 120 : 60)); else if (!sp_limit_parse(e, &until)) { const char *r = strstr(e, "ready_at="); until = r != NULL ? strtol(r + 9, NULL, 10) : 0; } else if (strstr(e, "ready_at=") != NULL) until = strtol(strstr(e, "ready_at=") + 9, NULL, 10); if (until <= now) return 0; sp_cooldown_set(sp_usage_active(), until, e); if (a->cfg->limit_switch != NULL && a->cfg->limit_switch(a->cfg->switch_ctx)) { if (err != NULL) sp_buf_clear(err); return 1; } (*tries)++; if (a->cfg->limit_wait == NULL || !a->cfg->limit_wait(a->cfg->limit_ctx, until, e)) return 0; if (err != NULL) sp_buf_clear(err); return 1; } static int agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, struct sp_buf *answer, struct sp_buf *err) { struct sp_buf obs; size_t step, i; int rc = -1, limit_tries = 0; if (sp_buf_init(&obs) != 0) { sp_buf_puts(err, "agent: out of memory"); return -1; } if (resume) { if (!a->has_pending || a->pending_from > a->pending.ncalls) { sp_buf_puts(err, "agent: no turn is waiting for input"); goto out; } for (i = a->pending_from; i < a->pending.ncalls; i++) { int r = run_one(a, conv, &a->pending.calls[i], 1, decision, &obs, err); if (r != 0) { if (r > 0) sp_buf_puts(err, "agent: approval " "needed again"); goto out; } } sp_reply_free(&a->pending); a->has_pending = 0; a->pending_from = 0; } /* * max_steps counts tool rounds, not requests: a turn with N tool rounds * needs N+1 requests, because the last one carries the answer and runs * no tool. Counting requests against max_steps therefore refused the * answer of a turn that had spent exactly its budget and ended in * "step limit (8) reached without an answer" after eight rounds. * So 'step' keeps counting requests (it is also what a quota wait * rewinds), and the budget is judged by the guard below, which lets one * request past the last round - the one that may answer. */ for (step = 0; ; step++) { struct sp_reply reply; size_t sent; memset(&reply, 0, sizeof(reply)); if (a->cfg->cancel != NULL && *a->cfg->cancel) { sp_buf_puts(err, "agent: cancelled by operator"); goto out; } if (a->cfg->steer != NULL) { struct sp_buf steer; if (sp_buf_init(&steer) != 0) goto oom; if (a->cfg->steer(a->cfg->steer_ctx, &steer) > 0 && steer.len > 0) { if (sp_conv_push(conv, "user", NULL, steer.p) != 0) { sp_buf_free(&steer); goto oom; } if (a->sess != NULL) (void)sp_session_append(a->sess, "user", steer.p, err); } sp_buf_free(&steer); } /* compaction happens before the budget is judged, never after */ if (a->host != NULL) { size_t cb = sp_conv_bytes(conv), cn = conv->n; if (sp_host_compact(a->host, conv, a->cfg->max_bytes) > 0) { a->stats.compactions++; if (a->cfg != NULL && a->cfg->on_compact != NULL) a->cfg->on_compact(a->cfg->on_compact_ctx, cb, sp_conv_bytes(conv), cn, conv->n); } } sent = sp_conv_bytes(conv); if (a->cfg->max_bytes > 0 && sent > a->cfg->max_bytes) { sp_buf_printf(err, "agent: conversation budget exceeded " "(~%zu > %zu bytes); nothing sent", sent, a->cfg->max_bytes); goto out; } a->stats.bytes_sent += sent; a->stats.steps++; { struct sp_prov_result pr; enum sp_prov_decision pd; pd = sp_host_provider_preflight(a->host, a->tr.provider, a->tr.key_id, &pr); if (pd == SP_PROV_WAIT_QUOTA || pd == SP_PROV_DENY) { sp_buf_printf(err, "provider quota/policy: %s (ready_at=%ld retry_after=%lds)", pr.reason[0] ? pr.reason : "denied", pr.ready_at, pr.retry_after_s); if (pd == SP_PROV_WAIT_QUOTA && limit_retry(a, err, 0, 0, pr.ready_at, &limit_tries)) { a->stats.steps--; step--; continue; } goto out; } if (pd == SP_PROV_DELAY && pr.retry_after_s > 0) { if (pr.retry_after_s <= 30) sleep((unsigned)pr.retry_after_s); else { sp_buf_printf(err, "provider quota/policy: %s (ready_at=%ld retry_after=%lds)", pr.reason[0] ? pr.reason : "delay", pr.ready_at, pr.retry_after_s); goto out; } } } { int sent_rc; if (a->cfg->stream != NULL && a->tr.send_stream != NULL) sent_rc = a->tr.send_stream(a->tr.ctx, conv, &reply, err, a->cfg->stream, a->cfg->stream_ctx); else sent_rc = a->tr.send(a->tr.ctx, conv, &reply, err); if (sent_rc != 0) { sp_host_provider_account(a->host, a->tr.provider, a->tr.key_id, reply.status, 0, 0); if (limit_retry(a, err, reply.status, reply.retry_after_s, 0, &limit_tries)) { sp_reply_free(&reply); a->stats.steps--; step--; continue; } sp_reply_free(&reply); goto out; } } if (reply.status < 200 || reply.status > 299) { sp_host_provider_account(a->host, a->tr.provider, a->tr.key_id, reply.status, (size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0), (size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0)); quota_hint(a->tr.provider, a->tr.key_id, reply.status, reply.retry_after_s); /* a refused call benches the provider the run is on */ if (reply.status == 429 || reply.status == 402 || reply.status == 529) sp_cooldown_set(sp_usage_active(), (long)time(NULL) + (reply.retry_after_s > 0 ? reply.retry_after_s : 300), "refused (HTTP limit)"); sp_buf_printf(err, "agent: transport status %ld", reply.status); if (limit_retry(a, err, reply.status, reply.retry_after_s, 0, &limit_tries)) { sp_reply_free(&reply); a->stats.steps--; step--; continue; } sp_reply_free(&reply); goto out; } sp_usage_record(sp_usage_active(), reply.tokens_in, reply.tokens_out); a->stats.tokens_in += (size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0); a->stats.tokens_out += (size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0); sp_host_provider_account(a->host, a->tr.provider, a->tr.key_id, reply.status, (size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0), (size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0)); if (reply.ncalls == 0) { const char *text = reply.content != NULL ? reply.content : ""; if (sp_buf_puts(answer, text) != 0 || sp_conv_push(conv, "assistant", NULL, text) != 0) { sp_reply_free(&reply); goto oom; } if (a->sess != NULL && sp_session_append(a->sess, "assistant", text, err) != 0) { sp_reply_free(&reply); goto out; } sp_reply_free(&reply); rc = 0; goto out; } /* * The reply asks for a tool round. 'step' requests have been sent * so far, the first max_steps of which were allowed to run one * round each; when the budget is spent this one may not open * another. It is refused before the assistant message and its * calls enter the conversation, so the turn ends on the last * complete round instead of on a call with no observation. */ if (step >= a->cfg->max_steps) { sp_reply_free(&reply); sp_buf_printf(err, "agent: step limit (%zu) reached without an answer", a->cfg->max_steps); goto out; } { struct sp_msg am; memset(&am, 0, sizeof(am)); am.role = "assistant"; am.content = reply.content; am.calls = reply.calls_json; if (sp_conv_add(conv, &am) != 0) { sp_reply_free(&reply); goto oom; } } for (i = 0; i < reply.ncalls; i++) { int r = run_one(a, conv, &reply.calls[i], 0, 0, &obs, err); if (r == 1) { /* * Pause with the assistant message already in the * conversation; the calls from here on have no * observation yet. The next run resumes them. */ a->pending = reply; memset(&reply, 0, sizeof(reply)); a->pending_from = i; a->has_pending = 1; rc = SP_AGENT_INPUT_REQUIRED; goto out; } if (r != 0) { sp_reply_free(&reply); goto out; } } sp_reply_free(&reply); } oom: sp_buf_puts(err, "agent: out of memory"); out: sp_buf_free(&obs); return rc; } int sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer, struct sp_buf *err) { struct sp_conv local; struct sp_conv *conv; int rc; if (a == NULL || a->reg == NULL || a->cfg == NULL) return -1; if (a->cfg->max_steps == 0) return -1; if (a->has_pending) { sp_buf_puts(err, "agent: a turn is waiting for input"); return -1; } if (a->conv != NULL) { conv = a->conv; } else { sp_conv_init(&local); conv = &local; } sp_buf_clear(answer); /* * A turn gate runs before the model does. Kid mode ends the day here: the * child gets a sentence, the model gets nothing to answer. */ if (a->host != NULL) { char msg[256]; msg[0] = '\0'; if (sp_host_turn_blocked(a->host, msg, sizeof(msg))) { sp_buf_puts(answer, msg[0] != '\0' ? msg : "today is over"); if (conv == &local) sp_conv_free(&local); return 0; } } sp_host_turn(a->host); if (sp_conv_push(conv, "user", NULL, user_text) != 0) { sp_buf_puts(err, "agent: out of memory"); if (conv == &local) sp_conv_free(&local); return -1; } if (a->sess != NULL && sp_session_append(a->sess, "user", user_text, err) != 0) { if (conv == &local) sp_conv_free(&local); return -1; } rc = agent_loop(a, conv, 0, 0, answer, err); if (rc == SP_AGENT_INPUT_REQUIRED && conv == &local) { /* nowhere to resume from: do not leave a dangling pending turn */ sp_reply_free(&a->pending); a->has_pending = 0; a->pending_from = 0; sp_buf_puts(err, "agent: input required without a persistent " "conversation"); rc = -1; } if (conv == &local) sp_conv_free(&local); return rc; } int sp_agent_resume(struct sp_agent *a, int decision, struct sp_buf *answer, struct sp_buf *err) { if (a == NULL || a->cfg == NULL || a->conv == NULL || !a->has_pending) { sp_buf_puts(err, "agent: no turn is waiting for input"); return -1; } sp_buf_clear(answer); return agent_loop(a, a->conv, 1, decision ? 1 : 0, answer, err); }