The user's rule: what the config says is the default, -m overrides it for one run, /model overrides it for the running process - and nothing is written to the config or to the session. The session sidecar from the previous change made /model persistent, which is exactly the harness behaviour this rejects. - removed <session>.model writing and restoring; a reopened session starts on the config default or -m, not on the last /model choice. - /new no longer copies the current model into the new session. - Telegram's /model and probe buttons no longer write 90-model.conf; the switch lasts for the gateway process. - existing .model sidecars were moved out of ~/.splinter; the stale 90-model drop-in was moved aside earlier. - test_engine asserts that /model leaves no sidecar and that reopening uses test-model, not test-model-2; test_gateway asserts that no 90-model.conf is written. - docs: "choice lasts for this run and is not saved". Verified with the real config: default is junction/qwen3.6-35b-judged, -m junction/qwen3.6-35b uses qwen3.6-35b for that run, /model switches to claude-haiku for that run and the next start is judged again. make check: all tests passed.
3068 lines
84 KiB
C
3068 lines
84 KiB
C
/*
|
|
* splinter -- the engine every front end talks to.
|
|
*
|
|
* Copyright (c) 2026 Konrad Lother
|
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
*
|
|
* The code in here used to live in two places that could not see each other:
|
|
* main.c built the agent, and src/ui.c ran it -- with the curses thread model,
|
|
* the approval condition variable, the slash commands and the provider
|
|
* switching all inside the drawing code. A second front end had to copy all of
|
|
* it, and the gateway had already started to.
|
|
*
|
|
* Now the engine owns the moving parts and publishes events; the front end
|
|
* owns a screen and a keyboard. Nothing in this file knows what a WINDOW is,
|
|
* and no front end has to know how a turn is started or cancelled.
|
|
*/
|
|
#include <ctype.h>
|
|
#include <errno.h>
|
|
#include <pthread.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <strings.h>
|
|
#include <sys/stat.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
|
|
#include "splinter.h"
|
|
#include "splinter_engine.h"
|
|
#include "splinter_plugin.h"
|
|
#include "agents.h"
|
|
#include "interview.h"
|
|
#include "cmdscript.h"
|
|
#include "config.h"
|
|
#include "folder.h"
|
|
#include "i18n.h"
|
|
#include "log.h"
|
|
#include "mcp.h"
|
|
#include "prompt.h"
|
|
#include "providers.h"
|
|
#include "skills.h"
|
|
#include "swarm.h"
|
|
#include "usage.h"
|
|
|
|
/* /connect: the questions, one answer per line */
|
|
/* one id per engine opened in this process, even within the same second */
|
|
static unsigned g_session_seq;
|
|
|
|
static void
|
|
new_session_id(char *buf, size_t cap)
|
|
{
|
|
snprintf(buf, cap, "sess-%ld-%d-%u", (long)time(NULL), (int)getpid(),
|
|
++g_session_seq);
|
|
}
|
|
|
|
struct engine_cc {
|
|
int active;
|
|
int step;
|
|
char id[64];
|
|
char endpoint[520];
|
|
char model[260];
|
|
char key_env[80];
|
|
};
|
|
|
|
struct sp_engine {
|
|
/* what main handed over; conf is shared, not owned */
|
|
struct sp_config *conf;
|
|
struct sp_agent_config base;
|
|
struct sp_agent ag;
|
|
struct sp_registry reg;
|
|
struct sp_session_info sess;
|
|
struct sp_conv conv;
|
|
struct sp_host *host;
|
|
struct sp_mock mock;
|
|
int have_mock;
|
|
|
|
char prompt_expanded[8192];
|
|
char cur_model[256];
|
|
char cur_endpoint[512];
|
|
/* a /model chosen while a turn runs: applied between requests */
|
|
char pend_model[320];
|
|
int has_pend_model;
|
|
pthread_mutex_t model_lock;
|
|
char theme[48];
|
|
char agent_name[48];
|
|
char home_id[64]; /* provider before a profile moved it */
|
|
|
|
/* agent profiles: Tab switches through them */
|
|
struct sp_agents agents;
|
|
int agent_cur;
|
|
struct sp_tool_policy policy;
|
|
char *base_prompt;
|
|
|
|
/* /connect */
|
|
struct engine_cc cc;
|
|
int quit;
|
|
|
|
/* the fleet, when asked for */
|
|
struct swarm swarm;
|
|
int have_swarm;
|
|
|
|
/* ------------------------------------------------------------- turn */
|
|
pthread_mutex_t lock;
|
|
pthread_cond_t cond;
|
|
pthread_t th;
|
|
int have_thread; /* a thread exists and is joinable */
|
|
int running; /* it has not finished yet */
|
|
volatile int cancel;
|
|
char *turn_text; /* owned; the worker frees it */
|
|
struct sp_agent_config turn_cfg; /* lives as long as the thread */
|
|
struct sp_buf answer, err;
|
|
struct sp_buf live, think; /* the step being streamed */
|
|
struct sp_buf steer; /* text typed during the turn */
|
|
int have_steer;
|
|
size_t steers;
|
|
long max_wait; /* seconds, 0: 12 h */
|
|
|
|
/* the approval a tool is parked on */
|
|
int approve_pending;
|
|
int approve_result;
|
|
char approve_name[64];
|
|
char approve_args[256];
|
|
int approve_auth;
|
|
|
|
/* the last turn, for the sidebar and /status */
|
|
size_t last_ms, last_steps, last_calls;
|
|
size_t turn_out0; /* tokens_out when the turn began */
|
|
size_t turn_in0; /* tokens_in when the turn began */
|
|
double turn_cost0; /* cost when the turn began */
|
|
struct {
|
|
unsigned turns;
|
|
unsigned long ms;
|
|
size_t in, out;
|
|
double cost;
|
|
} judged, plain; /* the two kinds, for /cost */
|
|
size_t last_turn_out; /* output tokens it produced */
|
|
struct timespec turn_t0;
|
|
/*
|
|
* The agent's counters, copied on the thread that owns them (the turn
|
|
* worker or the synchronous caller) and read under e->lock. Reading
|
|
* ag.stats directly from a front-end thread was a data race.
|
|
*/
|
|
struct sp_agent_stats snapshot;
|
|
|
|
/* events, in the order the turn produced them */
|
|
struct sp_event *q;
|
|
size_t nq, capq;
|
|
};
|
|
|
|
static void cmd_model_apply(struct sp_engine *, const char *,
|
|
struct sp_buf *, int);
|
|
static void engine_apply_pending_model(struct sp_engine *);
|
|
|
|
/* --------------------------------------------------------------- events */
|
|
|
|
/* the caller holds e->lock */
|
|
static void
|
|
ev_push_locked(struct sp_engine *e, int kind, long n, const char *a,
|
|
const char *b)
|
|
{
|
|
struct sp_event *ev;
|
|
|
|
if (e->nq == e->capq) {
|
|
size_t nc = e->capq != 0 ? e->capq * 2 : 64;
|
|
struct sp_event *nq = realloc(e->q, nc * sizeof(*nq));
|
|
|
|
if (nq == NULL)
|
|
return;
|
|
e->q = nq;
|
|
e->capq = nc;
|
|
}
|
|
ev = &e->q[e->nq++];
|
|
ev->kind = kind;
|
|
ev->n = n;
|
|
ev->a = a != NULL ? strdup(a) : NULL;
|
|
ev->b = b != NULL ? strdup(b) : NULL;
|
|
if ((a != NULL && ev->a == NULL) || (b != NULL && ev->b == NULL)) {
|
|
free(ev->a);
|
|
free(ev->b);
|
|
e->nq--;
|
|
}
|
|
}
|
|
|
|
static void
|
|
ev_push(struct sp_engine *e, int kind, long n, const char *a, const char *b)
|
|
{
|
|
pthread_mutex_lock(&e->lock);
|
|
ev_push_locked(e, kind, n, a, b);
|
|
pthread_mutex_unlock(&e->lock);
|
|
}
|
|
|
|
int
|
|
sp_engine_poll(struct sp_engine *e, struct sp_event *out)
|
|
{
|
|
if (e == NULL || out == NULL)
|
|
return 0;
|
|
pthread_mutex_lock(&e->lock);
|
|
if (e->nq == 0) {
|
|
pthread_mutex_unlock(&e->lock);
|
|
return 0;
|
|
}
|
|
*out = e->q[0];
|
|
memmove(&e->q[0], &e->q[1], (e->nq - 1) * sizeof(e->q[0]));
|
|
e->nq--;
|
|
pthread_mutex_unlock(&e->lock);
|
|
return 1;
|
|
}
|
|
|
|
void
|
|
sp_engine_event_free(struct sp_event *ev)
|
|
{
|
|
if (ev == NULL)
|
|
return;
|
|
free(ev->a);
|
|
free(ev->b);
|
|
ev->a = ev->b = NULL;
|
|
ev->kind = SP_EV_NONE;
|
|
}
|
|
|
|
static void snapshot_stats(struct sp_engine *);
|
|
static int capture_interview(struct sp_engine *, struct sp_buf *);
|
|
|
|
/* ------------------------------------------------------------- snapshot */
|
|
|
|
int
|
|
sp_engine_state(struct sp_engine *e, struct sp_engine_state *st)
|
|
{
|
|
if (e == NULL || st == NULL)
|
|
return -1;
|
|
memset(st, 0, sizeof(*st));
|
|
if (e->host != NULL)
|
|
sp_host_set_model(e->host, e->cur_model);
|
|
snprintf(st->model, sizeof(st->model), "%s", e->cur_model);
|
|
snprintf(st->endpoint, sizeof(st->endpoint), "%s", e->cur_endpoint);
|
|
snprintf(st->agent, sizeof(st->agent), "%s", e->agent_name);
|
|
snprintf(st->session, sizeof(st->session), "%s", e->sess.id);
|
|
snprintf(st->dir, sizeof(st->dir), "%s", e->sess.dir);
|
|
snprintf(st->theme, sizeof(st->theme), "%s", e->theme);
|
|
pthread_mutex_lock(&e->lock);
|
|
st->tokens_in = e->snapshot.tokens_in;
|
|
st->tokens_out = e->snapshot.tokens_out;
|
|
st->cost = e->snapshot.cost;
|
|
st->ctx_used = e->snapshot.last_in;
|
|
st->cached = e->snapshot.last_cached;
|
|
st->turn_tokens_out = e->running && e->snapshot.tokens_out >=
|
|
e->turn_out0 ? e->snapshot.tokens_out - e->turn_out0 :
|
|
(e->running ? 0 : e->last_turn_out);
|
|
st->steps = e->snapshot.steps;
|
|
st->calls = e->snapshot.tool_calls;
|
|
st->compactions = e->snapshot.compactions;
|
|
st->last_ms = e->last_ms;
|
|
st->last_steps = e->last_steps;
|
|
st->last_calls = e->last_calls;
|
|
st->busy = e->running;
|
|
st->quit = e->quit;
|
|
st->waiting = e->approve_pending;
|
|
st->agents_n = (int)e->agents.n;
|
|
st->agent_cur = e->agent_cur;
|
|
pthread_mutex_unlock(&e->lock);
|
|
if (e->conf != NULL) {
|
|
const char *active = sp_usage_active();
|
|
struct sp_provider p;
|
|
size_t idx;
|
|
|
|
st->ctx_max = e->conf->ctx;
|
|
if (active != NULL && *active != '\0' &&
|
|
sp_provider_find(e->conf, active, &idx) &&
|
|
sp_provider_at(e->conf, idx, &p) == 0 && p.ctx > 0)
|
|
st->ctx_max = p.ctx;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* ------------------------------------------------------------- accessors */
|
|
|
|
struct sp_agent *sp_engine_agent(struct sp_engine *e) { return &e->ag; }
|
|
struct sp_host *sp_engine_host(struct sp_engine *e) { return e->host; }
|
|
struct sp_config *sp_engine_config(struct sp_engine *e) { return e->conf; }
|
|
struct sp_registry *sp_engine_registry(struct sp_engine *e) { return &e->reg; }
|
|
struct swarm *sp_engine_swarm(struct sp_engine *e) { return e->have_swarm ? &e->swarm : NULL; }
|
|
const struct sp_conv *sp_engine_conv(struct sp_engine *e) { return &e->conv; }
|
|
|
|
void
|
|
sp_engine_set_theme(struct sp_engine *e, const char *name)
|
|
{
|
|
if (e == NULL)
|
|
return;
|
|
snprintf(e->theme, sizeof(e->theme), "%s", name != NULL ? name : "");
|
|
}
|
|
|
|
void
|
|
sp_engine_set_stream(struct sp_engine *e, sp_stream_cb cb, void *ctx)
|
|
{
|
|
if (e == NULL)
|
|
return;
|
|
e->base.stream = cb;
|
|
e->base.stream_ctx = ctx;
|
|
}
|
|
|
|
const char *
|
|
sp_engine_state_dir(struct sp_engine *e) { return e->sess.dir; }
|
|
|
|
size_t
|
|
sp_engine_models(struct sp_engine *e, struct sp_model_choice *v, size_t max)
|
|
{
|
|
if (e == NULL)
|
|
return 0;
|
|
return sp_provider_choices(e->conf, e->cur_model, v, max);
|
|
}
|
|
|
|
/*
|
|
* The endpoint says what it really serves; the configured model may be one of
|
|
* several aliases or not listed at all. Only the provider the session is on is
|
|
* asked: /model with no argument must open at once, and one GET is enough to
|
|
* show the rest of that endpoint's menu.
|
|
*/
|
|
size_t
|
|
sp_engine_served_models(struct sp_engine *e, struct sp_model_choice *v,
|
|
size_t max)
|
|
{
|
|
struct sp_provider p;
|
|
struct sp_buf ids, perr;
|
|
const char *act;
|
|
char *m, *save = NULL;
|
|
size_t i, n = 0, np;
|
|
|
|
if (e == NULL || e->conf == NULL || v == NULL || max == 0 ||
|
|
e->cur_endpoint[0] == '\0')
|
|
return 0;
|
|
memset(&p, 0, sizeof(p));
|
|
act = sp_usage_active();
|
|
np = sp_provider_count(e->conf);
|
|
for (i = 0; i < np; i++) {
|
|
struct sp_provider q;
|
|
|
|
if (sp_provider_at(e->conf, i, &q) != 0)
|
|
continue;
|
|
if ((act != NULL && *act != '\0' &&
|
|
strcmp(q.id, act) == 0) ||
|
|
strcmp(q.endpoint, e->cur_endpoint) == 0) {
|
|
p = q;
|
|
break;
|
|
}
|
|
}
|
|
if (p.id[0] == '\0') {
|
|
/* --endpoint/--model without a provider block */
|
|
snprintf(p.id, sizeof(p.id), "%s",
|
|
act != NULL && *act != '\0' ? act : "main");
|
|
snprintf(p.kind, sizeof(p.kind), "%s", e->conf->kind);
|
|
snprintf(p.endpoint, sizeof(p.endpoint), "%s", e->cur_endpoint);
|
|
snprintf(p.model, sizeof(p.model), "%s", e->cur_model);
|
|
snprintf(p.key_env, sizeof(p.key_env), "%s", e->conf->key_env);
|
|
}
|
|
if (p.endpoint[0] == '\0' || strcmp(p.kind, "cli") == 0)
|
|
return 0;
|
|
if (sp_buf_init(&ids) != 0)
|
|
return 0;
|
|
if (sp_buf_init(&perr) != 0) {
|
|
sp_buf_free(&ids);
|
|
return 0;
|
|
}
|
|
if (sp_provider_served(&p, &ids, &perr) == 0 && ids.p != NULL) {
|
|
for (m = strtok_r(ids.p, "\n", &save);
|
|
m != NULL && n < max; m = strtok_r(NULL, "\n", &save)) {
|
|
if (*m == '\0' || strcmp(m, p.model) == 0)
|
|
continue;
|
|
snprintf(v[n].sel, sizeof(v[n].sel), "%s/%s",
|
|
sp_provider_label(p.id), m);
|
|
snprintf(v[n].label, sizeof(v[n].label), "%s/%s",
|
|
sp_provider_label(p.id), m);
|
|
v[n].current = strcmp(m, e->cur_model) == 0;
|
|
n++;
|
|
}
|
|
}
|
|
sp_buf_free(&ids);
|
|
sp_buf_free(&perr);
|
|
return n;
|
|
}
|
|
|
|
/* <session dir>/<id>.agent: the profile a session was left in */
|
|
static void
|
|
profile_path(struct sp_engine *e, char *buf, size_t cap)
|
|
{
|
|
snprintf(buf, cap, "%s/%s.agent", e->sess.dir, e->sess.id);
|
|
}
|
|
|
|
static void
|
|
profile_save(struct sp_engine *e)
|
|
{
|
|
char path[700];
|
|
FILE *f;
|
|
|
|
if (e->agent_name[0] == '\0')
|
|
return;
|
|
profile_path(e, path, sizeof(path));
|
|
f = fopen(path, "w");
|
|
if (f == NULL)
|
|
return;
|
|
fprintf(f, "%s\n", e->agent_name);
|
|
fclose(f);
|
|
(void)chmod(path, 0600);
|
|
}
|
|
|
|
/*
|
|
* The transcript note after a successful /model. The choice lives only in
|
|
* this engine: nothing is written to the config and nothing to the session,
|
|
* so the next start is the config (or -m), not the last thing someone tried.
|
|
*/
|
|
static void
|
|
session_model_note(struct sp_engine *e, const char *sel, struct sp_buf *out,
|
|
const char *model, const char *provider)
|
|
{
|
|
(void)e;
|
|
(void)sel;
|
|
sp_buf_printf(out, sp_t("model.switched"), model, provider);
|
|
}
|
|
|
|
static int
|
|
profile_load(struct sp_engine *e, char *buf, size_t cap)
|
|
{
|
|
char path[700], line[64];
|
|
FILE *f;
|
|
|
|
profile_path(e, path, sizeof(path));
|
|
f = fopen(path, "r");
|
|
if (f == NULL)
|
|
return 0;
|
|
if (fgets(line, sizeof(line), f) == NULL) {
|
|
fclose(f);
|
|
return 0;
|
|
}
|
|
fclose(f);
|
|
line[strcspn(line, "\r\n")] = '\0';
|
|
if (line[0] == '\0')
|
|
return 0;
|
|
snprintf(buf, cap, "%.47s", line);
|
|
return 1;
|
|
}
|
|
|
|
const char *
|
|
sp_engine_session_id(struct sp_engine *e) { return e->sess.id; }
|
|
|
|
int
|
|
sp_engine_agents(struct sp_engine *e) { return (int)e->agents.n; }
|
|
|
|
int
|
|
sp_engine_agent_cur(struct sp_engine *e) { return e->agent_cur; }
|
|
|
|
const char *
|
|
sp_engine_agent_name(struct sp_engine *e, int idx)
|
|
{
|
|
if (e == NULL || idx < 0 || (size_t)idx >= e->agents.n)
|
|
return "";
|
|
return e->agents.v[idx].name;
|
|
}
|
|
|
|
/* ------------------------------------------------------------ formatting */
|
|
|
|
/*
|
|
* A tool call as a person reads it. The model sends {"command":"ls 2\u003e\u00261"};
|
|
* what belongs on the screen is command: ls 2>&1 . Strings are unescaped,
|
|
* numbers and booleans kept, anything nested is left as it came.
|
|
*
|
|
* Kept in the engine, not in a front end: the transcript row, the approval
|
|
* question and a GUI's call list must all name the same call the same way.
|
|
*/
|
|
static void
|
|
pretty_args(const char *json, char *out, size_t cap)
|
|
{
|
|
const char *p = json;
|
|
size_t n = 0;
|
|
int first = 1;
|
|
|
|
out[0] = '\0';
|
|
while (*p == ' ')
|
|
p++;
|
|
if (*p != '{') {
|
|
snprintf(out, cap, "%s", json);
|
|
return;
|
|
}
|
|
p++;
|
|
while (*p != '\0' && *p != '}' && n + 8 < cap) {
|
|
char key[48];
|
|
size_t k = 0;
|
|
|
|
while (*p == ' ' || *p == ',')
|
|
p++;
|
|
if (*p != '"')
|
|
break;
|
|
p++;
|
|
while (*p != '\0' && *p != '"' && k + 1 < sizeof(key))
|
|
key[k++] = *p++;
|
|
key[k] = '\0';
|
|
if (*p == '"')
|
|
p++;
|
|
while (*p == ' ' || *p == ':')
|
|
p++;
|
|
if (!first)
|
|
n += (size_t)snprintf(out + n, cap - n, " ");
|
|
first = 0;
|
|
n += (size_t)snprintf(out + n, cap - n, "%s: ", key);
|
|
if (*p == '"') {
|
|
p++;
|
|
while (*p != '\0' && *p != '"' && n + 4 < cap) {
|
|
if (*p == '\\' && p[1] != '\0') {
|
|
p++;
|
|
if (*p == 'n') {
|
|
out[n++] = ' ';
|
|
} else if (*p == 't') {
|
|
out[n++] = ' ';
|
|
} else if (*p == 'u' && strlen(p) >= 5) {
|
|
unsigned cp = 0;
|
|
int i;
|
|
|
|
for (i = 1; i <= 4; i++) {
|
|
char c = p[i];
|
|
|
|
cp = cp * 16 + (unsigned)(c >= 'a' ?
|
|
c - 'a' + 10 : c >= 'A' ?
|
|
c - 'A' + 10 : c - '0');
|
|
}
|
|
p += 4;
|
|
if (cp < 0x80)
|
|
out[n++] = (char)cp;
|
|
else if (cp < 0x800) {
|
|
out[n++] = (char)(0xc0 | (cp >> 6));
|
|
out[n++] = (char)(0x80 | (cp & 0x3f));
|
|
} else {
|
|
out[n++] = (char)(0xe0 | (cp >> 12));
|
|
out[n++] = (char)(0x80 | ((cp >> 6) & 0x3f));
|
|
out[n++] = (char)(0x80 | (cp & 0x3f));
|
|
}
|
|
} else
|
|
out[n++] = *p;
|
|
p++;
|
|
continue;
|
|
}
|
|
out[n++] = *p++;
|
|
}
|
|
if (*p == '"')
|
|
p++;
|
|
} else {
|
|
/* a number, a boolean, an object: as it is, up to the next key */
|
|
int depth = 0;
|
|
|
|
while (*p != '\0' && n + 4 < cap) {
|
|
if (*p == '{' || *p == '[')
|
|
depth++;
|
|
else if (*p == '}' || *p == ']') {
|
|
if (depth == 0)
|
|
break;
|
|
depth--;
|
|
} else if (*p == ',' && depth == 0)
|
|
break;
|
|
out[n++] = *p++;
|
|
}
|
|
}
|
|
out[n] = '\0';
|
|
}
|
|
out[n < cap ? n : cap - 1] = '\0';
|
|
}
|
|
|
|
/*
|
|
* The argument that says what a call is about, per tool: a shell call is its
|
|
* command, a read is its path. Once the verb has said "Run", the key in front
|
|
* of the value ("command: du -sh") only repeats the harness to itself.
|
|
*/
|
|
static const char *
|
|
primary_key(const char *name)
|
|
{
|
|
static const struct {
|
|
const char *tool, *key;
|
|
} keys[] = {
|
|
{ "run", "command" },
|
|
{ "read", "path" },
|
|
{ "write", "path" },
|
|
{ "edit", "path" },
|
|
{ "list", "path" },
|
|
{ "search", "pattern" },
|
|
{ "websearch", "query" },
|
|
{ "webfetch", "url" },
|
|
{ "echo", "text" },
|
|
{ "delegate", "task" },
|
|
};
|
|
size_t i;
|
|
|
|
for (i = 0; i < sizeof(keys) / sizeof(keys[0]); i++)
|
|
if (strcmp(name, keys[i].tool) == 0)
|
|
return keys[i].key;
|
|
return NULL;
|
|
}
|
|
|
|
void
|
|
sp_call_summary(const char *name, const char *args, char *out, size_t cap)
|
|
{
|
|
char detail[512] = "";
|
|
const char *key;
|
|
size_t n;
|
|
|
|
if (name == NULL)
|
|
name = "?";
|
|
/*
|
|
* The value of the primary key, read out of the object instead of off
|
|
* the front of the pretty text: the model may order its arguments as it
|
|
* likes, and a "write" carries the whole file content next to the path.
|
|
* Everything else in the call is noise on one row.
|
|
*/
|
|
key = primary_key(name);
|
|
if (key != NULL && args != NULL && args[0] == '{') {
|
|
mcp_json *v = mcp_parse(args);
|
|
|
|
if (v != NULL) {
|
|
const char *val = mcp_arg_string(v, key);
|
|
|
|
if (val != NULL)
|
|
snprintf(detail, sizeof(detail), "%s", val);
|
|
mcp_json_free(v);
|
|
}
|
|
}
|
|
if (detail[0] == '\0')
|
|
pretty_args(args != NULL ? args : "", detail, sizeof(detail));
|
|
snprintf(out, cap, "%s", name);
|
|
n = strlen(out);
|
|
if (*detail != '\0' && n + 2 < cap)
|
|
snprintf(out + n, cap - n, " %s", detail);
|
|
}
|
|
|
|
/*
|
|
* What the tool returned, shortened for a transcript. A full `run` can carry
|
|
* a 300 KB JSON dump; two limits, both about the screen: sixteen rows and
|
|
* four kilobytes. The whole observation is in the session log either way.
|
|
*/
|
|
#define OBS_ROWS 16
|
|
#define OBS_BYTES 4096
|
|
|
|
int
|
|
sp_obs_short(const char *obs, struct sp_buf *out)
|
|
{
|
|
size_t len, keep, rows, i, rest = 0;
|
|
|
|
if (obs == NULL)
|
|
return SP_OBS_NONE;
|
|
while (*obs == '\n' || *obs == '\r')
|
|
obs++;
|
|
len = strlen(obs);
|
|
if (len == 0)
|
|
return SP_OBS_NONE;
|
|
while (len > 0 && (obs[len - 1] == '\n' || obs[len - 1] == '\r'))
|
|
len--;
|
|
/*
|
|
* A call that said nothing but how it ended belongs on the call row -
|
|
*
|
|
* >> Run mkdir -p build [exit status 0]
|
|
*
|
|
* instead of two rows for every quiet command.
|
|
*/
|
|
if (len >= 14 && len <= 32 && strncmp(obs, "[exit status ", 13) == 0 &&
|
|
obs[len - 1] == ']' && memchr(obs, '\n', len) == NULL) {
|
|
sp_buf_clear(out);
|
|
if (sp_buf_add(out, obs, len) != 0)
|
|
return SP_OBS_NONE;
|
|
return SP_OBS_JOIN;
|
|
}
|
|
keep = len;
|
|
for (rows = 0, i = 0; i < len; i++) {
|
|
if (i >= OBS_BYTES || rows >= OBS_ROWS) {
|
|
keep = i;
|
|
break;
|
|
}
|
|
if (obs[i] == '\n')
|
|
rows++;
|
|
}
|
|
if (keep < len) {
|
|
/* a cut in the middle of a line is the byte limit talking */
|
|
if (obs[keep] != '\n') {
|
|
size_t cut = keep;
|
|
|
|
while (cut > 0 && obs[cut - 1] != '\n')
|
|
cut--;
|
|
if (cut > 0)
|
|
keep = cut;
|
|
}
|
|
for (i = keep; i < len; i++)
|
|
if (obs[i] == '\n')
|
|
rest++;
|
|
if (obs[len - 1] != '\n')
|
|
rest++;
|
|
}
|
|
sp_buf_clear(out);
|
|
if (sp_buf_add(out, obs, keep) != 0)
|
|
return SP_OBS_NONE;
|
|
if (keep < len && rest > 0) {
|
|
char mark[80];
|
|
|
|
snprintf(mark, sizeof(mark), sp_t("ui.more_lines"), rest);
|
|
if (sp_buf_printf(out, "\n%s", mark) != 0)
|
|
return SP_OBS_NONE;
|
|
}
|
|
return SP_OBS_SHOWN;
|
|
}
|
|
|
|
/* the caller owns ag.stats; this is how it becomes readable elsewhere */
|
|
static void
|
|
snapshot_stats(struct sp_engine *e)
|
|
{
|
|
pthread_mutex_lock(&e->lock);
|
|
e->snapshot = e->ag.stats;
|
|
pthread_mutex_unlock(&e->lock);
|
|
}
|
|
|
|
/* -------------------------------------------------------------- callbacks */
|
|
|
|
static void
|
|
engine_stream_cb(void *ctx, int kind, const char *text)
|
|
{
|
|
struct sp_engine *e = ctx;
|
|
|
|
if (text == NULL || *text == '\0')
|
|
return;
|
|
pthread_mutex_lock(&e->lock);
|
|
/*
|
|
* SP_STREAM_TOOL carries the name of a call that has begun, not text:
|
|
* showing it in the answer glued two calls' names together. The call row
|
|
* comes from tool_begin.
|
|
*/
|
|
if (kind == SP_STREAM_TEXT)
|
|
(void)sp_buf_puts(&e->live, text);
|
|
else if (kind == SP_STREAM_THINK)
|
|
(void)sp_buf_puts(&e->think, text);
|
|
pthread_mutex_unlock(&e->lock);
|
|
ev_push(e, SP_EV_STREAM, kind, text, NULL);
|
|
}
|
|
|
|
/* an agent note (a retry, a wait) goes to the front end's status line */
|
|
static void
|
|
engine_note(void *ctx, const char *text)
|
|
{
|
|
struct sp_engine *e = ctx;
|
|
|
|
ev_push(e, SP_EV_NOTE, 0, text != NULL ? text : "", NULL);
|
|
}
|
|
|
|
static void
|
|
engine_tool_begin(void *ctx, const char *name, const char *args)
|
|
{
|
|
struct sp_engine *e = ctx;
|
|
char *think = NULL, *live = NULL;
|
|
|
|
if (name == NULL)
|
|
return;
|
|
/*
|
|
* The step is over as far as the screen is concerned: its reasoning and
|
|
* its answer go into the queue in that order, then the call itself, and
|
|
* the buffers start empty for the next step.
|
|
*/
|
|
/*
|
|
* The agent has counted this step by now; make it visible to the
|
|
* sidebar without touching ag.stats from a reader.
|
|
*/
|
|
snapshot_stats(e);
|
|
pthread_mutex_lock(&e->lock);
|
|
if (e->think.p != NULL && e->think.len > 0)
|
|
think = strdup(e->think.p);
|
|
if (e->live.p != NULL && e->live.len > 0)
|
|
live = strdup(e->live.p);
|
|
sp_buf_clear(&e->think);
|
|
sp_buf_clear(&e->live);
|
|
pthread_mutex_unlock(&e->lock);
|
|
/*
|
|
* One step event per call, even when the transport cannot stream: a
|
|
* client's step bookkeeping then has a single rule, and the UI's
|
|
* segment update with an empty text is a no-op anyway.
|
|
*/
|
|
ev_push(e, SP_EV_STEP, 0, think != NULL ? think : "",
|
|
live != NULL ? live : "");
|
|
ev_push(e, SP_EV_TOOL, 0, name, args);
|
|
free(think);
|
|
free(live);
|
|
}
|
|
|
|
static void
|
|
engine_tool_end(void *ctx, const char *name, const char *obs)
|
|
{
|
|
struct sp_engine *e = ctx;
|
|
struct sp_buf short_obs;
|
|
int kind;
|
|
|
|
if (sp_buf_init(&short_obs) != 0)
|
|
return;
|
|
kind = sp_obs_short(obs, &short_obs);
|
|
if (kind != SP_OBS_NONE)
|
|
ev_push(e, SP_EV_TOOL_RESULT, kind == SP_OBS_JOIN ? 1 : 0,
|
|
name, short_obs.p != NULL ? short_obs.p : "");
|
|
sp_buf_free(&short_obs);
|
|
/* a /model typed during the turn takes effect before the next request */
|
|
engine_apply_pending_model(e);
|
|
}
|
|
|
|
/*
|
|
* A tool needs permission. The turn thread parks on the engine's condition
|
|
* variable; the front end asks the operator and calls sp_engine_approve().
|
|
* Ctrl-C must work here too: the wait ends on cancel and the call is denied.
|
|
*/
|
|
static int
|
|
engine_approve(void *ctx, const char *name, int auth, const char *args)
|
|
{
|
|
struct sp_engine *e = ctx;
|
|
int answer;
|
|
|
|
pthread_mutex_lock(&e->lock);
|
|
snprintf(e->approve_name, sizeof(e->approve_name), "%s",
|
|
name != NULL ? name : "?");
|
|
snprintf(e->approve_args, sizeof(e->approve_args), "%.200s",
|
|
args != NULL ? args : "");
|
|
e->approve_auth = auth;
|
|
e->approve_result = 0;
|
|
e->approve_pending = 1;
|
|
pthread_mutex_unlock(&e->lock);
|
|
ev_push(e, SP_EV_APPROVAL, auth, e->approve_name, e->approve_args);
|
|
pthread_mutex_lock(&e->lock);
|
|
while (e->approve_pending && !e->cancel)
|
|
pthread_cond_wait(&e->cond, &e->lock);
|
|
answer = e->cancel ? 0 : e->approve_result;
|
|
e->approve_pending = 0;
|
|
pthread_mutex_unlock(&e->lock);
|
|
return answer;
|
|
}
|
|
|
|
int
|
|
sp_engine_approval(struct sp_engine *e, char *name, size_t namelen,
|
|
int *auth, char *args, size_t argslen)
|
|
{
|
|
int pending;
|
|
|
|
if (e == NULL)
|
|
return 0;
|
|
pthread_mutex_lock(&e->lock);
|
|
pending = e->approve_pending;
|
|
if (pending) {
|
|
if (name != NULL && namelen > 0)
|
|
snprintf(name, namelen, "%s", e->approve_name);
|
|
if (args != NULL && argslen > 0)
|
|
snprintf(args, argslen, "%s", e->approve_args);
|
|
if (auth != NULL)
|
|
*auth = e->approve_auth;
|
|
}
|
|
pthread_mutex_unlock(&e->lock);
|
|
return pending;
|
|
}
|
|
|
|
int
|
|
sp_engine_approve(struct sp_engine *e, int allow)
|
|
{
|
|
int pending;
|
|
|
|
if (e == NULL)
|
|
return 0;
|
|
pthread_mutex_lock(&e->lock);
|
|
pending = e->approve_pending;
|
|
if (pending) {
|
|
e->approve_pending = 0;
|
|
e->approve_result = allow != 0;
|
|
pthread_cond_broadcast(&e->cond);
|
|
}
|
|
pthread_mutex_unlock(&e->lock);
|
|
return pending;
|
|
}
|
|
|
|
int
|
|
sp_engine_cancel(struct sp_engine *e)
|
|
{
|
|
if (e == NULL)
|
|
return -1;
|
|
pthread_mutex_lock(&e->lock);
|
|
e->cancel = 1;
|
|
pthread_cond_broadcast(&e->cond);
|
|
pthread_mutex_unlock(&e->lock);
|
|
return 0;
|
|
}
|
|
|
|
int
|
|
sp_engine_steer(struct sp_engine *e, const char *text)
|
|
{
|
|
if (e == NULL || text == NULL || *text == '\0')
|
|
return -1;
|
|
pthread_mutex_lock(&e->lock);
|
|
if (!e->running) {
|
|
pthread_mutex_unlock(&e->lock);
|
|
return -1;
|
|
}
|
|
if (sp_buf_puts(&e->steer, text) != 0 ||
|
|
sp_buf_puts(&e->steer, " ") != 0) {
|
|
pthread_mutex_unlock(&e->lock);
|
|
return -1;
|
|
}
|
|
e->have_steer = 1;
|
|
pthread_mutex_unlock(&e->lock);
|
|
return 0;
|
|
}
|
|
|
|
int
|
|
sp_engine_take_steer(struct sp_engine *e, struct sp_buf *out)
|
|
{
|
|
int took = 0;
|
|
|
|
if (e == NULL || out == NULL)
|
|
return 0;
|
|
pthread_mutex_lock(&e->lock);
|
|
if (!e->running && e->have_steer) {
|
|
const char *p = e->steer.p;
|
|
size_t n = p != NULL ? strlen(p) : 0;
|
|
|
|
while (n > 0 && (p[n - 1] == ' ' || p[n - 1] == '\t'))
|
|
n--;
|
|
if (n > 0 && sp_buf_add(out, p, n) == 0)
|
|
took = 1;
|
|
e->have_steer = 0;
|
|
sp_buf_clear(&e->steer);
|
|
}
|
|
pthread_mutex_unlock(&e->lock);
|
|
return took;
|
|
}
|
|
|
|
static int
|
|
engine_steer_cb(void *ctx, struct sp_buf *out)
|
|
{
|
|
struct sp_engine *e = ctx;
|
|
int took = 0;
|
|
|
|
pthread_mutex_lock(&e->lock);
|
|
if (e->have_steer) {
|
|
e->have_steer = 0;
|
|
e->steers++;
|
|
took = sp_buf_puts(out, e->steer.p != NULL ? e->steer.p : "") == 0 ?
|
|
1 : -1;
|
|
sp_buf_clear(&e->steer);
|
|
}
|
|
pthread_mutex_unlock(&e->lock);
|
|
return took;
|
|
}
|
|
|
|
/*
|
|
* The turn hit a usage limit: say so in the prompt and wait for the reset on
|
|
* the turn thread. The screen stays alive (another thread); Ctrl-C ends it.
|
|
*/
|
|
static int
|
|
engine_limit_wait(void *ctx, long until, const char *why)
|
|
{
|
|
struct sp_engine *e = ctx;
|
|
char when[32], line[300];
|
|
struct tm tm;
|
|
time_t tt = (time_t)until;
|
|
long wait = e->max_wait > 0 ? e->max_wait : 12 * 3600;
|
|
|
|
(void)why;
|
|
if (until - (long)time(NULL) > wait)
|
|
return 0;
|
|
strftime(when, sizeof(when), "%a %H:%M", localtime_r(&tt, &tm));
|
|
snprintf(line, sizeof(line), sp_t("ui.limit_wait"), when);
|
|
ev_push(e, SP_EV_NOTE, 0, line, NULL);
|
|
while ((long)time(NULL) < until && !e->cancel) {
|
|
struct timespec ts = { 0, 250000000L };
|
|
|
|
nanosleep(&ts, NULL);
|
|
}
|
|
ev_push(e, SP_EV_NOTE, 0, "", NULL);
|
|
return !e->cancel;
|
|
}
|
|
|
|
/* a provider at its limit: another member of its pool, if one has room */
|
|
static int
|
|
engine_switch(void *ctx)
|
|
{
|
|
struct sp_engine *e = ctx;
|
|
|
|
return sp_provider_failover(&e->ag, e->conf);
|
|
}
|
|
|
|
static void
|
|
engine_compact(void *ctx, size_t before, size_t after, size_t mb, size_t ma)
|
|
{
|
|
struct sp_engine *e = ctx;
|
|
char b1[32], b2[32], t1[32], t2[32];
|
|
size_t tb = before / 4, ta = after / 4;
|
|
char msg[256];
|
|
|
|
if (before >= 1024)
|
|
snprintf(b1, sizeof(b1), "%.1fKiB", before / 1024.0);
|
|
else
|
|
snprintf(b1, sizeof(b1), "%zuB", before);
|
|
if (after >= 1024)
|
|
snprintf(b2, sizeof(b2), "%.1fKiB", after / 1024.0);
|
|
else
|
|
snprintf(b2, sizeof(b2), "%zuB", after);
|
|
if (tb >= 1000)
|
|
snprintf(t1, sizeof(t1), "~%.1fk tok", tb / 1000.0);
|
|
else
|
|
snprintf(t1, sizeof(t1), "~%zu tok", tb);
|
|
if (ta >= 1000)
|
|
snprintf(t2, sizeof(t2), "~%.1fk tok", ta / 1000.0);
|
|
else
|
|
snprintf(t2, sizeof(t2), "~%zu tok", ta);
|
|
snprintf(msg, sizeof(msg), sp_t("ui.compacted"), mb, ma, t1, t2, b1,
|
|
b2);
|
|
ev_push(e, SP_EV_ENTRY, 0, "splinter", msg);
|
|
}
|
|
|
|
/* ----------------------------------------------------------------- turns */
|
|
|
|
static void *
|
|
turn_thread(void *arg)
|
|
{
|
|
struct sp_engine *e = arg;
|
|
char *text = e->turn_text;
|
|
|
|
for (;;) {
|
|
int rc;
|
|
char *next = NULL;
|
|
|
|
e->ag.cfg = &e->turn_cfg;
|
|
sp_openai_set_cancel(&e->cancel);
|
|
if (e->have_swarm)
|
|
swarm_report_busy(&e->swarm, 1);
|
|
/*
|
|
* A leftover steer starts a second turn in this same worker.
|
|
* The step buffers belong to one turn and must not carry the
|
|
* previous answer into the next step event.
|
|
*/
|
|
pthread_mutex_lock(&e->lock);
|
|
sp_buf_clear(&e->live);
|
|
sp_buf_clear(&e->think);
|
|
pthread_mutex_unlock(&e->lock);
|
|
sp_buf_clear(&e->answer);
|
|
sp_buf_clear(&e->err);
|
|
pthread_mutex_lock(&e->lock);
|
|
e->turn_out0 = e->ag.stats.tokens_out;
|
|
e->turn_in0 = e->ag.stats.tokens_in;
|
|
e->turn_cost0 = e->ag.stats.cost;
|
|
pthread_mutex_unlock(&e->lock);
|
|
rc = sp_agent_run(&e->ag, text, &e->answer, &e->err);
|
|
if (e->have_swarm)
|
|
swarm_report_busy(&e->swarm, 0);
|
|
sp_openai_set_cancel(NULL);
|
|
/*
|
|
* The reasoning is on screen already (it streamed); the log keeps
|
|
* the whole of it, the final step's included.
|
|
*/
|
|
pthread_mutex_lock(&e->lock);
|
|
if (e->think.p != NULL && e->think.len > 0)
|
|
sp_logf("thinking", "%s", e->think.p);
|
|
/*
|
|
* A steer the turn took at a step boundary is already in the
|
|
* conversation. Only one it never reached becomes the next message.
|
|
*/
|
|
if (e->cancel) {
|
|
/* cancelled: the text typed for this turn is not a prompt */
|
|
e->have_steer = 0;
|
|
sp_buf_clear(&e->steer);
|
|
} else if (rc == 0 && e->have_steer) {
|
|
e->have_steer = 0;
|
|
e->steers++;
|
|
next = strdup(e->steer.p != NULL ? e->steer.p : "");
|
|
sp_buf_clear(&e->steer);
|
|
}
|
|
pthread_mutex_unlock(&e->lock);
|
|
if (rc == 0 && capture_interview(e, &e->answer)) {
|
|
char note[700];
|
|
|
|
snprintf(note, sizeof(note), sp_td("interview.saved",
|
|
"interview saved to USER.txt"));
|
|
ev_push(e, SP_EV_ENTRY, 0, "splinter", note);
|
|
}
|
|
engine_apply_pending_model(e);
|
|
ev_push(e, SP_EV_TURN_END, rc,
|
|
e->answer.p != NULL ? e->answer.p : "",
|
|
e->err.p != NULL ? e->err.p : "");
|
|
/*
|
|
* e->turn_text is the first text and belongs to the engine; a
|
|
* steer's text is the worker's own copy. Clearing the pointer
|
|
* with the free keeps sp_engine_close() from freeing it twice.
|
|
*/
|
|
pthread_mutex_lock(&e->lock);
|
|
if (e->turn_text == text)
|
|
e->turn_text = NULL;
|
|
pthread_mutex_unlock(&e->lock);
|
|
free(text);
|
|
text = NULL;
|
|
snapshot_stats(e);
|
|
if (next != NULL && *next != '\0') {
|
|
/*
|
|
* A single-step turn ends with the answer, so a steer
|
|
* typed during it had no step boundary to land on. It
|
|
* becomes the next message, run like any other turn.
|
|
*/
|
|
text = next;
|
|
ev_push(e, SP_EV_ENTRY, 0, "you", text);
|
|
ev_push(e, SP_EV_STATE, 0, NULL, NULL);
|
|
continue;
|
|
}
|
|
free(next);
|
|
break;
|
|
}
|
|
free(text);
|
|
/*
|
|
* The old screen said how many steers the turn took; the count moved
|
|
* here with the loop, and a front end that has no prompt line to put it
|
|
* in still gets it as a transcript entry.
|
|
*/
|
|
pthread_mutex_lock(&e->lock);
|
|
if (e->steers > 0) {
|
|
char note[64];
|
|
|
|
snprintf(note, sizeof(note), "(%zu steering%s applied)",
|
|
e->steers, e->steers == 1 ? "" : "s");
|
|
ev_push_locked(e, SP_EV_ENTRY, 0, "splinter", note);
|
|
}
|
|
pthread_mutex_unlock(&e->lock);
|
|
/*
|
|
* The turn's numbers are part of the first state event, not of the
|
|
* join: a remote front end has no join of its own, and the sidebar
|
|
* must not show the previous turn until the next event arrives.
|
|
*/
|
|
{
|
|
struct timespec now;
|
|
long ms;
|
|
|
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
|
ms = (long)((now.tv_sec - e->turn_t0.tv_sec) * 1000 +
|
|
(now.tv_nsec - e->turn_t0.tv_nsec) / 1000000);
|
|
pthread_mutex_lock(&e->lock);
|
|
e->last_ms = ms;
|
|
e->last_turn_out = e->ag.stats.tokens_out >= e->turn_out0 ?
|
|
e->ag.stats.tokens_out - e->turn_out0 : 0;
|
|
{
|
|
struct sp_engine *ce = e;
|
|
int is_judged = strstr(ce->cur_model, "judged") != NULL;
|
|
size_t tin = ce->ag.stats.tokens_in >= ce->turn_in0 ?
|
|
ce->ag.stats.tokens_in - ce->turn_in0 : 0;
|
|
double c = ce->ag.stats.cost >= ce->turn_cost0 ?
|
|
ce->ag.stats.cost - ce->turn_cost0 : 0;
|
|
|
|
if (is_judged) {
|
|
ce->judged.turns++;
|
|
ce->judged.ms += (unsigned long)ms;
|
|
ce->judged.in += tin;
|
|
ce->judged.out += ce->last_turn_out;
|
|
ce->judged.cost += c;
|
|
} else {
|
|
ce->plain.turns++;
|
|
ce->plain.ms += (unsigned long)ms;
|
|
ce->plain.in += tin;
|
|
ce->plain.out += ce->last_turn_out;
|
|
ce->plain.cost += c;
|
|
}
|
|
}
|
|
e->last_steps = e->ag.stats.steps;
|
|
e->last_calls = e->ag.stats.tool_calls;
|
|
pthread_mutex_unlock(&e->lock);
|
|
}
|
|
/*
|
|
* The events go into the queue before the turn is marked idle: a front
|
|
* end that sees "not busy" must be able to drain everything that
|
|
* produced it.
|
|
*/
|
|
ev_push(e, SP_EV_STATE, 0, NULL, NULL);
|
|
ev_push(e, SP_EV_BUSY, 0, NULL, NULL);
|
|
pthread_mutex_lock(&e->lock);
|
|
e->running = 0;
|
|
pthread_cond_broadcast(&e->cond);
|
|
pthread_mutex_unlock(&e->lock);
|
|
return NULL;
|
|
}
|
|
|
|
int
|
|
sp_engine_submit(struct sp_engine *e, const char *text)
|
|
{
|
|
if (e == NULL || text == NULL || *text == '\0')
|
|
return -1;
|
|
pthread_mutex_lock(&e->lock);
|
|
if (e->running) {
|
|
pthread_mutex_unlock(&e->lock);
|
|
return -1;
|
|
}
|
|
/* a previous turn is joinable; collect it before starting the next */
|
|
if (e->have_thread) {
|
|
pthread_mutex_unlock(&e->lock);
|
|
(void)sp_engine_wait(e);
|
|
pthread_mutex_lock(&e->lock);
|
|
}
|
|
e->turn_text = strdup(text);
|
|
if (e->turn_text == NULL) {
|
|
pthread_mutex_unlock(&e->lock);
|
|
return -1;
|
|
}
|
|
e->turn_cfg = e->base;
|
|
e->turn_cfg.cancel = &e->cancel;
|
|
e->turn_cfg.steer = engine_steer_cb;
|
|
e->turn_cfg.steer_ctx = e;
|
|
e->turn_cfg.stream = engine_stream_cb;
|
|
e->turn_cfg.stream_ctx = e;
|
|
e->turn_cfg.approve = engine_approve;
|
|
e->turn_cfg.approve_ctx = e;
|
|
e->turn_cfg.tool_begin = engine_tool_begin;
|
|
e->turn_cfg.tool_begin_ctx = e;
|
|
e->turn_cfg.tool_end = engine_tool_end;
|
|
e->turn_cfg.tool_end_ctx = e;
|
|
e->turn_cfg.note = engine_note;
|
|
e->turn_cfg.note_ctx = e;
|
|
e->turn_cfg.on_compact = engine_compact;
|
|
e->turn_cfg.on_compact_ctx = e;
|
|
if (e->base.limit_wait != NULL) {
|
|
e->turn_cfg.limit_wait = engine_limit_wait;
|
|
e->turn_cfg.limit_ctx = e;
|
|
}
|
|
if (e->conf != NULL && e->conf->npools > 0) {
|
|
e->turn_cfg.limit_switch = engine_switch;
|
|
e->turn_cfg.switch_ctx = e;
|
|
}
|
|
/* the profile's own consent rule wins over the configured one */
|
|
if (e->agents.n > 0 && e->agent_cur >= 0 &&
|
|
(size_t)e->agent_cur < e->agents.n &&
|
|
e->agents.v[e->agent_cur].autonomous >= 0)
|
|
e->turn_cfg.autonomous =
|
|
e->agents.v[e->agent_cur].autonomous;
|
|
e->cancel = 0;
|
|
e->steers = 0;
|
|
e->approve_pending = 0;
|
|
sp_buf_clear(&e->think);
|
|
sp_buf_clear(&e->live);
|
|
clock_gettime(CLOCK_MONOTONIC, &e->turn_t0);
|
|
e->running = 1;
|
|
/*
|
|
* The handle is claimed before the thread exists and "busy" is queued
|
|
* while the lock is still held: a worker that starts and finishes at
|
|
* once must not get its events in front of the busy event, and a front
|
|
* end that saw "not busy" must find a thread to join.
|
|
*/
|
|
e->have_thread = 1;
|
|
ev_push_locked(e, SP_EV_BUSY, 1, NULL, NULL);
|
|
if (pthread_create(&e->th, NULL, turn_thread, e) != 0) {
|
|
e->running = 0;
|
|
e->have_thread = 0;
|
|
free(e->turn_text);
|
|
e->turn_text = NULL;
|
|
ev_push_locked(e, SP_EV_BUSY, 0, NULL, NULL);
|
|
pthread_mutex_unlock(&e->lock);
|
|
return -1;
|
|
}
|
|
pthread_mutex_unlock(&e->lock);
|
|
return 0;
|
|
}
|
|
|
|
int
|
|
sp_engine_quit(struct sp_engine *e)
|
|
{
|
|
int quit;
|
|
|
|
if (e == NULL)
|
|
return 0;
|
|
pthread_mutex_lock(&e->lock);
|
|
quit = e->quit;
|
|
pthread_mutex_unlock(&e->lock);
|
|
return quit;
|
|
}
|
|
|
|
int
|
|
sp_engine_busy(struct sp_engine *e)
|
|
{
|
|
int busy;
|
|
|
|
if (e == NULL)
|
|
return 0;
|
|
pthread_mutex_lock(&e->lock);
|
|
busy = e->running;
|
|
pthread_mutex_unlock(&e->lock);
|
|
return busy;
|
|
}
|
|
|
|
int
|
|
sp_engine_wait(struct sp_engine *e)
|
|
{
|
|
pthread_t th;
|
|
int have, running;
|
|
|
|
if (e == NULL)
|
|
return -1;
|
|
pthread_mutex_lock(&e->lock);
|
|
have = e->have_thread;
|
|
running = e->running;
|
|
th = e->th;
|
|
if (have && !running)
|
|
e->have_thread = 0;
|
|
pthread_mutex_unlock(&e->lock);
|
|
if (!have)
|
|
return 0;
|
|
if (running)
|
|
return -1; /* a front end waits for SP_EV_BUSY, not for us */
|
|
pthread_join(th, NULL);
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
* Join the turn from close: unlike sp_engine_wait() this one blocks, because
|
|
* the engine is about to go away and the worker must not find freed memory.
|
|
* A cancel was set first, so the wait is bounded by whatever the transport
|
|
* needs to kill its child.
|
|
*/
|
|
static void
|
|
engine_join(struct sp_engine *e)
|
|
{
|
|
pthread_t th;
|
|
int have;
|
|
|
|
pthread_mutex_lock(&e->lock);
|
|
while (e->running)
|
|
pthread_cond_wait(&e->cond, &e->lock);
|
|
have = e->have_thread;
|
|
th = e->th;
|
|
e->have_thread = 0;
|
|
pthread_mutex_unlock(&e->lock);
|
|
if (have)
|
|
pthread_join(th, NULL);
|
|
}
|
|
|
|
/*
|
|
* One synchronous request: what -p, the slash prompt and a test want. No
|
|
* queue, no thread; the caller's stream callback sees the text as it arrives.
|
|
*/
|
|
/*
|
|
* The answer that ends with INTERVIEW_COMPLETE: save the summary to USER.txt
|
|
* (once), keep the marker out of the answer and the conversation, and say so.
|
|
* Both paths - the turn thread and the synchronous -p path - end here.
|
|
*/
|
|
static int
|
|
capture_interview(struct sp_engine *e, struct sp_buf *answer)
|
|
{
|
|
char clean[16384];
|
|
size_t k;
|
|
|
|
if (answer == NULL || answer->p == NULL)
|
|
return 0;
|
|
if (!sp_interview_capture(e->sess.dir, answer->p, clean,
|
|
sizeof(clean)))
|
|
return 0;
|
|
sp_buf_clear(answer);
|
|
(void)sp_buf_puts(answer, clean);
|
|
for (k = e->conv.n; k > 0; k--)
|
|
if (e->conv.v[k - 1].role != NULL &&
|
|
strcmp(e->conv.v[k - 1].role, "assistant") == 0) {
|
|
char *c2 = strdup(clean);
|
|
|
|
if (c2 != NULL) {
|
|
free(e->conv.v[k - 1].content);
|
|
e->conv.v[k - 1].content = c2;
|
|
}
|
|
break;
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
int
|
|
sp_engine_prompt(struct sp_engine *e, const char *text, sp_stream_cb stream,
|
|
void *stream_ctx, struct sp_buf *answer, struct sp_buf *err)
|
|
{
|
|
struct sp_agent_config cfg;
|
|
int rc;
|
|
|
|
if (e == NULL || text == NULL)
|
|
return -1;
|
|
if (sp_engine_busy(e))
|
|
return -1;
|
|
pthread_mutex_lock(&e->lock);
|
|
e->cancel = 0;
|
|
e->have_steer = 0;
|
|
sp_buf_clear(&e->steer);
|
|
pthread_mutex_unlock(&e->lock);
|
|
cfg = e->base;
|
|
if (stream != NULL) {
|
|
cfg.stream = stream;
|
|
cfg.stream_ctx = stream_ctx;
|
|
}
|
|
e->ag.cfg = &cfg;
|
|
rc = sp_agent_run(&e->ag, text, answer, err);
|
|
e->ag.cfg = &e->base;
|
|
if (rc == 0)
|
|
(void)capture_interview(e, answer);
|
|
snapshot_stats(e);
|
|
return rc;
|
|
}
|
|
|
|
/* -------------------------------------------------------------- profiles */
|
|
|
|
/* a built-in profile's description in the user's language */
|
|
static const char *
|
|
agent_desc(const struct sp_agent_def *d)
|
|
{
|
|
if (strcmp(d->source, "(built in)") == 0) {
|
|
if (strcmp(d->name, "build") == 0)
|
|
return sp_t("agent.desc.build");
|
|
if (strcmp(d->name, "plan") == 0)
|
|
return sp_t("agent.desc.plan");
|
|
}
|
|
return d->description;
|
|
}
|
|
|
|
/*
|
|
* Switch the agent profile: its tool policy and prompt take effect on the next
|
|
* turn, and its model (if it names one) answers it. The provider the chat was
|
|
* on is remembered the first time a profile moves it and comes back with the
|
|
* next profile that names no model.
|
|
*/
|
|
static int
|
|
agent_switch(struct sp_engine *e, int idx, int announce)
|
|
{
|
|
const struct sp_agent_def *d;
|
|
char msg[400];
|
|
|
|
if (e->agents.n == 0 || idx < 0 || (size_t)idx >= e->agents.n)
|
|
return -1;
|
|
d = &e->agents.v[idx];
|
|
if (sp_agents_activate(&e->ag, d, e->base_prompt != NULL ?
|
|
e->base_prompt : "", &e->policy) != 0) {
|
|
char msg[200];
|
|
|
|
snprintf(msg, sizeof(msg), sp_t("agent.failed"), d->name);
|
|
ev_push(e, SP_EV_ENTRY, 0, "error", msg);
|
|
return -1;
|
|
}
|
|
e->agent_cur = idx;
|
|
snprintf(e->agent_name, sizeof(e->agent_name), "%.24s", d->name);
|
|
profile_save(e);
|
|
if (e->conf != NULL) {
|
|
struct sp_choice ch;
|
|
const char *want = d->model[0] != '\0' ? d->model :
|
|
(e->home_id[0] != '\0' ? e->home_id : NULL);
|
|
|
|
if (want != NULL && sp_provider_choose(e->conf, want, &ch) == 0 &&
|
|
strcmp(ch.d->kind, "cli") != 0 && ch.d->endpoint[0] != '\0') {
|
|
struct sp_buf perr;
|
|
|
|
if (d->model[0] != '\0' && e->home_id[0] == '\0')
|
|
snprintf(e->home_id, sizeof(e->home_id), "%s",
|
|
sp_usage_active());
|
|
if (sp_buf_init(&perr) == 0) {
|
|
if (sp_provider_apply(&e->ag, ch.d->kind,
|
|
ch.d->endpoint,
|
|
ch.model[0] != '\0' ? ch.model : ch.d->model,
|
|
ch.d->key_env, &perr) == 0) {
|
|
sp_usage_set_active(ch.d->id);
|
|
snprintf(e->cur_model, sizeof(e->cur_model),
|
|
"%s", ch.model[0] != '\0' ? ch.model :
|
|
ch.d->model);
|
|
snprintf(e->cur_endpoint,
|
|
sizeof(e->cur_endpoint), "%s",
|
|
ch.d->endpoint);
|
|
}
|
|
sp_buf_free(&perr);
|
|
}
|
|
if (d->model[0] == '\0')
|
|
e->home_id[0] = '\0';
|
|
}
|
|
}
|
|
if (announce) {
|
|
snprintf(msg, sizeof(msg), sp_t("agent.switched"), d->name,
|
|
agent_desc(d), d->max_auth == 0 ? sp_t("agent.readonly") : "");
|
|
ev_push(e, SP_EV_ENTRY, 0, "splinter", msg);
|
|
/* at open there is no front end yet; a client gets state directly */
|
|
ev_push(e, SP_EV_STATE, 0, NULL, NULL);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int
|
|
sp_engine_agent_switch(struct sp_engine *e, int idx)
|
|
{
|
|
if (e == NULL)
|
|
return -1;
|
|
return agent_switch(e, idx, 1);
|
|
}
|
|
|
|
/* --------------------------------------------------------------- commands */
|
|
|
|
/* the shell a '!' line runs in; its output becomes a transcript entry */
|
|
#define SHELL_MAX (64 * 1024)
|
|
|
|
static void
|
|
engine_shell(struct sp_engine *e, const char *cmd)
|
|
{
|
|
struct sp_buf out;
|
|
FILE *fp;
|
|
char chunk[4096];
|
|
size_t n, total = 0;
|
|
|
|
fp = popen(cmd, "r");
|
|
if (fp == NULL) {
|
|
ev_push(e, SP_EV_ENTRY, 0, "error", "cannot run the shell");
|
|
return;
|
|
}
|
|
if (sp_buf_init(&out) != 0) {
|
|
pclose(fp);
|
|
return;
|
|
}
|
|
while ((n = fread(chunk, 1, sizeof(chunk), fp)) > 0) {
|
|
total += n;
|
|
if (out.len < SHELL_MAX) {
|
|
size_t take = n;
|
|
|
|
if (out.len + take > SHELL_MAX)
|
|
take = SHELL_MAX - out.len;
|
|
(void)sp_buf_add(&out, chunk, take);
|
|
}
|
|
}
|
|
pclose(fp);
|
|
if (total > out.len)
|
|
(void)sp_buf_printf(&out, "\n[... %zu bytes not shown]",
|
|
total - out.len);
|
|
ev_push(e, SP_EV_ENTRY, 0, "shell",
|
|
out.p != NULL && out.len > 0 ? out.p : "(no output)");
|
|
sp_buf_free(&out);
|
|
}
|
|
|
|
/* /connect in the terminal: the same questions the gateway asks, per line */
|
|
static void
|
|
connect_ask(struct engine_cc *cc, struct sp_buf *out)
|
|
{
|
|
switch (cc->step) {
|
|
case 1:
|
|
sp_buf_puts(out, sp_t("connect.endpoint"));
|
|
break;
|
|
case 2:
|
|
sp_buf_puts(out, sp_t("connect.model"));
|
|
break;
|
|
case 3:
|
|
if (cc->key_env[0] != '\0')
|
|
sp_buf_printf(out, sp_t("connect.key_named"),
|
|
cc->key_env);
|
|
else
|
|
sp_buf_puts(out, sp_t("connect.key"));
|
|
break;
|
|
default:
|
|
sp_buf_puts(out, sp_t("connect.name"));
|
|
break;
|
|
}
|
|
}
|
|
|
|
/* returns 1: the line was an answer (handled), 0: nothing is running */
|
|
static int
|
|
connect_answer(struct sp_engine *e, const char *line, struct sp_buf *out)
|
|
{
|
|
struct engine_cc *cc = &e->cc;
|
|
|
|
if (!cc->active)
|
|
return 0;
|
|
if (strcmp(line, "/cancel") == 0 || strcasecmp(line, "cancel") == 0) {
|
|
memset(cc, 0, sizeof(*cc));
|
|
sp_buf_puts(out, sp_t("connect.cancel"));
|
|
return 1;
|
|
}
|
|
switch (cc->step) {
|
|
case 0:
|
|
if (!sp_provider_id_ok(line)) {
|
|
sp_buf_puts(out, sp_t("connect.name_bad"));
|
|
return 1;
|
|
}
|
|
snprintf(cc->id, sizeof(cc->id), "%s", line);
|
|
break;
|
|
case 1:
|
|
if (strcmp(line, "ollama") == 0) {
|
|
snprintf(cc->endpoint, sizeof(cc->endpoint),
|
|
"http://127.0.0.1:11434/v1");
|
|
} else if (strcmp(line, "opencode") == 0) {
|
|
snprintf(cc->endpoint, sizeof(cc->endpoint),
|
|
"https://opencode.ai/zen/go/v1");
|
|
snprintf(cc->key_env, sizeof(cc->key_env),
|
|
"OPENCODE_GO_API_KEY");
|
|
} else if (!sp_provider_endpoint_ok(line)) {
|
|
sp_buf_puts(out, sp_t("connect.endpoint_bad"));
|
|
return 1;
|
|
} else {
|
|
snprintf(cc->endpoint, sizeof(cc->endpoint), "%s", line);
|
|
}
|
|
break;
|
|
case 2:
|
|
if (!sp_provider_model_ok(line)) {
|
|
sp_buf_puts(out, sp_t("connect.model_bad"));
|
|
return 1;
|
|
}
|
|
snprintf(cc->model, sizeof(cc->model), "%s", line);
|
|
break;
|
|
default:
|
|
if (strcmp(line, "-") == 0)
|
|
cc->key_env[0] = '\0';
|
|
else if (strcmp(line, "/skip") != 0) {
|
|
if (!sp_provider_key_ok(line)) {
|
|
sp_buf_puts(out, sp_t("connect.key_bad"));
|
|
return 1;
|
|
}
|
|
snprintf(cc->key_env, sizeof(cc->key_env), "%s", line);
|
|
}
|
|
{
|
|
char dir[720];
|
|
struct sp_buf cerr;
|
|
|
|
sp_buf_init(&cerr);
|
|
if (e->conf == NULL ||
|
|
sp_provider_dir(dir, sizeof(dir)) != 0) {
|
|
sp_buf_puts(out, sp_t("connect.nodir"));
|
|
} else if (sp_provider_add(e->conf, dir, cc->id,
|
|
cc->endpoint, cc->model, cc->key_env,
|
|
&cerr) != 0) {
|
|
sp_buf_printf(out, sp_t("connect.failed"),
|
|
cerr.p != NULL ? cerr.p : "?");
|
|
} else {
|
|
sp_buf_printf(out, sp_t("connect.saved"),
|
|
cc->id, cc->model, cc->endpoint);
|
|
}
|
|
sp_buf_free(&cerr);
|
|
}
|
|
memset(cc, 0, sizeof(*cc));
|
|
return 1;
|
|
}
|
|
cc->step++;
|
|
sp_buf_puts(out, "\n");
|
|
connect_ask(cc, out);
|
|
return 1;
|
|
}
|
|
|
|
static int
|
|
name_cmp(const void *a, const void *b)
|
|
{
|
|
return strcmp((const char *)a, (const char *)b);
|
|
}
|
|
|
|
static int
|
|
slash_add(char (*names)[64], int *n, int max, const char *name)
|
|
{
|
|
int i;
|
|
|
|
if (name == NULL || *name == '\0' || *n >= max)
|
|
return 0;
|
|
for (i = 0; i < *n; i++)
|
|
if (strcmp(names[i], name) == 0)
|
|
return 0;
|
|
snprintf(names[(*n)++], 64, "%s", name);
|
|
return 1;
|
|
}
|
|
|
|
int
|
|
sp_engine_command_names(struct sp_engine *e, char (*names)[64], int max)
|
|
{
|
|
static const char *builtin[] = {
|
|
"agent", "agents", "compact", "connect", "continue", "cost", "exit", "model",
|
|
"new", "q", "quit", "rename", "reset", "resume", "rm", "status",
|
|
"swarm", "usage", "widgets"
|
|
};
|
|
struct sp_buf b;
|
|
char cdir[700], *p, *tok, *save;
|
|
size_t i;
|
|
int n = 0;
|
|
|
|
if (e == NULL || names == NULL || max <= 0)
|
|
return 0;
|
|
for (i = 0; i < sizeof(builtin) / sizeof(builtin[0]); i++)
|
|
slash_add(names, &n, max, builtin[i]);
|
|
if (e->host != NULL && sp_buf_init(&b) == 0) {
|
|
if (sp_host_command_help(e->host, &b) > 0 && b.p != NULL) {
|
|
for (tok = strtok_r(b.p, " \t\r\n", &save); tok != NULL;
|
|
tok = strtok_r(NULL, " \t\r\n", &save)) {
|
|
p = tok;
|
|
if (*p == '/')
|
|
p++;
|
|
if (*p != '\0')
|
|
slash_add(names, &n, max, p);
|
|
}
|
|
}
|
|
sp_buf_free(&b);
|
|
}
|
|
if (sp_buf_init(&b) == 0) {
|
|
if (sp_cmdscript_dir(e->sess.dir, cdir, sizeof(cdir)) == 0 &&
|
|
sp_cmdscript_list(cdir, &b) > 0 && b.p != NULL) {
|
|
for (tok = strtok_r(b.p, " \t\r\n", &save); tok != NULL;
|
|
tok = strtok_r(NULL, " \t\r\n", &save))
|
|
if (*tok != '\0')
|
|
slash_add(names, &n, max, tok);
|
|
}
|
|
sp_buf_free(&b);
|
|
}
|
|
/* stable order for the popup; qsort because the shift loop tripped the
|
|
* analyzer's overlap check for no reason */
|
|
qsort(names, (size_t)n, sizeof(names[0]), name_cmp);
|
|
return n;
|
|
}
|
|
|
|
/*
|
|
* /model: list, switch provider, pool or model. The choice is written to the
|
|
* session's own sidecar, so reopening that conversation brings it back without
|
|
* changing what a new conversation starts on. 'probe' asks the configured
|
|
* endpoints which models they really serve.
|
|
*/
|
|
static void
|
|
cmd_model_apply(struct sp_engine *e, const char *args, struct sp_buf *out,
|
|
int defer)
|
|
{
|
|
struct sp_provider p;
|
|
struct sp_buf perr;
|
|
size_t idx = 0, i, n;
|
|
char poolname[40];
|
|
int is_pool = 0;
|
|
|
|
/*
|
|
* Replacing the transport under a request in flight frees the curl
|
|
* context the turn is still reading. While a turn runs, the selector is
|
|
* remembered and applied by engine_apply_pending_model() between
|
|
* requests (tool_end) or at the end of the turn.
|
|
*/
|
|
if (defer && args[0] != '\0' && strcmp(args, "probe") != 0 &&
|
|
sp_engine_busy(e)) {
|
|
pthread_mutex_lock(&e->model_lock);
|
|
snprintf(e->pend_model, sizeof(e->pend_model), "%s", args);
|
|
e->has_pend_model = 1;
|
|
pthread_mutex_unlock(&e->model_lock);
|
|
sp_buf_printf(out, sp_t("model.pending"), args);
|
|
ev_push(e, SP_EV_STATE, 0, NULL, NULL);
|
|
return;
|
|
}
|
|
snprintf(poolname, sizeof(poolname), "%s", args);
|
|
is_pool = sp_pool_find(e->conf, args) != NULL;
|
|
if (!is_pool) {
|
|
const char *sl = strchr(args, '/');
|
|
|
|
if (sl != NULL && (size_t)(sl - args) < sizeof(poolname)) {
|
|
memcpy(poolname, args, (size_t)(sl - args));
|
|
poolname[sl - args] = '\0';
|
|
is_pool = sp_pool_find(e->conf, poolname) != NULL;
|
|
}
|
|
}
|
|
if (e->conf == NULL) {
|
|
sp_buf_puts(out, sp_t("model.none"));
|
|
} else if (args[0] == '\0') {
|
|
sp_buf_puts(out, sp_t("model.choose"));
|
|
n = sp_provider_count(e->conf);
|
|
for (i = 0; i < n; i++)
|
|
if (sp_provider_at(e->conf, i, &p) == 0)
|
|
sp_buf_printf(out, "\n %s/%s%s",
|
|
sp_provider_label(p.id), p.model,
|
|
strcmp(p.model, e->cur_model) == 0 ?
|
|
" *" : "");
|
|
if (e->conf->npools > 0)
|
|
sp_buf_printf(out, "\n%s", sp_t("model.pools"));
|
|
for (i = 0; i < e->conf->npools; i++) {
|
|
size_t j;
|
|
|
|
sp_buf_printf(out, "\n %s pool (%s):",
|
|
e->conf->pool[i].id, e->conf->pool[i].strategy);
|
|
for (j = 0; j < e->conf->pool[i].nmembers; j++)
|
|
sp_buf_printf(out, " %s",
|
|
e->conf->pool[i].member[j]);
|
|
}
|
|
} else if (strcmp(args, "probe") == 0) {
|
|
size_t total = 0;
|
|
|
|
n = sp_provider_count(e->conf);
|
|
for (i = 0; i < n; i++) {
|
|
struct sp_buf ids, perr2;
|
|
char *m, *save = NULL;
|
|
|
|
if (sp_provider_at(e->conf, i, &p) != 0 ||
|
|
p.endpoint[0] == '\0' ||
|
|
strcmp(p.kind, "cli") == 0)
|
|
continue;
|
|
if (sp_buf_init(&ids) != 0)
|
|
break;
|
|
if (sp_buf_init(&perr2) != 0) {
|
|
sp_buf_free(&ids);
|
|
break;
|
|
}
|
|
if (sp_provider_served(&p, &ids, &perr2) == 0 &&
|
|
ids.p != NULL) {
|
|
for (m = strtok_r(ids.p, "\n", &save);
|
|
m != NULL; m = strtok_r(NULL, "\n", &save)) {
|
|
if (*m == '\0')
|
|
continue;
|
|
sp_buf_printf(out, "\n %s/%s",
|
|
sp_provider_label(p.id), m);
|
|
total++;
|
|
}
|
|
}
|
|
sp_buf_free(&ids);
|
|
sp_buf_free(&perr2);
|
|
}
|
|
if (total == 0)
|
|
sp_buf_puts(out, sp_t("model.probe_none"));
|
|
} else if (is_pool) {
|
|
struct sp_choice ch;
|
|
|
|
if (sp_provider_choose(e->conf, args, &ch) != 0) {
|
|
sp_buf_printf(out, sp_t("model.unknown"), args);
|
|
} else {
|
|
sp_buf_init(&perr);
|
|
if (sp_provider_apply(&e->ag, ch.d->kind, ch.d->endpoint,
|
|
ch.model[0] != '\0' ? ch.model : ch.d->model,
|
|
ch.d->key_env, &perr) != 0) {
|
|
sp_buf_printf(out, sp_t("model.failed"),
|
|
perr.p != NULL ? perr.p : "?");
|
|
} else {
|
|
sp_usage_set_active(ch.d->id);
|
|
snprintf(e->cur_endpoint, sizeof(e->cur_endpoint),
|
|
"%s", ch.d->endpoint);
|
|
snprintf(e->cur_model, sizeof(e->cur_model), "%s",
|
|
ch.model[0] != '\0' ? ch.model : ch.d->model);
|
|
session_model_note(e, poolname, out,
|
|
e->cur_model,
|
|
sp_provider_label(ch.d->id));
|
|
}
|
|
sp_buf_free(&perr);
|
|
}
|
|
} else if (sp_provider_find(e->conf, args, &idx)) {
|
|
/* a provider id: its configured model, main included */
|
|
sp_buf_init(&perr);
|
|
if (sp_provider_use(&e->ag, e->conf, idx, &perr) != 0) {
|
|
sp_buf_printf(out, sp_t("model.failed"),
|
|
perr.p != NULL ? perr.p : "?");
|
|
} else if (sp_provider_at(e->conf, idx, &p) == 0) {
|
|
char sel[320];
|
|
|
|
snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), "%s",
|
|
p.endpoint);
|
|
snprintf(e->cur_model, sizeof(e->cur_model), "%s",
|
|
p.model);
|
|
snprintf(sel, sizeof(sel), "%s/%s",
|
|
sp_provider_label(p.id), p.model);
|
|
session_model_note(e, sel, out, p.model,
|
|
sp_provider_label(p.id));
|
|
}
|
|
sp_buf_free(&perr);
|
|
} else {
|
|
struct sp_choice ch;
|
|
|
|
memset(&ch, 0, sizeof(ch));
|
|
if (sp_provider_choose(e->conf, args, &ch) == 0 &&
|
|
ch.d != NULL) {
|
|
/* provider/model, or a model one provider owns */
|
|
const char *model = ch.model[0] != '\0' ?
|
|
ch.model : ch.d->model;
|
|
char sel[320];
|
|
|
|
sp_buf_init(&perr);
|
|
if (sp_provider_apply(&e->ag, ch.d->kind,
|
|
ch.d->endpoint, model, ch.d->key_env, &perr) != 0) {
|
|
sp_buf_printf(out, sp_t("model.failed"),
|
|
perr.p != NULL ? perr.p : "?");
|
|
} else {
|
|
sp_usage_set_active(ch.d->id);
|
|
snprintf(e->cur_endpoint, sizeof(e->cur_endpoint),
|
|
"%s", ch.d->endpoint);
|
|
snprintf(e->cur_model, sizeof(e->cur_model), "%s",
|
|
model);
|
|
snprintf(sel, sizeof(sel), "%s/%s",
|
|
sp_provider_label(ch.d->id), model);
|
|
session_model_note(e, sel, out, e->cur_model,
|
|
sp_provider_label(ch.d->id));
|
|
}
|
|
sp_buf_free(&perr);
|
|
} else {
|
|
/*
|
|
* A bare model the config does not own: it goes on the
|
|
* endpoint this session is already talking to.
|
|
*/
|
|
const char *act = sp_usage_active();
|
|
char sel[320];
|
|
int ok;
|
|
|
|
memset(&p, 0, sizeof(p));
|
|
if (act == NULL || *act == '\0' ||
|
|
!sp_provider_find(e->conf, act, &idx))
|
|
idx = 0;
|
|
if (sp_provider_at(e->conf, idx, &p) != 0) {
|
|
sp_buf_printf(out, sp_t("model.unknown"),
|
|
args);
|
|
} else {
|
|
sp_buf_init(&perr);
|
|
ok = sp_provider_apply(&e->ag, p.kind,
|
|
p.endpoint, args, p.key_env, &perr) == 0;
|
|
if (ok) {
|
|
snprintf(e->cur_model,
|
|
sizeof(e->cur_model), "%s", args);
|
|
snprintf(sel, sizeof(sel), "%s/%s",
|
|
sp_provider_label(p.id), args);
|
|
session_model_note(e, sel, out, args,
|
|
sp_provider_label(p.id));
|
|
} else {
|
|
sp_buf_printf(out, sp_t("model.failed"),
|
|
perr.p != NULL ? perr.p : "?");
|
|
}
|
|
sp_buf_free(&perr);
|
|
}
|
|
}
|
|
}
|
|
if (e->host != NULL)
|
|
sp_host_set_model(e->host, e->cur_model);
|
|
ev_push(e, SP_EV_STATE, 0, NULL, NULL);
|
|
}
|
|
|
|
/* the ordinary /model: a running turn defers the switch */
|
|
static void
|
|
cmd_model(struct sp_engine *e, const char *args, struct sp_buf *out)
|
|
{
|
|
cmd_model_apply(e, args, out, 1);
|
|
}
|
|
|
|
/* apply the selector a /model left while the turn was running */
|
|
static void
|
|
engine_apply_pending_model(struct sp_engine *e)
|
|
{
|
|
char sel[320];
|
|
struct sp_buf out;
|
|
|
|
pthread_mutex_lock(&e->model_lock);
|
|
if (!e->has_pend_model) {
|
|
pthread_mutex_unlock(&e->model_lock);
|
|
return;
|
|
}
|
|
snprintf(sel, sizeof(sel), "%s", e->pend_model);
|
|
e->has_pend_model = 0;
|
|
pthread_mutex_unlock(&e->model_lock);
|
|
if (sp_buf_init(&out) != 0)
|
|
return;
|
|
cmd_model_apply(e, sel, &out, 0);
|
|
if (out.p != NULL && out.len > 0)
|
|
ev_push(e, SP_EV_ENTRY, 0, "splinter", out.p);
|
|
sp_buf_free(&out);
|
|
}
|
|
|
|
static void
|
|
cmd_new(struct sp_engine *e, struct sp_buf *out)
|
|
{
|
|
struct sp_session_info old = e->sess;
|
|
char id[64];
|
|
struct sp_buf serr;
|
|
const char *base;
|
|
|
|
memset(&e->sess, 0, sizeof(e->sess));
|
|
new_session_id(id, sizeof(id));
|
|
base = e->base_prompt != NULL ? e->base_prompt :
|
|
e->base.system_prompt;
|
|
sp_buf_init(&serr);
|
|
if (sp_session_open(&e->sess, old.dir, id, &serr) != 0 ||
|
|
sp_conv_reset(&e->conv, base) != 0) {
|
|
sp_buf_printf(out, sp_t("session.failed"),
|
|
serr.p != NULL ? serr.p : "?");
|
|
e->sess = old;
|
|
} else {
|
|
e->ag.sess = &e->sess;
|
|
sp_openai_set_session(e->sess.id);
|
|
/*
|
|
* /new drops the conversation, not the way of working: the
|
|
* profile's prompt goes back on top of the bare base, exactly
|
|
* as it was at startup. Without this the sidebar still said
|
|
* "plan" while the instructions were build's.
|
|
*/
|
|
if (e->agents.n > 0 && e->agent_cur >= 0 &&
|
|
(size_t)e->agent_cur < e->agents.n)
|
|
(void)sp_agents_activate(&e->ag,
|
|
&e->agents.v[e->agent_cur], base, &e->policy);
|
|
(void)sp_log_open(e->sess.dir, e->sess.id);
|
|
sp_logf("session", "started: %s", e->sess.id);
|
|
profile_save(e);
|
|
ev_push(e, SP_EV_CLEAR, 0, NULL, NULL);
|
|
sp_buf_printf(out, sp_t("session.new"), e->sess.id);
|
|
}
|
|
sp_buf_free(&serr);
|
|
}
|
|
|
|
static const char *
|
|
skip_ws(const char *p)
|
|
{
|
|
while (*p == ' ' || *p == '\t')
|
|
p++;
|
|
return p;
|
|
}
|
|
|
|
/*
|
|
* /rename [ID] TITLE. Without an id the current session gets the title; an id
|
|
* that names an existing session in this directory renames that one, so
|
|
* /rename sess-... Titel works while another session stays open.
|
|
*/
|
|
static void
|
|
cmd_rename(struct sp_engine *e, const char *args, struct sp_buf *out)
|
|
{
|
|
char id[64], path[800], title[1536];
|
|
struct sp_buf serr;
|
|
const char *p = skip_ws(args), *rest;
|
|
size_t n;
|
|
|
|
if (*p == '\0') {
|
|
sp_buf_puts(out, sp_t("session.rename_usage"));
|
|
return;
|
|
}
|
|
n = strcspn(p, " \t");
|
|
rest = skip_ws(p + n);
|
|
if (*rest != '\0' && n < sizeof(id)) {
|
|
snprintf(id, sizeof(id), "%.*s", (int)n, p);
|
|
snprintf(path, sizeof(path), "%s/%s.jsonl", e->sess.dir, id);
|
|
if (access(path, R_OK) == 0) {
|
|
if (sp_buf_init(&serr) != 0)
|
|
return;
|
|
if (sp_session_set_title(e->sess.dir, id, rest,
|
|
&serr) == 0) {
|
|
sp_buf_printf(out, sp_t("session.renamed"), id,
|
|
rest);
|
|
} else
|
|
sp_buf_printf(out, sp_t("session.rename_failed"),
|
|
serr.p != NULL ? serr.p : "?");
|
|
sp_buf_free(&serr);
|
|
return;
|
|
}
|
|
}
|
|
/* no such session id in the first token: the whole line is the title */
|
|
if (sp_buf_init(&serr) != 0)
|
|
return;
|
|
snprintf(title, sizeof(title), "%s", p);
|
|
if (sp_session_set_title(e->sess.dir, e->sess.id, title, &serr) == 0)
|
|
sp_buf_printf(out, sp_t("session.renamed"), e->sess.id, title);
|
|
else
|
|
sp_buf_printf(out, sp_t("session.rename_failed"),
|
|
serr.p != NULL ? serr.p : "?");
|
|
sp_buf_free(&serr);
|
|
}
|
|
|
|
/*
|
|
* /rm ID removes a session that is not the one this engine has open. The id
|
|
* must be complete; "last" is the newest session in the directory.
|
|
*/
|
|
static void
|
|
cmd_rm(struct sp_engine *e, const char *args, struct sp_buf *out)
|
|
{
|
|
char id[64], latest[64];
|
|
struct sp_buf serr;
|
|
const char *p = skip_ws(args);
|
|
size_t n;
|
|
|
|
if (*p == '\0') {
|
|
sp_buf_puts(out, sp_t("session.rm_usage"));
|
|
return;
|
|
}
|
|
n = strcspn(p, " \t");
|
|
if (n == 0 || n >= sizeof(id) || *skip_ws(p + n) != '\0') {
|
|
sp_buf_puts(out, sp_t("session.rm_usage"));
|
|
return;
|
|
}
|
|
snprintf(id, sizeof(id), "%.*s", (int)n, p);
|
|
if (strcmp(id, "last") == 0) {
|
|
if (sp_session_latest(e->sess.dir, latest,
|
|
sizeof(latest)) != 0) {
|
|
sp_buf_printf(out, sp_t("session.no_session"), id);
|
|
return;
|
|
}
|
|
snprintf(id, sizeof(id), "%s", latest);
|
|
}
|
|
if (strcmp(id, e->sess.id) == 0) {
|
|
sp_buf_puts(out, sp_t("session.rm_current"));
|
|
return;
|
|
}
|
|
if (sp_buf_init(&serr) != 0)
|
|
return;
|
|
if (sp_session_delete(e->sess.dir, id, &serr) == 0)
|
|
sp_buf_printf(out, sp_t("session.removed"), id);
|
|
else if (serr.p != NULL && strstr(serr.p, "no such session") != NULL)
|
|
sp_buf_printf(out, sp_t("session.no_session"), id);
|
|
else
|
|
sp_buf_printf(out, sp_t("session.remove_failed"), id,
|
|
serr.p != NULL ? serr.p : "?");
|
|
sp_buf_free(&serr);
|
|
}
|
|
|
|
static void
|
|
cmd_status(struct sp_engine *e, struct sp_buf *out)
|
|
{
|
|
size_t comp = 0, failed = 0;
|
|
unsigned turns = 0;
|
|
time_t now = time(NULL);
|
|
char tbuf[64];
|
|
struct tm tm;
|
|
|
|
(void)localtime_r(&now, &tm);
|
|
strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
|
|
if (e->host != NULL)
|
|
sp_host_compaction_stats(e->host, &comp, &failed, &turns);
|
|
sp_buf_printf(out, sp_t("status.title"), tbuf);
|
|
sp_buf_puts(out, "\n");
|
|
sp_buf_printf(out, " %-8s %s\n", sp_t("status.session"), e->sess.id);
|
|
sp_buf_printf(out, " %-8s %s\n", sp_t("status.dir"), e->sess.dir);
|
|
sp_buf_printf(out, " %-8s %s\n", sp_t("status.model"),
|
|
e->cur_model[0] != '\0' ? e->cur_model : "-");
|
|
sp_buf_printf(out, " %-8s %s\n", sp_t("status.endpoint"),
|
|
e->cur_endpoint[0] != '\0' ? e->cur_endpoint : "-");
|
|
sp_buf_printf(out, " %-8s %s\n", sp_t("status.theme"), e->theme);
|
|
sp_buf_printf(out, " %-8s %s\n", sp_t("status.agent"), e->agent_name);
|
|
sp_buf_printf(out, " %-8s ", sp_t("status.last"));
|
|
sp_buf_printf(out, sp_t("status.last_value"), e->last_ms,
|
|
e->last_steps, e->last_calls);
|
|
sp_buf_puts(out, "\n");
|
|
sp_buf_printf(out, " %-8s ", sp_t("status.tokens"));
|
|
sp_buf_printf(out, sp_t("status.tokens_value"),
|
|
e->snapshot.tokens_in, e->snapshot.tokens_out);
|
|
sp_buf_puts(out, "\n");
|
|
sp_buf_printf(out, " %-8s ", sp_t("status.compact"));
|
|
sp_buf_printf(out, sp_t("status.compact_value"), comp, failed, turns,
|
|
e->snapshot.compactions);
|
|
sp_buf_puts(out, "\n");
|
|
sp_buf_printf(out, " %-8s ", sp_t("status.limits"));
|
|
sp_buf_printf(out, sp_t("status.limits_value"), e->base.max_bytes,
|
|
e->base.max_steps, e->base.autonomous ?
|
|
sp_t("status.autonomous") : "");
|
|
sp_buf_puts(out, "\n");
|
|
if (e->host != NULL) {
|
|
struct sp_meter m;
|
|
char seg[512];
|
|
|
|
sp_host_meter_get(e->host, &m);
|
|
sp_buf_printf(out, " %-8s ", sp_t("status.meter"));
|
|
sp_buf_printf(out, sp_t("status.meter_value"), m.ctx_used,
|
|
m.ctx_max, m.cached, m.tok_in, m.tok_out);
|
|
sp_buf_puts(out, "\n");
|
|
if (sp_host_status_text(e->host, seg, sizeof(seg)) > 0)
|
|
sp_buf_printf(out, " %-8s %s\n", sp_t("status.bar"),
|
|
seg);
|
|
}
|
|
if (e->have_swarm) {
|
|
char sws[256], list[1024];
|
|
|
|
swarm_status(&e->swarm, sws, sizeof(sws));
|
|
sp_buf_printf(out, " %-8s ", sp_t("status.swarm"));
|
|
sp_buf_printf(out, sp_t("status.swarm_value"), sws,
|
|
e->swarm.id);
|
|
sp_buf_puts(out, "\n");
|
|
swarm_list(&e->swarm, list, sizeof(list));
|
|
sp_buf_printf(out, "%s", list);
|
|
}
|
|
}
|
|
|
|
static void
|
|
cmd_widgets(struct sp_engine *e, struct sp_buf *out)
|
|
{
|
|
char buf[4096];
|
|
|
|
if (e->host == NULL || sp_host_widget_count(e->host) == 0)
|
|
sp_buf_puts(out, sp_t("widgets.none"));
|
|
else if (sp_host_widget_snapshot(e->host, buf, sizeof(buf)) > 0)
|
|
sp_buf_printf(out, "%s", buf);
|
|
}
|
|
|
|
static void
|
|
cmd_swarm(struct sp_engine *e, const char *args, struct sp_buf *out)
|
|
{
|
|
if (!e->have_swarm || e->swarm.role == SWARM_NONE) {
|
|
sp_buf_printf(out, "swarm: standalone (no fleet in %s)",
|
|
SWARM_PATH);
|
|
return;
|
|
}
|
|
if (args[0] == '\0' || strcmp(args, "ls") == 0 ||
|
|
strcmp(args, "list") == 0) {
|
|
char list[1024];
|
|
|
|
swarm_list(&e->swarm, list, sizeof(list));
|
|
sp_buf_printf(out, "%s", list);
|
|
return;
|
|
}
|
|
{
|
|
const char *p = args;
|
|
char *end;
|
|
long id = -1;
|
|
int target;
|
|
|
|
while (*p == ' ')
|
|
p++;
|
|
if (*p >= '0' && *p <= '9') {
|
|
id = strtol(p, &end, 10);
|
|
p = end;
|
|
while (*p == ' ')
|
|
p++;
|
|
}
|
|
if (*p == '\0') {
|
|
sp_buf_printf(out, "usage: /swarm [N] <text|/cmd> "
|
|
"(0=master, no N=least busy)\n /swarm ls");
|
|
return;
|
|
}
|
|
if (e->swarm.role != SWARM_MASTER && id != 0) {
|
|
sp_buf_printf(out,
|
|
"swarm: only master (0) can route commands");
|
|
return;
|
|
}
|
|
target = swarm_route(&e->swarm, (int)id, p);
|
|
if (target < 0)
|
|
sp_buf_printf(out, "swarm: route failed (id %ld)", id);
|
|
else
|
|
sp_buf_printf(out, "swarm: routed to %d", target);
|
|
}
|
|
}
|
|
|
|
static void
|
|
cmd_agents(struct sp_engine *e, struct sp_buf *out)
|
|
{
|
|
size_t i;
|
|
|
|
for (i = 0; i < e->agents.n; i++) {
|
|
const struct sp_agent_def *d = &e->agents.v[i];
|
|
|
|
sp_buf_printf(out, "%c %-12s %s %s\n",
|
|
(int)i == e->agent_cur ? '*' : ' ', d->name,
|
|
agent_desc(d), d->max_auth == 0 ?
|
|
sp_t("agent.readonly") : "");
|
|
if (strcmp(d->source, "(built in)") != 0)
|
|
sp_buf_printf(out, " %s\n", d->source);
|
|
}
|
|
sp_buf_puts(out, sp_t("agent.help"));
|
|
}
|
|
|
|
/*
|
|
* What the session has cost so far and what the provider told us about it.
|
|
* judge calls happen upstream; the usage object only carries the final answer,
|
|
* so this reports what is measurable and says where it stops.
|
|
*/
|
|
static void
|
|
cmd_cost(struct sp_engine *e, struct sp_buf *out)
|
|
{
|
|
struct sp_agent_stats st = e->snapshot;
|
|
unsigned cachepct = 0;
|
|
|
|
if (st.last_in > 0 && st.last_cached > 0)
|
|
cachepct = (unsigned)(100.0 * (double)st.last_cached /
|
|
(double)st.last_in);
|
|
sp_buf_printf(out, "cost: $%.4f reported, %zu in / %zu out, "
|
|
"last ctx %u%% cached\n", st.cost, st.tokens_in, st.tokens_out,
|
|
cachepct);
|
|
sp_buf_printf(out, "average: $%.5f/turn, %zu ms/turn, %zu calls\n",
|
|
e->judged.turns + e->plain.turns > 0 ?
|
|
st.cost / (double)(e->judged.turns + e->plain.turns) : 0.0,
|
|
e->judged.turns + e->plain.turns > 0 ?
|
|
(e->judged.ms + e->plain.ms) / (e->judged.turns + e->plain.turns) : 0,
|
|
st.tool_calls);
|
|
if (e->judged.turns > 0 || e->plain.turns > 0) {
|
|
sp_buf_printf(out, "judged: %u turns, %.0f ms/turn, "
|
|
"%.0f tok/turn, $%.5f/turn\n", e->judged.turns,
|
|
e->judged.turns ? (double)e->judged.ms / e->judged.turns : 0,
|
|
e->judged.turns ? (double)(e->judged.in + e->judged.out) /
|
|
e->judged.turns : 0,
|
|
e->judged.turns ? e->judged.cost / e->judged.turns : 0);
|
|
sp_buf_printf(out, "plain: %u turns, %.0f ms/turn, "
|
|
"%.0f tok/turn, $%.5f/turn\n", e->plain.turns,
|
|
e->plain.turns ? (double)e->plain.ms / e->plain.turns : 0,
|
|
e->plain.turns ? (double)(e->plain.in + e->plain.out) /
|
|
e->plain.turns : 0,
|
|
e->plain.turns ? e->plain.cost / e->plain.turns : 0);
|
|
if (e->judged.turns > 0 && e->plain.turns > 0)
|
|
sp_buf_printf(out, "delta: %+.0f ms, %+.0f tok, "
|
|
"%+.5f $/turn (judged - plain)\n",
|
|
(double)e->judged.ms / e->judged.turns -
|
|
(double)e->plain.ms / e->plain.turns,
|
|
(double)(e->judged.in + e->judged.out) /
|
|
e->judged.turns -
|
|
(double)(e->plain.in + e->plain.out) /
|
|
e->plain.turns,
|
|
(e->judged.cost / e->judged.turns) -
|
|
(e->plain.cost / e->plain.turns));
|
|
}
|
|
if (strstr(e->cur_model, "judged") != NULL)
|
|
sp_buf_puts(out, "note: judge calls happen upstream; the "
|
|
"provider's usage carries only the final answer, so they "
|
|
"are not in $ or tokens above - only latency and the "
|
|
"reported tokens are measurable\n");
|
|
}
|
|
|
|
int
|
|
sp_engine_input(struct sp_engine *e, const char *line, struct sp_buf *out)
|
|
{
|
|
char name[64], args[1536], cdir[700];
|
|
const char *sp;
|
|
|
|
if (e == NULL || line == NULL || out == NULL)
|
|
return SP_INPUT_HANDLED;
|
|
if (e->cc.active)
|
|
return connect_answer(e, line, out) ?
|
|
SP_INPUT_HANDLED : SP_INPUT_PROMPT;
|
|
if (line[0] == '!' && line[1] != '\0') {
|
|
engine_shell(e, line + 1);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (line[0] != '/' || line[1] == '\0')
|
|
return SP_INPUT_PROMPT;
|
|
/* the harness' own continuation prompt, kept for the old muscle memory */
|
|
if (strcmp(line, "/resume") == 0) {
|
|
sp_buf_puts(out, "Continue with the task you were working on. "
|
|
"Do not repeat work that is already done.");
|
|
return SP_INPUT_PROMPT;
|
|
}
|
|
sp = strchr(line, ' ');
|
|
if (sp == NULL) {
|
|
snprintf(name, sizeof(name), "%.63s", line + 1);
|
|
args[0] = '\0';
|
|
} else {
|
|
size_t nlen = (size_t)(sp - (line + 1));
|
|
|
|
if (nlen >= sizeof(name))
|
|
nlen = sizeof(name) - 1;
|
|
memcpy(name, line + 1, nlen);
|
|
name[nlen] = '\0';
|
|
snprintf(args, sizeof(args), "%s", sp + 1);
|
|
}
|
|
/*
|
|
* Commands that rebuild the conversation or the prompt cannot run in
|
|
* the middle of a turn. They are not steered into the model either: the
|
|
* operator gets an honest "after this turn" and can repeat it then.
|
|
*/
|
|
if (sp_engine_busy(e) &&
|
|
(strcmp(name, "new") == 0 || strcmp(name, "reset") == 0 ||
|
|
strcmp(name, "compact") == 0 || strcmp(name, "agent") == 0 ||
|
|
strcmp(name, "agents") == 0 || strcmp(name, "connect") == 0)) {
|
|
sp_buf_puts(out, sp_t("ui.command_busy"));
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "agent") == 0 || strcmp(name, "agents") == 0) {
|
|
if (args[0] != '\0') {
|
|
int idx = sp_agents_find(&e->agents, args);
|
|
|
|
if (idx < 0) {
|
|
sp_buf_printf(out, sp_t("agent.none"), args);
|
|
sp_buf_puts(out, "\n");
|
|
} else
|
|
(void)agent_switch(e, idx, 1);
|
|
} else
|
|
cmd_agents(e, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "quit") == 0 || strcmp(name, "exit") == 0 ||
|
|
strcmp(name, "q") == 0) {
|
|
e->quit = 1;
|
|
ev_push(e, SP_EV_QUIT, 0, NULL, NULL);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "widgets") == 0 || strcmp(name, "widget") == 0) {
|
|
cmd_widgets(e, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "usage") == 0) {
|
|
sp_usage_report(e->conf, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "compact") == 0) {
|
|
size_t before = sp_conv_bytes(&e->conv);
|
|
size_t msgs = e->conv.n;
|
|
size_t tokens = e->conf != NULL &&
|
|
e->conf->compact_target > 0 ?
|
|
e->conf->compact_target : 8000;
|
|
size_t budget = tokens * 4;
|
|
int changed;
|
|
|
|
if (args[0] != '\0') {
|
|
char *end;
|
|
unsigned long n = strtoul(args, &end, 10);
|
|
|
|
if (*end == '\0' && n > 0 && n < 1000000) {
|
|
tokens = (size_t)n;
|
|
budget = tokens * 4;
|
|
}
|
|
}
|
|
changed = e->host != NULL ?
|
|
sp_host_compact(e->host, &e->conv, budget) : 0;
|
|
sp_buf_printf(out, "compact: %zu->%zu msgs, %zu->%zu bytes "
|
|
"(target %zu tokens)%s", msgs, e->conv.n, before,
|
|
sp_conv_bytes(&e->conv), tokens,
|
|
changed ? "" : " - nothing to do");
|
|
ev_push(e, SP_EV_STATE, 0, NULL, NULL);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "cost") == 0) {
|
|
cmd_cost(e, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "status") == 0) {
|
|
cmd_status(e, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "swarm") == 0) {
|
|
cmd_swarm(e, args, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "model") == 0) {
|
|
cmd_model(e, args, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "new") == 0 || strcmp(name, "reset") == 0) {
|
|
cmd_new(e, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "rename") == 0) {
|
|
cmd_rename(e, args, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "rm") == 0) {
|
|
cmd_rm(e, args, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "continue") == 0) {
|
|
char goal[1001];
|
|
|
|
if (sp_session_get_goal(e->sess.dir, e->sess.id, goal,
|
|
sizeof(goal)) != 0) {
|
|
sp_buf_puts(out, sp_t("focus.none"));
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
sp_buf_printf(out, sp_td("focus.continue_prompt",
|
|
"Continue working toward this goal: %s. Pick up where the "
|
|
"session stopped: check the current state, do the next "
|
|
"concrete step, and report what changed. When the goal is "
|
|
"fully achieved, end your final answer with the single "
|
|
"line GOAL_COMPLETE."), goal);
|
|
return SP_INPUT_PROMPT;
|
|
}
|
|
if (strcmp(name, "connect") == 0) {
|
|
if (sp_config_loaded_path() == NULL) {
|
|
sp_buf_puts(out, sp_t("connect.nodir"));
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
memset(&e->cc, 0, sizeof(e->cc));
|
|
e->cc.active = 1;
|
|
e->cc.step = 0;
|
|
sp_buf_puts(out, sp_t("connect.start"));
|
|
sp_buf_puts(out, "\n");
|
|
connect_ask(&e->cc, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
/*
|
|
* /goal <text> is a command and a prompt: the plugin stores the goal,
|
|
* then a turn asks the model for the short recap that the plugin will
|
|
* inject every few turns. /goal without text stays a status command.
|
|
*/
|
|
if (strcmp(name, "goal") == 0 && args[0] != '\0' && e->host != NULL) {
|
|
struct sp_buf confirm;
|
|
|
|
if (sp_buf_init(&confirm) == 0) {
|
|
int set = sp_host_command(e->host, name, args, &confirm);
|
|
|
|
if (set == 0) {
|
|
if (confirm.p != NULL && confirm.len > 0)
|
|
ev_push(e, SP_EV_ENTRY, 0, "splinter",
|
|
confirm.p);
|
|
sp_buf_clear(out);
|
|
sp_buf_printf(out, sp_td("focus.recap_prompt",
|
|
"Goal: %s. Write a short recap to remember: "
|
|
"3-5 bullets, what must be true at the end, "
|
|
"the first concrete steps, and open "
|
|
"questions. When the goal is fully achieved, "
|
|
"end your final answer with the single line "
|
|
"GOAL_COMPLETE."), args);
|
|
sp_buf_free(&confirm);
|
|
return SP_INPUT_PROMPT;
|
|
}
|
|
sp_buf_free(&confirm);
|
|
}
|
|
}
|
|
if (e->host != NULL && sp_host_command(e->host, name, args, out) == 0)
|
|
return SP_INPUT_HANDLED;
|
|
/*
|
|
* Not a plugin command. A program in commands/ wins over 'unknown': its
|
|
* output is not a reply for the operator, it is context for the model,
|
|
* so the turn runs after this.
|
|
*/
|
|
{
|
|
struct sp_buf cerr;
|
|
|
|
sp_buf_clear(out);
|
|
if (sp_buf_init(&cerr) != 0)
|
|
return SP_INPUT_HANDLED;
|
|
if (sp_cmdscript_dir(e->sess.dir, cdir, sizeof(cdir)) == 0 &&
|
|
sp_cmdscript_exists(cdir, name) &&
|
|
sp_slash_script(cdir, name, args, out, &cerr) == 0 &&
|
|
out->p != NULL) {
|
|
ev_push(e, SP_EV_ENTRY, 0, "shell", out->p);
|
|
sp_buf_free(&cerr);
|
|
return SP_INPUT_SUBMIT;
|
|
}
|
|
sp_buf_free(&cerr);
|
|
}
|
|
sp_buf_clear(out);
|
|
sp_buf_printf(out, sp_t("cmd.unknown"), name);
|
|
sp_buf_printf(out, "\n %s ", sp_t("cmd.available"));
|
|
if (e->host != NULL)
|
|
(void)sp_host_command_help(e->host, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
|
|
/* ---------------------------------------------------------------- opening */
|
|
|
|
/* the session directory and id, opened */
|
|
static int
|
|
open_session(struct sp_engine *e, const struct sp_engine_opts *o,
|
|
struct sp_buf *err, int *code)
|
|
{
|
|
static char sessbuf[512], idbuf[64];
|
|
const char *dir = o->session_dir;
|
|
const char *id = o->session_id;
|
|
const char *envdir = getenv("SPLINTER_SESSION_DIR");
|
|
|
|
/*
|
|
* Tests and throwaway runs get their own directory without a config:
|
|
* the suite used to create hundreds of "hallo" sessions in the user's
|
|
* ~/.splinter because --no-config does not change where sessions go.
|
|
*/
|
|
if (dir == NULL && envdir != NULL && *envdir != '\0')
|
|
dir = envdir;
|
|
if (dir == NULL) {
|
|
const char *home = getenv("HOME");
|
|
|
|
snprintf(sessbuf, sizeof(sessbuf), "%s/.splinter",
|
|
home != NULL ? home : ".");
|
|
dir = sessbuf;
|
|
}
|
|
/*
|
|
* -c means "the last session that happened *here*". The cwd at start is
|
|
* the key, so a session in another tree is never silently loaded.
|
|
*/
|
|
if (o->continue_last && id == NULL) {
|
|
char cwd[512];
|
|
|
|
if (getcwd(cwd, sizeof(cwd)) == NULL ||
|
|
sp_session_last_for(dir, cwd, idbuf, sizeof(idbuf)) != 0) {
|
|
sp_buf_printf(err, "no session in %s yet",
|
|
getcwd(cwd, sizeof(cwd)) != NULL ? cwd : ".");
|
|
*code = -2;
|
|
return -1;
|
|
}
|
|
id = idbuf;
|
|
}
|
|
if ((o->resume || o->continue_last) && id == NULL &&
|
|
sp_session_latest(dir, idbuf, sizeof(idbuf)) == 0)
|
|
id = idbuf;
|
|
if (id == NULL) {
|
|
new_session_id(idbuf, sizeof(idbuf));
|
|
id = idbuf;
|
|
}
|
|
if (sp_session_open(&e->sess, dir, id, err) != 0)
|
|
return -1;
|
|
(void)sp_log_open(e->sess.dir, e->sess.id);
|
|
/*
|
|
* The cli transport keys the program's own session on this, so claude or
|
|
* opencode continue one conversation for the whole splinter session.
|
|
*/
|
|
(void)setenv("SPLINTER_CLI_SESSION", e->sess.id, 0);
|
|
sp_openai_set_session(e->sess.id);
|
|
return 0;
|
|
}
|
|
|
|
/* the plugin host and its plugins; a failed plugin is reported and skipped */
|
|
static int
|
|
load_plugins(struct sp_engine *e, const struct sp_engine_opts *o,
|
|
struct sp_buf *err)
|
|
{
|
|
struct sp_host *host;
|
|
size_t k;
|
|
|
|
if (o->nplugins == 0)
|
|
return 0;
|
|
host = sp_host_new(&e->reg, &e->ag, &e->sess);
|
|
if (host == NULL) {
|
|
sp_buf_puts(err, "cannot create plugin host");
|
|
return -1;
|
|
}
|
|
e->ag.host = host;
|
|
e->host = host;
|
|
sp_host_set_config(host, e->conf);
|
|
sp_host_set_model(host, e->cur_model);
|
|
for (k = 0; k < o->nplugins && k < SP_ENGINE_PLUGINS; k++) {
|
|
const char *p = o->plugins[k];
|
|
char self[512], found[800];
|
|
ssize_t sn;
|
|
|
|
/*
|
|
* A bare name ("lcm", from plugin lcm { }) is a shipped plugin:
|
|
* the tree next to the binary, then the installed layout.
|
|
*/
|
|
if (strchr(p, '/') == NULL &&
|
|
(strlen(p) < 3 || strcmp(p + strlen(p) - 3, ".so") != 0)) {
|
|
sn = readlink("/proc/self/exe", self, sizeof(self) - 1);
|
|
self[sn > 0 ? sn : 0] = '\0';
|
|
sp_plugin_path(self, p, found, sizeof(found));
|
|
p = found;
|
|
}
|
|
sp_buf_clear(err);
|
|
if (sp_plugin_load(host, p, err) != 0)
|
|
fprintf(stderr, "splinter: %s\n", err->len > 0 ? err->p :
|
|
sp_t("err.plugin_failed"));
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* a script file is one reply per line, in the mock transport's own protocol */
|
|
static int
|
|
load_script(struct sp_mock *m, const char *path, struct sp_buf *err)
|
|
{
|
|
FILE *f;
|
|
char line[8192];
|
|
|
|
f = fopen(path, "r");
|
|
if (f == NULL) {
|
|
sp_buf_printf(err, "%s: %s", path, strerror(errno));
|
|
return -1;
|
|
}
|
|
while (fgets(line, sizeof(line), f) != NULL) {
|
|
line[strcspn(line, "\r\n")] = '\0';
|
|
if (line[0] == '\0' || line[0] == '#')
|
|
continue;
|
|
if (sp_mock_push(m, 200, line) != 0) {
|
|
fclose(f);
|
|
sp_buf_puts(err, sp_t("err.oom"));
|
|
return -1;
|
|
}
|
|
}
|
|
fclose(f);
|
|
return 0;
|
|
}
|
|
|
|
/* the transport the options name */
|
|
static int
|
|
pick_transport(struct sp_engine *e, const struct sp_engine_opts *o,
|
|
struct sp_buf *err)
|
|
{
|
|
const char *hto;
|
|
long http_timeout;
|
|
|
|
if (o->no_transport)
|
|
return 0;
|
|
if (o->kind != NULL && strcmp(o->kind, "anthropic") == 0) {
|
|
if (o->endpoint == NULL || o->model == NULL) {
|
|
sp_buf_puts(err, "an anthropic provider needs an "
|
|
"endpoint and a model");
|
|
return -1;
|
|
}
|
|
hto = getenv("SPLINTER_HTTP_TIMEOUT");
|
|
http_timeout = hto != NULL && *hto != '\0' ?
|
|
strtol(hto, NULL, 10) : 0;
|
|
if (http_timeout <= 0)
|
|
http_timeout = 900;
|
|
e->ag.tr = sp_anthropic_transport(o->endpoint, o->model,
|
|
getenv(o->key_env), &e->reg, http_timeout);
|
|
sp_provider_identify(&e->ag.tr, o->endpoint,
|
|
getenv(o->key_env));
|
|
return 0;
|
|
}
|
|
if (o->transport != NULL) {
|
|
struct sp_transport *tr;
|
|
|
|
if (e->host == NULL) {
|
|
sp_buf_puts(err, "--transport needs a plugin that "
|
|
"provides it");
|
|
return -1;
|
|
}
|
|
tr = sp_host_transport(e->host, o->transport);
|
|
if (tr == NULL) {
|
|
sp_buf_printf(err, "no plugin provides the '%s' "
|
|
"transport", o->transport);
|
|
return -1;
|
|
}
|
|
e->ag.tr = *tr;
|
|
return 0;
|
|
}
|
|
if (o->script != NULL) {
|
|
if (sp_mock_init(&e->mock) != 0) {
|
|
sp_buf_puts(err, sp_t("err.oom"));
|
|
return -1;
|
|
}
|
|
e->have_mock = 1;
|
|
if (load_script(&e->mock, o->script, err) != 0)
|
|
return -1;
|
|
e->ag.tr = sp_mock_transport(&e->mock);
|
|
return 0;
|
|
}
|
|
if (o->endpoint == NULL) {
|
|
sp_buf_puts(err, "no endpoint");
|
|
return -1;
|
|
}
|
|
if (o->model == NULL) {
|
|
sp_buf_puts(err, "--endpoint needs --model");
|
|
return -1;
|
|
}
|
|
hto = getenv("SPLINTER_HTTP_TIMEOUT");
|
|
http_timeout = hto != NULL && *hto != '\0' ? strtol(hto, NULL, 10) : 0;
|
|
if (http_timeout <= 0)
|
|
http_timeout = 900;
|
|
e->ag.tr = sp_openai_transport(o->endpoint, o->model,
|
|
getenv(o->key_env), &e->reg, http_timeout);
|
|
sp_provider_identify(&e->ag.tr, o->endpoint, getenv(o->key_env));
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
* The conversation: the system prompt, expanded (placeholders are facts about
|
|
* this machine), and with --resume the session's history.
|
|
*/
|
|
static int
|
|
setup_conversation(struct sp_engine *e, const struct sp_engine_opts *o,
|
|
struct sp_buf *err)
|
|
{
|
|
size_t loaded = 0;
|
|
|
|
sp_conv_init(&e->conv);
|
|
if (o->interview)
|
|
e->base.system_prompt = sp_interview_system();
|
|
sp_prompt_expand(e->base.system_prompt, e->prompt_expanded,
|
|
sizeof(e->prompt_expanded), o->model);
|
|
e->base.system_prompt = e->prompt_expanded;
|
|
if (e->base.system_prompt != NULL &&
|
|
e->base.system_prompt[0] != '\0' &&
|
|
sp_conv_push(&e->conv, "system", NULL,
|
|
e->base.system_prompt) != 0) {
|
|
sp_buf_puts(err, sp_t("err.oom"));
|
|
return -1;
|
|
}
|
|
e->ag.conv = &e->conv;
|
|
if (!o->resume && !o->continue_last)
|
|
return 0;
|
|
sp_buf_clear(err);
|
|
if (sp_session_load(&e->sess, &e->conv, &loaded, err) != 0)
|
|
return -1;
|
|
return 0;
|
|
}
|
|
|
|
int
|
|
sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o,
|
|
struct sp_buf *err)
|
|
{
|
|
struct sp_engine_opts local;
|
|
struct sp_engine *e;
|
|
char cwd[700];
|
|
int start = -1, code = -1;
|
|
|
|
if (out == NULL || o == NULL || o->conf == NULL || o->base == NULL)
|
|
return -1;
|
|
*out = NULL;
|
|
/*
|
|
* The model a session was left on wins over the configuration when the
|
|
* session comes back: a choice made with /model belongs to the
|
|
* conversation, not to every later start.
|
|
*/
|
|
local = *o;
|
|
o = &local;
|
|
e = calloc(1, sizeof(*e));
|
|
if (e == NULL) {
|
|
sp_buf_puts(err, sp_t("err.oom"));
|
|
return -1;
|
|
}
|
|
pthread_mutex_init(&e->lock, NULL);
|
|
pthread_mutex_init(&e->model_lock, NULL);
|
|
pthread_cond_init(&e->cond, NULL);
|
|
sp_buf_init(&e->answer);
|
|
sp_buf_init(&e->err);
|
|
sp_buf_init(&e->live);
|
|
sp_buf_init(&e->think);
|
|
sp_buf_init(&e->steer);
|
|
e->conf = o->conf;
|
|
e->base = *o->base;
|
|
if (e->conf != NULL) {
|
|
e->base.compact_threshold = e->conf->compact_threshold;
|
|
e->base.compact_target = e->conf->compact_target;
|
|
}
|
|
e->max_wait = o->conf->max_wait > 0 ? o->conf->max_wait : 12 * 3600;
|
|
/*
|
|
* A pool must be able to move the run to another member at a limit --
|
|
* also on the synchronous path (-p), which does not build the async
|
|
* turn's config. This is where the old binary did it, for every mode.
|
|
*/
|
|
if (e->conf->npools > 0) {
|
|
e->base.limit_switch = engine_switch;
|
|
e->base.switch_ctx = e;
|
|
}
|
|
snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), "%s",
|
|
o->endpoint != NULL ? o->endpoint : "");
|
|
snprintf(e->cur_model, sizeof(e->cur_model), "%s",
|
|
o->model != NULL ? o->model : "");
|
|
if (o->endpoint == NULL && o->conf->endpoint[0] != '\0')
|
|
snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), "%s",
|
|
o->conf->endpoint);
|
|
if (o->model == NULL && o->conf->model[0] != '\0')
|
|
snprintf(e->cur_model, sizeof(e->cur_model), "%s",
|
|
o->conf->model);
|
|
|
|
if (sp_builtin_register(&e->reg) != 0 ||
|
|
sp_skills_register(&e->reg, e->conf) != 0) {
|
|
sp_buf_puts(err, "cannot register the builtin tools");
|
|
goto fail;
|
|
}
|
|
if (open_session(e, o, err, &code) != 0)
|
|
goto fail;
|
|
e->ag.sess = &e->sess;
|
|
sp_logf("session", "started: %s", e->sess.id);
|
|
if (load_plugins(e, o, err) != 0)
|
|
goto fail;
|
|
/*
|
|
* Registered here, not with the builtins: folder_history needs the
|
|
* session directory, and delegate needs the host for its task-panel
|
|
* entries.
|
|
*/
|
|
if (sp_folder_register(&e->reg, e->sess.dir) != 0 ||
|
|
sp_delegate_register(&e->reg, e->conf, e->host) != 0) {
|
|
sp_buf_puts(err, "cannot register folder_history or delegate");
|
|
goto fail;
|
|
}
|
|
if (pick_transport(e, o, err) != 0) {
|
|
code = -2; /* a configuration the user can fix */
|
|
goto fail;
|
|
}
|
|
/*
|
|
* /model shows the run's providers, and a command line is part of the
|
|
* run: --endpoint/--model without a config file still has a provider.
|
|
*/
|
|
{
|
|
/*
|
|
* -m junction/model sets o->endpoint/model, but that is not a
|
|
* main provider: junction is. Copying it into the config made
|
|
* the picker show a phantom "main" beside the real provider.
|
|
* Only an endpoint that came from the command line without a
|
|
* matching configured provider becomes main.
|
|
*/
|
|
const char *act = sp_usage_active();
|
|
int from_provider = 0;
|
|
|
|
if (act != NULL && *act != '\0' &&
|
|
strcmp(act, "main") != 0 &&
|
|
sp_provider_find(e->conf, act, NULL))
|
|
from_provider = 1;
|
|
if (!from_provider) {
|
|
if (e->conf->endpoint[0] == '\0' && o->endpoint != NULL)
|
|
snprintf(e->conf->endpoint,
|
|
sizeof(e->conf->endpoint), "%s",
|
|
o->endpoint);
|
|
if (e->conf->model[0] == '\0' && o->model != NULL)
|
|
snprintf(e->conf->model,
|
|
sizeof(e->conf->model), "%.255s",
|
|
o->model);
|
|
}
|
|
}
|
|
if (setup_conversation(e, o, err) != 0)
|
|
goto fail;
|
|
e->ag.reg = &e->reg;
|
|
e->ag.cfg = &e->base;
|
|
if (getcwd(cwd, sizeof(cwd)) == NULL)
|
|
cwd[0] = '\0';
|
|
if (!o->interview &&
|
|
sp_agents_load(&e->agents, cwd, getenv("HOME")) != 0) {
|
|
sp_buf_puts(err, "cannot load the agent profiles");
|
|
goto fail;
|
|
}
|
|
e->base_prompt = sp_agents_base(&e->conv);
|
|
{
|
|
/*
|
|
* What the interview learned about the user rides in the system
|
|
* prompt of every session, not in a tool the model has to call.
|
|
*/
|
|
char *ub = sp_interview_user_block(e->sess.dir);
|
|
|
|
if (ub != NULL) {
|
|
size_t bl = e->base_prompt != NULL ?
|
|
strlen(e->base_prompt) : 0;
|
|
char *nb = malloc(bl + strlen(ub) + 1);
|
|
|
|
if (nb != NULL) {
|
|
snprintf(nb, bl + strlen(ub) + 1, "%s%s",
|
|
e->base_prompt != NULL ? e->base_prompt : "",
|
|
ub);
|
|
free(e->base_prompt);
|
|
e->base_prompt = nb;
|
|
}
|
|
free(ub);
|
|
}
|
|
}
|
|
if (e->agents.n == 0 && e->base_prompt != NULL && e->conv.n > 0 &&
|
|
e->conv.v[0].role != NULL &&
|
|
strcmp(e->conv.v[0].role, "system") == 0) {
|
|
char *copy = strdup(e->base_prompt);
|
|
|
|
if (copy != NULL) {
|
|
free(e->conv.v[0].content);
|
|
e->conv.v[0].content = copy;
|
|
}
|
|
}
|
|
if (e->agents.n > 0) {
|
|
char saved[48];
|
|
|
|
if (o->agent != NULL && *o->agent != '\0') {
|
|
start = sp_agents_find(&e->agents, o->agent);
|
|
if (start < 0) {
|
|
sp_buf_printf(err, "no agent '%s' "
|
|
"(splinter --agent-list)", o->agent);
|
|
code = -2;
|
|
goto fail;
|
|
}
|
|
} else if (profile_load(e, saved, sizeof(saved)))
|
|
start = sp_agents_find(&e->agents, saved);
|
|
if (start < 0)
|
|
start = sp_agents_find(&e->agents, "build");
|
|
if (start < 0)
|
|
start = 0;
|
|
if (agent_switch(e, start, 0) != 0) {
|
|
sp_buf_puts(err, "cannot activate the agent profile");
|
|
code = -2;
|
|
goto fail;
|
|
}
|
|
}
|
|
if (o->swarm) {
|
|
swarm_init(&e->swarm, cwd);
|
|
e->have_swarm = 1;
|
|
}
|
|
*out = e;
|
|
return 0;
|
|
fail:
|
|
sp_engine_close(e);
|
|
return code;
|
|
}
|
|
|
|
void
|
|
sp_engine_close(struct sp_engine *e)
|
|
{
|
|
if (e == NULL)
|
|
return;
|
|
if (sp_engine_busy(e))
|
|
(void)sp_engine_cancel(e);
|
|
engine_join(e);
|
|
if (e->have_swarm)
|
|
swarm_close(&e->swarm);
|
|
sp_transport_dispose(&e->ag.tr);
|
|
sp_buf_free(&e->answer);
|
|
sp_buf_free(&e->err);
|
|
sp_buf_free(&e->live);
|
|
sp_buf_free(&e->think);
|
|
sp_buf_free(&e->steer);
|
|
free(e->base_prompt);
|
|
free(e->turn_text);
|
|
sp_agents_free(&e->agents);
|
|
sp_conv_free(&e->conv);
|
|
sp_host_free(e->host);
|
|
sp_registry_free(&e->reg);
|
|
if (e->have_mock)
|
|
sp_mock_free(&e->mock);
|
|
while (e->nq > 0) {
|
|
sp_engine_event_free(&e->q[0]);
|
|
memmove(&e->q[0], &e->q[1], (e->nq - 1) * sizeof(e->q[0]));
|
|
e->nq--;
|
|
}
|
|
free(e->q);
|
|
pthread_cond_destroy(&e->cond);
|
|
pthread_mutex_destroy(&e->model_lock);
|
|
pthread_mutex_destroy(&e->lock);
|
|
free(e);
|
|
}
|
|
|
|
/* a session id that is one file name, nothing else */
|
|
static int
|
|
valid_session_id(const char *id)
|
|
{
|
|
size_t i, n;
|
|
|
|
if (id == NULL || *id == '\0')
|
|
return 0;
|
|
n = strlen(id);
|
|
if (n >= sizeof(((struct sp_session_info *)0)->id))
|
|
return 0;
|
|
for (i = 0; i < n; i++)
|
|
if (!isalnum((unsigned char)id[i]) && id[i] != '-' &&
|
|
id[i] != '_' && id[i] != '.')
|
|
return 0;
|
|
return strstr(id, "..") == NULL;
|
|
}
|
|
|
|
int
|
|
sp_engine_switch(struct sp_engine **ep, const struct sp_engine_opts *tmpl,
|
|
const char *id, struct sp_buf *err)
|
|
{
|
|
struct sp_engine_opts o, back;
|
|
struct sp_engine *old, *ne = NULL;
|
|
struct sp_buf oerr;
|
|
char keep[64], path[800], picked[64];
|
|
const char *dir;
|
|
int rc;
|
|
|
|
if (ep == NULL || *ep == NULL || tmpl == NULL) {
|
|
if (err != NULL)
|
|
sp_buf_puts(err, "no engine to switch");
|
|
return -1;
|
|
}
|
|
old = *ep;
|
|
if (sp_engine_busy(old)) {
|
|
if (err != NULL)
|
|
sp_buf_puts(err, "a turn is running");
|
|
return -1;
|
|
}
|
|
snprintf(keep, sizeof(keep), "%s", sp_engine_session_id(old));
|
|
dir = sp_engine_state_dir(old);
|
|
o = *tmpl;
|
|
if (id == NULL || strcmp(id, "last") == 0) {
|
|
o.session_id = NULL;
|
|
o.resume = 1;
|
|
o.continue_last = 0;
|
|
} else if (strcmp(id, "new") == 0) {
|
|
o.session_id = NULL;
|
|
o.resume = 0;
|
|
o.continue_last = 0;
|
|
} else {
|
|
if (!valid_session_id(id)) {
|
|
if (err != NULL)
|
|
sp_buf_puts(err, "invalid session id");
|
|
return -1;
|
|
}
|
|
/*
|
|
* Copy the id before the old engine is closed: a caller may
|
|
* have passed sp_engine_session_id() of that very engine.
|
|
*/
|
|
snprintf(picked, sizeof(picked), "%s", id);
|
|
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, picked);
|
|
if (access(path, R_OK) != 0) {
|
|
if (err != NULL)
|
|
sp_buf_puts(err, "no such session");
|
|
return -1;
|
|
}
|
|
o.session_id = picked;
|
|
o.resume = 1;
|
|
o.continue_last = 0;
|
|
}
|
|
/* one plugin instance at a time: close before the next open */
|
|
*ep = NULL;
|
|
sp_engine_close(old);
|
|
sp_buf_init(&oerr);
|
|
rc = sp_engine_open(&ne, &o, &oerr);
|
|
if (rc == 0) {
|
|
*ep = ne;
|
|
sp_buf_free(&oerr);
|
|
return 0;
|
|
}
|
|
/*
|
|
* The session did not open. Put the engine back on the session it had,
|
|
* so the front end still has a working conversation; only if that also
|
|
* fails does *ep stay NULL and the caller has to stop.
|
|
*/
|
|
back = *tmpl;
|
|
back.session_id = keep;
|
|
back.resume = 1;
|
|
back.continue_last = 0;
|
|
if (sp_engine_open(&ne, &back, &oerr) == 0) {
|
|
*ep = ne;
|
|
} else {
|
|
struct sp_engine_opts fresh = *tmpl;
|
|
|
|
fresh.session_id = NULL;
|
|
fresh.resume = 0;
|
|
fresh.continue_last = 0;
|
|
if (sp_engine_open(&ne, &fresh, &oerr) == 0)
|
|
*ep = ne;
|
|
}
|
|
if (err != NULL) {
|
|
if (oerr.len > 0 && oerr.p != NULL)
|
|
sp_buf_printf(err, "cannot open the session: %s",
|
|
oerr.p);
|
|
else
|
|
sp_buf_puts(err, "cannot open the session");
|
|
}
|
|
sp_buf_free(&oerr);
|
|
return -1;
|
|
}
|