A mutate tool that says 'wrote 23 bytes' tells the operator nothing. write and edit now put a one-hunk diff into the observation - common prefix and suffix as context - so the model sees what it did and the transcript shows it as its own 'anderung:' entry. One hunk, not a general diff algorithm: a tool changes one place, and the point is to see which. Verified against kontron: asking for an edit produced @@ -1,2 +1,2 @@ zeile eins -zeile zwei +zeile zwei geaendert and the file on disk really was changed.
1466 lines
39 KiB
C
1466 lines
39 KiB
C
/*
|
|
* 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|
|
|
* +---------------------------------+------------+
|
|
* | status bar |
|
|
* +----------------------------------------------+
|
|
*
|
|
* 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 <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 "splinter_plugin.h"
|
|
#include "theme.h"
|
|
#include "ui.h"
|
|
|
|
#define MAX_ENTRIES 512
|
|
|
|
struct entry {
|
|
char *role;
|
|
char *text;
|
|
};
|
|
|
|
struct ui_state {
|
|
struct entry entries[MAX_ENTRIES];
|
|
size_t n;
|
|
size_t scroll; /* lines scrolled back from the bottom */
|
|
long last_ms;
|
|
size_t tokens_in;
|
|
size_t tokens_out;
|
|
size_t out_chars; /* characters streamed in this/last turn */
|
|
char hist[128][1024]; /* what was typed before */
|
|
size_t nhist;
|
|
int hist_pos; /* -1: editing a fresh line */
|
|
struct sp_buf last_think; /* the previous turn's reasoning */
|
|
size_t last_steps;
|
|
size_t last_calls;
|
|
const char *endpoint;
|
|
int quit;
|
|
struct sp_theme theme;
|
|
};
|
|
|
|
static WINDOW *ui_hist;
|
|
static WINDOW *ui_side;
|
|
static WINDOW *ui_input;
|
|
static WINDOW *ui_status;
|
|
|
|
static size_t align_utf8(const char *s, size_t len, size_t pos);
|
|
|
|
enum {
|
|
PAIR_MAIN = 1, /* fg on bg */
|
|
PAIR_ACCENT, /* accent on bg */
|
|
PAIR_DIM, /* border on bg */
|
|
PAIR_STATUS /* bg on status */
|
|
};
|
|
|
|
|
|
/*
|
|
* 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; /* streamed text so far */
|
|
struct sp_buf think; /* the model's reasoning so far */
|
|
char tool[64]; /* last tool the model called */
|
|
char tool_line[256]; /* name + args, for the live area */
|
|
char tools_done[16][256]; /* finished calls, in order */
|
|
char diffs[8][4096]; /* observations that carry a diff */
|
|
int ndiffs;
|
|
int ntools_done;
|
|
int tool_tick;
|
|
/* 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;
|
|
};
|
|
|
|
/*
|
|
* 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;
|
|
}
|
|
|
|
/* Keep the observations that carry a diff; the rest is noise in the transcript. */
|
|
static void
|
|
tool_end_cb(void *ctx, const char *name, const char *obs)
|
|
{
|
|
struct turn *t = ctx;
|
|
|
|
(void)name;
|
|
if (obs == NULL || strstr(obs, "--- a/") == NULL)
|
|
return;
|
|
pthread_mutex_lock(&t->lock);
|
|
if (t->ndiffs < 8)
|
|
snprintf(t->diffs[t->ndiffs++], sizeof(t->diffs[0]), "%s", obs);
|
|
pthread_mutex_unlock(&t->lock);
|
|
}
|
|
|
|
static void
|
|
tool_begin_cb(void *ctx, const char *name, const char *args)
|
|
{
|
|
struct turn *t = ctx;
|
|
|
|
if (name == NULL)
|
|
return;
|
|
pthread_mutex_lock(&t->lock);
|
|
snprintf(t->tool_line, sizeof(t->tool_line), "%s %.120s", name,
|
|
args != NULL ? args : "");
|
|
if (t->ntools_done < 16)
|
|
snprintf(t->tools_done[t->ntools_done++],
|
|
sizeof(t->tools_done[0]), "%s %.200s", name,
|
|
args != NULL ? args : "");
|
|
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);
|
|
}
|
|
|
|
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;
|
|
|
|
t->rc = sp_agent_run(t->ag, t->text, &t->answer, &t->err);
|
|
t->done = 1;
|
|
return NULL;
|
|
}
|
|
|
|
/*
|
|
* Colour assignment, and the reasoning behind it:
|
|
*
|
|
* The terminal background stays the terminal's own (-1). Painting every glyph
|
|
* on a palette colour looks like a 1995 desktop and is unreadable in a modern
|
|
* terminal - it also fights whatever scheme the user already chose. The palette
|
|
* supplies the accents, which is where its character is, and every accent is
|
|
* pushed until it is legible against black (the usual terminal background).
|
|
*/
|
|
/*
|
|
* Colour assignment.
|
|
*
|
|
* Two facts drive this:
|
|
* 1. this curses port reports COLORS=256 but does not honour -1 in
|
|
* init_pair(), so "terminal default" is not available - every pair needs
|
|
* real indices, and a failed init_pair silently leaves white on black;
|
|
* 2. a CDE palette is eight mid-tones. Painted literally, the accent sits
|
|
* 8% away from the background and nobody can read it.
|
|
*
|
|
* So the palette paints, and every role is pushed away from the background
|
|
* until it is legible: foreground far, accent very far, secondary text at
|
|
* least visible.
|
|
*/
|
|
static void
|
|
init_colors(const struct sp_theme *t)
|
|
{
|
|
unsigned char bg[3], fg[3], accent[3], dim[3], status_bg[3];
|
|
short n;
|
|
|
|
if (!has_colors())
|
|
return;
|
|
/* COLORS is only valid after start_color(); reading it earlier gave 0,
|
|
* which silently fell back to the eight basic colours - the whole palette
|
|
* collapsed to white on black. */
|
|
start_color();
|
|
n = (short)(COLORS > 0 ? COLORS : 8);
|
|
|
|
memcpy(bg, t->bg, 3);
|
|
/* the darkest CDE colour is still a mid-tone: no terminal wants that */
|
|
sp_color_darken(bg, 45000);
|
|
memcpy(fg, t->fg, 3);
|
|
memcpy(accent, t->accent, 3);
|
|
memcpy(dim, t->border, 3);
|
|
memcpy(status_bg, t->status, 3);
|
|
|
|
sp_color_separate(fg, bg, 120000); /* text */
|
|
sp_color_separate(accent, bg, 100000); /* the user's own lines */
|
|
sp_color_separate(dim, bg, 60000); /* labels: visible, not loud */
|
|
sp_color_darken(status_bg, 60000); /* the bar is a surface, not text */
|
|
|
|
/* the chat area is black: text on a palette surface reads as a block of
|
|
* colour, and the operator asked for black, not for a tinted pane */
|
|
init_pair(PAIR_MAIN, sp_color_rgb(fg[0], fg[1], fg[2], n), COLOR_BLACK);
|
|
init_pair(PAIR_ACCENT, sp_color_rgb(accent[0], accent[1], accent[2], n),
|
|
COLOR_BLACK);
|
|
init_pair(PAIR_DIM, sp_color_rgb(dim[0], dim[1], dim[2], n),
|
|
COLOR_BLACK);
|
|
init_pair(PAIR_STATUS,
|
|
sp_color_rgb(fg[0], fg[1], fg[2], n),
|
|
sp_color_rgb(status_bg[0], status_bg[1], status_bg[2], 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.
|
|
*/
|
|
static size_t
|
|
text_rows(const char *text, int cols)
|
|
{
|
|
size_t rows = 0;
|
|
const char *p = text;
|
|
|
|
if (text == NULL || *text == '\0' || cols < 2)
|
|
return 0;
|
|
while (*p != '\0') {
|
|
const char *nl = strchr(p, '\n');
|
|
size_t linelen = nl != NULL ? (size_t)(nl - p) : strlen(p);
|
|
|
|
rows += linelen == 0 ? 1 :
|
|
(linelen + (size_t)cols - 1) / (size_t)cols;
|
|
if (nl == NULL)
|
|
break;
|
|
p = nl + 1;
|
|
}
|
|
return rows;
|
|
}
|
|
|
|
/*
|
|
* 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.
|
|
*/
|
|
static int
|
|
entry_lines(int cols, const struct entry *e)
|
|
{
|
|
size_t rows, len;
|
|
char *render;
|
|
|
|
if (cols < 2)
|
|
return 1;
|
|
len = strlen(role_label(e->role)) + 2 + strlen(e->text) + 1;
|
|
render = malloc(len);
|
|
if (render == NULL)
|
|
return 1;
|
|
snprintf(render, len, "%s: %s", role_label(e->role), e->text);
|
|
rows = text_rows(render, cols);
|
|
free(render);
|
|
if (rows == 0)
|
|
rows = 1;
|
|
return (int)rows;
|
|
}
|
|
|
|
/*
|
|
* Byte offsets computed from column arithmetic can land inside a UTF-8
|
|
* sequence, and half a sequence is not a character: it draws as a replacement
|
|
* glyph. Every slice therefore starts and ends on a sequence boundary.
|
|
*/
|
|
static size_t
|
|
align_utf8(const char *s, size_t len, size_t pos)
|
|
{
|
|
if (s == NULL || pos >= len)
|
|
return pos;
|
|
while (pos < len && ((unsigned char)s[pos] & 0xc0) == 0x80)
|
|
pos++;
|
|
return pos;
|
|
}
|
|
|
|
/*
|
|
* A real viewport, not a best effort: total height is computed first, the
|
|
* window shows the bottom of it, and an entry taller than the screen is shown
|
|
* from the offset that puts its end on screen -- never skipped, which would look
|
|
* like the answer was lost.
|
|
*/
|
|
static void
|
|
draw_history(struct ui_state *s, int reserve)
|
|
{
|
|
int rows, cols, y = 0;
|
|
size_t idx, total = 0;
|
|
long skip = 0;
|
|
|
|
getmaxyx(ui_hist, rows, cols);
|
|
werase(ui_hist);
|
|
wbkgd(ui_hist, COLOR_PAIR(PAIR_MAIN));
|
|
/* while a turn runs the bottom lines belong to it */
|
|
if (reserve > 0 && reserve < rows)
|
|
rows -= reserve;
|
|
|
|
for (idx = 0; idx < s->n; idx++)
|
|
total += (size_t)entry_lines(cols, &s->entries[idx]);
|
|
if (total > (size_t)rows)
|
|
skip = (long)(total - (size_t)rows);
|
|
if ((long)s->scroll > 0)
|
|
skip -= (long)s->scroll;
|
|
if (skip < 0)
|
|
skip = 0;
|
|
|
|
for (idx = 0; idx < s->n && y < rows; idx++) {
|
|
const struct entry *e = &s->entries[idx];
|
|
int lines = entry_lines(cols, e);
|
|
char *render;
|
|
size_t len = strlen(e->role) + 2 + strlen(e->text) + 1;
|
|
long off;
|
|
int ny, nx;
|
|
|
|
if (skip >= lines) {
|
|
skip -= lines;
|
|
continue;
|
|
}
|
|
render = malloc(len);
|
|
if (render == NULL)
|
|
break;
|
|
snprintf(render, len, "%s: %s", role_label(e->role), e->text);
|
|
|
|
off = (long)align_utf8(render, strlen(render),
|
|
(size_t)(skip * cols));
|
|
if (off > (long)strlen(render))
|
|
off = (long)strlen(render);
|
|
skip = 0;
|
|
|
|
wmove(ui_hist, y, 0);
|
|
if (strcmp(e->role, "you") == 0)
|
|
wattron(ui_hist, COLOR_PAIR(PAIR_ACCENT) | A_BOLD);
|
|
else if (strcmp(e->role, "agent") == 0)
|
|
wattron(ui_hist, COLOR_PAIR(PAIR_MAIN));
|
|
else if (strcmp(e->role, "error") == 0)
|
|
wattron(ui_hist, COLOR_PAIR(PAIR_ACCENT) | A_BOLD);
|
|
else
|
|
wattron(ui_hist, COLOR_PAIR(PAIR_DIM));
|
|
ui_add_text(ui_hist, render + off, rows * cols);
|
|
wattrset(ui_hist, A_NORMAL);
|
|
free(render);
|
|
|
|
getyx(ui_hist, ny, nx);
|
|
y = nx == 0 ? ny : ny + 1;
|
|
}
|
|
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));
|
|
}
|
|
|
|
static void
|
|
draw_sidebar(struct ui_state *s, const char *id, const char *dir,
|
|
struct sp_host *host)
|
|
{
|
|
int cols, y = 0;
|
|
|
|
cols = getmaxx(ui_side);
|
|
werase(ui_side);
|
|
|
|
sidebar_heading(&y, cols, sp_t("sidebar.session"));
|
|
mvwaddnstr(ui_side, y++, 0, id != NULL ? id : sp_t("ui.empty"),
|
|
cols - 1);
|
|
if (dir != NULL)
|
|
mvwaddnstr(ui_side, y++, 0, dir, cols - 1);
|
|
y++;
|
|
|
|
sidebar_heading(&y, cols, sp_t("sidebar.transport"));
|
|
mvwaddnstr(ui_side, y++, 0, s->endpoint != NULL ? s->endpoint : sp_t("sidebar.script"),
|
|
cols - 1);
|
|
y++;
|
|
|
|
sidebar_heading(&y, cols, sp_t("sidebar.theme"));
|
|
wattron(ui_side, COLOR_PAIR(PAIR_ACCENT));
|
|
mvwaddnstr(ui_side, y++, 0, s->theme.name, cols - 1);
|
|
wattron(ui_side, COLOR_PAIR(PAIR_MAIN));
|
|
y++;
|
|
|
|
sidebar_heading(&y, cols, sp_t("sidebar.last_turn"));
|
|
mvwprintw(ui_side, y++, 0, sp_t("sidebar.ms"), s->last_ms);
|
|
mvwprintw(ui_side, y++, 0, sp_t("sidebar.steps"), s->last_steps);
|
|
mvwprintw(ui_side, y++, 0, sp_t("sidebar.tool_calls"), s->last_calls);
|
|
y++;
|
|
|
|
sidebar_heading(&y, cols, sp_t("sidebar.output"));
|
|
if (s->tokens_out > 0)
|
|
mvwprintw(ui_side, y++, 0, sp_t("sidebar.tokens"),
|
|
s->tokens_out, s->tokens_in);
|
|
else
|
|
mvwprintw(ui_side, y++, 0, sp_t("sidebar.chars"),
|
|
s->out_chars, s->out_chars / 4);
|
|
y++;
|
|
|
|
sidebar_heading(&y, cols, sp_t("sidebar.widgets"));
|
|
if (host == NULL || sp_host_widget_count(host) == 0) {
|
|
wattron(ui_side, COLOR_PAIR(PAIR_DIM));
|
|
mvwaddnstr(ui_side, y++, 0, sp_t("sidebar.no_widgets"), cols - 1);
|
|
} else {
|
|
char snap[1024];
|
|
char *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)) {
|
|
if (y >= getmaxy(ui_side))
|
|
break;
|
|
mvwaddnstr(ui_side, y++, 0, line, cols - 1);
|
|
}
|
|
}
|
|
wattrset(ui_side, A_NORMAL);
|
|
|
|
wnoutrefresh(ui_side);
|
|
}
|
|
|
|
static void
|
|
draw_status(struct ui_state *s)
|
|
{
|
|
int cols = getmaxx(ui_status);
|
|
|
|
werase(ui_status);
|
|
wattron(ui_status, COLOR_PAIR(PAIR_STATUS));
|
|
mvwhline(ui_status, 0, 0, ' ', cols);
|
|
mvwprintw(ui_status, 0, 1, sp_t("status.title"), SP_VERSION);
|
|
{
|
|
char right[96];
|
|
|
|
snprintf(right, sizeof(right), "%s %ldms ", s->theme.name,
|
|
s->last_ms);
|
|
if ((int)strlen(right) + 1 < cols)
|
|
mvwaddnstr(ui_status, 0, cols - (int)strlen(right) - 1,
|
|
right, cols - 1);
|
|
}
|
|
wattroff(ui_status, COLOR_PAIR(PAIR_STATUS));
|
|
wnoutrefresh(ui_status);
|
|
}
|
|
|
|
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 idx, const char *text)
|
|
{
|
|
char *copy;
|
|
|
|
if (idx >= s->n)
|
|
return;
|
|
copy = strdup(text != NULL ? text : "");
|
|
if (copy == NULL)
|
|
return;
|
|
free(s->entries[idx].text);
|
|
s->entries[idx].text = copy;
|
|
}
|
|
|
|
static void
|
|
add_entry(struct ui_state *s, const char *role, const char *text)
|
|
{
|
|
struct entry *e;
|
|
|
|
if (s->n == MAX_ENTRIES) {
|
|
free(s->entries[0].role);
|
|
free(s->entries[0].text);
|
|
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);
|
|
e->text = strdup(text != NULL ? text : "");
|
|
}
|
|
|
|
static void
|
|
layout(void)
|
|
{
|
|
int rows, cols, chat_w, side_w;
|
|
|
|
getmaxyx(stdscr, rows, cols);
|
|
chat_w = cols * 3 / 4;
|
|
if (cols - chat_w < 12)
|
|
chat_w = cols > 24 ? cols - 16 : cols;
|
|
side_w = cols - chat_w;
|
|
/*
|
|
* Order, top to bottom: chat and sidebar, then the status line, then the
|
|
* input. Status above the prompt, the way Hermes shows it - the line you
|
|
* read while typing sits directly above what you type.
|
|
*/
|
|
ui_hist = newwin(rows - 2, chat_w, 0, 0);
|
|
wbkgd(ui_hist, COLOR_PAIR(PAIR_MAIN));
|
|
ui_side = newwin(rows - 2, side_w, 0, chat_w);
|
|
ui_status = newwin(1, cols, rows - 2, 0);
|
|
ui_input = newwin(1, cols, rows - 1, 0);
|
|
keypad(ui_input, TRUE);
|
|
}
|
|
|
|
int
|
|
sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *theme_name,
|
|
struct sp_host *host)
|
|
{
|
|
struct ui_state s;
|
|
struct sp_buf answer = { 0 }, err = { 0 };
|
|
size_t ans_idx = (size_t)-1; /* live answer entry, if any */
|
|
char input[1024];
|
|
int rc = 0;
|
|
|
|
memset(&s, 0, sizeof(s));
|
|
sp_buf_init(&s.last_think);
|
|
s.endpoint = endpoint;
|
|
if (sp_buf_init(&answer) != 0 || sp_buf_init(&err) != 0)
|
|
return 1;
|
|
if (sp_theme_load(theme_name, &s.theme, &err) != 0) {
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err.p != NULL ? err.p : sp_t("err.theme"));
|
|
return 1;
|
|
}
|
|
|
|
/*
|
|
* 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, ag->sess != NULL ? ag->sess->dir : NULL);
|
|
/*
|
|
* 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);
|
|
}
|
|
}
|
|
add_entry(&s, "splinter", sp_t("ui.ready"));
|
|
|
|
for (;;) {
|
|
struct timespec t0, t1;
|
|
int ch;
|
|
char pending_steer[1024];
|
|
|
|
pending_steer[0] = '\0';
|
|
|
|
draw_history(&s, 0);
|
|
draw_sidebar(&s, ag->sess != NULL ? ag->sess->id : NULL,
|
|
ag->sess != NULL ? ag->sess->dir : NULL, host);
|
|
draw_status(&s);
|
|
werase(ui_input);
|
|
mvwaddstr(ui_input, 0, 0, sp_t("ui.prompt_mark"));
|
|
wnoutrefresh(ui_input);
|
|
doupdate();
|
|
|
|
{
|
|
size_t len = 0;
|
|
|
|
wmove(ui_input, 0, 2);
|
|
wrefresh(ui_input);
|
|
/*
|
|
* A widget that ticks is useless if the screen only refreshes
|
|
* when a key is pressed. The input read times out every 500 ms
|
|
* and that timeout repaints the sidebar and the status line --
|
|
* cheap, and it makes clock/focus/cps actually alive.
|
|
*/
|
|
wtimeout(ui_input, 500);
|
|
for (;;) {
|
|
ch = wgetch(ui_input);
|
|
if (ch == ERR) {
|
|
draw_sidebar(&s, ag->sess != NULL ?
|
|
ag->sess->id : NULL,
|
|
ag->sess != NULL ? ag->sess->dir : NULL,
|
|
host);
|
|
draw_status(&s);
|
|
wnoutrefresh(ui_input);
|
|
doupdate();
|
|
continue;
|
|
}
|
|
if (ch == '\n' || ch == '\r' || ch == KEY_ENTER)
|
|
break;
|
|
if (ch == 4) {
|
|
s.quit = 1;
|
|
break;
|
|
}
|
|
if (ch == 12)
|
|
break;
|
|
if (ch == 3) {
|
|
len = 0;
|
|
werase(ui_input);
|
|
mvwaddstr(ui_input, 0, 0, sp_t("ui.prompt_mark"));
|
|
wrefresh(ui_input);
|
|
continue;
|
|
}
|
|
if (ch == KEY_UP || ch == KEY_DOWN) {
|
|
if (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, sizeof(input), "%s",
|
|
s.hist[s.hist_pos]);
|
|
len = strlen(input);
|
|
}
|
|
input[len] = '\0';
|
|
werase(ui_input);
|
|
mvwaddstr(ui_input, 0, 0, sp_t("ui.prompt_mark"));
|
|
ui_add_text(ui_input, input,
|
|
getmaxx(ui_input) - 3);
|
|
wrefresh(ui_input);
|
|
continue;
|
|
}
|
|
if (ch == KEY_BACKSPACE || ch == 127 || ch == 8) {
|
|
if (len > 0) {
|
|
len--;
|
|
mvwaddch(ui_input, 0,
|
|
(int)len + 2, ' ');
|
|
wmove(ui_input, 0,
|
|
(int)len + 2);
|
|
wrefresh(ui_input);
|
|
}
|
|
continue;
|
|
}
|
|
if (ch >= 32 && ch != 127 &&
|
|
len < sizeof(input) - 2) {
|
|
/*
|
|
* Bytes, not wide chars: a UTF-8 sequence arrives
|
|
* as several keys. The line is redrawn from the
|
|
* buffer so curses converts the whole string.
|
|
*/
|
|
input[len++] = (char)ch;
|
|
input[len] = '\0';
|
|
werase(ui_input);
|
|
mvwaddstr(ui_input, 0, 0, sp_t("ui.prompt_mark"));
|
|
ui_add_text(ui_input, input, getmaxx(ui_input) - 3);
|
|
wrefresh(ui_input);
|
|
}
|
|
}
|
|
input[len] = '\0';
|
|
wtimeout(ui_input, -1);
|
|
}
|
|
|
|
if (s.quit)
|
|
break;
|
|
if (input[0] == '\0')
|
|
continue;
|
|
|
|
/*
|
|
* A leading '!' runs a shell command here and puts the result in the
|
|
* conversation, so the model sees what the operator saw. The output is
|
|
* capped: a runaway command must not eat the budget in one keystroke.
|
|
*/
|
|
if (input[0] == '!' && input[1] != '\0') {
|
|
FILE *p2;
|
|
char chunk[512], outbuf[4096];
|
|
size_t used = 0;
|
|
int status;
|
|
|
|
p2 = popen(input + 1, "r");
|
|
outbuf[0] = '\0';
|
|
if (p2 == NULL) {
|
|
snprintf(outbuf, sizeof(outbuf), "popen: %s",
|
|
strerror(errno));
|
|
} else {
|
|
size_t got;
|
|
|
|
while (used < sizeof(outbuf) - 1 &&
|
|
(got = fread(chunk, 1, sizeof(chunk), p2)) > 0) {
|
|
if (got > sizeof(outbuf) - 1 - used)
|
|
got = sizeof(outbuf) - 1 - used;
|
|
memcpy(outbuf + used, chunk, got);
|
|
used += got;
|
|
}
|
|
outbuf[used] = '\0';
|
|
status = pclose(p2);
|
|
if (used == 0)
|
|
snprintf(outbuf, sizeof(outbuf),
|
|
sp_t("shell.no_output"),
|
|
WIFEXITED(status) ?
|
|
WEXITSTATUS(status) : -1);
|
|
}
|
|
add_entry(&s, "shell", input + 1);
|
|
add_entry(&s, "splinter", outbuf);
|
|
if (ag->conv != NULL) {
|
|
struct sp_buf note;
|
|
|
|
if (sp_buf_init(¬e) == 0) {
|
|
sp_buf_printf(¬e, "[shell] %s\n%s",
|
|
input + 1, outbuf);
|
|
(void)sp_conv_push(ag->conv, "user", NULL,
|
|
note.p);
|
|
sp_buf_free(¬e);
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
|
|
/*
|
|
* 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.
|
|
*/
|
|
if (input[0] == '/' && host != NULL) {
|
|
char name[64], args[1536], outbuf[2048];
|
|
struct sp_buf out;
|
|
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)
|
|
continue;
|
|
if (sp_host_command(host, name, args, &out) != 0) {
|
|
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);
|
|
continue;
|
|
}
|
|
|
|
hist_push(&s, ag->sess != NULL ? ag->sess->dir : NULL, input);
|
|
add_entry(&s, "you", input);
|
|
draw_history(&s, 0);
|
|
draw_sidebar(&s, ag->sess != NULL ? ag->sess->id : NULL,
|
|
ag->sess != NULL ? ag->sess->dir : NULL, host);
|
|
draw_status(&s);
|
|
werase(ui_input);
|
|
mvwaddstr(ui_input, 0, 0, sp_t("ui.working"));
|
|
wrefresh(ui_input);
|
|
doupdate();
|
|
|
|
sp_buf_clear(&answer);
|
|
sp_buf_clear(&err);
|
|
clock_gettime(CLOCK_MONOTONIC, &t0);
|
|
{
|
|
struct turn tu;
|
|
const struct sp_agent_config *orig = ag->cfg;
|
|
struct sp_agent_config cfg = *orig;
|
|
pthread_t th;
|
|
|
|
memset(&tu, 0, sizeof(tu));
|
|
tu.ag = ag;
|
|
tu.text = input;
|
|
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;
|
|
sp_openai_set_cancel(&tu.cancel);
|
|
cfg.tool_end = tool_end_cb;
|
|
cfg.tool_end_ctx = &tu;
|
|
cfg.tool_begin = tool_begin_cb;
|
|
cfg.tool_begin_ctx = &tu;
|
|
ag->cfg = &cfg;
|
|
|
|
if (pthread_create(&th, NULL, turn_thread, &tu) != 0) {
|
|
sp_openai_set_cancel(NULL);
|
|
ag->cfg = orig;
|
|
snprintf((char *)input, sizeof(input), "%s",
|
|
sp_t("err.thread"));
|
|
rc = -1;
|
|
} else {
|
|
/*
|
|
* While the turn runs: type to steer (Enter queues the
|
|
* text for the next step), Ctrl-C cancels, Ctrl-D quits
|
|
* after the turn.
|
|
*/
|
|
char line[1024];
|
|
size_t llen = 0;
|
|
int cancelled = 0, drained = 0, drained_d = 0;
|
|
size_t think_idx = (size_t)-1;
|
|
|
|
ans_idx = (size_t)-1;
|
|
|
|
wtimeout(ui_input, 100);
|
|
for (;;) {
|
|
int c;
|
|
struct timespec now;
|
|
long ms;
|
|
|
|
pthread_mutex_lock(&tu.lock);
|
|
if (tu.done) {
|
|
pthread_mutex_unlock(&tu.lock);
|
|
break;
|
|
}
|
|
pthread_mutex_unlock(&tu.lock);
|
|
|
|
c = wgetch(ui_input);
|
|
/*
|
|
* 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.
|
|
*/
|
|
{
|
|
int pending;
|
|
char nm[64], ar[256];
|
|
int auth = SP_AUTH_READ;
|
|
|
|
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);
|
|
if (pending) {
|
|
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);
|
|
}
|
|
continue;
|
|
}
|
|
}
|
|
if (c == ERR) {
|
|
char think[4096];
|
|
char live[8192];
|
|
size_t tlen2 = 0, llen2 = 0;
|
|
|
|
pthread_mutex_lock(&tu.lock);
|
|
if (tu.think.len > 0) {
|
|
tlen2 = tu.think.len;
|
|
if (tlen2 > sizeof(think) - 1)
|
|
tlen2 = sizeof(think) - 1;
|
|
memcpy(think, tu.think.p, tlen2);
|
|
}
|
|
if (tu.live.len > 0) {
|
|
llen2 = tu.live.len;
|
|
if (llen2 > sizeof(live) - 1)
|
|
llen2 = sizeof(live) - 1;
|
|
memcpy(live, tu.live.p, llen2);
|
|
}
|
|
pthread_mutex_unlock(&tu.lock);
|
|
think[tlen2] = '\0';
|
|
live[llen2] = '\0';
|
|
|
|
/*
|
|
* 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.
|
|
*/
|
|
if (tlen2 > 0) {
|
|
if (think_idx == (size_t)-1) {
|
|
think_idx = s.n;
|
|
add_entry(&s, "thinking", "");
|
|
}
|
|
entry_set_text(&s, think_idx,
|
|
think);
|
|
}
|
|
if (tu.ntools_done > drained) {
|
|
int k;
|
|
|
|
pthread_mutex_lock(&tu.lock);
|
|
for (k = drained;
|
|
k < tu.ntools_done; k++)
|
|
add_entry(&s, "tool",
|
|
tu.tools_done[k]);
|
|
drained = tu.ntools_done;
|
|
pthread_mutex_unlock(&tu.lock);
|
|
}
|
|
if (tu.ndiffs > drained_d) {
|
|
int k;
|
|
|
|
pthread_mutex_lock(&tu.lock);
|
|
for (k = drained_d; k < tu.ndiffs; k++)
|
|
add_entry(&s, "diff",
|
|
tu.diffs[k]);
|
|
drained_d = tu.ndiffs;
|
|
pthread_mutex_unlock(&tu.lock);
|
|
}
|
|
if (llen2 > 0) {
|
|
if (ans_idx == (size_t)-1) {
|
|
ans_idx = s.n;
|
|
add_entry(&s, "agent", "");
|
|
}
|
|
entry_set_text(&s, ans_idx,
|
|
live);
|
|
}
|
|
s.out_chars = llen2;
|
|
draw_history(&s, 0);
|
|
doupdate();
|
|
/* redraw the clock in the status bar */
|
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
|
ms = (long)((now.tv_sec - t0.tv_sec) *
|
|
1000 + (now.tv_nsec -
|
|
t0.tv_nsec) / 1000000);
|
|
werase(ui_input);
|
|
mvwprintw(ui_input, 0, 0,
|
|
sp_t("ui.running_steer"),
|
|
ms / 1000);
|
|
ui_add_text(ui_input, line,
|
|
getmaxx(ui_input) - 20);
|
|
wrefresh(ui_input);
|
|
continue;
|
|
}
|
|
if (c == KEY_PPAGE) {
|
|
s.scroll += 3;
|
|
draw_history(&s, 0);
|
|
draw_sidebar(&s, ag->sess != NULL ?
|
|
ag->sess->id : NULL,
|
|
ag->sess != NULL ? ag->sess->dir :
|
|
NULL, host);
|
|
draw_status(&s);
|
|
doupdate();
|
|
continue;
|
|
}
|
|
if (c == KEY_NPAGE) {
|
|
if (s.scroll > 3)
|
|
s.scroll = s.scroll >= 3 ? s.scroll - 3 : 0;
|
|
else
|
|
s.scroll = 0;
|
|
continue;
|
|
}
|
|
if (c == 3) {
|
|
tu.cancel = 1;
|
|
cancelled = 1;
|
|
break;
|
|
}
|
|
if (c == 4) {
|
|
s.quit = 1;
|
|
break;
|
|
}
|
|
if (c == '\n' || c == '\r' || c == KEY_ENTER) {
|
|
if (llen > 0) {
|
|
pthread_mutex_lock(&tu.lock);
|
|
snprintf(tu.steer,
|
|
sizeof(tu.steer), "%s",
|
|
line);
|
|
snprintf(pending_steer,
|
|
sizeof(pending_steer),
|
|
"%s", line);
|
|
tu.have_steer = 1;
|
|
pthread_mutex_unlock(&tu.lock);
|
|
llen = 0;
|
|
line[0] = '\0';
|
|
mvwaddstr(ui_input, 0, 0,
|
|
sp_t("ui.steering_queued"));
|
|
wclrtoeol(ui_input);
|
|
wrefresh(ui_input);
|
|
}
|
|
continue;
|
|
}
|
|
if ((c == KEY_BACKSPACE || c == 127 || c == 8) &&
|
|
llen > 0) {
|
|
llen--;
|
|
line[llen] = '\0';
|
|
continue;
|
|
}
|
|
if (c >= 32 && c != 127 &&
|
|
llen < sizeof(line) - 2) {
|
|
line[llen++] = (char)c;
|
|
line[llen] = '\0';
|
|
}
|
|
}
|
|
wtimeout(ui_input, -1);
|
|
pthread_join(th, NULL);
|
|
/*
|
|
* 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;
|
|
(void)cancelled;
|
|
rc = tu.rc;
|
|
sp_buf_clear(&answer);
|
|
sp_buf_clear(&err);
|
|
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);
|
|
}
|
|
{
|
|
int k;
|
|
|
|
pthread_mutex_lock(&tu.lock);
|
|
for (k = drained; k < tu.ntools_done; k++)
|
|
add_entry(&s, "tool",
|
|
tu.tools_done[k]);
|
|
drained = tu.ntools_done;
|
|
pthread_mutex_unlock(&tu.lock);
|
|
}
|
|
{
|
|
int k;
|
|
|
|
pthread_mutex_lock(&tu.lock);
|
|
for (k = drained_d; k < tu.ndiffs; k++)
|
|
add_entry(&s, "diff", tu.diffs[k]);
|
|
drained_d = tu.ndiffs;
|
|
pthread_mutex_unlock(&tu.lock);
|
|
}
|
|
/* the reasoning stays in the transcript, as a dim
|
|
* entry, capped so a long plan cannot push the chat
|
|
* out of the window */
|
|
/*
|
|
* The reasoning keeps its full text. Cutting it to a tail
|
|
* at the end of the turn made the block shrink, and
|
|
* everything below it jumped up - the same complaint as
|
|
* before, one layer deeper. It grew here, it stays here.
|
|
*/
|
|
if (tu.think.len > 0) {
|
|
if (think_idx == (size_t)-1) {
|
|
think_idx = s.n;
|
|
add_entry(&s, "thinking",
|
|
tu.think.p);
|
|
} else
|
|
entry_set_text(&s, think_idx,
|
|
tu.think.p);
|
|
}
|
|
sp_buf_free(&tu.answer);
|
|
sp_buf_free(&tu.err);
|
|
sp_buf_free(&tu.live);
|
|
sp_buf_free(&tu.think);
|
|
pthread_cond_destroy(&tu.cond);
|
|
pthread_mutex_destroy(&tu.lock);
|
|
}
|
|
}
|
|
clock_gettime(CLOCK_MONOTONIC, &t1);
|
|
|
|
s.last_ms = (long)((t1.tv_sec - t0.tv_sec) * 1000 +
|
|
(t1.tv_nsec - 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) {
|
|
if (ans_idx != (size_t)-1)
|
|
entry_set_text(&s, ans_idx, answer.p);
|
|
else
|
|
add_entry(&s, "agent", answer.p);
|
|
} else
|
|
add_entry(&s, "error", err.p != NULL ? err.p :
|
|
sp_t("err.turn_failed"));
|
|
|
|
/*
|
|
* 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: same conversation, immediately answered.
|
|
*/
|
|
if (pending_steer[0] != '\0') {
|
|
int rc2;
|
|
|
|
add_entry(&s, "you", pending_steer);
|
|
sp_buf_clear(&answer);
|
|
sp_buf_clear(&err);
|
|
rc2 = sp_agent_run(ag, pending_steer, &answer, &err);
|
|
if (rc2 == 0)
|
|
add_entry(&s, "agent", answer.p);
|
|
else
|
|
add_entry(&s, "error", err.p != NULL ? err.p :
|
|
sp_t("err.followup_failed"));
|
|
pending_steer[0] = '\0';
|
|
}
|
|
}
|
|
|
|
endwin();
|
|
sp_buf_free(&s.last_think);
|
|
sp_buf_free(&answer);
|
|
sp_buf_free(&err);
|
|
return rc;
|
|
}
|