Files
splinter/src/backend/agent.c
T
lotherk 80f055711d races: five data races fixed, make check-tsan to keep them fixed
Found with ThreadSanitizer over the whole suite, not by reading:

- ack: sp_ack_dir() returned one static buffer. The waiter and the
  answerer (the gateway is both) sprintf'd into each other's path, so an
  approval request could be looked for in the wrong place. One buffer per
  thread now; test_ack asserts the two threads get different addresses.
- mcp: `stopping` was a plain volatile int with no happens-before, so a
  server thread could read 0 after shutdown killed its child and keep
  using buffers that teardown frees. Acquire/release accessors.
- foreign: fr.ready was set before the paths it guards were filled, so a
  second thread returned early and read empty paths; the flag and the host
  handle are now an atomic pair (publish) plus a mutex (the init itself).
- embed: catch_up() read c->path, c->offset and c->id outside the lock. A
  session switch mid-index published the old file's byte offset into the
  new session's index - everything below that offset was never searched
  again. A generation counter makes that run drop its batch, and the
  search path takes its snapshot under the same lock.

Proof, both directions:
- make check-tsan: 45/45 test binaries free of races (new target; the
  tree is rebuilt under TSan and back, like check-asan).
- test_embed's new gated test (a server that holds the batch until the
  session has been switched): without the generation check short.emb ends
  with 4 records, 1 of them leaked from the other session; with it, 1
  and 0. The test is deterministic, so it fails on a plain build too.
- test_ack: reverting to `static char root[]` fails
  "the two threads do not share one buffer".
- make check: all tests passed; make check-asan: 45/45 clean.
2026-11-23 08:30:29 +00:00

1255 lines
37 KiB
C

/*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <poll.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include "splinter.h"
#include "i18n.h"
#include "splinter_plugin.h"
#include "ack.h"
#include "log.h"
#include "mcp.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);
}
/*
* pipe(2) fills both ends or neither, and nothing between here and the
* pipe() call can return, so one guard covers both. gcc's -fanalyzer
* reports stop[1] as leaked here anyway (checked 2026-11-22): the
* warning reproduces with a separate guard per fd too, so it is the
* analyzer losing track of the descriptor through the call to
* sp_ack_wait(), not a path that skips the close.
*/
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) {
struct sp_sess_rec rec;
memset(&rec, 0, sizeof(rec));
rec.role = "tool";
rec.text = obs->p;
rec.name = call->name;
rec.call_id = call->id;
if (sp_session_append_rec(a->sess, &rec, 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;
}
#define SP_NET_RETRIES 3
#define SP_NET_WAIT_S 5
/*
* A tool call with broken JSON is a model step gone wrong, not a broken link:
* the same prompt tends to produce the same call. So each retry says what was
* wrong, and it waits like a network retry does -- five attempts in one
* millisecond bought nothing, which is why the operator still saw the error.
*
* After the last attempt the turn does not die: the model is asked for words
* instead ("look, then continue"), because the work in the session is worth
* more than an error message nobody can act on.
*/
#define SP_BAD_TOOL_TRIES 5
/* mark whether anything was streamed before an error: a retry after that
* would print the same answer a second time */
struct stream_guard {
sp_stream_cb cb;
void *ctx;
int produced;
};
static void
guarded_stream(void *ctx, int kind, const char *text)
{
struct stream_guard *g = ctx;
/*
* Only an answer (or a tool call) makes a retry unsafe. Reasoning that
* was streamed before a provider cut the stream is not an answer: a
* retry may repeat it, but a turn without one would be lost. This is
* why "stream ended with no answer" after a reasoning-only stream used
* to abort with no retry at all.
*/
if (kind == SP_STREAM_TEXT || kind == SP_STREAM_TOOL)
g->produced = 1;
if (g->cb != NULL)
g->cb(g->ctx, kind, text);
}
/*
* Five seconds between retries; SPLINTER_RETRY_WAIT_MS overrides it so the
* tests do not sleep through their own suite, and an operator can shorten a
* long wait on a flaky link.
*/
static int
retry_wait_ms(void)
{
static int ms = -1;
if (ms < 0) {
const char *v = getenv("SPLINTER_RETRY_WAIT_MS");
ms = v != NULL && atoi(v) >= 0 ? atoi(v) : SP_NET_WAIT_S * 1000;
}
return ms;
}
/* sleep in small steps, so Ctrl-C does not have to wait out a retry */
static int
retry_sleep(struct sp_agent *a, int ms)
{
int left = ms;
while (left > 0) {
struct timespec ts;
int step = left > 100 ? 100 : left;
if (a->cfg->cancel != NULL && *a->cfg->cancel)
return 0;
ts.tv_sec = 0;
ts.tv_nsec = (long)step * 1000000L;
(void)nanosleep(&ts, NULL);
left -= step;
}
return 1;
}
/*
* One request, with the retry policy: a failure that left no text on the
* screen is tried again up to three times, five seconds apart. After the
* first streamed chunk a retry would duplicate the answer, so the turn fails
* with the provider's error instead. A 401 or 404 is the configuration's
* answer, not a transient fault, and is not repeated.
*
* 0: reply is the answer; 1: a usage limit was waited out, ask again;
* -1: failed, err explains.
*/
static int
agent_request(struct sp_agent *a, struct sp_conv *conv, struct sp_reply *reply,
struct sp_buf *err, int *limit_tries)
{
struct stream_guard guard;
int attempt;
memset(reply, 0, sizeof(*reply));
guard.cb = a->cfg->stream;
guard.ctx = a->cfg->stream_ctx;
for (attempt = 0; ; attempt++) {
int sent_rc;
guard.produced = 0;
if (guard.cb != NULL && a->tr.send_stream != NULL)
sent_rc = a->tr.send_stream(a->tr.ctx, conv, reply, err,
guarded_stream, &guard);
else
sent_rc = a->tr.send(a->tr.ctx, conv, reply, err);
if (sent_rc == 0 && reply->status >= 200 &&
reply->status <= 299) {
if (a->host != NULL) {
struct sp_judge_next jn;
if (reply->served_by[0] != '\0')
sp_host_set_served_by(a->host,
reply->served_by);
memset(&jn, 0, sizeof(jn));
jn.valid = reply->judge_valid;
jn.next = reply->judge_next;
jn.in = reply->judge_in;
jn.step = reply->judge_step;
jn.every = reply->judge_every;
snprintf(jn.target, sizeof(jn.target), "%s",
reply->judge_target);
snprintf(jn.model, sizeof(jn.model), "%s",
reply->judge_model);
snprintf(jn.cache, sizeof(jn.cache), "%s",
reply->judge_cache);
sp_host_set_judge_next(a->host, &jn);
sp_host_set_cache_mode(a->host,
reply->cache_mode);
}
if (a->cfg->note != NULL)
a->cfg->note(a->cfg->note_ctx, "");
return 0;
}
if (sent_rc != 0) {
sp_host_provider_account(a->host, a->tr.provider,
a->tr.key_id, reply->status, 0, 0);
} else {
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)");
if (reply->status >= 400 && reply->status < 500 &&
reply->content != NULL && reply->content[0] != '\0')
sp_buf_printf(err, "agent: transport status %ld: "
"%.400s", reply->status, reply->content);
else
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);
return 1;
}
/*
* 4xx is the request's answer, not a transient fault: an
* in-stream 400 (a bad tool schema at the judge) must be shown
* once, not retried three times. No status at all is a broken
* connection and is retried.
*/
if (attempt < SP_NET_RETRIES && !guard.produced &&
((sent_rc != 0 && reply->status < 400) ||
reply->status >= 500)) {
int wait = retry_wait_ms();
/* junction's Retry-After is the better guess than ours */
if (reply->retry_after_s > 0) {
long ra = reply->retry_after_s * 1000;
if (ra > 120000)
ra = 120000;
if (ra > wait)
wait = (int)ra;
}
sp_logf("agent", "retry %d/%d in %dms: %s",
attempt + 1, SP_NET_RETRIES, wait,
err->p != NULL ? err->p : "?");
if (a->cfg->note != NULL) {
char line[300];
snprintf(line, sizeof(line), sp_td("ui.retry_note",
"retrying in %d s: %s"), wait / 1000,
err->p != NULL ? err->p : "no answer");
a->cfg->note(a->cfg->note_ctx, line);
}
sp_buf_clear(err);
sp_reply_free(reply);
if (!retry_sleep(a, wait)) {
sp_buf_puts(err,
"agent: cancelled by operator");
return -1;
}
continue;
}
if (a->cfg->note != NULL)
a->cfg->note(a->cfg->note_ctx, "");
/* The caller only reads the reply on success; a terminal failure
* kept the body and the calls of the last attempt alive. */
sp_reply_free(reply);
return -1;
}
}
/*
* Tool arguments that start with an object must be valid JSON, and the whole
* string must be that one object. A bare string is the mock/script shape and
* stays allowed. One model step with "{command:" reached the endpoint as an
* assistant tool_call and made every endpoint answer 500; another sent two
* objects in one string and mcp_parse() quietly took the first, so half the
* work vanished. Validation happens before that message enters the
* conversation.
*/
static int
tool_args_valid(const struct sp_reply *r, size_t *bad)
{
size_t i;
for (i = 0; i < r->ncalls; i++) {
const char *args = r->calls[i].args;
mcp_json *v;
if (args == NULL || args[0] == '\0' || args[0] != '{')
continue;
v = mcp_parse_exact(args);
if (v == NULL) {
if (bad != NULL)
*bad = i;
return 0;
}
mcp_json_free(v);
}
return 1;
}
/*
* Every tool_call of an assistant message needs its tool result, or each
* later request is refused by the endpoint. A round that ends early (a
* failure between calls) answers the calls it did not get to with an error
* observation; when even that cannot be added, the round is taken back out
* of the conversation instead. 'mark' is the index of the assistant message;
* results are appended in call order, so those present answer the first
* calls.
*/
static void
close_round(struct sp_conv *conv, const struct sp_reply *r, size_t mark)
{
struct sp_msg tm;
size_t i, answered = 0;
if (conv == NULL || r == NULL || mark >= conv->n)
return;
for (i = mark + 1; i < conv->n; i++)
if (conv->v[i].role != NULL &&
strcmp(conv->v[i].role, "tool") == 0)
answered++;
for (i = answered; i < r->ncalls; i++) {
memset(&tm, 0, sizeof(tm));
tm.role = "tool";
tm.name = r->calls[i].name;
tm.call_id = r->calls[i].id;
tm.content = "error: not run, the turn ended before this call";
if (sp_conv_add(conv, &tm) != 0)
goto rollback;
}
return;
rollback:
while (conv->n > mark) {
struct sp_msg *m = &conv->v[--conv->n];
free(m->role);
free(m->name);
free(m->call_id);
free(m->content);
free(m->calls);
memset(m, 0, sizeof(*m));
}
}
/* the assistant message that opened the newest tool round, or conv->n */
static size_t
round_mark(const struct sp_conv *conv)
{
size_t i;
for (i = conv->n; i > 0; i--)
if (conv->v[i - 1].role != NULL &&
strcmp(conv->v[i - 1].role, "assistant") == 0 &&
conv->v[i - 1].calls != NULL)
return i - 1;
return conv->n;
}
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, mark;
int rc = -1, limit_tries = 0, bad_tool_tries = 0;
/* the last request asked for words: whatever comes back ends the turn */
int last_chance = 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) {
/* calls before i ran: never run them twice */
a->pending_from = i;
sp_buf_puts(err, "agent: approval needed again");
goto out;
}
if (r != 0) {
/*
* The round cannot be resumed cleanly: answer
* what is left and drop the pending turn, so a
* retry does not run executed calls again.
*/
close_round(conv, &a->pending,
round_mark(conv));
sp_reply_free(&a->pending);
a->has_pending = 0;
a->pending_from = 0;
goto out;
}
a->pending_from = i + 1;
}
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;
}
sp_logf("user", "%s", steer.p);
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 */
{
size_t cb = sp_conv_bytes(conv), cn = conv->n;
size_t cbudget = a->cfg->max_bytes;
int changed = 0;
/*
* The token threshold is the automatic compaction: past
* it, the request is compacted to the target instead of
* waiting for the byte ceiling.
*
* last_in is only known after a turn the provider
* answered with usage. A resumed session starts at 0,
* and a provider that does not report usage leaves it
* there. Such a session grows past every endpoint's
* window, and then the first request fails before it
* can report a size - so compaction never fires and
* every further resume fails the same way. The local
* bytes are always there; the same four bytes per
* token the target below uses turn them into a size
* that can be judged before anything is sent.
*/
if (a->cfg->compact_threshold > 0 &&
a->cfg->compact_target > 0 &&
(a->stats.last_in > a->cfg->compact_threshold ||
cb > a->cfg->compact_threshold * 4))
cbudget = a->cfg->compact_target * 4;
/*
* The engine always builds the host, plugins or not:
* it is how the compactor learns whether the tools
* exist. A fallback here would compact without that
* knowledge and lose the hint.
*/
changed = sp_host_compact(a->host, conv, cbudget);
if (changed > 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 req_rc = agent_request(a, conv, &reply, err,
&limit_tries);
if (req_rc == 1) { /* limit waited out: ask again */
a->stats.steps--;
step--;
continue;
}
if (req_rc != 0)
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);
if (reply.cost > 0)
a->stats.cost += reply.cost;
/*
* Some providers do not report usage on a tool-call step. A zero
* there is "unknown", not "the context became empty": keep the
* last known prompt size, or the status bar drops to 0 after
* every tool call.
*/
if (reply.tokens_in > 0) {
a->stats.last_in = (size_t)reply.tokens_in;
a->stats.last_cached = (size_t)(reply.tokens_cached > 0 ?
reply.tokens_cached : 0);
}
if (reply.tokens_cached > 0)
a->stats.tokens_cached += (size_t)reply.tokens_cached;
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 (last_chance && reply.ncalls > 0) {
/*
* The model was asked not to call a tool and called one
* anyway. It did not run and it will not: the turn ends on
* the words it wrote, and a call it never explained is
* not silently dropped - it is in the log.
*/
sp_logf("agent", "a call came back after the turn was "
"asked for words; it did not run: %.400s",
reply.calls[0].args != NULL ?
reply.calls[0].args : "");
if (reply.content == NULL || reply.content[0] == '\0') {
free(reply.content);
reply.content = strdup(sp_td("agent.badcall_answer",
"I could not send a runnable tool call: the "
"arguments were not valid JSON. Nothing ran. "
"The raw call is in the log; tell me how to "
"continue."));
if (reply.content == NULL) {
sp_reply_free(&reply);
goto oom;
}
}
reply.ncalls = 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;
}
if (reply.ncalls > 0) {
size_t bad = 0;
if (!tool_args_valid(&reply, &bad)) {
/*
* A call the token limit cut off is not a call the model
* could not write: the same request truncates it again,
* so the correction has to ask for a *smaller* call.
*/
int cut_off = strcmp(reply.finish, "length") == 0 ||
strcmp(reply.finish, "max_tokens") == 0;
const char *what = reply.calls[bad].args;
const char *name = reply.calls[bad].name != NULL ?
reply.calls[bad].name : "?";
struct sp_buf note;
int push_rc;
bad_tool_tries++;
/*
* The whole call, not 240 bytes of it: "mal gucken"
* means the operator can read what the model did.
*/
sp_logf("agent", "malformed tool arguments for "
"%s (try %d/%d, %zu bytes, finish=%s%s): %s",
name, bad_tool_tries, SP_BAD_TOOL_TRIES,
what != NULL ? strlen(what) : (size_t)0,
reply.finish[0] != '\0' ? reply.finish : "-",
cut_off ? ", cut off" : "",
what != NULL ? what : "");
sp_buf_clear(err);
if (sp_buf_init(&note) != 0)
goto oom;
if (bad_tool_tries < SP_BAD_TOOL_TRIES) {
/*
* Asking again with the identical prompt asks
* for the identical call. Say what was wrong
* instead, and say it as a user message: a tool
* result without a call before it is refused by
* the endpoint.
*/
if (cut_off)
sp_buf_printf(&note,
"That call (%s) was cut off by the "
"output limit, so its arguments are not "
"valid JSON (%s). Send a smaller call - "
"one command, short arguments - or answer "
"without a tool.", name,
what != NULL && what[0] != '\0' ?
what : "empty");
else
sp_buf_printf(&note,
"That call (%s) was not run: its arguments "
"are not valid JSON (%s). Send it again as one "
"complete JSON object, or answer without a "
"tool.", name,
what != NULL && what[0] != '\0' ?
what : "empty");
} else {
/*
* The last word goes to words. The turn keeps
* its session and the operator gets an answer
* they can act on, instead of a turn that died
* on "model sent malformed tool arguments".
*/
sp_logf("agent", "no valid tool call after "
"%d tries: asking for words instead",
SP_BAD_TOOL_TRIES);
sp_buf_printf(&note,
"Every tool call you sent had arguments that "
"are not valid JSON, so none of them ran. Do "
"not send another call. Answer in plain text: "
"say what you wanted to do, step by step, and "
"what is still open.");
last_chance = 1;
}
push_rc = sp_conv_push(conv, "user", NULL, note.p);
if (push_rc == 0) {
sp_logf("user", "%s", note.p);
if (a->sess != NULL)
(void)sp_session_append(a->sess,
"user", note.p, err);
}
sp_buf_free(&note);
sp_reply_free(&reply);
if (push_rc != 0)
goto oom;
if (last_chance)
continue;
if (a->cfg->note != NULL) {
char line[256];
snprintf(line, sizeof(line),
sp_td("ui.badtool_note",
"broken tool call, trying again "
"in %d s (%d/%d)"),
retry_wait_ms() / 1000, bad_tool_tries,
SP_BAD_TOOL_TRIES);
a->cfg->note(a->cfg->note_ctx, line);
}
if (!retry_sleep(a, retry_wait_ms())) {
sp_buf_puts(err,
"agent: cancelled by operator");
goto out;
}
continue;
}
bad_tool_tries = 0;
}
/*
* 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;
}
mark = conv->n;
{
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;
}
/*
* A turn that asks for tools used to leave no line at
* all, so a resumed session had answers with no calls
* and results with no name. Write the turn with its
* tool_calls; the results follow as they run.
*/
if (a->sess != NULL) {
struct sp_sess_rec rec;
memset(&rec, 0, sizeof(rec));
rec.role = "assistant";
rec.text = reply.content;
rec.calls = reply.calls_json;
if (sp_session_append_rec(a->sess, &rec,
err) != 0) {
sp_reply_free(&reply);
goto out;
}
}
}
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) {
close_round(conv, &reply, mark);
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);
sp_logf("user", "%s", user_text != NULL ? user_text : "");
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);
}