Files
splinter/src/ui.c
T
lotherkandClaude Opus 5.5 b05bb34cc7 ui: a tool call reads like a call; a joined swarm session stays usable
The transcript said

  [23:12:05] <werkzeug> run  command: touch /tmp/.../made

which is the harness talking about itself. Hermes prints one row per call -
emoji, a capitalized verb, a one-line preview of the primary argument
(agent/display.py builds it per tool, 80 chars) and a duration; its long
outputs end in "... (N more lines)". opencode's TUI does the same shape: a
header line for the call, the output indented underneath.

So the row is ">> Run  touch /tmp/.../made" (verb capitalized, no
"command:" and no JSON for a shell call), and the observation hangs under it
as "| output", cut at 4 KiB with "... N lines". The log keeps the rest.

Also: the swarm master never sent "unlock", so a second splinter in the same
directory sat on "[swarm locked]" and swallowed every key - one of the
intermittent failures in the suite. Joining unlocks; the master locks a slave
only while it routes work to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 06:42:10 +00:00

3488 lines
95 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* splinter -- curses chat interface.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Layout, fixed and deliberate:
*
* +---------------------------------+------------+
* | history | sidebar |
* | three quarters | one quarter|
* | starts clear, only ever grows | model |
* | | usage |
* | | widgets |
* | | session |
* | | directory |
* +---------------------------------+------------+
* | build> prompt, or "12s tool steer>" |
* +----------------------------------------------+
*
* No status bar: the running time and the tool lead the prompt, and /usage,
* /status and /widgets put the same numbers into the transcript on demand.
*
* Only the UI thread ever calls into curses. Anything that wants to appear in
* the sidebar hands over finished text and never touches a WINDOW.
*
* Redraws happen when something changed -- after a turn, after a key -- so an
* idle splinter burns no CPU.
*
* Keys: Enter sends, Ctrl-L redraws, Ctrl-C drops the input line, Ctrl-D quits.
*/
#include <ctype.h>
#include <curses.h>
#include <errno.h>
#include <iconv.h>
#include "decomp.h"
#include <locale.h>
#include <sys/wait.h>
#include <wchar.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "splinter.h"
#include "i18n.h"
#include "log.h"
#include "cmdscript.h"
#include "splinter_plugin.h"
#include "config.h"
#include "providers.h"
#include <strings.h>
#include <unistd.h>
#include "md.h"
#include "theme.h"
#include "ui.h"
#include "usage.h"
#include "agents.h"
#include "providers.h"
/* set while a turn runs: widgets hold still instead of ticking under the answer */
static volatile int g_turn_busy;
/*
* Who is speaking. Not the role - the name: the person from $USER, the model from
* the configuration. 'thinking is thinking' was a label talking about itself.
*/
static char g_who[128] = "you";
static char g_model[128] = "model";
#define MAX_ENTRIES 512
struct elayout; /* the wrapped lines of one entry, below */
struct entry {
char *role;
char *text;
time_t ts; /* when it arrived, for the IRC-style prefix */
size_t id; /* stable across eviction; see add_entry */
/*
* The wrapped lines, kept between frames. Wrapping a long transcript
* from scratch on every keystroke and every 100 ms tick was the reason
* the window felt slow: one frame cost as much as the whole log.
* Rebuilt only when the text or the width changed.
*/
struct elayout *cache;
int cache_cols;
};
struct ui_state {
struct entry entries[MAX_ENTRIES];
size_t n;
size_t next_id; /* ids start at 1 */
size_t scroll; /* lines scrolled back from the bottom */
size_t scroll_max; /* maxscroll of the last frame */
size_t scroll_base; /* maxscroll when the reader scrolled */
long last_ms;
size_t tokens_in;
size_t tokens_out;
size_t out_chars; /* characters streamed in this/last turn */
size_t total_out_chars; /* cumulative assistant output chars */
char hist[128][1024]; /* what was typed before */
size_t nhist;
int hist_pos; /* -1: editing a fresh line */
int last_day; /* for the "--- 2026-11-13 ---" line */
struct sp_buf last_think; /* the previous turn's reasoning */
size_t last_steps;
size_t last_calls;
const char *endpoint;
const char *model;
char cur_endpoint[512]; /* owned: /model moves them */
char cur_model[256];
struct sp_config *conf; /* for /model, may be NULL */
struct ui_connect { /* /connect, one answer per line */
int active;
int step;
char id[64];
char endpoint[520];
char model[260];
char key_env[80];
} cc;
int quit;
struct sp_theme theme;
struct swarm *sw; /* local fleet, may be NULL/SWARM_NONE */
/* agent profiles: Tab switches through them */
struct sp_agents agents;
int agent_cur;
struct sp_tool_policy policy;
char *base_prompt; /* the system prompt without a profile */
char home_id[64]; /* provider before a profile moved it */
};
static char g_start_agent[48] = "build";
void
sp_ui_start_agent(const char *name)
{
snprintf(g_start_agent, sizeof(g_start_agent), "%s",
name != NULL && *name != '\0' ? name : "build");
}
static WINDOW *ui_hist;
static WINDOW *ui_side;
static WINDOW *ui_input;
/*
* The agent whose profile is active. The sidebar used to show it; with one
* text field the prompt carries the name, so "build> " says what Tab did.
*/
static char ui_agent[32];
enum {
PAIR_MAIN = 1, /* fg on bg */
PAIR_ACCENT, /* accent on bg */
PAIR_DIM, /* border on bg */
PAIR_STATUS, /* hints and questions */
PAIR_INPUT, /* the input line */
PAIR_ERROR /* errors */
};
/*
* A turn runs on its own thread so the operator can keep typing. Curses stays
* with the UI thread: the worker only touches this struct, under a mutex.
* Steering is picked up at the next step boundary by the loop itself.
*/
struct turn {
struct sp_agent *ag;
const char *text;
struct sp_buf answer;
struct sp_buf err;
int rc;
volatile int done;
volatile int cancel;
char steer[1024];
int have_steer;
int steers;
struct sp_buf live; /* the current step's text, streamed */
struct sp_buf think; /* the current step's reasoning */
/*
* What the turn produced, in the order it happened: a finished step's
* reasoning, its text, the call it made, a note. The turn thread cannot
* touch the entry list, so it queues here and the UI drains this. Before,
* tool calls were pasted into the reasoning text and the answer text of
* all steps ran together in one buffer - two problems that only existed
* because there was no queue.
*/
struct tun_ev {
int kind; /* 't' reasoning, 'a' answer, 'x' tool, 'n' note */
char *text;
} *ev;
int nev, capev;
char tool[64]; /* last tool the model called */
char tool_line[512]; /* name + args, for the live area */
int tool_tick;
int compacted; /* compaction events to show in chat */
size_t c_bytes_before;
size_t c_bytes_after;
size_t c_msgs_before;
size_t c_msgs_after;
/* a mutate/destructive tool is waiting for the operator */
int approve_pending;
int approve_result;
char approve_name[64];
char approve_args[256];
int approve_auth;
pthread_cond_t cond;
pthread_mutex_t lock;
};
static int ev_push(struct turn *, int, const char *);
/*
* Called from the turn thread right before a tool runs. The UI drains the list
* on its next tick and writes the calls into the transcript in order - so the
* operator sees which tool ran with which arguments, not just that something
* happened.
*/
/*
* Approval, asked on the screen.
*
* The turn runs on its own thread and must block here until a human answers;
* the UI thread keeps reading keys meanwhile. That is the whole reason this is
* a condition variable and not a prompt on stdout - a curses program cannot
* read stdin behind its own back without eating the keystrokes it needs.
*/
static int
approve_cb(void *ctx, const char *name, int auth, const char *args)
{
struct turn *t = ctx;
int answer;
pthread_mutex_lock(&t->lock);
snprintf(t->approve_name, sizeof(t->approve_name), "%s",
name != NULL ? name : "?");
snprintf(t->approve_args, sizeof(t->approve_args), "%.200s",
args != NULL ? args : "");
t->approve_auth = auth;
t->approve_result = 0;
t->approve_pending = 1;
pthread_cond_broadcast(&t->cond);
while (t->approve_pending && !t->cancel)
pthread_cond_wait(&t->cond, &t->lock);
answer = t->cancel ? 0 : t->approve_result;
t->approve_pending = 0;
pthread_mutex_unlock(&t->lock);
return answer;
}
/*
* What the tool returned, into the transcript. A full `run` can carry a
* 300 KB JSON dump, and printing that would bury the conversation, so the
* entry keeps the head of it and says how much is left. The whole text is in
* the session log either way - the log gets what the harness saw, not what
* fits on screen.
*/
#define OBS_SHOW 4096 /* bytes of an observation the transcript keeps */
static void
tool_end_cb(void *ctx, const char *name, const char *obs)
{
struct turn *t = ctx;
char *shown;
size_t len, keep, i, rest = 0;
(void)name;
if (obs == NULL || *obs == '\0')
return;
while (*obs == '\n' || *obs == '\r')
obs++;
len = strlen(obs);
if (len == 0)
return;
while (len > 0 && (obs[len - 1] == '\n' || obs[len - 1] == '\r'))
len--;
if (len <= OBS_SHOW) {
shown = strdup(obs);
if (shown == NULL)
return;
} else {
keep = OBS_SHOW;
while (keep > 0 && obs[keep - 1] != '\n')
keep--;
if (keep == 0)
keep = OBS_SHOW;
for (i = keep; i < len; i++)
if (obs[i] == '\n')
rest++;
shown = malloc(keep + 128);
if (shown == NULL)
return;
memcpy(shown, obs, keep);
shown[keep] = '\0';
if (rest > 0) {
char mark[80];
snprintf(mark, sizeof(mark), sp_t("ui.more_lines"), rest);
snprintf(shown + keep, 128, "\n%s", mark);
}
}
pthread_mutex_lock(&t->lock);
(void)ev_push(t, 'o', shown);
pthread_mutex_unlock(&t->lock);
free(shown);
}
/*
* 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.
*/
static void
pretty_args(const char *json, char *out, size_t cap)
{
const char *p = json;
size_t n = 0;
int first = 1;
out[0] = '\0';
while (*p == ' ')
p++;
if (*p != '{') {
snprintf(out, cap, "%s", json);
return;
}
p++;
while (*p != '\0' && *p != '}' && n + 8 < cap) {
char key[48];
size_t k = 0;
while (*p == ' ' || *p == ',')
p++;
if (*p != '"')
break;
p++;
while (*p != '\0' && *p != '"' && k + 1 < sizeof(key))
key[k++] = *p++;
key[k] = '\0';
if (*p == '"')
p++;
while (*p == ' ' || *p == ':')
p++;
if (!first)
n += (size_t)snprintf(out + n, cap - n, " ");
first = 0;
n += (size_t)snprintf(out + n, cap - n, "%s: ", key);
if (*p == '"') {
p++;
while (*p != '\0' && *p != '"' && n + 4 < cap) {
if (*p == '\\' && p[1] != '\0') {
p++;
if (*p == 'n') {
out[n++] = ' ';
} else if (*p == 't') {
out[n++] = ' ';
} else if (*p == 'u' && strlen(p) >= 5) {
unsigned cp = 0;
int i;
for (i = 1; i <= 4; i++) {
char c = p[i];
cp = cp * 16 + (unsigned)(c >= 'a' ?
c - 'a' + 10 : c >= 'A' ?
c - 'A' + 10 : c - '0');
}
p += 4;
if (cp < 0x80)
out[n++] = (char)cp;
else if (cp < 0x800) {
out[n++] = (char)(0xc0 | (cp >> 6));
out[n++] = (char)(0x80 | (cp & 0x3f));
} else {
out[n++] = (char)(0xe0 | (cp >> 12));
out[n++] = (char)(0x80 | ((cp >> 6) & 0x3f));
out[n++] = (char)(0x80 | (cp & 0x3f));
}
} else
out[n++] = *p;
p++;
continue;
}
out[n++] = *p++;
}
if (*p == '"')
p++;
} else {
/* a number, a boolean, an object: as it is, up to the next key */
int depth = 0;
while (*p != '\0' && n + 4 < cap) {
if (*p == '{' || *p == '[')
depth++;
else if (*p == '}' || *p == ']') {
if (depth == 0)
break;
depth--;
} else if (*p == ',' && depth == 0)
break;
out[n++] = *p++;
}
}
out[n] = '\0';
}
out[n < cap ? n : cap - 1] = '\0';
}
/* queue one event for the UI; the caller holds t->lock */
static int
ev_push(struct turn *t, int kind, const char *text)
{
struct tun_ev *nv;
if (text == NULL || *text == '\0')
return 0;
if (t->nev == t->capev) {
int nc = t->capev != 0 ? t->capev * 2 : 16;
nv = realloc(t->ev, (size_t)nc * sizeof(*nv));
if (nv == NULL)
return -1;
t->ev = nv;
t->capev = nc;
}
t->ev[t->nev].text = strdup(text);
if (t->ev[t->nev].text == NULL)
return -1;
t->ev[t->nev].kind = kind;
t->nev++;
return 0;
}
/*
* A tool call is its own line in the transcript, queued here (the turn runs on
* another thread and must not touch the entry list) and drained by the UI.
* It used to be faked into the reasoning text as "› name args", which made it
* uncountable, uncollapsible and a second copy of the same text.
*/
static void
tool_begin_cb(void *ctx, const char *name, const char *args)
{
struct turn *t = ctx;
const char *a = args != NULL ? args : "";
char shown[512];
if (name == NULL)
return;
pretty_args(a, shown, sizeof(shown));
pthread_mutex_lock(&t->lock);
snprintf(t->tool_line, sizeof(t->tool_line), "%s %s", name, a);
/*
* The step is over as far as the screen is concerned: its reasoning and
* its text go into the queue in that order, then the call itself, and
* the buffers start empty for the next step.
*/
(void)ev_push(t, 't', t->think.p);
(void)ev_push(t, 'a', t->live.p);
sp_buf_clear(&t->think);
sp_buf_clear(&t->live);
{
/*
* ">> Run du -sh ../xsrc" reads like the thing that happened. The
* argument of a shell call is the command; saying "command:" before
* it, or pasting the JSON, is the harness talking about itself.
*/
char call[640], verb[64];
const char *detail = shown;
size_t n;
snprintf(verb, sizeof(verb), "%s", name);
verb[0] = (char)toupper((unsigned char)verb[0]);
if (strcmp(name, "run") == 0 && strncmp(detail, "command: ", 9) == 0)
detail += 9;
n = strlen(detail);
if (n > 200)
snprintf(call, sizeof(call), "%s %.200s...", verb, detail);
else
snprintf(call, sizeof(call), "%s %s", verb, detail);
(void)ev_push(t, 'x', call);
}
pthread_mutex_unlock(&t->lock);
}
static void
stream_cb(void *ctx, int kind, const char *text)
{
struct turn *t = ctx;
if (text == NULL)
return;
pthread_mutex_lock(&t->lock);
if (kind == SP_STREAM_TEXT) {
(void)sp_buf_puts(&t->live, text);
} else if (kind == SP_STREAM_THINK) {
(void)sp_buf_puts(&t->think, text);
} else if (kind == SP_STREAM_TOOL) {
snprintf(t->tool, sizeof(t->tool), "%s", text);
t->tool_tick++;
}
pthread_mutex_unlock(&t->lock);
}
/*
* The turn hit a usage limit: say so in the status line and in the reasoning,
* and wait for the reset on the turn thread. The screen stays alive (it is
* another thread), Ctrl-C ends the wait, and /resume goes on later.
*/
static long g_max_wait = 12 * 3600;
static int
ui_limit_wait(void *ctx, long until, const char *why)
{
struct turn *t = ctx;
char when[32], line[300];
struct tm tm;
time_t tt = (time_t)until;
if (until - (long)time(NULL) > g_max_wait)
return 0;
strftime(when, sizeof(when), "%a %H:%M", localtime_r(&tt, &tm));
(void)why;
snprintf(line, sizeof(line), sp_t("ui.limit_wait"), when);
pthread_mutex_lock(&t->lock);
snprintf(t->tool_line, sizeof(t->tool_line), "%s", line);
(void)ev_push(t, 'n', line);
pthread_mutex_unlock(&t->lock);
while ((long)time(NULL) < until && !t->cancel) {
struct timespec ts = { 0, 250000000L };
nanosleep(&ts, NULL);
}
pthread_mutex_lock(&t->lock);
t->tool_line[0] = '\0';
pthread_mutex_unlock(&t->lock);
return !t->cancel;
}
static int
steer_cb(void *ctx, struct sp_buf *out)
{
struct turn *t = ctx;
int took = 0;
pthread_mutex_lock(&t->lock);
if (t->have_steer) {
t->have_steer = 0;
t->steers++;
took = sp_buf_puts(out, t->steer) == 0 ? 1 : -1;
}
pthread_mutex_unlock(&t->lock);
return took;
}
static void *
turn_thread(void *arg)
{
struct turn *t = arg;
g_turn_busy = 1;
t->rc = sp_agent_run(t->ag, t->text, &t->answer, &t->err);
t->done = 1;
g_turn_busy = 0;
return NULL;
}
/*
* Colour assignment: the theme paints (theme.h says which role comes from
* where). This curses port does not honour -1 in init_pair(), so every pair
* gets real indices; an X resource theme without RGB uses the terminal's own
* indices 0..15, which is the same palette.
*/
static short
rgb(const unsigned char c[3], short n)
{
return sp_color_rgb(c[0], c[1], c[2], n);
}
static void
init_colors(const struct sp_theme *t)
{
short n;
if (!has_colors())
return;
/* COLORS is only valid after start_color() */
start_color();
n = (short)(COLORS > 0 ? COLORS : 8);
if (t->indexed) {
short accent = n >= 16 ? t->idx_accent : COLOR_BLUE;
short dim = n >= 16 ? t->idx_border : COLOR_WHITE;
short errc = n >= 16 ? t->idx_error : COLOR_RED;
init_pair(PAIR_MAIN, t->idx_fg, t->idx_bg);
init_pair(PAIR_ACCENT, accent, t->idx_bg);
init_pair(PAIR_DIM, dim, t->idx_bg);
init_pair(PAIR_STATUS, t->idx_bg, t->idx_fg);
init_pair(PAIR_INPUT, t->idx_fg, t->idx_bg);
init_pair(PAIR_ERROR, errc, t->idx_bg);
return;
}
init_pair(PAIR_MAIN, rgb(t->fg, n), rgb(t->bg, n));
init_pair(PAIR_ACCENT, rgb(t->accent, n), rgb(t->bg, n));
init_pair(PAIR_DIM, rgb(t->border, n), rgb(t->bg, n));
init_pair(PAIR_STATUS, rgb(t->status_fg, n), rgb(t->status, n));
init_pair(PAIR_INPUT, rgb(t->input_fg, n), rgb(t->input_bg, n));
init_pair(PAIR_ERROR, rgb(t->error, n), rgb(t->bg, n));
}
/*
* Text goes to curses as ASCII.
*
* Measured, not assumed: the vendored NetBSD curses emits Latin-1 bytes for
* wide characters (ü -> 0xFC) instead of re-encoding to the locale charset, so
* UTF-8 would reach the terminal as mojibake. ncurses passes the bytes through;
* this port does not. Until that is fixed in the library, the UI transliterates
* and the data keeps its exact UTF-8.
*
* iconv(3) does the work, with //TRANSLIT: a hand-written table turned German
* typography into question marks (— “ ” … all became '?'), which is how a
* readable answer turns into noise. Characters that cannot be transliterated
* become '?' - one per character, never silently dropped.
*/
static const struct sp_decomp *
decomp_find(unsigned int cp)
{
size_t lo = 0, hi = sp_decomp_count;
while (lo < hi) {
size_t mid = (lo + hi) / 2;
if (sp_decomp_table[mid].cp == cp)
return &sp_decomp_table[mid];
if (sp_decomp_table[mid].cp < cp)
lo = mid + 1;
else
hi = mid;
}
return NULL;
}
/* Decode one UTF-8 sequence; returns bytes consumed, or 0 on a broken byte. */
static size_t
utf8_next(const unsigned char *s, size_t left, unsigned int *cp)
{
if (left == 0)
return 0;
if (s[0] < 0x80) {
*cp = s[0];
return 1;
}
if ((s[0] & 0xe0) == 0xc0 && left >= 2) {
*cp = ((unsigned int)(s[0] & 0x1f) << 6) | (s[1] & 0x3f);
return 2;
}
if ((s[0] & 0xf0) == 0xe0 && left >= 3) {
*cp = ((unsigned int)(s[0] & 0x0f) << 12) |
((unsigned int)(s[1] & 0x3f) << 6) | (s[2] & 0x3f);
return 3;
}
if ((s[0] & 0xf8) == 0xf0 && left >= 4) {
*cp = ((unsigned int)(s[0] & 0x07) << 18) |
((unsigned int)(s[1] & 0x3f) << 12) |
((unsigned int)(s[2] & 0x3f) << 6) | (s[3] & 0x3f);
return 4;
}
return 0;
}
/*
* UTF-8 -> ASCII for the screen.
*
* Two mechanisms, and the split is the point: letters come from a table
* generated out of Unicode's decompositions (glibc's iconv transliterates "ß"
* but turns "ü" into "?"), punctuation goes through iconv (— becomes --, …
* becomes ...). A character neither can express becomes one '?' — visible, not
* silently dropped.
*
* The conversation and the session log keep the exact UTF-8; only the screen
* is ASCII, because this curses port writes Latin-1 bytes for wide characters.
*/
int
sp_ui_ascii(const char *in, char *out, size_t cap)
{
iconv_t cd;
const unsigned char *s;
size_t left, used = 0;
int rc = 0;
if (in == NULL || out == NULL || cap == 0)
return -1;
cd = iconv_open("ASCII//TRANSLIT", "UTF-8");
s = (const unsigned char *)in;
left = strlen(in);
while (left > 0) {
unsigned int cp = 0;
size_t n = utf8_next(s, left, &cp);
const char *rep = NULL;
char tmp[16];
if (n == 0) { /* broken byte: one '?' and move on */
if (used + 2 > cap) {
rc = -1;
break;
}
out[used++] = '?';
s++;
left--;
continue;
}
if (cp < 0x80) {
tmp[0] = (char)cp;
tmp[1] = '\0';
rep = tmp;
} else {
const struct sp_decomp *d = decomp_find(cp);
if (d != NULL) {
rep = d->ascii;
} else if (cd != (iconv_t)-1) {
char *ip = (char *)s, *op = tmp;
size_t il = n, ol = sizeof(tmp) - 1;
if (iconv(cd, &ip, &il, &op, &ol) != (size_t)-1) {
*op = '\0';
rep = tmp;
}
}
if (rep == NULL)
rep = "?";
}
{
size_t rl = strlen(rep);
if (used + rl + 1 > cap) {
rc = -1;
break;
}
memcpy(out + used, rep, rl);
used += rl;
}
s += n;
left -= n;
}
out[used] = '\0';
if (cd != (iconv_t)-1)
iconv_close(cd);
return rc;
}
static void
ui_add_text(WINDOW *w, const char *s, int maxcols)
{
char out[1024];
if (s == NULL)
return;
if (sp_ui_ascii(s, out, sizeof(out)) != 0)
snprintf(out, sizeof(out), "%.900s", s);
waddnstr(w, out, maxcols);
}
/* A role is stored as its English key and displayed in the chosen language. */
static const char *
role_label(const char *role)
{
char key[48];
const char *t;
if (role == NULL)
return "";
snprintf(key, sizeof(key), "role.%s", role);
t = sp_t(key);
if (t == NULL || strcmp(t, key) == 0)
return role;
return t;
}
/*
* Row accounting for text that contains newlines.
*
* The first version counted rows as strlen()/cols, which is only true for one
* long line. A model's reasoning is full of newlines, so the real height was
* much larger than the estimate and the text painted over the answer below it -
* "it just goes anywhere on the screen". Every row is therefore computed from
* the actual line structure: split on '\n', then wrap each line.
*/
size_t sp_ui_ascii_char(const char *s, char *out, size_t cap);
/*
* Rows an entry really occupies: the role prefix shortens the first row, so the
* height is computed from exactly the string that gets drawn ("role: text"),
* not from the text plus an estimate. Getting this wrong lost the last
* character of an entry - a truncated ``` closing a code block.
*/
/*
* IRC shape, as asked for: a timestamp, then who is speaking.
*
* [15:20:13] <you> der text
* [15:20:14] * agent is thinking ...
* [15:20:31] <agent> die antwort
*
* A timestamp is cheap and makes a transcript readable hours later; without one
* every old line looks like it happened just now.
*/
static void
entry_prefix(const struct entry *e, char *buf, size_t len)
{
struct tm tm;
char clock[16], who[64];
(void)localtime_r(&e->ts, &tm);
strftime(clock, sizeof(clock), "%H:%M:%S", &tm);
if (strcmp(e->role, "thinking") == 0) {
/* no '*': the markdown pass would eat it as emphasis */
snprintf(buf, len, "[%s] ~ %s: ", clock, sp_t("ui.thinking"));
} else if (strcmp(e->role, "you") == 0) {
snprintf(who, sizeof(who), "%.40s", g_who);
snprintf(buf, len, "[%s] <%s> ", clock, who);
} else if (strcmp(e->role, "agent") == 0) {
snprintf(who, sizeof(who), "%.40s", g_model);
{
char *dot = strstr(who, ".gguf");
if (dot != NULL)
*dot = '\0';
}
snprintf(buf, len, "[%s] <%s> ", clock, who);
} else if (strcmp(e->role, "tool") == 0) {
snprintf(buf, len, "[%s] >> ", clock);
} else if (strcmp(e->role, "observation") == 0) {
snprintf(buf, len, "[%s] | ", clock);
} else if (strcmp(e->role, "splinter") == 0) {
snprintf(buf, len, "[%s] --- ", clock);
} else {
snprintf(who, sizeof(who), "%.40s", role_label(e->role));
snprintf(buf, len, "[%s] <%s> ", clock, who);
}
}
/*
* Markdown, the little of it a chat actually contains.
*
* **bold** *italic* `code` # heading ``` fence
*
* The markers are removed before anything is measured, because a line measured
* with its asterisks wraps in a different place than the one that is drawn. Each
* kept character carries an attribute, so a bold word stays bold across a wrap.
*
* Fence blocks are drawn dim and their marker lines disappear: an answer full of
* C code should look like code, not like three backticks around code.
*/
#define MD_BOLD 0x01
#define MD_ITALIC 0x02
#define MD_CODE 0x04
/*
* Is the '*' run at p (len 1 or 2) emphasis, or just an asterisk? The rules of
* CommonMark, short: an opener is followed by text and preceded by a space or
* punctuation, a closer is preceded by text, and an opener needs its closer on
* the same line. Without this "void *ctx, const char *name" in a code answer
* lost its pointers and came out italic.
*/
static int
emph_ok(const char *start, const char *p, int len, int open_now, int in_code)
{
char prev = p > start ? p[-1] : ' ';
char next = p[len];
int prev_space = prev == ' ' || prev == '\t' || prev == '\n';
int next_space = next == '\0' || next == ' ' || next == '\t' ||
next == '\n';
const char *q;
if (in_code)
return 0;
if (open_now) /* a closer: it must follow text */
return !prev_space;
if (next_space) /* an opener: it must precede text */
return 0;
if (!(prev_space || strchr("([{\"'-,.;:/", prev) != NULL))
return 0;
/*
* ... and a closer must follow on this line before another opener does:
* the nearest opener takes the closer, the earlier ones stay asterisks.
*/
for (q = p + len; *q != '\0' && *q != '\n'; q++) {
int rl = 0;
if (*q != '*')
continue;
while (q[rl] == '*')
rl++;
if (rl == len) {
char pq = q[-1], nq = q[rl];
if (pq != ' ' && pq != '\t')
return 1; /* a closer */
if (nq != '\0' && nq != ' ' && nq != '\t' && nq != '\n')
return 0; /* a nearer opener */
}
q += rl - 1;
}
return 0;
}
static size_t
md_strip_n(const char *in, char *out, unsigned char *attr)
{
size_t o = 0;
int bold = 0, italic = 0, code = 0, fence = 0;
const char *p = in != NULL ? in : "";
while (*p != '\0') {
/* a fence line is a mode switch, not text */
if ((p[0] == '`' && p[1] == '`' && p[2] == '`') &&
(p == in || p[-1] == '\n')) {
fence = !fence;
while (*p != '\0' && *p != '\n')
p++;
continue;
}
if (*p == '\n') {
out[o] = '\n';
attr[o++] = fence ? MD_CODE : 0;
p++;
bold = italic = code = 0;
continue;
}
if (p[0] == '#' && (p == in || p[-1] == '\n')) {
while (*p == '#')
p++;
while (*p == ' ')
p++;
bold = 1;
continue;
}
if (!fence && p[0] == '*' && p[1] == '*' &&
emph_ok(in, p, 2, bold, code)) {
bold = !bold;
p += 2;
continue;
}
if (!fence && *p == '`') {
code = !code;
p++;
continue;
}
/*
* Only the asterisk marks italics. An underscore is part of names:
* Qwen3.6-35B-A3B-UD-Q8_K_XL came out as Qwen3.6-35B-A3B-UD-Q8KX,
* which is a different model as far as a reader is concerned.
*/
if (!fence && *p == '*' && emph_ok(in, p, 1, italic, code)) {
italic = !italic;
p++;
continue;
}
out[o] = *p;
attr[o] = (unsigned char)((fence ? MD_CODE : 0) |
(bold ? MD_BOLD : 0) | (italic ? MD_ITALIC : 0) |
(code ? MD_CODE : 0));
o++;
p++;
}
out[o] = '\0';
attr[o] = 0;
return o;
}
static int
md_prepare(const char *in, char **plain_out, unsigned char **attr_out)
{
struct sp_buf tb;
const char *src;
size_t n;
*plain_out = NULL;
*attr_out = NULL;
if (sp_buf_init(&tb) != 0)
return -1;
if (sp_md_table_format(in, &tb) < 0) {
sp_buf_free(&tb);
return -1;
}
src = tb.len > 0 ? tb.p : (in != NULL ? in : "");
n = strlen(src);
*plain_out = malloc(n + 1);
*attr_out = malloc(n + 1);
if (*plain_out == NULL || *attr_out == NULL) {
free(*plain_out);
free(*attr_out);
*plain_out = NULL;
*attr_out = NULL;
sp_buf_free(&tb);
return -1;
}
md_strip_n(src, *plain_out, *attr_out);
sp_buf_free(&tb);
return 0;
}
/*
* One character of 's', UTF-8 or not, as ASCII in 'out'; returns how many bytes
* of 's' it took (at least 1 unless *s is NUL).
*
* A UTF-8 character is one unit. Handing sp_ui_ascii a single byte of a two-byte
* sequence produced '??hler' where 'Zaehler' belonged - the transliteration
* needs the whole character. The copy of that character used to live in a
* char[2] on md_draw's stack, and a three- or four-byte character ('...', an
* emoji) wrote past it on every redraw.
*/
size_t
sp_ui_ascii_char(const char *s, char *out, size_t cap)
{
char one[5]; /* four UTF-8 bytes and the NUL */
size_t len = 1, k;
unsigned char c = (unsigned char)s[0];
if (cap == 0)
return c != 0 ? 1 : 0;
out[0] = '\0';
if (c == 0)
return 0;
if (c < 0x80) {
if (cap > 1) {
out[0] = (char)c;
out[1] = '\0';
}
return 1;
}
if ((c & 0xe0) == 0xc0)
len = 2;
else if ((c & 0xf0) == 0xe0)
len = 3;
else if ((c & 0xf8) == 0xf0)
len = 4;
for (k = 0; k < len && s[k] != '\0'; k++)
one[k] = s[k];
one[k] = '\0';
if (sp_ui_ascii(one, out, cap) != 0 && cap > 1) {
out[0] = '?';
out[1] = '\0';
}
return k;
}
/*
* The history pane, laid out once and drawn from that layout.
*
* The earlier version counted rows in one function and drew in another, and
* the two disagreed (the scroll offset was a byte count, the wrap a column
* count), which is why text landed in "zones" and scrolling jumped. Here an
* entry is turned into visual lines exactly once -- word wrapped, with the
* continuation lines hanging under the text -- and both the height and the
* drawing read that same list.
*/
struct vline {
size_t beg, end; /* bytes of the plain text */
int indent; /* columns left of the text */
};
struct elayout {
char *plain;
unsigned char *attr;
struct vline *v;
size_t n, cap;
int blank; /* a gap before this entry */
};
static int
vl_add(struct elayout *l, size_t beg, size_t end, int indent)
{
if (l->n == l->cap) {
size_t nc = l->cap != 0 ? l->cap * 2 : 16;
struct vline *nv = realloc(l->v, nc * sizeof(*nv));
if (nv == NULL)
return -1;
l->v = nv;
l->cap = nc;
}
l->v[l->n].beg = beg;
l->v[l->n].end = end;
l->v[l->n].indent = indent;
l->n++;
return 0;
}
/* Word wrap 'p' into 'l'; every line but the first hangs under 'ind'. */
static void
wrap_text(struct elayout *l, const char *p, int cols, int ind)
{
size_t i = 0;
int first = 1;
for (;;) {
int indent = first ? 0 : ind;
size_t avail = (size_t)(cols - indent > 0 ? cols - indent : 1);
size_t beg = i, end, w = 0, brk = 0;
int haveb = 0, wrapped = 0;
for (;;) {
char o[8];
size_t n, cw;
if (p[i] == '\0' || p[i] == '\n') {
end = i;
break;
}
n = sp_ui_ascii_char(p + i, o, sizeof(o));
if (n == 0)
n = 1;
cw = strlen(o);
if (w + cw > avail && i > beg) {
wrapped = 1;
if (haveb && brk > beg) {
end = brk;
i = brk;
} else
end = i;
break;
}
if (p[i] == ' ' && !(i > beg && p[i - 1] == ' ')) {
brk = i;
haveb = 1;
}
w += cw;
i += n;
}
if (vl_add(l, beg, end, indent) != 0)
return;
first = 0;
if (wrapped) {
while (p[i] == ' ')
i++;
if (p[i] == '\n')
i++;
if (p[i] == '\0')
break;
continue;
}
if (p[i] == '\0')
break;
i++; /* the newline */
}
}
static void
elayout_free(struct elayout *l)
{
free(l->plain);
free(l->attr);
free(l->v);
memset(l, 0, sizeof(*l));
}
/* the visual lines of one entry, prefix included; cached in the entry */
static struct elayout *
entry_layout(struct entry *e, int cols)
{
char prefix[256];
char *render;
size_t len;
int ind;
const char *brk;
struct elayout *l;
if (e->cache != NULL && e->cache_cols == cols)
return e->cache;
if (e->cache == NULL) {
e->cache = calloc(1, sizeof(*e->cache));
if (e->cache == NULL)
return NULL;
} else
elayout_free(e->cache);
l = e->cache;
e->cache_cols = cols;
entry_prefix(e, prefix, sizeof(prefix));
/* a table that starts the answer must not start behind the prefix */
brk = sp_md_table_starts(e->text) ? "\n" : "";
len = strlen(prefix) + strlen(brk) + strlen(e->text) + 1;
render = malloc(len);
if (render == NULL)
return l;
snprintf(render, len, "%s%s%s", prefix, brk, e->text);
if (md_prepare(render, &l->plain, &l->attr) != 0) {
free(l->plain);
free(l->attr);
l->plain = render;
l->attr = NULL;
} else
free(render);
/*
* Chat lines hang under their text. Command output, shell output and
* diffs are columns the author laid out: shifting them would break them.
*/
if (strcmp(e->role, "splinter") == 0 || strcmp(e->role, "shell") == 0)
ind = 0;
else {
ind = (int)strlen(prefix);
if (ind > 24)
ind = 24;
if (ind > cols / 3)
ind = cols / 3;
}
wrap_text(l, l->plain, cols, ind);
/* blank lines at the end are not content */
while (l->n > 1 && l->v[l->n - 1].beg == l->v[l->n - 1].end)
l->n--;
return l;
}
static void
draw_vline(int y, const struct elayout *l, const struct vline *vl)
{
attr_t base;
short pair;
size_t i;
int x = 1 + vl->indent;
(void)wattr_get(ui_hist, &base, &pair, NULL);
base &= ~A_COLOR;
for (i = vl->beg; i < vl->end;) {
char o[8];
unsigned a = l->attr != NULL ? l->attr[i] : 0;
attr_t at = base;
size_t n = sp_ui_ascii_char(l->plain + i, o, sizeof(o));
if (n == 0)
n = 1;
if (a & MD_BOLD)
at |= A_BOLD;
if (a & MD_ITALIC)
at |= A_UNDERLINE;
(void)wattr_set(ui_hist, at, (a & MD_CODE) ? PAIR_DIM : pair, NULL);
mvwaddstr(ui_hist, y, x, o);
x += (int)strlen(o);
i += n;
}
(void)wattr_set(ui_hist, base, pair, NULL);
}
static void
draw_history(struct ui_state *s)
{
int rows, cols, y = 0;
size_t idx, total = 0, first, line = 0, maxscroll;
struct elayout *l;
unsigned char *blank;
getmaxyx(ui_hist, rows, cols);
cols -= 2; /* padding left and right */
werase(ui_hist);
wbkgd(ui_hist, COLOR_PAIR(PAIR_MAIN));
if (s->n == 0 || cols < 2 || rows < 1) {
wnoutrefresh(ui_hist);
return;
}
blank = calloc(s->n, 1);
if (blank == NULL) {
wnoutrefresh(ui_hist);
return;
}
for (idx = 0; idx < s->n; idx++) {
l = entry_layout(&s->entries[idx], cols);
if (l == NULL)
continue;
/* a new question starts a new exchange: one line of air */
blank[idx] = idx > 0 && strcmp(s->entries[idx].role, "you") == 0;
total += l->n + (size_t)blank[idx];
}
maxscroll = total > (size_t)rows ? total - (size_t)rows : 0;
/* scrolled up and text arrived below: keep the reader where he is */
if (s->scroll > 0 && s->scroll <= s->scroll_max &&
maxscroll > s->scroll_base)
s->scroll += maxscroll - s->scroll_base;
if (s->scroll > maxscroll)
s->scroll = maxscroll;
s->scroll_max = maxscroll;
s->scroll_base = maxscroll - s->scroll;
first = maxscroll - s->scroll; /* index of the top visible line */
for (idx = 0; idx < s->n && y < rows; idx++) {
const struct entry *e = &s->entries[idx];
size_t k;
if (strcmp(e->role, "you") == 0)
wattrset(ui_hist, COLOR_PAIR(PAIR_ACCENT) | A_BOLD);
else if (strcmp(e->role, "agent") == 0)
wattrset(ui_hist, COLOR_PAIR(PAIR_MAIN));
else if (strcmp(e->role, "error") == 0)
wattrset(ui_hist, COLOR_PAIR(PAIR_ERROR) | A_BOLD);
else
wattrset(ui_hist, COLOR_PAIR(PAIR_DIM));
if (blank[idx]) {
if (line >= first && y < rows)
y++;
line++;
}
l = s->entries[idx].cache;
if (l == NULL)
continue;
for (k = 0; k < l->n && y < rows; k++, line++) {
if (line < first)
continue;
draw_vline(y, l, &l->v[k]);
y++;
}
wattrset(ui_hist, A_NORMAL);
}
free(blank);
wnoutrefresh(ui_hist);
}
/*
* The streaming turn is drawn as the last thing in the history pane: the tail
* of what has arrived so far. It is not an entry yet - entries are what was
* completed, and mixing the two would make the log look like it changed.
*/
/*
* While a turn runs, the left pane shows what the harness is doing, in the same
* place the conversation lives: the model's reasoning dimmed above, the answer
* as it arrives below. The sidebar keeps the counters - numbers are not text.
*/
static void
sidebar_heading(int *y, int cols, const char *text)
{
wattron(ui_side, COLOR_PAIR(PAIR_DIM) | A_BOLD);
mvwaddnstr(ui_side, *y, 0, text, cols - 1);
wattroff(ui_side, A_BOLD);
(*y)++;
wattron(ui_side, COLOR_PAIR(PAIR_MAIN));
}
/* wrap 'text' into the sidebar from row *y, at most 'maxrows' rows */
static void
side_text(int *y, int cols, const char *text, int maxrows)
{
int rows = 0;
while (*text != '\0' && rows < maxrows && *y < getmaxy(ui_side)) {
size_t n = strlen(text), take = n;
if (take > (size_t)cols - 1) {
take = (size_t)cols - 1;
while (take > 0 && text[take] != ' ')
take--;
if (take == 0)
take = (size_t)cols - 1;
}
mvwaddnstr(ui_side, (*y)++, 0, text, (int)take);
rows++;
text += take;
while (*text == ' ')
text++;
}
}
/*
* A path, wrapped at its slashes: "/home/k/src/splinter/plugins" cuts after a
* "/", never in the middle of a name. A path is what the operator checks first
* when a tool wrote somewhere it should not have.
*/
static void
side_path(int *y, int cols, const char *path, int maxrows)
{
int rows = 0;
size_t len = strlen(path), off = 0;
size_t width = (size_t)cols - 1;
if (width < 4)
width = 4;
while (off < len && rows < maxrows && *y < getmaxy(ui_side)) {
size_t take = len - off, cut;
if (take > width) {
take = width;
cut = take;
while (cut > 0 && path[off + cut] != '/')
cut--;
if (cut == 0)
take = width; /* no slash in reach: hard cut */
else
take = cut + 1; /* keep the slash on this line */
}
mvwaddnstr(ui_side, (*y)++, 0, path + off, (int)take);
off += take;
rows++;
}
}
static void
draw_sidebar(struct ui_state *s, const char *id, const char *dir,
struct sp_host *host)
{
int cols, y = 0;
char key[64];
const char *act = sp_usage_active();
if (ui_side == NULL)
return; /* one text field: no sidebar */
(void)dir;
cols = getmaxx(ui_side);
werase(ui_side);
/* who is answering: the profile, the provider, the model */
sidebar_heading(&y, cols, sp_t("sidebar.model"));
if (s->agents.n > 0) {
wattron(ui_side, A_BOLD);
{
char tag[64];
snprintf(tag, sizeof(tag), "[%s]",
s->agents.v[s->agent_cur].name);
mvwaddnstr(ui_side, y++, 0, tag, cols - 1);
}
wattroff(ui_side, A_BOLD);
}
{
char line[300];
snprintf(line, sizeof(line), "%s%s%s", act,
g_model[0] != '\0' ? " / " : "", g_model);
side_text(&y, cols, line, 2);
}
y++;
/* how much of each allowance is used: the provider in use, and any that
* has a limit or is benched */
{
const struct sp_config *cfg = s->conf;
struct sp_usage u;
size_t i;
int printed = 0;
char brief[96], line[200];
for (i = 0; i <= (cfg != NULL ? cfg->ndelegates : 0); i++) {
const char *pid = i == 0 ? act : cfg->delegate[i - 1].id;
if (i > 0 && strcmp(pid, act) == 0)
continue;
sp_usage_for(cfg, pid, &u);
if (i > 0 && u.frac < 0 && u.benched_until == 0)
continue;
if (!printed) {
sidebar_heading(&y, cols, sp_t("sidebar.usage"));
printed = 1;
}
sp_usage_brief(&u, brief, sizeof(brief));
snprintf(line, sizeof(line), "%-9.9s %s", pid, brief);
if (u.frac >= 0.9 || u.benched_until > 0)
wattron(ui_side, COLOR_PAIR(PAIR_ACCENT) | A_BOLD);
if (y < getmaxy(ui_side))
mvwaddnstr(ui_side, y++, 0, line, cols - 1);
wattrset(ui_side, COLOR_PAIR(PAIR_MAIN));
}
if (printed)
y++;
}
/* what the plugins want to show: the goal, the plan, tasks ... */
if (host != NULL && sp_host_widget_count(host) > 0) {
char snap[1024], *line, *save = NULL;
sp_host_widget_snapshot(host, snap, sizeof(snap));
for (line = strtok_r(snap, "\n", &save); line != NULL;
line = strtok_r(NULL, "\n", &save)) {
char name[48], *colon = strchr(line, ':');
char *text;
size_t nl;
if (colon == NULL)
continue;
nl = (size_t)(colon - line);
if (nl >= sizeof(name))
continue;
memcpy(name, line, nl);
name[nl] = '\0';
text = colon + 1;
while (*text == ' ')
text++;
/* a text that repeats its own name ("plan: 0 tasks") */
if (strncmp(text, name, nl) == 0 && text[nl] == ':') {
text += nl + 1;
while (*text == ' ')
text++;
}
if (*text == '\0' || y >= getmaxy(ui_side) - 2)
continue;
snprintf(key, sizeof(key), "widget.%s", name);
sidebar_heading(&y, cols, sp_td(key, name));
side_text(&y, cols, text, 4);
y++;
}
}
/* the last turn, in one line */
if (s->last_ms > 0 && y < getmaxy(ui_side) - 2) {
char line[160];
sidebar_heading(&y, cols, sp_t("sidebar.last_turn"));
snprintf(line, sizeof(line), sp_t("sidebar.turn_line"),
(double)s->last_ms / 1000.0, s->last_steps, s->last_calls);
side_text(&y, cols, line, 1);
if (s->tokens_out > 0) {
snprintf(line, sizeof(line), sp_t("sidebar.tokens"),
s->tokens_out, s->tokens_in);
side_text(&y, cols, line, 1);
}
y++;
}
if (id != NULL && y < getmaxy(ui_side) - 2) {
sidebar_heading(&y, cols, sp_t("sidebar.session"));
wattron(ui_side, COLOR_PAIR(PAIR_DIM));
side_text(&y, cols, id, 1);
}
/*
* Where this splinter runs. Every tool acts relative to it, so it has to
* be on screen: a delegate that wrote into the wrong tree was the one
* question nobody could answer from the screen. $HOME is shown as ~.
*/
{
char cwd[700], shown[760];
const char *home = getenv("HOME");
if (getcwd(cwd, sizeof(cwd)) != NULL) {
if (home != NULL && *home != '\0' &&
strncmp(cwd, home, strlen(home)) == 0 &&
(cwd[strlen(home)] == '/' || cwd[strlen(home)] == '\0'))
snprintf(shown, sizeof(shown), "~%s", cwd + strlen(home));
else
snprintf(shown, sizeof(shown), "%s", cwd);
sidebar_heading(&y, cols, sp_t("sidebar.cwd"));
wattron(ui_side, COLOR_PAIR(PAIR_DIM));
side_path(&y, cols, shown, 4);
}
}
wattrset(ui_side, A_NORMAL);
wnoutrefresh(ui_side);
}
/*
* Feed the meter the status plugins read. The harness counts; a plugin must not
* count for itself or the two numbers drift apart.
*/
static struct sp_host *g_status_host;
/* the UI's fields of the meter; the tasks plugin owns others */
static void
set_ui_fields(struct sp_meter *m, void *ctx)
{
const struct ui_state *s = ctx;
const char *ctxmax = getenv("SPLINTER_CTX_MAX");
m->ctx_used = s->tokens_in;
if (ctxmax != NULL && *ctxmax != '\0')
m->ctx_max = (size_t)strtoul(ctxmax, NULL, 10);
m->tok_in = s->tokens_in;
m->tok_out = s->tokens_out;
if (s->last_ms > 0 && s->tokens_out > 0)
m->tps = (long)((double)s->tokens_out * 1000.0 /
(double)s->last_ms);
}
static void
update_meter(struct ui_state *s, struct sp_host *host)
{
if (host != NULL)
sp_host_meter_update(host, set_ui_fields, s);
}
static void
hist_load(struct ui_state *s, const char *dir)
{
char path[600];
FILE *f;
if (dir == NULL)
return;
snprintf(path, sizeof(path), "%s/history", dir);
f = fopen(path, "r");
if (f == NULL)
return;
while (s->nhist < 128 && fgets(s->hist[s->nhist], 1024, f) != NULL) {
s->hist[s->nhist][strcspn(s->hist[s->nhist], "\r\n")] = '\0';
if (s->hist[s->nhist][0] != '\0')
s->nhist++;
}
fclose(f);
s->hist_pos = -1;
}
static void
hist_push(struct ui_state *s, const char *dir, const char *line)
{
char path[600];
FILE *f;
if (line == NULL || line[0] == '\0')
return;
/* typing the same thing twice in a row is not two history entries */
if (s->nhist > 0 && strcmp(s->hist[s->nhist - 1], line) == 0)
return;
if (s->nhist == 128) {
memmove(&s->hist[0], &s->hist[1], sizeof(s->hist[0]) * 127);
s->nhist--;
}
snprintf(s->hist[s->nhist], 1024, "%s", line);
s->nhist++;
s->hist_pos = -1;
if (dir == NULL)
return;
snprintf(path, sizeof(path), "%s/history", dir);
f = fopen(path, "a");
if (f == NULL)
return;
fprintf(f, "%s\n", line);
fclose(f);
}
/* Replace an entry's text in place: a streaming turn keeps one entry per role
* and rewrites it, so the transcript grows where the reader is looking. */
static void
entry_set_text(struct ui_state *s, size_t id, const char *text)
{
char *copy;
size_t i;
for (i = s->n; i > 0; i--) /* the live entry is near the end */
if (s->entries[i - 1].id == id)
break;
if (i == 0)
return; /* evicted meanwhile: nothing to do */
copy = strdup(text != NULL ? text : "");
if (copy == NULL)
return;
free(s->entries[i - 1].text);
s->entries[i - 1].text = copy;
/* the wrapped lines belong to the old text */
if (s->entries[i - 1].cache != NULL) {
elayout_free(s->entries[i - 1].cache);
free(s->entries[i - 1].cache);
s->entries[i - 1].cache = NULL;
}
}
/*
* Append an entry and return its id. Callers that update an entry later (the
* live answer, the reasoning) keep the id, not the index: at MAX_ENTRIES the
* oldest entry is evicted and every index moves by one - the streamed answer
* then went into the wrong entry, or into none.
*/
static size_t
add_entry(struct ui_state *s, const char *role, const char *text)
{
struct entry *e;
size_t id;
if (s->n == MAX_ENTRIES) {
free(s->entries[0].role);
free(s->entries[0].text);
if (s->entries[0].cache != NULL) {
elayout_free(s->entries[0].cache);
free(s->entries[0].cache);
}
memmove(&s->entries[0], &s->entries[1],
sizeof(s->entries[0]) * (MAX_ENTRIES - 1));
s->n--;
}
e = &s->entries[s->n++];
e->role = strdup(role != NULL ? role : "?");
e->text = strdup(text != NULL ? text : "");
if (e->role == NULL || e->text == NULL) {
/* out of memory: an entry with no text is better than a NULL */
free(e->role);
free(e->text);
s->n--;
return 0;
}
e->ts = time(NULL);
e->id = id = ++s->next_id;
e->cache = NULL;
e->cache_cols = 0;
{
struct tm tm;
int day;
(void)localtime_r(&e->ts, &tm);
day = tm.tm_yday + tm.tm_year * 400;
if (s->last_day != 0 && day != s->last_day) {
char stamp[64];
struct entry *d;
/*
* The day changed while splinter was running. Say it once, in
* the chat, so a transcript that spans midnight still reads in
* order - and never again until it changes again.
*/
strftime(stamp, sizeof(stamp), "--- %Y-%m-%d ---", &tm);
if (s->n < MAX_ENTRIES) {
d = &s->entries[s->n];
d->role = strdup("splinter");
d->text = strdup(stamp);
if (d->role != NULL && d->text != NULL) {
d->ts = e->ts;
d->id = ++s->next_id;
d->cache = NULL;
d->cache_cols = 0;
s->n++;
} else {
free(d->role);
free(d->text);
}
}
}
s->last_day = day;
}
return id;
}
/*
* 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.
*/
/* 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;
}
static void
agent_switch(struct ui_state *s, struct sp_agent *ag, int idx, int announce)
{
const struct sp_agent_def *d;
char msg[400];
if (s->agents.n == 0 || idx < 0 || (size_t)idx >= s->agents.n)
return;
d = &s->agents.v[idx];
s->agent_cur = idx;
snprintf(ui_agent, sizeof(ui_agent), "%.24s", d->name);
(void)sp_agents_activate(ag, d, s->base_prompt != NULL ?
s->base_prompt : "", &s->policy);
if (s->conf != NULL) {
struct sp_choice ch;
const char *want = d->model[0] != '\0' ? d->model :
(s->home_id[0] != '\0' ? s->home_id : NULL);
if (want != NULL && sp_provider_choose(s->conf, want, &ch) == 0 &&
strcmp(ch.d->kind, "cli") != 0 && ch.d->endpoint[0] != '\0') {
struct sp_buf perr;
if (d->model[0] != '\0' && s->home_id[0] == '\0')
snprintf(s->home_id, sizeof(s->home_id), "%s",
sp_usage_active());
if (sp_buf_init(&perr) == 0) {
if (sp_provider_apply(ag, ch.d->kind,
ch.d->endpoint,
ch.model[0] != '\0' ? ch.model : ch.d->model,
ch.d->key_env, &perr) == 0) {
sp_usage_set_active(ch.d->id);
snprintf(s->cur_model, sizeof(s->cur_model),
"%s", ch.model[0] != '\0' ? ch.model :
ch.d->model);
snprintf(s->cur_endpoint,
sizeof(s->cur_endpoint), "%s",
ch.d->endpoint);
}
sp_buf_free(&perr);
}
if (d->model[0] == '\0')
s->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") : "");
add_entry(s, "splinter", msg);
}
}
static void
layout(void)
{
int rows, cols;
getmaxyx(stdscr, rows, cols);
/*
* The conversation on three quarters, the sidebar on the last one, the
* input below both. The conversation starts at the top and grows
* downward; what was written stays where it is.
*/
{
int side_w = cols / 4;
int chat_w = cols - side_w - 1;
if (side_w < 18)
side_w = cols > 50 ? 18 : 0;
if (side_w == 0)
chat_w = cols;
ui_hist = newwin(rows - 1, chat_w, 0, 0);
ui_side = side_w > 0 ?
newwin(rows - 1, side_w, 0, chat_w + 1) : NULL;
}
wbkgd(ui_hist, COLOR_PAIR(PAIR_MAIN));
ui_input = newwin(1, cols, rows - 1, 0);
wbkgd(ui_input, COLOR_PAIR(PAIR_INPUT));
keypad(ui_input, TRUE);
/* a one-line window that may scroll is a screen that jumps */
scrollok(ui_input, FALSE);
}
/*
* The terminal changed size: the windows were cut for the old one. layout()
* used to run once, so after a resize the four windows kept their old
* geometry and drew over each other.
*/
static void
relayout(int input_timeout_ms)
{
if (ui_hist != NULL)
delwin(ui_hist);
if (ui_side != NULL)
delwin(ui_side);
if (ui_input != NULL)
delwin(ui_input);
ui_hist = ui_side = ui_input = NULL;
layout();
wtimeout(ui_input, input_timeout_ms);
clearok(curscr, TRUE);
}
/* the session id and directory the sidebar shows, NULL-safe */
#define SESS_ID(ag) ((ag)->sess != NULL ? (ag)->sess->id : NULL)
#define SESS_DIR(ag) ((ag)->sess != NULL ? (ag)->sess->dir : NULL)
/* history, sidebar and status line, then one doupdate() */
static void
redraw(struct ui_state *s, struct sp_agent *ag, struct sp_host *host)
{
draw_history(s);
draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host);
doupdate();
}
/*
* The prompt mark, always followed by one space: the catalogue reader trims
* trailing blanks, so "> " in the .msg file arrives as ">".
*/
static const char *
prompt_mark(void)
{
static char buf[64];
const char *m = sp_t("ui.prompt_mark");
size_t n = strlen(m);
snprintf(buf, sizeof(buf), "%s%s%s", ui_agent, m,
n > 0 && m[n - 1] == ' ' ? "" : " ");
return buf;
}
/* the prompt line with what has been typed so far */
static void
draw_prompt(const char *input)
{
const char *mark = prompt_mark();
char *ascii;
size_t n, avail, cap;
int w = getmaxx(ui_input);
werase(ui_input);
mvwaddstr(ui_input, 0, 0, mark);
/*
* The line is one row and never wraps: when the text is longer than the
* room, the end of it stays visible and the start scrolls out to the
* left. The last column stays empty -- writing into the bottom-right
* cell of a window that cannot scroll is an error in curses, and in
* this port a crash.
*/
avail = (size_t)(w - (int)strlen(mark) - 2);
if (input == NULL || w < 8 || avail < 1)
return;
cap = strlen(input) * 4 + 16;
ascii = malloc(cap);
if (ascii == NULL)
return;
if (sp_ui_ascii(input, ascii, cap) != 0)
snprintf(ascii, cap, "%s", input);
n = strlen(ascii);
if (n > avail)
waddnstr(ui_input, ascii + (n - avail), (int)avail);
else
waddnstr(ui_input, ascii, (int)n);
free(ascii);
}
/*
* Read one line at the prompt. Enter ends it; Ctrl-D sets s->quit. While no
* key comes, the read times out every 500 ms and repaints sidebar and status
* line: a widget that ticks is useless if the screen only refreshes on a key.
*/
static int
slash_add_match(char matches[][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(matches[i], name) == 0)
return 0;
snprintf(matches[(*n)++], 64, "%s", name);
return 1;
}
static int
slash_collect(struct sp_agent *ag, struct sp_host *host,
char matches[][64], int max)
{
int n = 0;
struct sp_buf b;
char cdir[700], *p, *tok, *save;
slash_add_match(matches, &n, max, "status");
slash_add_match(matches, &n, max, "usage");
slash_add_match(matches, &n, max, "widgets");
slash_add_match(matches, &n, max, "agent");
slash_add_match(matches, &n, max, "resume");
slash_add_match(matches, &n, max, "swarm");
if (host != NULL && sp_buf_init(&b) == 0) {
if (sp_host_command_help(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_match(matches, &n, max, p);
}
}
sp_buf_free(&b);
}
if (sp_buf_init(&b) == 0) {
if (sp_cmdscript_dir(ag && ag->sess ? ag->sess->dir : NULL,
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_match(matches, &n, max, tok);
}
sp_buf_free(&b);
}
/* simple sort for stable popup */
for (int i = 1; i < n; i++) {
char tmp[64]; int j = i;
snprintf(tmp, sizeof(tmp), "%s", matches[i]);
while (j > 0 && strcmp(matches[j-1], tmp) > 0) {
snprintf(matches[j], 64, "%s", matches[j-1]);
j--;
}
snprintf(matches[j], 64, "%s", tmp);
}
return n;
}
static void
ui_read_line(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
char *input, size_t cap)
{
size_t len = 0;
int ch;
int locked = (s->sw != NULL && s->sw->role == SWARM_SLAVE && s->sw->locked);
input[0] = '\0';
if (locked) {
werase(ui_input);
mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] "));
wnoutrefresh(ui_input);
} else
draw_prompt(input);
wnoutrefresh(ui_input);
doupdate();
wtimeout(ui_input, 500);
if (s->sw != NULL)
swarm_report_busy(s->sw, 0);
for (;;) {
/* poll fleet: accept/read, update lock/inbox */
if (s->sw != NULL) {
swarm_poll(s->sw);
locked = (s->sw->role == SWARM_SLAVE && s->sw->locked);
if (swarm_take_inbox(s->sw, input, cap)) {
wtimeout(ui_input, -1);
return;
}
}
ch = wgetch(ui_input);
if (ch == ERR) {
{
char msg[200];
int got = 0;
while (sp_host_status_take(host, msg, sizeof(msg))) {
add_entry(s, "splinter", msg);
got = 1;
}
if (got)
draw_history(s);
}
draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host);
if (locked) {
werase(ui_input);
mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] "));
wnoutrefresh(ui_input);
} else {
draw_prompt(input);
wnoutrefresh(ui_input);
}
doupdate();
continue;
}
if (ch == '\n' || ch == '\r' || ch == KEY_ENTER) {
if (locked) continue;
break;
}
if (ch == 4) {
s->quit = 1;
break;
}
/*
* Ctrl-L repaints, KEY_RESIZE re-cuts the windows.
*/
if (ch == 12 || ch == KEY_RESIZE) {
if (ch == KEY_RESIZE)
relayout(500);
else
clearok(curscr, TRUE);
draw_history(s);
draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host);
if (locked) {
werase(ui_input);
mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] "));
} else
draw_prompt(input);
wnoutrefresh(ui_input);
doupdate();
continue;
}
if (ch == 3) {
if (locked) continue;
len = 0;
input[0] = '\0';
draw_prompt(input);
wrefresh(ui_input);
continue;
}
if (ch == KEY_UP || ch == KEY_DOWN) {
if (locked || s->nhist == 0)
continue;
if (s->hist_pos < 0)
s->hist_pos = (int)s->nhist;
if (ch == KEY_UP && s->hist_pos > 0)
s->hist_pos--;
else if (ch == KEY_DOWN && s->hist_pos < (int)s->nhist - 1)
s->hist_pos++;
else if (ch == KEY_DOWN)
s->hist_pos = (int)s->nhist;
if (s->hist_pos >= (int)s->nhist || s->hist_pos < 0)
len = 0;
else {
snprintf(input, cap, "%s", s->hist[s->hist_pos]);
len = strlen(input);
}
input[len] = '\0';
draw_prompt(input);
wrefresh(ui_input);
continue;
}
/*
* PgUp/PgDn and Shift+arrows scroll the chat pane.
*/
if (ch == KEY_PPAGE || ch == KEY_SR) {
s->scroll += (ch == KEY_SR ? 1 : 10);
draw_history(s);
draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host);
if (locked) {
werase(ui_input);
mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] "));
} else
draw_prompt(input);
wnoutrefresh(ui_input);
doupdate();
continue;
}
if (ch == KEY_NPAGE || ch == KEY_SF) {
size_t step = (ch == KEY_SF ? 1 : 10);
s->scroll = s->scroll > step ? s->scroll - step : 0;
draw_history(s);
draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host);
if (locked) {
werase(ui_input);
mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] "));
} else
draw_prompt(input);
wnoutrefresh(ui_input);
doupdate();
continue;
}
if (ch == KEY_BACKSPACE || ch == 127 || ch == 8) {
if (locked) continue;
if (len > 0) {
/* drop a whole UTF-8 sequence, not half of one */
do
len--;
while (len > 0 && ((unsigned char)input[len] & 0xc0) == 0x80);
input[len] = '\0';
draw_prompt(input);
wrefresh(ui_input);
}
continue;
}
/*
* Tab (Shift-Tab back) switches the agent profile, unless a /command
* is being completed.
*/
if ((ch == '\t' || ch == KEY_BTAB) &&
!(input[0] == '/' && strchr(input, ' ') == NULL)) {
if (locked || s->agents.n < 2)
continue;
agent_switch(s, ag, ch == '\t' ?
(s->agent_cur + 1) % (int)s->agents.n :
(s->agent_cur + (int)s->agents.n - 1) % (int)s->agents.n,
1);
draw_history(s);
draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host);
draw_prompt(input);
wnoutrefresh(ui_input);
doupdate();
continue;
}
/*
* Slash completion: Tab shows available /commands.
*/
if (ch == '\t' && input[0] == '/' && strchr(input, ' ') == NULL) {
if (locked) continue;
{
char matches[32][64];
int nm = slash_collect(ag, host, matches, 32);
const char *prefix = input + 1;
size_t plen = strlen(prefix);
char *m[32];
int k = 0, i2;
for (i2 = 0; i2 < nm; i2++)
if (strncmp(matches[i2], prefix, plen) == 0)
m[k++] = matches[i2];
if (k == 1) {
snprintf(input, cap, "/%s ", m[0]);
len = strlen(input);
} else if (k > 1) {
size_t c = strlen(m[0]);
for (i2 = 1; i2 < k; i2++) {
size_t j = 0;
while (j < c && m[0][j] == m[i2][j]) j++;
c = j;
}
if (c > plen) {
snprintf(input, cap, "/%.*s", (int)c, m[0]);
len = strlen(input);
}
{
char hint[512]; size_t off = 0;
off += snprintf(hint + off, sizeof(hint) - off, " ");
for (i2 = 0; i2 < k && off + 2 < sizeof(hint); i2++)
off += snprintf(hint + off, sizeof(hint) - off, "/%s ", m[i2]);
{
/* no status bar: the last row */
int hy = getmaxy(ui_hist) - 1;
wattron(ui_hist, COLOR_PAIR(PAIR_STATUS));
mvwhline(ui_hist, hy, 0, ' ', getmaxx(ui_hist));
mvwaddnstr(ui_hist, hy, 0, hint, getmaxx(ui_hist) - 1);
wattroff(ui_hist, COLOR_PAIR(PAIR_STATUS));
wnoutrefresh(ui_hist);
}
}
}
draw_prompt(input);
wnoutrefresh(ui_input);
doupdate();
}
continue;
}
if (locked)
continue;
if (ch >= 32 && ch < 256 && len + 1 < cap) {
input[len++] = (char)ch;
input[len] = '\0';
draw_prompt(input);
wrefresh(ui_input);
}
}
wtimeout(ui_input, -1);
}
static void
ui_shell(struct ui_state *s, struct sp_agent *ag, const char *cmd)
{
FILE *fp;
char buf[8192];
size_t n = 0;
char shcmd[4096];
int c;
(void)ag;
snprintf(shcmd, sizeof(shcmd), "sh -c '%.*s' 2>&1",
(int)(sizeof(shcmd) - 20), cmd);
/* simple: avoid single quotes breaking; MVP */
fp = popen(cmd, "r");
if (fp == NULL) {
add_entry(s, "shell", "popen failed");
return;
}
while (n + 1 < sizeof(buf) && (c = fgetc(fp)) != EOF)
buf[n++] = (char)c;
buf[n] = '\0';
pclose(fp);
add_entry(s, "shell", n > 0 ? buf : "(no output)");
}
/*
* A leading slash is a command for the harness, not a prompt: it never reaches
* the model, and its reply is shown as the harness speaking. Unknown commands
* list what exists. Returns 1 when the line was handled; 0 when a program in
* commands/ replaced it with text for the model, so a turn runs with 'input'.
*/
/* /connect in the terminal: the same questions the gateway asks, per line */
static void
ui_connect_ask(struct ui_state *s, struct sp_buf *out)
{
switch (s->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 (s->cc.key_env[0] != '\0')
sp_buf_printf(out, sp_t("connect.key_named"),
s->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
ui_connect_answer(struct ui_state *s, struct sp_agent *ag, const char *line,
struct sp_buf *out)
{
(void)ag;
if (!s->cc.active)
return 0;
if (strcmp(line, "/cancel") == 0 || strcasecmp(line, "cancel") == 0) {
memset(&s->cc, 0, sizeof(s->cc));
sp_buf_puts(out, sp_t("connect.cancel"));
return 1;
}
switch (s->cc.step) {
case 0:
if (!sp_provider_id_ok(line)) {
sp_buf_puts(out, sp_t("connect.name_bad"));
return 1;
}
snprintf(s->cc.id, sizeof(s->cc.id), "%s", line);
break;
case 1:
if (strcmp(line, "ollama") == 0) {
snprintf(s->cc.endpoint, sizeof(s->cc.endpoint),
"http://127.0.0.1:11434/v1");
} else if (strcmp(line, "opencode") == 0) {
snprintf(s->cc.endpoint, sizeof(s->cc.endpoint),
"https://opencode.ai/zen/go/v1");
snprintf(s->cc.key_env, sizeof(s->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(s->cc.endpoint, sizeof(s->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(s->cc.model, sizeof(s->cc.model), "%s", line);
break;
default:
if (strcmp(line, "-") == 0)
s->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(s->cc.key_env, sizeof(s->cc.key_env), "%s",
line);
}
{
char dir[720];
struct sp_buf cerr;
sp_buf_init(&cerr);
if (s->conf == NULL ||
sp_provider_dir(dir, sizeof(dir)) != 0) {
sp_buf_puts(out, sp_t("connect.nodir"));
} else if (sp_provider_add(s->conf, dir, s->cc.id,
s->cc.endpoint, s->cc.model, s->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"),
s->cc.id, s->cc.model, s->cc.endpoint);
}
sp_buf_free(&cerr);
}
memset(&s->cc, 0, sizeof(s->cc));
return 1;
}
s->cc.step++;
sp_buf_puts(out, "\n");
ui_connect_ask(s, out);
return 1;
}
static int
ui_slash(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
char *input, size_t cap)
{
char name[64], args[1536], outbuf[2048], cdir[700];
struct sp_buf out, cerr;
const char *sp;
sp = strchr(input, ' ');
if (sp == NULL) {
snprintf(name, sizeof(name), "%.63s", input + 1);
args[0] = '\0';
} else {
size_t nlen = (size_t)(sp - (input + 1));
if (nlen >= sizeof(name))
nlen = sizeof(name) - 1;
memcpy(name, input + 1, nlen);
name[nlen] = '\0';
snprintf(args, sizeof(args), "%s", sp + 1);
}
if (sp_buf_init(&out) != 0)
return 1;
if (strcmp(name, "agent") == 0 || strcmp(name, "agents") == 0) {
size_t i;
if (args[0] != '\0') {
int idx = sp_agents_find(&s->agents, args);
if (idx < 0)
{
sp_buf_printf(&out, sp_t("agent.none"), args);
sp_buf_puts(&out, "\n");
}
else {
agent_switch(s, ag, idx, 1);
snprintf(outbuf, sizeof(outbuf), "%s", "");
sp_buf_free(&out);
return 1;
}
}
{
for (i = 0; i < s->agents.n; i++) {
const struct sp_agent_def *d = &s->agents.v[i];
sp_buf_printf(&out, "%c %-12s %s %s\n",
(int)i == s->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"));
snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : "");
sp_buf_free(&out);
add_entry(s, "splinter", outbuf);
return 1;
}
if (strcmp(name, "quit") == 0 || strcmp(name, "exit") == 0 ||
strcmp(name, "q") == 0) {
s->quit = 1;
sp_buf_free(&out);
return 1;
}
/*
* /widgets: what a plugin published. The sidebar used to show these lines
* all the time; one text field shows them when asked, as text.
*/
if (strcmp(name, "widgets") == 0 || strcmp(name, "widget") == 0) {
char buf[4096];
if (host == NULL || sp_host_widget_count(host) == 0)
sp_buf_puts(&out, sp_t("widgets.none"));
else if (sp_host_widget_snapshot(host, buf, sizeof(buf)) > 0)
sp_buf_printf(&out, "%s", buf);
snprintf(outbuf, sizeof(outbuf), "%s", out.p != NULL ? out.p : "");
sp_buf_free(&out);
add_entry(s, "splinter", outbuf);
return 1;
}
if (strcmp(name, "usage") == 0) {
sp_usage_report(s->conf, &out);
snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : "");
sp_buf_free(&out);
add_entry(s, "splinter", outbuf);
return 1;
}
if (strcmp(name, "status") == 0) {
size_t comp = 0, failed = 0; unsigned turns = 0;
time_t now = time(NULL);
char tbuf[64];
struct tm tm;
(void)localtime_r(&now, &tm);
strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
sp_host_compaction_stats(host, &comp, &failed, &turns);
sp_buf_printf(&out, "status (%s)\n", tbuf);
sp_buf_printf(&out, " session %s\n dir %s\n",
ag->sess ? ag->sess->id : "-", ag->sess ? ag->sess->dir : "-");
sp_buf_printf(&out, " model %s\n endpoint %s\n theme %s\n",
s->model ? s->model : "-", s->endpoint ? s->endpoint : "-",
s->theme.name);
sp_buf_printf(&out, " last %ld ms, %zu steps, %zu tool calls\n",
s->last_ms, s->last_steps, s->last_calls);
sp_buf_printf(&out, " tokens in %zu, out %zu (session stats in %zu out %zu)\n",
s->tokens_in, s->tokens_out,
ag->stats.tokens_in, ag->stats.tokens_out);
sp_buf_printf(&out, " output %zu chars this turn, %zu total\n",
s->out_chars, s->total_out_chars);
sp_buf_printf(&out, " compact %zu applied, %zu failed, %zu turns (agent %zu)\n",
comp, failed, turns, ag->stats.compactions);
if (ag->cfg != NULL)
sp_buf_printf(&out, " limits max_bytes %zu, max_steps %zu%s\n",
ag->cfg->max_bytes, ag->cfg->max_steps,
ag->cfg->autonomous ? ", autonomous" : "");
if (host != NULL) {
struct sp_meter m;
char seg[512];
sp_host_meter_get(host, &m);
sp_buf_printf(&out, " meter ctx %zu/%zu, cache %zu, tok %zu/%zu\n",
m.ctx_used, m.ctx_max, m.cached, m.tok_in, m.tok_out);
update_meter(s, host);
if (sp_host_status_text(host, seg, sizeof(seg)) > 0)
sp_buf_printf(&out, " bar %s\n", seg);
}
if (s->sw != NULL && s->sw->role != SWARM_NONE) {
char sws[256], list[1024];
swarm_status(s->sw, sws, sizeof(sws));
sp_buf_printf(&out, " swarm %s (id %d)\n", sws, s->sw->id);
swarm_list(s->sw, list, sizeof(list));
sp_buf_printf(&out, "%s", list);
}
snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : "");
sp_buf_free(&out);
add_entry(s, "splinter", outbuf);
return 1;
}
if (strcmp(name, "swarm") == 0) {
char list[1024];
if (s->sw == NULL || s->sw->role == SWARM_NONE) {
sp_buf_printf(&out, "swarm: standalone (no fleet in %s)", SWARM_PATH);
} else if (args[0] == '\0' || strcmp(args, "ls") == 0 || strcmp(args, "list") == 0) {
swarm_list(s->sw, list, sizeof(list));
sp_buf_printf(&out, "%s", list);
} else {
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");
} else {
if (s->sw->role != SWARM_MASTER && id != 0) {
/* slave: forward request to master? MVP: only master routes */
sp_buf_printf(&out, "swarm: only master (0) can route commands");
} else {
target = swarm_route(s->sw, (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);
}
}
}
snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : "");
sp_buf_free(&out);
add_entry(s, "splinter", outbuf);
return 1;
}
/*
* /model: the same list the gateway offers, without buttons. No argument
* lists them, an id switches provider, any other word is a model on the
* current endpoint. The choice is written for the next start, like the
* gateway's.
*/
if (strcmp(name, "model") == 0) {
struct sp_provider p;
struct sp_buf perr, serr;
size_t idx = 0, i, n;
char poolname[40];
int is_pool = 0;
/*
* A pool is a selector too, and so is "pool/model": the run starts
* on the member with the most room and moves at a limit, exactly
* what naming the pool in -m does.
*/
snprintf(poolname, sizeof(poolname), "%s", args);
is_pool = sp_pool_find(s->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(s->conf, poolname) != NULL;
}
}
if (s->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(s->conf);
for (i = 0; i < n; i++)
if (sp_provider_at(s->conf, i, &p) == 0)
sp_buf_printf(&out, "\n %s %s%s",
p.id, p.model,
strcmp(p.model, s->model) == 0 ?
" *" : "");
/* a pool is a selector too: it starts on the member with
* the most room and moves at a limit */
if (s->conf->npools > 0)
sp_buf_printf(&out, "\n%s", sp_t("model.pools"));
for (i = 0; i < s->conf->npools; i++) {
size_t j;
sp_buf_printf(&out, "\n %s pool (%s):",
s->conf->pool[i].id,
s->conf->pool[i].strategy);
for (j = 0; j < s->conf->pool[i].nmembers; j++)
sp_buf_printf(&out, " %s",
s->conf->pool[i].member[j]);
}
} else if (is_pool) {
struct sp_choice ch;
if (sp_provider_choose(s->conf, args, &ch) != 0) {
sp_buf_printf(&out, sp_t("model.unknown"),
args);
} else {
sp_buf_init(&perr);
if (sp_provider_apply(ag, ch.d->kind,
ch.d->endpoint,
ch.model[0] != '\0' ? ch.model : ch.d->model,
ch.d->key_env, &perr) != 0) {
sp_buf_printf(&out, sp_t("model.failed"),
perr.p != NULL ? perr.p : "?");
} else {
sp_usage_set_active(ch.d->id);
snprintf(s->cur_endpoint,
sizeof(s->cur_endpoint), "%s",
ch.d->endpoint);
snprintf(s->cur_model, sizeof(s->cur_model),
"%s", ch.model[0] != '\0' ?
ch.model : ch.d->model);
sp_buf_printf(&out, sp_t("model.pool"),
poolname, s->cur_model, ch.d->id);
}
sp_buf_free(&perr);
}
} else if (sp_provider_find(s->conf, args, &idx)) {
sp_buf_init(&perr);
if (sp_provider_use(ag, s->conf, idx, &perr) != 0) {
sp_buf_printf(&out, sp_t("model.failed"),
perr.p != NULL ? perr.p : "?");
} else if (sp_provider_at(s->conf, idx, &p) == 0) {
snprintf(s->cur_endpoint,
sizeof(s->cur_endpoint), "%s", p.endpoint);
snprintf(s->cur_model, sizeof(s->cur_model),
"%s", p.model);
sp_buf_init(&serr);
sp_buf_printf(&out, sp_provider_save_choice(
s->conf, &p, &serr) == 0 ?
sp_t("model.saved") : sp_t("model.switched"),
p.model, p.id);
sp_buf_free(&serr);
}
sp_buf_free(&perr);
} else {
struct sp_provider chosen;
int ok;
memset(&p, 0, sizeof(p));
if (!sp_provider_find(s->conf, s->model, &idx) ||
sp_provider_at(s->conf, idx, &p) != 0)
(void)sp_provider_at(s->conf, 0, &p);
sp_buf_init(&perr);
ok = sp_provider_apply(ag, p.kind, p.endpoint, args,
p.key_env, &perr) == 0;
if (ok) {
memset(&chosen, 0, sizeof(chosen));
snprintf(chosen.id, sizeof(chosen.id), "%s",
p.id);
snprintf(chosen.endpoint,
sizeof(chosen.endpoint), "%s", p.endpoint);
snprintf(chosen.model, sizeof(chosen.model),
"%s", args);
snprintf(chosen.key_env, sizeof(chosen.key_env),
"%s", p.key_env);
snprintf(s->cur_model, sizeof(s->cur_model),
"%s", args);
sp_buf_init(&serr);
sp_buf_printf(&out, sp_provider_save_choice(
s->conf, &chosen, &serr) == 0 ?
sp_t("model.saved") : sp_t("model.switched"),
args, p.id);
sp_buf_free(&serr);
} else {
sp_buf_printf(&out, sp_t("model.failed"),
perr.p != NULL ? perr.p : "?");
}
sp_buf_free(&perr);
}
snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : "");
sp_buf_free(&out);
add_entry(s, "splinter", outbuf);
return 1;
}
if (strcmp(name, "new") == 0 || strcmp(name, "reset") == 0) {
static struct sp_session_info fresh;
char id[64], dir[512];
struct sp_buf serr;
/* 'fresh' may be the current session: read the directory first */
snprintf(dir, sizeof(dir), "%s",
ag->sess != NULL ? ag->sess->dir : "");
memset(&fresh, 0, sizeof(fresh));
snprintf(id, sizeof(id), "sess-%ld-%d", (long)time(NULL),
(int)getpid());
sp_buf_init(&serr);
if (ag->sess == NULL ||
sp_session_open(&fresh, dir, id, &serr) != 0 ||
sp_conv_reset(ag->conv, ag->cfg != NULL ?
ag->cfg->system_prompt : NULL) != 0) {
sp_buf_printf(&out, sp_t("session.failed"),
serr.p != NULL ? serr.p : "?");
} else {
ag->sess = &fresh;
s->n = 0; /* the pane is the old conversation */
s->scroll = 0;
sp_buf_printf(&out, sp_t("session.new"), fresh.id);
}
sp_buf_free(&serr);
snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : "");
sp_buf_free(&out);
add_entry(s, "splinter", outbuf);
return 1;
}
if (strcmp(name, "connect") == 0) {
if (sp_config_loaded_path() == NULL) {
/* --no-config: there is no file to write the line to */
sp_buf_puts(&out, sp_t("connect.nodir"));
snprintf(outbuf, sizeof(outbuf), "%s",
out.p != NULL ? out.p : "");
sp_buf_free(&out);
add_entry(s, "splinter", outbuf);
return 1;
}
memset(&s->cc, 0, sizeof(s->cc));
s->cc.active = 1;
s->cc.step = 0;
sp_buf_puts(&out, sp_t("connect.start"));
sp_buf_puts(&out, "\n");
ui_connect_ask(s, &out);
snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : "");
sp_buf_free(&out);
add_entry(s, "splinter", outbuf);
return 1;
}
if (host != NULL && sp_host_command(host, name, args, &out) == 0) {
snprintf(outbuf, sizeof(outbuf), "%s", out.p != NULL ? out.p : "");
sp_buf_free(&out);
add_entry(s, "splinter", outbuf);
return 1;
}
/*
* 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.
*/
sp_buf_clear(&out);
if (sp_buf_init(&cerr) != 0) {
sp_buf_free(&out);
return 1;
}
if (sp_cmdscript_dir(SESS_DIR(ag), cdir, sizeof(cdir)) == 0 &&
sp_cmdscript_exists(cdir, name) &&
sp_slash_script(cdir, name, args, &out, &cerr) == 0 &&
out.p != NULL) {
add_entry(s, "shell", out.p);
snprintf(input, cap, "%s", out.p);
sp_buf_free(&out);
sp_buf_free(&cerr);
return 0;
}
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"));
(void)sp_host_command_help(host, &out);
snprintf(outbuf, sizeof(outbuf), "%s", out.p != NULL ? out.p : "");
sp_buf_free(&out);
add_entry(s, "splinter", outbuf);
return 1;
}
/* what the screen keeps of a running turn between two ticks */
struct turn_view {
struct timespec t0;
int drained; /* events already in the transcript */
struct seg {
size_t id; /* entry showing the open part, 0 = none */
size_t off; /* bytes before the open entry */
size_t shown; /* bytes the open entry shows */
} think, ans; /* the reasoning, the answer */
char line[1024]; /* steering text being typed */
size_t llen;
};
/*
* One growing text of the turn -- the reasoning, the answer -- shown append
* only. It grows in its entry while that entry is the last one. Once anything
* was appended below it (a tool line, the answer), that entry is left as it
* is and the rest of the text continues in a new entry at the bottom. Nothing
* that is on screen moves; the transcript only gets longer.
*/
static void
seg_show(struct ui_state *s, struct seg *g, const char *role, const char *text)
{
size_t len = text != NULL ? strlen(text) : 0;
const char *p;
if (g->off > len) { /* the buffer started over */
g->off = 0;
g->shown = 0;
g->id = 0;
}
/*
* While the open entry is the last one it may keep growing. Once
* something was appended below it (a tool call, the answer), what is on
* screen stays as it is: the bytes it shows move into off and the rest
* continues in a new entry. That is the whole append-only rule.
*/
if (g->id != 0 && !(s->n > 0 && s->entries[s->n - 1].id == g->id)) {
g->off += g->shown;
g->shown = 0;
g->id = 0;
}
if (len <= g->off)
return;
p = text + g->off;
while (*p == '\n')
p++;
if (*p == '\0')
return;
if (g->id == 0)
g->id = add_entry(s, role, "");
entry_set_text(s, g->id, p);
g->shown = len - g->off;
}
/* a turn's side effects into the transcript: diffs, calls, compaction */
static void
compact_cb(void *ctx, size_t before, size_t after, size_t mb, size_t ma)
{
struct turn *t = ctx;
pthread_mutex_lock(&t->lock);
if (t->compacted == 0) {
t->c_bytes_before = before;
t->c_msgs_before = mb;
}
t->c_bytes_after = after;
t->c_msgs_after = ma;
t->compacted++;
pthread_mutex_unlock(&t->lock);
}
static void
turn_drain(struct ui_state *s, struct turn *tu, struct turn_view *v)
{
int k, compacted = 0;
size_t cb = 0, ca = 0, cm = 0, cn = 0;
struct tun_ev ev[24];
int nev = 0;
pthread_mutex_lock(&tu->lock);
/*
* Take the events that arrived since the last tick, in order. The
* strings change hands here: the turn drops its pointer, the UI adds
* the entry and frees it.
*/
while (v->drained < tu->nev && nev < (int)(sizeof(ev) / sizeof(ev[0]))) {
ev[nev].kind = tu->ev[v->drained].kind;
ev[nev].text = tu->ev[v->drained].text;
tu->ev[v->drained].text = NULL;
nev++;
v->drained++;
}
compacted = tu->compacted;
cb = tu->c_bytes_before; ca = tu->c_bytes_after;
cm = tu->c_msgs_before; cn = tu->c_msgs_after;
tu->compacted = 0;
tu->c_bytes_before = tu->c_bytes_after = 0;
tu->c_msgs_before = tu->c_msgs_after = 0;
pthread_mutex_unlock(&tu->lock);
for (k = 0; k < nev; k++) {
const char *role = ev[k].kind == 'x' ? "tool" :
ev[k].kind == 'o' ? "observation" :
ev[k].kind == 'n' ? "splinter" :
ev[k].kind == 't' ? "thinking" : "agent";
/* the log gets what the screen gets, in the same order */
if (ev[k].kind == 't')
sp_logf("thinking", "%s", ev[k].text);
add_entry(s, role, ev[k].text);
free(ev[k].text);
}
if (compacted > 0) {
char msg[256];
size_t tb = cb / 4, ta = ca / 4;
{
char b1[32], b2[32], t1[32], t2[32];
if (cb >= 1024) snprintf(b1, sizeof(b1), "%.1fKiB", cb/1024.0); else snprintf(b1, sizeof(b1), "%zuB", cb);
if (ca >= 1024) snprintf(b2, sizeof(b2), "%.1fKiB", ca/1024.0); else snprintf(b2, sizeof(b2), "%zuB", ca);
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);
if (compacted == 1)
snprintf(msg, sizeof(msg),
"context compacted: %zu→%zu msgs, %s→%s (%s→%s)",
cm, cn, t1, t2, b1, b2);
else
snprintf(msg, sizeof(msg),
"context compacted %dx: %zu→%zu msgs, %s→%s (%s→%s)",
compacted, cm, cn, t1, t2, b1, b2);
}
add_entry(s, "splinter", msg);
}
}
/*
* A tool needs permission. The question goes where the prompt is, and y/N
* answers it; the turn thread is parked on a condition variable until it
* does. Returns 1 while a question is open (the key is consumed).
*/
static int
turn_approval(struct turn *tu, int c)
{
int pending, auth = SP_AUTH_READ;
char nm[64], ar[256];
pthread_mutex_lock(&tu->lock);
pending = tu->approve_pending;
if (pending) {
snprintf(nm, sizeof(nm), "%s", tu->approve_name);
snprintf(ar, sizeof(ar), "%s", tu->approve_args);
auth = tu->approve_auth;
}
pthread_mutex_unlock(&tu->lock);
/*
* Ctrl-C and Ctrl-D are not answers: they go on to turn_key, which
* cancels and wakes approve_cb. Swallowing them here left the operator
* no way out of a question but y or n.
*/
if (!pending || c == 3 || c == 4)
return 0;
werase(ui_input);
mvwprintw(ui_input, 0, 0, sp_t("ui.approve"), nm,
auth == SP_AUTH_MUTATE ? sp_t("auth.mutate") :
sp_t("auth.destructive"), ar);
wrefresh(ui_input);
if (c == 'y' || c == 'Y' || c == 'n' || c == 'N' || c == 27) {
pthread_mutex_lock(&tu->lock);
tu->approve_result = (c == 'y' || c == 'Y');
tu->approve_pending = 0;
pthread_cond_broadcast(&tu->cond);
pthread_mutex_unlock(&tu->lock);
}
return 1;
}
/*
* One tick without a key: the turn so far, on screen. The turn is not drawn
* into a box of its own: it is two entries that grow in place, the reasoning
* first, the answer after the tool calls. Nothing moves when the turn ends -
* which is what a jumping block feels like.
*/
static void
turn_paint(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
struct turn *tu, struct turn_view *v)
{
char *think = NULL, *live = NULL;
struct timespec now;
long ms;
int w, used;
pthread_mutex_lock(&tu->lock);
if (tu->think.len > 0 && tu->think.p != NULL)
think = strdup(tu->think.p);
if (tu->live.len > 0 && tu->live.p != NULL)
live = strdup(tu->live.p);
pthread_mutex_unlock(&tu->lock);
turn_drain(s, tu, v);
if (think != NULL)
seg_show(s, &v->think, "thinking", think);
if (live != NULL) {
seg_show(s, &v->ans, "agent", live);
s->out_chars = strlen(live);
}
free(think);
free(live);
draw_history(s);
draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host);
/* a fleet moves on while a turn runs; nothing draws it any more */
if (s->sw != NULL)
swarm_poll(s->sw);
/*
* The prompt becomes the steering line: elapsed seconds, the tool that
* is running, then what is typed. One row, never wrapped - wrapped input
* scrolls the screen.
*/
clock_gettime(CLOCK_MONOTONIC, &now);
ms = (long)((now.tv_sec - v->t0.tv_sec) * 1000 +
(now.tv_nsec - v->t0.tv_nsec) / 1000000);
s->last_ms = ms;
update_meter(s, host);
werase(ui_input);
w = getmaxx(ui_input) - 1;
{
/* no status bar: the running time and the tool lead the input */
char mark[160], tool[64] = "";
pthread_mutex_lock(&tu->lock);
if (tu->tool_line[0] != '\0')
snprintf(tool, sizeof(tool), " %.40s", tu->tool_line);
pthread_mutex_unlock(&tu->lock);
snprintf(mark, sizeof(mark), "%lds%s %s", ms / 1000, tool,
sp_td("ui.steer_mark", "steer> "));
{
size_t ml = strlen(mark);
if (ml > 0 && mark[ml - 1] != ' ' && ml + 1 < sizeof(mark))
snprintf(mark + ml, sizeof(mark) - ml, " ");
}
mvwaddnstr(ui_input, 0, 0, mark, w);
used = (int)strlen(mark);
}
if (used < w)
ui_add_text(ui_input, v->line, w - used - 1);
wclrtoeol(ui_input);
wnoutrefresh(ui_input);
doupdate();
}
/*
* The keys of a running turn: type to steer (Enter queues the text for the
* next step), PgUp/PgDn and Shift+Up/Down scroll, Ctrl-C cancels, Ctrl-D
* cancels and quits. Returns 1 when the turn was cancelled.
*/
static int
turn_key(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
struct turn *tu, struct turn_view *v, int c, char *pending_steer,
size_t ps_cap)
{
if (c == KEY_PPAGE || c == KEY_SR) {
s->scroll += (c == KEY_SR ? 1 : 10);
redraw(s, ag, host);
return 0;
}
if (c == KEY_NPAGE || c == KEY_SF) {
size_t step = (c == KEY_SF ? 1 : 10);
s->scroll = s->scroll > step ? s->scroll - step : 0;
redraw(s, ag, host);
return 0;
}
if (c == KEY_RESIZE) {
relayout(100);
redraw(s, ag, host);
return 0;
}
/*
* Cancel under the lock and wake the turn: it may be asleep in
* approve_cb. Setting the flag alone left a turn that was waiting for a
* yes waiting forever, and Ctrl-D did not cancel at all before the join.
*/
if (c == 3 || c == 4) {
pthread_mutex_lock(&tu->lock);
tu->cancel = 1;
pthread_cond_broadcast(&tu->cond);
pthread_mutex_unlock(&tu->lock);
if (c == 4)
s->quit = 1;
return 1;
}
if (c == '\n' || c == '\r' || c == KEY_ENTER) {
if (v->llen > 0) {
pthread_mutex_lock(&tu->lock);
snprintf(tu->steer, sizeof(tu->steer), "%s", v->line);
snprintf(pending_steer, ps_cap, "%s", v->line);
tu->have_steer = 1;
pthread_mutex_unlock(&tu->lock);
v->llen = 0;
v->line[0] = '\0';
mvwaddstr(ui_input, 0, 0, sp_t("ui.steering_queued"));
wclrtoeol(ui_input);
wrefresh(ui_input);
}
return 0;
}
if ((c == KEY_BACKSPACE || c == 127 || c == 8) && v->llen > 0) {
v->line[--v->llen] = '\0';
return 0;
}
if (c >= 32 && c < 256 && c != 127 && v->llen < sizeof(v->line) - 2) {
v->line[v->llen++] = (char)c;
v->line[v->llen] = '\0';
}
return 0;
}
/*
* One turn on its own thread while this one keeps the screen alive, then its
* result in the transcript. A steer typed too late for a step boundary comes
* back in 'pending_steer'. Returns the turn's rc.
*/
static int
ui_turn(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
const char *text, char *pending_steer, size_t ps_cap)
{
struct turn tu;
struct turn_view v;
const struct sp_agent_config *orig = ag->cfg;
struct sp_agent_config cfg = *orig;
if (s->agents.n > 0 && s->agents.v[s->agent_cur].autonomous >= 0)
cfg.autonomous = s->agents.v[s->agent_cur].autonomous;
struct sp_buf answer, err;
struct timespec t1;
pthread_t th;
int rc, cancelled = 0;
pending_steer[0] = '\0';
memset(&v, 0, sizeof(v));
clock_gettime(CLOCK_MONOTONIC, &v.t0);
if (sp_buf_init(&answer) != 0 || sp_buf_init(&err) != 0)
return -1;
memset(&tu, 0, sizeof(tu));
tu.ag = ag;
tu.text = text;
sp_buf_init(&tu.answer);
sp_buf_init(&tu.err);
sp_buf_init(&tu.live);
sp_buf_init(&tu.think);
pthread_mutex_init(&tu.lock, NULL);
pthread_cond_init(&tu.cond, NULL);
cfg.cancel = &tu.cancel;
cfg.steer = steer_cb;
cfg.steer_ctx = &tu;
cfg.stream = stream_cb;
cfg.stream_ctx = &tu;
cfg.approve = approve_cb;
cfg.approve_ctx = &tu;
cfg.tool_end = tool_end_cb;
cfg.tool_end_ctx = &tu;
cfg.tool_begin = tool_begin_cb;
cfg.tool_begin_ctx = &tu;
cfg.on_compact = compact_cb;
cfg.on_compact_ctx = &tu;
if (orig->limit_wait != NULL) {
cfg.limit_wait = ui_limit_wait;
cfg.limit_ctx = &tu;
}
sp_openai_set_cancel(&tu.cancel);
ag->cfg = &cfg;
if (s->sw) swarm_report_busy(s->sw, 1);
if (pthread_create(&th, NULL, turn_thread, &tu) != 0) {
sp_buf_puts(&err, sp_t("err.thread"));
rc = -1;
} else {
wtimeout(ui_input, 100);
for (;;) {
int c, done;
pthread_mutex_lock(&tu.lock);
done = tu.done;
pthread_mutex_unlock(&tu.lock);
if (done)
break;
c = wgetch(ui_input);
if (turn_approval(&tu, c))
continue;
if (c == ERR) {
turn_paint(s, ag, host, &tu, &v);
continue;
}
if (turn_key(s, ag, host, &tu, &v, c, pending_steer,
ps_cap)) {
cancelled = 1;
break;
}
}
wtimeout(ui_input, -1);
/*
* A cancelled turn: wait for the worker with the screen alive.
* Every transport kills its own child or curl when the flag is
* set; the cli transport did not, and this join froze the whole
* screen until `claude -p` decided to finish. Now the hint is on
* screen, the repaint continues, and a second Ctrl-C leaves at
* once instead of holding the terminal hostage.
*/
if (cancelled) {
wtimeout(ui_input, 100);
for (;;) {
int c2, done2;
pthread_mutex_lock(&tu.lock);
done2 = tu.done;
pthread_mutex_unlock(&tu.lock);
if (done2)
break;
werase(ui_input);
mvwaddstr(ui_input, 0, 0,
sp_t("ui.cancelling"));
wclrtoeol(ui_input);
wrefresh(ui_input);
c2 = wgetch(ui_input);
if (c2 == 3 || c2 == 4) {
endwin();
_exit(1);
}
if (c2 == ERR)
turn_paint(s, ag, host, &tu, &v);
}
wtimeout(ui_input, -1);
}
pthread_join(th, NULL);
if (s->sw) swarm_report_busy(s->sw, 0);
rc = tu.rc;
if (tu.answer.p != NULL)
sp_buf_puts(&answer, tu.answer.p);
if (tu.err.p != NULL)
sp_buf_puts(&err, tu.err.p);
if (tu.steers > 0 && answer.len > 0) {
char note[64];
snprintf(note, sizeof(note), " (%d steering%s applied)",
tu.steers, tu.steers == 1 ? "" : "s");
sp_buf_puts(&answer, note);
}
turn_drain(s, &tu, &v);
/*
* The reasoning is on screen already (it streamed); the log keeps
* the whole of it, tool calls included as their own entries.
*/
if (tu.think.len > 0 && tu.think.p != NULL)
sp_logf("thinking", "%s", tu.think.p);
}
/*
* Restore the caller's config: the patched copy lives on this stack and
* must not outlive the turn. Leaving it set handed the follow-up turn a
* dangling steer callback, which then consumed the same text twice.
*/
sp_openai_set_cancel(NULL);
ag->cfg = orig;
/*
* A steer the turn took at a step boundary is already in the
* conversation. Only one it never reached becomes the next message -
* before, every steer was sent twice.
*/
if (tu.have_steer == 0 || cancelled)
pending_steer[0] = '\0';
clock_gettime(CLOCK_MONOTONIC, &t1);
s->last_ms = (long)((t1.tv_sec - v.t0.tv_sec) * 1000 +
(t1.tv_nsec - v.t0.tv_nsec) / 1000000);
s->last_steps = ag->stats.steps;
s->last_calls = ag->stats.tool_calls;
s->tokens_in = ag->stats.tokens_in;
s->tokens_out = ag->stats.tokens_out;
if (rc == 0) {
const char *ap = answer.p != NULL ? answer.p : "";
/*
* The answer the agent returns is the last step's text. What the
* model said before its tool calls ("I'll read the file") streamed
* into the entry too; replacing the entry with the final text
* would take it away. Keep the streamed text when it ends in the
* final answer.
*/
{
size_t lv = tu.live.len, la = strlen(ap);
if (lv > 0 && tu.live.p != NULL) {
/* streamed: show what is left of it, then stop */
seg_show(s, &v.ans, "agent", tu.live.p);
/* a final answer longer than what streamed was
* not streamed: it gets its own entry */
if (la > lv)
add_entry(s, "agent", ap);
} else
add_entry(s, "agent", ap);
}
s->total_out_chars += strlen(ap);
s->out_chars = strlen(ap);
} else
add_entry(s, "error", err.len > 0 ? err.p :
sp_t("err.turn_failed"));
sp_buf_free(&tu.answer);
sp_buf_free(&tu.err);
sp_buf_free(&tu.live);
sp_buf_free(&tu.think);
{
int k;
for (k = 0; k < tu.nev; k++)
free(tu.ev[k].text);
free(tu.ev);
}
pthread_cond_destroy(&tu.cond);
pthread_mutex_destroy(&tu.lock);
sp_buf_free(&answer);
sp_buf_free(&err);
return rc;
}
/* curses up, colours, windows, and the conversation so far on screen */
static int
ui_start(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
const char *endpoint, const char *model, const char *theme_name,
struct swarm *sw, struct sp_config *conf)
{
struct sp_buf err;
const char *user = getenv("USER");
memset(s, 0, sizeof(*s));
sp_buf_init(&s->last_think);
snprintf(s->cur_endpoint, sizeof(s->cur_endpoint), "%s",
endpoint != NULL ? endpoint : "");
snprintf(s->cur_model, sizeof(s->cur_model), "%s",
model != NULL ? model : "");
s->endpoint = s->cur_endpoint;
s->conf = conf;
if (conf != NULL && conf->max_wait > 0)
g_max_wait = conf->max_wait;
s->sw = sw;
s->model = s->cur_model;
if (user != NULL && *user != '\0')
snprintf(g_who, sizeof(g_who), "%s", user);
if (model != NULL && *model != '\0') {
/* a path like /models/x/y.gguf: the name is the last part */
const char *slash = strrchr(model, '/');
size_t n;
snprintf(g_model, sizeof(g_model), "%s",
slash != NULL ? slash + 1 : model);
n = strlen(g_model);
if (n > 4 && strcmp(g_model + n - 4, ".gguf") == 0)
g_model[n - 4] = '\0';
}
g_status_host = host; /* the status line is drawn per tick */
if (sp_buf_init(&err) != 0)
return -1;
if (sp_theme_load(theme_name, &s->theme, &err) != 0) {
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : sp_t("err.theme"));
sp_buf_free(&err);
return -1;
}
sp_buf_free(&err);
/*
* Without this, curses treats every byte above 0x7f as garbage: German
* umlauts and every UTF-8 answer would arrive as replacement characters.
*/
setlocale(LC_ALL, "");
initscr();
/*
* raw(), not cbreak(): cbreak leaves ISIG on, so the terminal driver turns
* Ctrl-C into SIGINT and kills the harness before wgetch() can report the
* key - "Ctrl-C cancels the turn" was a claim, and pressing it proved the
* opposite. raw() hands every byte to us and we decide.
*/
raw();
noecho();
keypad(stdscr, TRUE);
curs_set(1);
init_colors(&s->theme);
layout();
hist_load(s, SESS_DIR(ag));
{
char cwd[700];
if (getcwd(cwd, sizeof(cwd)) == NULL)
cwd[0] = '\0';
if (sp_agents_load(&s->agents, cwd, getenv("HOME")) == 0 &&
s->agents.n > 0) {
int idx = sp_agents_find(&s->agents, g_start_agent);
s->base_prompt = sp_agents_base(ag->conv);
agent_switch(s, ag, idx < 0 ? 0 : idx, idx > 0);
}
}
/*
* A resumed session starts with its history on screen: the conversation is
* the same object the model will be given, so showing it is not a summary,
* it is the thing.
*/
if (ag->conv != NULL) {
size_t i;
for (i = 0; i < ag->conv->n; i++) {
const struct sp_msg *m = &ag->conv->v[i];
if (m->role == NULL || m->content == NULL)
continue;
if (strcmp(m->role, "user") == 0)
add_entry(s, "you", m->content);
else if (strcmp(m->role, "assistant") == 0) {
add_entry(s, "agent", m->content);
s->total_out_chars += strlen(m->content);
}
}
}
s->out_chars = 0;
add_entry(s, "splinter", sp_t("ui.ready"));
return 0;
}
int
sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model,
const char *theme_name, struct sp_host *host, struct swarm *sw,
struct sp_config *conf)
{
struct ui_state s;
char input[1024], pending[1024];
if (ui_start(&s, ag, host, endpoint, model, theme_name, sw, conf) != 0)
return 1;
for (;;) {
draw_history(&s);
draw_sidebar(&s, SESS_ID(ag), SESS_DIR(ag), host);
werase(ui_input);
mvwaddstr(ui_input, 0, 0, prompt_mark());
wnoutrefresh(ui_input);
doupdate();
ui_read_line(&s, ag, host, input, sizeof(input));
if (s.quit)
break;
if (input[0] == '\0')
continue;
if (input[0] == '!' && input[1] != '\0') {
ui_shell(&s, ag, input + 1);
continue;
}
/* after a stopped wait (or any stopped turn): go on */
if (strcmp(input, "/resume") == 0)
snprintf(input, sizeof(input), "Continue with the task "
"you were working on. Do not repeat work that is "
"already done.");
if (input[0] == '/' && input[1] != '\0' &&
ui_slash(&s, ag, host, input, sizeof(input))) {
if (s.quit)
break;
continue;
}
if (s.cc.active) {
struct sp_buf o;
if (sp_buf_init(&o) == 0) {
(void)ui_connect_answer(&s, ag, input, &o);
add_entry(&s, "splinter", o.p != NULL ? o.p : "");
sp_buf_free(&o);
}
continue;
}
hist_push(&s, SESS_DIR(ag), input);
s.scroll = 0;
add_entry(&s, "you", input);
draw_history(&s);
draw_sidebar(&s, SESS_ID(ag), SESS_DIR(ag), host);
werase(ui_input);
mvwaddstr(ui_input, 0, 0, sp_t("ui.working"));
wrefresh(ui_input);
doupdate();
/*
* A failed turn is shown, not returned: the process ends when the
* operator quits, and that is a clean quit (ui.h). Passing the last
* turn's rc out made a cancelled turn exit 255.
*/
(void)ui_turn(&s, ag, host, input, pending, sizeof(pending));
/*
* A single-step turn ends with the answer, so a steer typed during
* it had no step boundary to land on. Rather than dropping it, it
* becomes the next message, run like any other turn - streamed,
* cancellable, asking for approval on the screen. It used to run
* here on the UI thread with none of that, the screen frozen.
*/
while (pending[0] != '\0' && !s.quit) {
snprintf(input, sizeof(input), "%s", pending);
s.scroll = 0;
add_entry(&s, "you", input);
redraw(&s, ag, host);
(void)ui_turn(&s, ag, host, input, pending,
sizeof(pending));
}
if (s.quit)
break;
}
endwin();
sp_buf_free(&s.last_think);
sp_agents_free(&s.agents);
free(s.base_prompt);
ag->policy = NULL;
return 0;
}