The operator's claude ran into its limit mid-work; the session was too full to continue there. The foreign plugin could already read and import it, but only through a tool call inside a turn - there was no way in from the command line. --claude, --opencode, --hermes and --from=NAME make the newest session that tool ran in this directory the session of the run: it is imported before the history is loaded, so the first turn already carries it. -c no longer fails in a folder that has no splinter session yet; it falls back to "no session" and lets the import decide. An empty placeholder session is removed again, whether the import worked or not. Repeating the call continues the same session instead of importing a second time: sp_session_foreign() reads the foreign= marker back, so the work done in splinter is kept. A second foreign_import into the same session replaces the history rather than appending it twice (path_join built "id/.jsonl", so the replace branch never fired). Test: tests/test_foreignopen.c builds a claude fixture under its own HOME and covers import, idempotency, replace-not-append, the empty placeholder and a folder with no foreign session. make check exit 0, check_asan.sh clean.
3843 lines
106 KiB
C
3843 lines
106 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 "embed.h"
|
|
#include "foreignopen.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];
|
|
};
|
|
|
|
/* one kind of turn, for /cost */
|
|
struct engine_tally {
|
|
unsigned turns;
|
|
unsigned long ms;
|
|
size_t in, out;
|
|
double cost;
|
|
};
|
|
|
|
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;
|
|
/* the session's embedding index: background thread, never on the turn */
|
|
struct sp_embed_ctx *emb;
|
|
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;
|
|
/*
|
|
* A /compact typed while a turn runs. The conversation belongs to the
|
|
* worker, so compacting now would race its appends and its realloc; and
|
|
* refusing the command outright was worse than it sounds: the operator
|
|
* sees "not while a turn runs" for a command that reads as instant, and
|
|
* by the time the turn is over nobody repeats it. Measured on a 253 KB
|
|
* request whose operator had run /compact three times (2026-11-22).
|
|
* So the request is kept - with the token target it was asked for - and
|
|
* applied where the turn thread no longer touches the conversation.
|
|
*/
|
|
size_t pend_compact_tokens;
|
|
int has_pend_compact;
|
|
/*
|
|
* Held by whoever works on the agent outside the turn thread: a
|
|
* daemon's Telegram turn for its whole length, an MCP session tool for
|
|
* one call. Taken with trylock only; the loser answers "busy".
|
|
*/
|
|
pthread_mutex_t turn_mx;
|
|
int ext_busy; /* a foreign turn holds turn_mx */
|
|
struct sp_engine *next_open; /* the list of open engines */
|
|
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 engine_tally 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 *);
|
|
static void engine_apply_pending_compact(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 void open_add(struct sp_engine *);
|
|
static void open_del(struct sp_engine *);
|
|
static int capture_interview(struct sp_engine *, struct sp_buf *);
|
|
|
|
/* ------------------------------------------------------------- snapshot */
|
|
|
|
/*
|
|
* cur_model/cur_endpoint change on the turn thread when a deferred /model is
|
|
* applied between requests, while the front end reads them. Writes and the
|
|
* front end's reads go through e->lock; never call these with it held.
|
|
*/
|
|
static void
|
|
cur_set(struct sp_engine *e, const char *model, const char *endpoint)
|
|
{
|
|
pthread_mutex_lock(&e->lock);
|
|
if (model != NULL)
|
|
snprintf(e->cur_model, sizeof(e->cur_model), "%s", model);
|
|
if (endpoint != NULL)
|
|
snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), "%s",
|
|
endpoint);
|
|
pthread_mutex_unlock(&e->lock);
|
|
}
|
|
|
|
static void
|
|
cur_get(struct sp_engine *e, char *model, size_t mcap, char *endpoint,
|
|
size_t ecap)
|
|
{
|
|
pthread_mutex_lock(&e->lock);
|
|
if (model != NULL && mcap > 0)
|
|
snprintf(model, mcap, "%s", e->cur_model);
|
|
if (endpoint != NULL && ecap > 0)
|
|
snprintf(endpoint, ecap, "%s", e->cur_endpoint);
|
|
pthread_mutex_unlock(&e->lock);
|
|
}
|
|
|
|
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));
|
|
cur_get(e, st->model, sizeof(st->model), st->endpoint,
|
|
sizeof(st->endpoint));
|
|
if (e->host != NULL)
|
|
sp_host_set_model(e->host, st->model);
|
|
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->cached_total = e->snapshot.tokens_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 || e->ext_busy;
|
|
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)
|
|
{
|
|
char model[256];
|
|
|
|
if (e == NULL)
|
|
return 0;
|
|
cur_get(e, model, sizeof(model), NULL, 0);
|
|
return sp_provider_choices(e->conf, 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;
|
|
char cmodel[256], cendpoint[512];
|
|
|
|
if (e == NULL || e->conf == NULL || v == NULL || max == 0)
|
|
return 0;
|
|
cur_get(e, cmodel, sizeof(cmodel), cendpoint, sizeof(cendpoint));
|
|
if (cendpoint[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, cendpoint) == 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", cendpoint);
|
|
snprintf(p.model, sizeof(p.model), "%s", cmodel);
|
|
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, cmodel) == 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);
|
|
}
|
|
|
|
/* <session dir>/<id>.model: the model /model chose in this session */
|
|
static void
|
|
session_model_path(struct sp_engine *e, char *buf, size_t cap)
|
|
{
|
|
snprintf(buf, cap, "%s/%s.model", e->sess.dir, e->sess.id);
|
|
}
|
|
|
|
static int
|
|
session_model_save(struct sp_engine *e, const char *sel, char *err,
|
|
size_t errcap)
|
|
{
|
|
char path[800], tmp[820];
|
|
FILE *f;
|
|
|
|
if (e == NULL || sel == NULL || *sel == '\0')
|
|
return -1;
|
|
session_model_path(e, path, sizeof(path));
|
|
snprintf(tmp, sizeof(tmp), "%s.tmp", path);
|
|
f = fopen(tmp, "w");
|
|
if (f == NULL) {
|
|
if (err != NULL && errcap > 0)
|
|
snprintf(err, errcap, "%s", strerror(errno));
|
|
return -1;
|
|
}
|
|
(void)fchmod(fileno(f), 0600);
|
|
fprintf(f, "%s\n", sel);
|
|
if (fclose(f) != 0 || rename(tmp, path) != 0) {
|
|
if (err != NULL && errcap > 0)
|
|
snprintf(err, errcap, "%s", strerror(errno));
|
|
(void)unlink(tmp);
|
|
return -1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int
|
|
session_model_read(struct sp_engine *e, char *buf, size_t cap)
|
|
{
|
|
char path[800], line[320];
|
|
FILE *f;
|
|
size_t n;
|
|
|
|
if (e == NULL || e->sess.dir[0] == '\0' || buf == NULL || cap == 0)
|
|
return -1;
|
|
session_model_path(e, path, sizeof(path));
|
|
f = fopen(path, "r");
|
|
if (f == NULL)
|
|
return -1;
|
|
if (fgets(line, sizeof(line), f) == NULL) {
|
|
fclose(f);
|
|
return -1;
|
|
}
|
|
fclose(f);
|
|
line[strcspn(line, "\r\n")] = '\0';
|
|
n = strlen(line);
|
|
if (n == 0 || n >= cap)
|
|
return -1;
|
|
memcpy(buf, line, n + 1);
|
|
return 0;
|
|
}
|
|
|
|
/* the selector that puts this engine back on the model it is on now */
|
|
static void
|
|
current_model_selector(struct sp_engine *e, char *buf, size_t cap)
|
|
{
|
|
const char *act = sp_usage_active();
|
|
|
|
if (act != NULL && *act != '\0')
|
|
snprintf(buf, cap, "%s/%s", sp_provider_label(act),
|
|
e->cur_model);
|
|
else
|
|
snprintf(buf, cap, "%s", e->cur_model);
|
|
}
|
|
|
|
/* the transcript note after a successful /model: saved in this session */
|
|
static void
|
|
session_model_note(struct sp_engine *e, const char *sel, struct sp_buf *out,
|
|
const char *model, const char *provider)
|
|
{
|
|
char err[128];
|
|
|
|
err[0] = '\0';
|
|
if (session_model_save(e, sel, err, sizeof(err)) != 0)
|
|
sp_buf_printf(out, sp_t("model.save_failed"), model, provider,
|
|
err[0] != '\0' ? err : "?");
|
|
else
|
|
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.
|
|
*/
|
|
/* Append s, clamped: the result never points past the terminator. */
|
|
static size_t
|
|
pretty_put(char *out, size_t cap, size_t n, const char *s)
|
|
{
|
|
int w;
|
|
|
|
if (n + 1 >= cap)
|
|
return n;
|
|
w = snprintf(out + n, cap - n, "%s", s);
|
|
if (w < 0)
|
|
return n;
|
|
if ((size_t)w >= cap - n)
|
|
return cap - 1;
|
|
return n + (size_t)w;
|
|
}
|
|
|
|
static void
|
|
pretty_args(const char *json, char *out, size_t cap)
|
|
{
|
|
const char *p = json;
|
|
size_t n = 0;
|
|
int first = 1;
|
|
|
|
if (cap == 0)
|
|
return;
|
|
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 = pretty_put(out, cap, n, " ");
|
|
first = 0;
|
|
n = pretty_put(out, cap, n, key);
|
|
n = pretty_put(out, cap, n, ": ");
|
|
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);
|
|
/*
|
|
* What compaction just dropped stays in the session file, and this is
|
|
* the moment it becomes worth finding again. The call only raises a
|
|
* flag; the embedding runs on its own thread.
|
|
*/
|
|
sp_embed_note_compaction(e->emb);
|
|
}
|
|
|
|
/* ----------------------------------------------------------------- turns */
|
|
|
|
/*
|
|
* Book one run of the agent into the judged/plain totals. A leftover steer
|
|
* starts another run in the same worker and moves the baselines, so each run
|
|
* is booked when it ends, not once for the whole worker. Returns the run's
|
|
* output tokens. Called on the turn thread, which owns ag.stats.
|
|
*/
|
|
static size_t
|
|
account_run(struct sp_engine *e, const struct timespec *t0)
|
|
{
|
|
struct timespec now;
|
|
unsigned long ms;
|
|
size_t tin, tout;
|
|
double c;
|
|
struct engine_tally *k;
|
|
|
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
|
ms = (unsigned long)((now.tv_sec - t0->tv_sec) * 1000 +
|
|
(now.tv_nsec - t0->tv_nsec) / 1000000);
|
|
pthread_mutex_lock(&e->lock);
|
|
tin = e->ag.stats.tokens_in >= e->turn_in0 ?
|
|
e->ag.stats.tokens_in - e->turn_in0 : 0;
|
|
tout = e->ag.stats.tokens_out >= e->turn_out0 ?
|
|
e->ag.stats.tokens_out - e->turn_out0 : 0;
|
|
c = e->ag.stats.cost >= e->turn_cost0 ?
|
|
e->ag.stats.cost - e->turn_cost0 : 0;
|
|
k = strstr(e->cur_model, "judged") != NULL ? &e->judged : &e->plain;
|
|
k->turns++;
|
|
k->ms += ms;
|
|
k->in += tin;
|
|
k->out += tout;
|
|
k->cost += c;
|
|
pthread_mutex_unlock(&e->lock);
|
|
return tout;
|
|
}
|
|
|
|
static void *
|
|
turn_thread(void *arg)
|
|
{
|
|
struct sp_engine *e = arg;
|
|
char *text = e->turn_text;
|
|
size_t steps0, calls0, out_sum = 0;
|
|
|
|
/* the sidebar's "last turn" is the whole worker, steers included */
|
|
steps0 = e->ag.stats.steps;
|
|
calls0 = e->ag.stats.tool_calls;
|
|
for (;;) {
|
|
int rc;
|
|
char *next = NULL;
|
|
struct timespec run_t0;
|
|
|
|
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);
|
|
clock_gettime(CLOCK_MONOTONIC, &run_t0);
|
|
rc = sp_agent_run(&e->ag, text, &e->answer, &e->err);
|
|
/* booked on the model that ran, before a pending /model moves it */
|
|
out_sum += account_run(e, &run_t0);
|
|
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);
|
|
/*
|
|
* A /compact typed while this turn ran. After the model switch, so
|
|
* the budget runs against the compactor of the provider that is
|
|
* about to send, and before the turn is marked idle, so the
|
|
* operator's next keystroke finds a compacted conversation.
|
|
*/
|
|
engine_apply_pending_compact(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 = out_sum;
|
|
e->last_steps = e->ag.stats.steps >= steps0 ?
|
|
e->ag.stats.steps - steps0 : 0;
|
|
e->last_calls = e->ag.stats.tool_calls >= calls0 ?
|
|
e->ag.stats.tool_calls - calls0 : 0;
|
|
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;
|
|
}
|
|
|
|
static int engine_submit(struct sp_engine *, const char *);
|
|
|
|
/*
|
|
* A turn starts only while nobody else works on the agent: turn_mx is held
|
|
* while the turn is marked running, so a foreign turn either sees it running
|
|
* or keeps it from starting.
|
|
*/
|
|
int
|
|
sp_engine_submit(struct sp_engine *e, const char *text)
|
|
{
|
|
int rc;
|
|
|
|
if (e == NULL || text == NULL || *text == '\0')
|
|
return -1;
|
|
if (pthread_mutex_trylock(&e->turn_mx) != 0)
|
|
return -1;
|
|
rc = engine_submit(e, text);
|
|
pthread_mutex_unlock(&e->turn_mx);
|
|
return rc;
|
|
}
|
|
|
|
static int
|
|
engine_submit(struct sp_engine *e, const char *text)
|
|
{
|
|
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 || e->ext_busy;
|
|
pthread_mutex_unlock(&e->lock);
|
|
return busy;
|
|
}
|
|
|
|
/* ---------------------------------------------- turns outside the engine */
|
|
|
|
/*
|
|
* The open engines, so a caller that only has the agent (the Telegram loop)
|
|
* can find the engine that owns it.
|
|
*/
|
|
static pthread_mutex_t open_mx = PTHREAD_MUTEX_INITIALIZER;
|
|
static struct sp_engine *open_list;
|
|
|
|
static void
|
|
open_add(struct sp_engine *e)
|
|
{
|
|
pthread_mutex_lock(&open_mx);
|
|
e->next_open = open_list;
|
|
open_list = e;
|
|
pthread_mutex_unlock(&open_mx);
|
|
}
|
|
|
|
static void
|
|
open_del(struct sp_engine *e)
|
|
{
|
|
struct sp_engine **pp;
|
|
|
|
pthread_mutex_lock(&open_mx);
|
|
for (pp = &open_list; *pp != NULL; pp = &(*pp)->next_open)
|
|
if (*pp == e) {
|
|
*pp = e->next_open;
|
|
break;
|
|
}
|
|
pthread_mutex_unlock(&open_mx);
|
|
}
|
|
|
|
static struct sp_engine *
|
|
engine_of_agent(struct sp_agent *ag)
|
|
{
|
|
struct sp_engine *e;
|
|
|
|
pthread_mutex_lock(&open_mx);
|
|
for (e = open_list; e != NULL; e = e->next_open)
|
|
if (&e->ag == ag)
|
|
break;
|
|
pthread_mutex_unlock(&open_mx);
|
|
return e;
|
|
}
|
|
|
|
int
|
|
sp_engine_hold(struct sp_engine *e)
|
|
{
|
|
if (e == NULL)
|
|
return -1;
|
|
if (pthread_mutex_trylock(&e->turn_mx) != 0)
|
|
return -1;
|
|
pthread_mutex_lock(&e->lock);
|
|
if (e->running) {
|
|
pthread_mutex_unlock(&e->lock);
|
|
pthread_mutex_unlock(&e->turn_mx);
|
|
return -1;
|
|
}
|
|
pthread_mutex_unlock(&e->lock);
|
|
return 0;
|
|
}
|
|
|
|
void
|
|
sp_engine_release(struct sp_engine *e)
|
|
{
|
|
if (e != NULL)
|
|
pthread_mutex_unlock(&e->turn_mx);
|
|
}
|
|
|
|
int
|
|
sp_engine_turn_begin(struct sp_engine *e)
|
|
{
|
|
if (sp_engine_hold(e) != 0)
|
|
return -1;
|
|
pthread_mutex_lock(&e->lock);
|
|
e->ext_busy = 1;
|
|
pthread_mutex_unlock(&e->lock);
|
|
return 0;
|
|
}
|
|
|
|
void
|
|
sp_engine_turn_end(struct sp_engine *e)
|
|
{
|
|
if (e == NULL)
|
|
return;
|
|
pthread_mutex_lock(&e->lock);
|
|
e->ext_busy = 0;
|
|
pthread_mutex_unlock(&e->lock);
|
|
/*
|
|
* A /compact typed during a foreign turn (the Telegram daemon's) lands
|
|
* here instead of in the turn thread, which never ran one.
|
|
*/
|
|
engine_apply_pending_compact(e);
|
|
pthread_mutex_unlock(&e->turn_mx);
|
|
}
|
|
|
|
int
|
|
sp_engine_agent_turn_begin(struct sp_agent *ag)
|
|
{
|
|
struct sp_engine *e = engine_of_agent(ag);
|
|
|
|
if (e == NULL)
|
|
return 0; /* not an engine's agent: nothing to share */
|
|
return sp_engine_turn_begin(e);
|
|
}
|
|
|
|
void
|
|
sp_engine_agent_turn_end(struct sp_agent *ag)
|
|
{
|
|
struct sp_engine *e = engine_of_agent(ag);
|
|
|
|
if (e != NULL)
|
|
sp_engine_turn_end(e);
|
|
}
|
|
|
|
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(sp_config_state_dir(e->conf), 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);
|
|
cur_set(e, ch.model[0] != '\0' ?
|
|
ch.model : ch.d->model,
|
|
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;
|
|
/*
|
|
* The profile swaps the agent's policy, prompt and transport, which
|
|
* the turn thread is using: Tab during a turn is refused, like /agent.
|
|
*/
|
|
if (sp_engine_busy(e)) {
|
|
ev_push(e, SP_EV_ENTRY, 0, "splinter", sp_t("ui.command_busy"));
|
|
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", "effort", "exit",
|
|
"model", "new", "q", "quit", "rename", "reset", "resume", "rm",
|
|
"self-check", "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(sp_config_state_dir(e->conf), 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);
|
|
cur_set(e, ch.model[0] != '\0' ? ch.model :
|
|
ch.d->model, ch.d->endpoint);
|
|
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];
|
|
|
|
cur_set(e, p.model, p.endpoint);
|
|
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);
|
|
cur_set(e, model, ch.d->endpoint);
|
|
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) {
|
|
cur_set(e, args, NULL);
|
|
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);
|
|
}
|
|
|
|
/*
|
|
* The token target of a /compact line: the argument when it parses, else the
|
|
* configured compact_target, else the documented 8000.
|
|
*/
|
|
static size_t
|
|
compact_tokens_from(struct sp_engine *e, const char *args)
|
|
{
|
|
size_t tokens = e->conf != NULL && e->conf->compact_target > 0 ?
|
|
e->conf->compact_target : 8000;
|
|
|
|
if (args != NULL && args[0] != '\0') {
|
|
char *end;
|
|
unsigned long n = strtoul(args, &end, 10);
|
|
|
|
if (*end == '\0' && n > 0 && n < 1000000)
|
|
tokens = (size_t)n;
|
|
}
|
|
return tokens;
|
|
}
|
|
|
|
/* /compact, applied now: the conversation is nobody else's at this point */
|
|
static void
|
|
cmd_compact(struct sp_engine *e, const char *args, struct sp_buf *out)
|
|
{
|
|
size_t before = sp_conv_bytes(&e->conv);
|
|
size_t msgs = e->conv.n;
|
|
size_t tokens = compact_tokens_from(e, args);
|
|
size_t budget = tokens * 4;
|
|
int changed;
|
|
|
|
if (e->host == NULL) {
|
|
sp_buf_puts(out, sp_td("ui.compact_nohost",
|
|
"compact: no plugin host, nothing to compact\n"));
|
|
return;
|
|
}
|
|
changed = sp_host_compact(e->host, &e->conv, budget);
|
|
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);
|
|
}
|
|
|
|
/*
|
|
* A /compact typed while a turn ran. Called from the turn thread with no turn
|
|
* in flight, so the conversation has one owner again.
|
|
*/
|
|
static void
|
|
engine_apply_pending_compact(struct sp_engine *e)
|
|
{
|
|
size_t tokens;
|
|
struct sp_buf out;
|
|
|
|
pthread_mutex_lock(&e->lock);
|
|
if (!e->has_pend_compact) {
|
|
pthread_mutex_unlock(&e->lock);
|
|
return;
|
|
}
|
|
tokens = e->pend_compact_tokens;
|
|
e->has_pend_compact = 0;
|
|
pthread_mutex_unlock(&e->lock);
|
|
if (sp_buf_init(&out) != 0)
|
|
return;
|
|
{
|
|
char arg[32];
|
|
|
|
snprintf(arg, sizeof(arg), "%zu", tokens);
|
|
cmd_compact(e, arg, &out);
|
|
}
|
|
if (out.p != NULL && out.len > 0)
|
|
ev_push(e, SP_EV_ENTRY, 0, "splinter", out.p);
|
|
sp_buf_free(&out);
|
|
}
|
|
|
|
/* 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);
|
|
/* the new session gets its own index; the old one stays on disk */
|
|
sp_embed_bind(e->emb, e->sess.dir, e->sess.id);
|
|
profile_save(e);
|
|
{
|
|
char sel[320];
|
|
|
|
current_model_selector(e, sel, sizeof(sel));
|
|
if (sel[0] != '\0')
|
|
(void)session_model_save(e, sel, NULL, 0);
|
|
}
|
|
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], model[256], endpoint[512];
|
|
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);
|
|
cur_get(e, model, sizeof(model), endpoint, sizeof(endpoint));
|
|
sp_buf_printf(out, " %-8s %s\n", sp_t("status.model"),
|
|
model[0] != '\0' ? model : "-");
|
|
sp_buf_printf(out, " %-8s %s\n", sp_t("status.endpoint"),
|
|
endpoint[0] != '\0' ? 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.embed"));
|
|
{
|
|
char etex[256];
|
|
|
|
sp_embed_status(e->emb, etex, sizeof(etex));
|
|
sp_buf_puts(out, etex);
|
|
}
|
|
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;
|
|
unsigned cachepct = 0;
|
|
char model[256];
|
|
struct engine_tally judged, plain;
|
|
|
|
/* the turn thread updates all of these under the lock */
|
|
pthread_mutex_lock(&e->lock);
|
|
st = e->snapshot;
|
|
judged = e->judged;
|
|
plain = e->plain;
|
|
snprintf(model, sizeof(model), "%s", e->cur_model);
|
|
pthread_mutex_unlock(&e->lock);
|
|
|
|
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",
|
|
judged.turns + plain.turns > 0 ?
|
|
st.cost / (double)(judged.turns + plain.turns) : 0.0,
|
|
judged.turns + plain.turns > 0 ?
|
|
(judged.ms + plain.ms) / (judged.turns + plain.turns) : 0,
|
|
st.tool_calls);
|
|
if (judged.turns > 0 || plain.turns > 0) {
|
|
sp_buf_printf(out, "judged: %u turns, %.0f ms/turn, "
|
|
"%.0f tok/turn, $%.5f/turn\n", judged.turns,
|
|
judged.turns ? (double)judged.ms / judged.turns : 0,
|
|
judged.turns ? (double)(judged.in + judged.out) /
|
|
judged.turns : 0,
|
|
judged.turns ? judged.cost / judged.turns : 0);
|
|
sp_buf_printf(out, "plain: %u turns, %.0f ms/turn, "
|
|
"%.0f tok/turn, $%.5f/turn\n", plain.turns,
|
|
plain.turns ? (double)plain.ms / plain.turns : 0,
|
|
plain.turns ? (double)(plain.in + plain.out) /
|
|
plain.turns : 0,
|
|
plain.turns ? plain.cost / plain.turns : 0);
|
|
if (judged.turns > 0 && plain.turns > 0)
|
|
sp_buf_printf(out, "delta: %+.0f ms, %+.0f tok, "
|
|
"%+.5f $/turn (judged - plain)\n",
|
|
(double)judged.ms / judged.turns -
|
|
(double)plain.ms / plain.turns,
|
|
(double)(judged.in + judged.out) /
|
|
judged.turns -
|
|
(double)(plain.in + plain.out) /
|
|
plain.turns,
|
|
(judged.cost / judged.turns) -
|
|
(plain.cost / plain.turns));
|
|
}
|
|
if (strstr(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");
|
|
}
|
|
|
|
/* ------------------------------------------------------------ /self-check */
|
|
|
|
/*
|
|
* A turn is everything from one user message to the next. The last three are
|
|
* the surprising ones: what was asked, what the model did, and the observation
|
|
* that came back -- including the failure it then talked around.
|
|
*/
|
|
#define SELF_CHECK_TURNS 3
|
|
#define SELF_CHECK_MSG_BYTES 1200 /* per message; the log has the rest */
|
|
#define SELF_CHECK_TOTAL 24000 /* the whole dump, so the prompt stays sane */
|
|
#define SELF_CHECK_FAIL_BYTES 400
|
|
|
|
static int
|
|
self_check_is(const struct sp_msg *m, const char *role)
|
|
{
|
|
return m->role != NULL && strcmp(m->role, role) == 0;
|
|
}
|
|
|
|
/* a tool result that says it failed: exit status, or an error line */
|
|
static int
|
|
self_check_failure(const struct sp_msg *m)
|
|
{
|
|
const char *p, *e;
|
|
long status;
|
|
|
|
if (!self_check_is(m, "tool") || m->content == NULL)
|
|
return 0;
|
|
p = strstr(m->content, "[exit status ");
|
|
if (p != NULL) {
|
|
e = p + 13;
|
|
status = strtol(e, NULL, 10);
|
|
if (status != 0 && (e[0] == '-' || (e[0] >= '0' && e[0] <= '9')))
|
|
return 1;
|
|
}
|
|
return strncmp(m->content, "error:", 6) == 0 ||
|
|
strstr(m->content, "\nerror:") != NULL ||
|
|
strstr(m->content, "\nno answer") != NULL;
|
|
}
|
|
|
|
/*
|
|
* One message as the model will read it here: the role, the tool name, the
|
|
* text cut to a size that still shows what happened. System messages (the
|
|
* prompt and lcm's summary) are not part of a turn.
|
|
*/
|
|
static void
|
|
self_check_line(struct sp_buf *b, const struct sp_msg *m, size_t cap)
|
|
{
|
|
const char *text = m->content != NULL ? m->content : "";
|
|
size_t len = strlen(text);
|
|
|
|
if (m->name != NULL && m->name[0] != '\0')
|
|
sp_buf_printf(b, "[%s %s] ",
|
|
m->role != NULL ? m->role : "?", m->name);
|
|
else
|
|
sp_buf_printf(b, "[%s] ", m->role != NULL ? m->role : "?");
|
|
if (len > cap) {
|
|
sp_buf_printf(b, "%.*s\n... %zu bytes cut ...",
|
|
(int)cap, text, len - cap);
|
|
} else {
|
|
sp_buf_puts(b, text);
|
|
}
|
|
sp_buf_puts(b, "\n");
|
|
}
|
|
|
|
/* the index where the last 'turns' user messages begin (0: fewer than that) */
|
|
static size_t
|
|
self_check_from(const struct sp_conv *c, size_t turns)
|
|
{
|
|
size_t i, seen = 0, first = c->n;
|
|
|
|
for (i = c->n; i > 0; i--) {
|
|
if (!self_check_is(&c->v[i - 1], "user"))
|
|
continue;
|
|
first = i - 1;
|
|
if (++seen == turns)
|
|
break;
|
|
}
|
|
return first;
|
|
}
|
|
|
|
/*
|
|
* /self-check: hand the model the tail of its own conversation and the errors
|
|
* in it, so it diagnoses itself instead of asking the operator. It runs as a
|
|
* real turn, so the model can go and repair the step it got wrong.
|
|
*/
|
|
/*
|
|
* /effort: how many hidden review rounds the router should run for this
|
|
* session. The names match junction's X-Junction-Effort header; a bare number
|
|
* is the exact count (0..12). Unset means the rule decides.
|
|
*/
|
|
static void
|
|
cmd_effort(const char *args, struct sp_buf *out)
|
|
{
|
|
int depth = -1;
|
|
|
|
if (args == NULL || *args == '\0') {
|
|
int cur = sp_openai_review_depth();
|
|
|
|
if (cur < 0)
|
|
sp_buf_puts(out, "effort: router rule decides");
|
|
else
|
|
sp_buf_printf(out, "effort: %d review round%s", cur,
|
|
cur == 1 ? "" : "s");
|
|
return;
|
|
}
|
|
if (!strcasecmp(args, "off") || !strcasecmp(args, "none"))
|
|
depth = 0;
|
|
else if (!strcasecmp(args, "low") || !strcasecmp(args, "default"))
|
|
depth = 4;
|
|
else if (!strcasecmp(args, "medium"))
|
|
depth = 7;
|
|
else if (!strcasecmp(args, "high"))
|
|
depth = 9;
|
|
else if (!strcasecmp(args, "max"))
|
|
depth = 12;
|
|
else {
|
|
char *end = NULL;
|
|
long n = strtol(args, &end, 10);
|
|
|
|
if (end != args) {
|
|
while (*end == ' ' || *end == '\t')
|
|
end++;
|
|
if (*end == '\0' && n >= 0 && n <= 12)
|
|
depth = (int)n;
|
|
}
|
|
}
|
|
if (depth < 0) {
|
|
sp_buf_puts(out, "effort: off|low|medium|high|max or 0..12");
|
|
return;
|
|
}
|
|
sp_openai_set_review_depth(depth);
|
|
if (depth == 0)
|
|
sp_buf_puts(out, "effort: 0 review rounds (off)");
|
|
else
|
|
sp_buf_printf(out, "effort: %d review round%s", depth,
|
|
depth == 1 ? "" : "s");
|
|
}
|
|
|
|
static int
|
|
cmd_self_check(struct sp_engine *e, struct sp_buf *out)
|
|
{
|
|
struct sp_buf body, fail;
|
|
size_t from, i, cut;
|
|
|
|
sp_buf_clear(out);
|
|
if (sp_buf_init(&body) != 0 || sp_buf_init(&fail) != 0) {
|
|
sp_buf_free(&body);
|
|
sp_buf_free(&fail);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
from = self_check_from(&e->conv, SELF_CHECK_TURNS);
|
|
for (i = from; i < e->conv.n; i++) {
|
|
if (self_check_is(&e->conv.v[i], "system"))
|
|
continue;
|
|
self_check_line(&body, &e->conv.v[i], SELF_CHECK_MSG_BYTES);
|
|
if (self_check_failure(&e->conv.v[i]))
|
|
self_check_line(&fail, &e->conv.v[i],
|
|
SELF_CHECK_FAIL_BYTES);
|
|
}
|
|
sp_buf_puts(out, sp_td("selfcheck.prompt",
|
|
"Something went wrong in this session, so check yourself instead "
|
|
"of asking the operator: read the tail of our conversation below "
|
|
"(tool output is shortened), find the step that failed, say what "
|
|
"the cause was, what you got wrong, and what you will do "
|
|
"differently now. Then continue the task from where it stopped. "
|
|
"Do not repeat work that is still valid."));
|
|
sp_buf_puts(out, "\n");
|
|
if (e->err.p != NULL && e->err.len > 0) {
|
|
sp_buf_puts(out, "\nlast turn failed with: ");
|
|
sp_buf_puts(out, e->err.p);
|
|
sp_buf_puts(out, "\n");
|
|
}
|
|
if (fail.len > 0) {
|
|
sp_buf_puts(out, "\nfailures in those turns:\n");
|
|
sp_buf_puts(out, fail.p);
|
|
}
|
|
if (body.len == 0) {
|
|
sp_buf_puts(out, "\n");
|
|
sp_buf_puts(out, sp_t("selfcheck.empty"));
|
|
} else {
|
|
sp_buf_puts(out, "\nthe last turns, as they entered the "
|
|
"conversation:\n");
|
|
if (body.len > SELF_CHECK_TOTAL) {
|
|
/* keep the newest part, starting on a line */
|
|
cut = body.len - SELF_CHECK_TOTAL;
|
|
while (cut < body.len && body.p[cut] != '\n')
|
|
cut++;
|
|
if (cut < body.len)
|
|
cut++;
|
|
sp_buf_printf(out, "... %zu bytes of older turns cut "
|
|
"...\n", cut);
|
|
sp_buf_puts(out, body.p + cut);
|
|
} else {
|
|
sp_buf_puts(out, body.p);
|
|
}
|
|
}
|
|
sp_buf_free(&body);
|
|
sp_buf_free(&fail);
|
|
return SP_INPUT_PROMPT;
|
|
}
|
|
|
|
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, "agent") == 0 ||
|
|
strcmp(name, "agents") == 0 || strcmp(name, "connect") == 0 ||
|
|
strcmp(name, "self-check") == 0 ||
|
|
strcmp(name, "selfcheck") == 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, "effort") == 0) {
|
|
cmd_effort(args, out);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
if (strcmp(name, "compact") == 0) {
|
|
/*
|
|
* While a turn runs the conversation belongs to the worker, so the
|
|
* request is remembered instead of applied - and instead of being
|
|
* refused, which is what made /compact look broken: the operator
|
|
* types it while the model is writing, reads "not while a turn
|
|
* runs", and never types it again. The turn end applies it.
|
|
*/
|
|
if (sp_engine_busy(e)) {
|
|
size_t tokens = compact_tokens_from(e, args);
|
|
|
|
pthread_mutex_lock(&e->lock);
|
|
e->pend_compact_tokens = tokens;
|
|
e->has_pend_compact = 1;
|
|
pthread_mutex_unlock(&e->lock);
|
|
sp_buf_printf(out, sp_td("ui.compact_pending",
|
|
"compaction queued: it runs when the turn ends "
|
|
"(target %zu tokens)\n"), tokens);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
cmd_compact(e, args, out);
|
|
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 (strcmp(name, "self-check") == 0 || strcmp(name, "selfcheck") == 0)
|
|
return cmd_self_check(e, out);
|
|
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(sp_config_state_dir(e->conf), cdir, sizeof(cdir)) == 0 &&
|
|
sp_cmdscript_exists(cdir, name)) {
|
|
if (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_clear(out);
|
|
sp_buf_puts(out, cerr.p != NULL ? cerr.p : "?");
|
|
sp_buf_free(&cerr);
|
|
return SP_INPUT_HANDLED;
|
|
}
|
|
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. *made is set when the id was invented
|
|
* here (no session to resume): that session is an empty placeholder, and a
|
|
* caller that is about to import another one may throw it away again.
|
|
*/
|
|
static int
|
|
open_session(struct sp_engine *e, const struct sp_engine_opts *o,
|
|
struct sp_buf *err, int *code, int *made)
|
|
{
|
|
static char 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)
|
|
dir = sp_config_session_dir(o->conf);
|
|
/*
|
|
* -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.
|
|
*
|
|
* With --claude/--opencode/--hermes the newest foreign session is about
|
|
* to be imported, so a directory that has no splinter session yet is
|
|
* not an error: that is exactly the case the option exists for (Claude
|
|
* Code stopped at its limit in a folder this tool never ran in). A
|
|
* fresh, empty session is created and the import replaces it; the
|
|
* "latest of any directory" fallback below must not run here, it would
|
|
* resume an unrelated conversation first.
|
|
*/
|
|
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) {
|
|
if (o->from_foreign == NULL ||
|
|
*o->from_foreign == '\0') {
|
|
sp_buf_printf(err, "no session in %s yet",
|
|
getcwd(cwd, sizeof(cwd)) != NULL ?
|
|
cwd : ".");
|
|
*code = -2;
|
|
return -1;
|
|
}
|
|
new_session_id(idbuf, sizeof(idbuf));
|
|
id = idbuf;
|
|
*made = 1;
|
|
} else {
|
|
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;
|
|
*made = 1;
|
|
}
|
|
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;
|
|
|
|
/*
|
|
* The host is created even without a single plugin: it is what carries
|
|
* the registry to the core compactor and the gate to the tools. Skipping
|
|
* it here left a plugin-less run with no compactor at all, so max_bytes
|
|
* killed every turn whose conversation was over the ceiling - the
|
|
* compaction that was supposed to save it could not be reached.
|
|
*/
|
|
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;
|
|
/*
|
|
* A folder that has history says so: the model should look in the
|
|
* earlier sessions before asking the user something they already
|
|
* answered. session_search and session_list (the session plugin) read
|
|
* them; the note stays out when there is nothing to find.
|
|
*/
|
|
{
|
|
struct sp_buf note;
|
|
size_t used;
|
|
|
|
if (sp_buf_init(¬e) == 0) {
|
|
(void)sp_session_folder_note(e->sess.dir, e->sess.id,
|
|
¬e);
|
|
if (note.len > 0 && note.p != NULL)
|
|
(void)sp_buf_puts(¬e, "\n\n");
|
|
(void)sp_task_scope_note(¬e);
|
|
used = strlen(e->prompt_expanded);
|
|
if (note.len > 0 && note.p != NULL &&
|
|
used + note.len + 2 < sizeof(e->prompt_expanded)) {
|
|
e->prompt_expanded[used] = '\n';
|
|
memcpy(e->prompt_expanded + used + 1, note.p,
|
|
note.len + 1);
|
|
}
|
|
sp_buf_free(¬e);
|
|
}
|
|
}
|
|
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;
|
|
/*
|
|
* --claude/--opencode/--hermes is a resume by definition: the imported
|
|
* session exists to be continued. Without this, a plain `--claude`
|
|
* (without -c) opened the imported file and then talked to an empty
|
|
* conversation, which reads exactly like a broken import.
|
|
*/
|
|
if (!o->resume && !o->continue_last &&
|
|
(o->from_foreign == NULL || *o->from_foreign == '\0'))
|
|
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], saved[320], saved_model[320];
|
|
int start = -1, code = -1, placeholder = 0;
|
|
|
|
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_mutex_init(&e->turn_mx, NULL);
|
|
pthread_cond_init(&e->cond, NULL);
|
|
open_add(e);
|
|
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, &placeholder) != 0)
|
|
goto fail;
|
|
/*
|
|
* The index belongs to the session, so it is created with it. It starts
|
|
* its own thread and begins reading the file in the background: a
|
|
* resumed session is searchable without anything having been compacted.
|
|
*/
|
|
e->emb = sp_embed_new(e->conf);
|
|
if (e->emb != NULL)
|
|
sp_embed_bind(e->emb, e->sess.dir, e->sess.id);
|
|
if (session_model_read(e, saved, sizeof(saved)) == 0) {
|
|
struct sp_choice ch;
|
|
|
|
memset(&ch, 0, sizeof(ch));
|
|
if (sp_provider_choose(e->conf, saved, &ch) == 0 &&
|
|
ch.d != NULL) {
|
|
local.endpoint = ch.d->endpoint;
|
|
snprintf(saved_model, sizeof(saved_model), "%s",
|
|
ch.model[0] != '\0' ? ch.model : ch.d->model);
|
|
local.model = saved_model;
|
|
local.kind = ch.d->kind;
|
|
local.key_env = ch.d->key_env;
|
|
sp_usage_set_active(ch.d->id);
|
|
} else {
|
|
/*
|
|
* A selector that no longer resolves (a legacy bare
|
|
* "main", a model the config dropped) must not be
|
|
* pasted onto the running endpoint as a model name.
|
|
* Fall back to the config default instead.
|
|
*/
|
|
sp_logf("session", "saved model '%s' is gone; "
|
|
"using the default", saved);
|
|
saved[0] = '\0';
|
|
}
|
|
if (saved[0] != '\0') {
|
|
snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), "%s",
|
|
local.endpoint != NULL ? local.endpoint : "");
|
|
snprintf(e->cur_model, sizeof(e->cur_model), "%.255s",
|
|
local.model != NULL ? local.model : "");
|
|
}
|
|
}
|
|
e->ag.sess = &e->sess;
|
|
sp_logf("session", "started: %s", e->sess.id);
|
|
if (load_plugins(e, o, err) != 0)
|
|
goto fail;
|
|
/*
|
|
* --claude/--opencode/--hermes: the newest session that tool ran here
|
|
* becomes the session of this run. Before setup_conversation, because
|
|
* that is what loads the history into the conversation.
|
|
*/
|
|
if (o->from_foreign != NULL && *o->from_foreign != '\0') {
|
|
struct sp_foreign_target ft;
|
|
char here[512], before[80];
|
|
int frc;
|
|
|
|
if (getcwd(here, sizeof(here)) == NULL)
|
|
snprintf(here, sizeof(here), ".");
|
|
snprintf(before, sizeof(before), "%s", e->sess.id);
|
|
ft.sess = &e->sess;
|
|
ft.reg = &e->reg;
|
|
ft.host = e->host;
|
|
ft.emb = e->emb;
|
|
frc = sp_foreign_open(&ft, o->from_foreign, here, err);
|
|
/*
|
|
* A run that started without a session to resume opened an empty
|
|
* placeholder, and the import replaced it (or never happened,
|
|
* because there was nothing to import). Either way nothing
|
|
* refers to it any more: leaving it behind puts an empty
|
|
* "session" into -c's list for the rest of the folder's life,
|
|
* and the next plain -c would resume that instead of saying
|
|
* there is nothing here yet.
|
|
*
|
|
* Only the placeholder goes: a session that existed before this
|
|
* run is never touched, whatever the import did.
|
|
*/
|
|
if (placeholder)
|
|
(void)sp_session_remove_if_empty(e->sess.dir, before);
|
|
if (frc != 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;
|
|
}
|
|
/* history_search: the way back into what compaction dropped */
|
|
if (e->emb != NULL && sp_embed_register(&e->reg, e->emb) != 0) {
|
|
sp_buf_puts(err, "cannot register history_search");
|
|
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(sp_config_state_dir(e->conf));
|
|
|
|
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;
|
|
open_del(e);
|
|
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_embed_free(e->emb);
|
|
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->turn_mx);
|
|
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;
|
|
}
|