/* pic's terminal UI: the event loop, transcript, footer and commands.
*
* Output model: everything finished is committed once to the terminal's
* scrollback (render.h); the live area at the bottom holds the reply being
* streamed, a running tool call, the status line, queued messages, the
* editor and the footer. A reply that fails mid-stream is only ever in the
* live area, so dropping it leaves no trace. Requests run as a child
* `pic --json --commands ... ask` (Pi's RPC command lines on its stdin: steer,
* follow_up, clear_queue, abort; events on its stdout, notices on its stderr).
* Esc sends abort; SIGINT, which pic also turns into a clean cancel, is the
* fallback. A "!" command runs as `pic bash`, which journals it. */
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <limits.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include "compact.h"
#include "cred.h"
#include "help.h"
#include "hooks.h"
#include "input.h"
#include "models.h"
#include "pic.h"
#include "platform.h"
#include "procs.h"
#include "prompts.h"
#include "skills.h"
#include "sqlite3.h"
#include "tui/editor.h"
#include "tui/atfile.h"
#include "tui/clipboard.h"
#include "tui/fuzzy.h"
#include "tui/markdown.h"
#include "tui/render.h"
#include "tui/term.h"
#include "tui/theme.h"
#include "tui/themes.h"
#include "tui/transcript.h"
#include "tui/keymap.h"
#include "tui/tui.h"
#include "tui/view.h"
#include "tui/viewport.h"
#include "tui/width.h"
#include "userdb.h"
#define BOLD "\x1b[1m"
#define RESET "\x1b[0m"
/* Pi's theme tokens (tui/theme.h) where the colours used to be hard-coded. */
#define DIM tui_fg(TUI_T_DIM)
#define CYAN tui_fg(TUI_T_ACCENT)
#define GREEN tui_fg(TUI_T_SUCCESS)
#define RED tui_fg(TUI_T_ERROR)
#define YELLOW tui_fg(TUI_T_WARNING)
#define MAX_QUEUED 16
typedef struct {
char *buf;
size_t len, cap;
} text;
static int text_add(text *t, const char *s, size_t n) {
if (t->len + n + 1 > t->cap) {
size_t cap = t->cap ? t->cap : 256;
char *grown;
while (cap < t->len + n + 1) {
cap *= 2;
}
if (!(grown = realloc(t->buf, cap))) {
return -1;
}
t->buf = grown;
t->cap = cap;
}
memcpy(t->buf + t->len, s, n);
t->len += n;
t->buf[t->len] = '\0';
return 0;
}
static void text_clear(text *t) {
t->len = 0;
if (t->buf) {
t->buf[0] = '\0';
}
}
/* A tool call: shown as a block from its start until it is committed. */
typedef struct {
char id[96], name[32];
char *title, *diff, *output, *content; /* content: write's text */
int state;
long start_ms, took_ms;
} toolblk;
/* A child pic process: a request (events) or a short command (output). */
typedef struct {
pid_t pid;
int in; /* a request's command pipe (Pi's RPC lines); -1 when it takes none */
int out, err; /* read ends; -1 once closed */
text outbuf, errbuf;
long long proc; /* its pic ps row; 0 when none */
} child;
/* A request child's row ends with it (pic ps). */
static void run_ended(child *c, int status) {
if (c->proc > 0) {
pic_proc_end(c->proc, WIFEXITED(status) ? WEXITSTATUS(status) : -1, WIFSIGNALED(status) ? WTERMSIG(status) : 0);
c->proc = 0;
}
}
typedef struct {
const pic_tui_options *o;
char model[160], conversation[64], name[128];
long window;
sqlite3 *db; /* in-memory, for reading JSON */
sqlite3_stmt *get;
tui_render *r;
tui_editor *ed;
tui_keys *keys;
int cols, rows;
/* the running request */
child run;
int working, interrupted, seen_end;
text stream; /* assistant text being streamed */
text thinking; /* its thinking, shown dimmed while it streams */
size_t stream_off; /* bytes of it already committed: always whole lines */
int stream_fence; /* inside a ``` block at stream_off */
long stop_at; /* the request was interrupted at this time (ms), 0: not */
int stop_level; /* signals sent so far: 1 SIGINT, 2 SIGTERM, 3 SIGKILL */
char status[256]; /* retry / compaction notices */
/* Tool calls of this reply, in order. A finished block stays here (live,
* so ctrl+o can still expand it) until the next reply text or the end of
* the request commits it; scrollback already printed cannot change. */
toolblk *blocks;
int nblocks;
int retry_n, retry_max, retried; /* the running retry (attempt, of), and the last attempt run */
long retry_delay, retry_at; /* its delay (ms) and when it started */
char branch[128]; /* the workspace's git branch, "" when none */
int spin;
/* tokens over this session of the UI */
long long in, out, cache_read, cache_write, context;
int expand_tools;
/* Messages typed while a reply runs. Steering and follow-ups are the child's
* (mirrored from its queue_update events, which is what is shown); queue holds
* what it cannot take: /commands, and everything when it takes no commands. */
char *steer_q[MAX_QUEUED], *follow_q[MAX_QUEUED];
int nsteer, nfollow;
char *sent_q[MAX_QUEUED]; /* sent over the pipe, not yet answered: lost if the child exits first */
int nsent;
char *queue[MAX_QUEUED];
int nqueue;
int skip_user; /* the next user message event is the request's own, already shown */
/* The continued conversation's request a crash left unfinished (its key),
* offered to resume (Enter) or drop (Esc); "" when none. */
char unfinished[96], unfinished_model[200];
int resuming; /* the child finishes the unfinished request */
int compacting; /* the child is /compact's: it ends with no agent_end, its refusal on stderr */
int finishing; /* its last reply is in: the child is about to settle, so new messages wait for the next request */
int clear_sent, clear_notice; /* a clear_queue is out; say what was restored when it answers */
int abort_sent; /* Esc sent abort over the pipe: SIGINT is the next rung */
double cost; /* the session's cost so far, when usage events carry one */
int ctrl_c_armed; /* a second Ctrl-C quits */
long d_at; /* a Ctrl+D on an empty editor was pressed at this time (ms): a second within QUIT_WINDOW_MS quits */
/* Ctrl+R: reverse search through the editor's history */
struct {
int on, fail; /* open; the query has no match (the last one shown stays) */
char q[256];
long at; /* the history entry shown, -1: none */
} hs;
/* /resume picker */
char **pick_ids, **pick_rows;
int npick, pick_at, picking;
/* the model picker */
char **mp_models, **mp_names, **mp_search;
long *mp_window;
size_t *mp_order, mp_n;
int nmodels, mp_open, mp_sel;
char mp_filter[128], default_model[160];
child refresh; /* the background catalog refresh */
int refreshing;
pic_skills skl; /* skills: /skill:name ARGS goes to the request as typed */
pic_prompts tpl; /* prompt templates: /name ARGS goes to the request as typed */
/* the slash menu */
int menu_sel;
char menu_dismissed[512];
/* the @file menu: the typed token it was listed for, and the list */
char at_key[520];
atfile_item at_items[5];
size_t at_n;
int at_valid;
char *last_reply; /* for /copy and ctrl+x */
int quit;
int links; /* the terminal draws OSC 8 hyperlinks */
char title[320]; /* the terminal title last written */
long esc_at; /* an Escape on an empty editor was pressed at this time (ms): a second one opens /tree */
/* a "!" or "!!" command the user ran: its output is drawn live, then committed */
struct {
child c; /* pic bash: its events are the output so far, then Pi's bash response */
int running, cancelled, no_context, kill_level, got_resp, exit_code, has_exit;
char *cmd, *live, *final;
long kill_at;
} bash;
/* the thinking level: "" means the saved default (see effective_level) */
char think_level[16];
char lvl_for[160]; /* the model lvls was worked out for */
const char *lvls[PIC_THINKING_LEVELS]; /* its supported levels, lowest first */
int nlvl;
char level[16]; /* the level requests use ('' when the model has none) */
int hide_thinking;
/* an overlay: /settings, /scoped-models, /thinking, /tree, /trust, /share, the theme picker */
int ov;
char ov_title[160], ov_hint[200], ov_filter[128];
char **ov_label, **ov_id;
unsigned char *ov_on;
size_t *ov_order, ov_m;
int ov_n, ov_sel;
char *ov_data; /* /share: the page waiting for a yes */
/* /tree: the entry chosen (and a conversation that ends there) while Pi's
* "Summarize branch?" is asked; custom: the editor's next line is the
* summary's instructions */
char branch_at[32], branch_sess[64];
int branch_custom;
/* fullscreen (Pi's tuiMode and fullscreen* settings) */
int copy_on_select;
tui_wheel wheel;
char flash[64]; /* a short confirmation in the status row ("Copied!") */
long flash_until;
/* Pi's themes and keybindings (tui/theme.h, tui/keymap.h) */
tui_themeset themes;
char theme_cli[64]; /* --theme: for this run, until a theme is chosen in /settings */
char theme_prev[64]; /* the theme before the picker previewed others */
tui_keymap *km;
char *startup_warn; /* problems found loading them at start, shown once the header is */
tui_transcript *tr; /* what was committed, to draw again when Ctrl+O or Ctrl+T changes it */
int last_blank; /* the last line committed was empty */
} app;
/* How long a stopping request gets after SIGINT before SIGTERM, and after
* that before SIGKILL. It normally exits at once; the margin is for a slow
* disk or a loaded machine, where recording the cancellation can take
* seconds and is worth waiting for. */
#define STOP_GRACE_MS 10000
/* Claude Code: Ctrl+D on an empty editor exits only when pressed twice within this long. */
#define QUIT_WINDOW_MS 800
enum { OV_NONE, OV_SETTINGS, OV_SCOPED, OV_THINKING, OV_TREE, OV_TRUST, OV_SHARE, OV_SUMMARY, OV_THEME, OV_FORK };
static volatile sig_atomic_t resized;
static volatile pid_t child_pid; /* the running request, for on_stop */
static int wake_pipe[2] = {-1, -1};
static long now_ms(void) { return (long)(pic_platform_get()->mono_ns() / 1000000); }
static void on_winch(int sig) {
(void)sig;
resized = 1;
if (wake_pipe[1] >= 0) {
ssize_t n = write(wake_pipe[1], "w", 1);
(void)n;
}
}
/* With hooks configured: `pic hooks end other` with this interface's
* PIC_HOOK_OWNER, made ready at start so on_stop runs it with
* async-signal-safe calls alone. */
static pic_host_exec stop_exec;
/* Terminated, hung up or crashed: the terminal is put back, and a running
* request is cancelled (pic finishes the cancel on its own; it ignores a
* reader that went away). With hooks, a detached process ends the
* conversations (SessionEnd) once that request has let the journal go. */
static void on_stop(int sig) {
pid_t run = child_pid;
if (run > 0) {
(void)kill(run, SIGINT);
}
tui_term_restore();
pic_host_exec_start(&stop_exec, run);
(void)signal(sig, SIG_DFL);
(void)raise(sig);
}
/* ---- JSON (through SQLite) -------------------------------------------- */
/* json_extract(doc, path) as a malloc'd string, or NULL. */
static char *jget(app *a, const char *doc, const char *path) {
char *out = NULL;
sqlite3_bind_text(a->get, 1, doc, -1, SQLITE_STATIC);
sqlite3_bind_text(a->get, 2, path, -1, SQLITE_STATIC);
if (sqlite3_step(a->get) == SQLITE_ROW && sqlite3_column_type(a->get, 0) != SQLITE_NULL) {
const char *t = (const char *)sqlite3_column_text(a->get, 0);
out = t ? strdup(t) : NULL;
}
sqlite3_reset(a->get);
sqlite3_clear_bindings(a->get);
return out;
}
static int jget_has(app *a, const char *doc, const char *path) {
char *s = jget(a, doc, path);
free(s);
return s != NULL;
}
static long long jnum(app *a, const char *doc, const char *path) {
char *s = jget(a, doc, path);
long long v = s ? strtoll(s, NULL, 10) : 0;
free(s);
return v;
}
/* ---- committing output ------------------------------------------------ */
static void commit_lines(app *a, tui_lines *l) {
(void)tui_transcript_lines(a->tr, (const char *const *)l->lines, l->n);
(void)tui_render_commit(a->r, (const char *const *)l->lines, l->n);
if (l->n) {
a->last_blank = !*l->lines[l->n - 1];
}
tui_lines_clear(l);
}
/* Commits a tool call, a "!" command or thinking as an item Ctrl+O and Ctrl+T
* draw again: its lines as they look now go to the screen. */
static void commit_drawn(app *a, tui_lines *l) {
(void)tui_render_commit(a->r, (const char *const *)l->lines, l->n);
if (l->n) {
a->last_blank = !*l->lines[l->n - 1];
}
tui_lines_clear(l);
}
static void commit_tool(app *a, const tui_tool *t) {
tui_lines l = {NULL, 0, 0};
if (!a->last_blank) { /* Pi's spacer above a tool block */
(void)tui_lines_add(&l, "", 0);
commit_lines(a, &l);
}
(void)tui_transcript_tool(a->tr, t);
(void)tui_tool_lines(t, a->expand_tools, a->cols > 2 ? (size_t)a->cols : 2, &l);
commit_drawn(a, &l);
}
static void commit_bash(app *a, const tui_bash *b) {
tui_lines l = {NULL, 0, 0};
(void)tui_transcript_bash(a->tr, b);
(void)tui_bash_lines(b, a->expand_tools, a->cols > 2 ? (size_t)a->cols : 2, &l);
commit_drawn(a, &l);
}
/* Everything committed, drawn again with the toggles as they are now (Pi
* re-renders every block on Ctrl+O and Ctrl+T). */
static void redraw_transcript(app *a) {
tui_lines l = {NULL, 0, 0};
if (tui_transcript_render(a->tr, a->expand_tools, a->hide_thinking, a->cols > 2 ? (size_t)a->cols : 2, &l) == 0) {
(void)tui_render_replace(a->r, (const char *const *)l.lines, l.n);
}
tui_lines_clear(&l);
}
/* Commits text wrapped to the width, each line prefixed with PREFIX (a
* style, or ""). */
static void commit_text(app *a, const char *prefix, const char *s) {
tui_lines l = {NULL, 0, 0}, out = {NULL, 0, 0};
size_t cols = a->cols > 2 ? (size_t)a->cols : 2;
if (tui_wrap(s, strlen(s), cols, &l) != 0) {
return;
}
for (size_t i = 0; i < l.n; i++) {
text t = {NULL, 0, 0};
(void)text_add(&t, prefix, strlen(prefix));
(void)text_add(&t, l.lines[i], strlen(l.lines[i]));
if (*prefix) {
(void)text_add(&t, RESET, strlen(RESET));
}
(void)tui_lines_add(&out, t.buf ? t.buf : "", t.len);
free(t.buf);
}
tui_lines_clear(&l);
commit_lines(a, &out);
}
static void notice(app *a, const char *style, const char *fmt, ...) {
char small[1024], *msg = small;
va_list ap;
int n;
va_start(ap, fmt);
n = vsnprintf(small, sizeof small, fmt, ap);
va_end(ap);
if (n >= (int)sizeof small && (msg = malloc((size_t)n + 1)) != NULL) { /* /hotkeys, /help: several kilobytes */
va_start(ap, fmt);
(void)vsnprintf(msg, (size_t)n + 1, fmt, ap);
va_end(ap);
}
commit_text(a, style, msg ? msg : small);
if (msg != small) {
free(msg);
}
}
/* A message the user sent, on Pi's user-message background. */
static void commit_user(app *a, const char *msg) {
tui_lines l = {NULL, 0, 0};
(void)tui_lines_add(&l, "", 0);
(void)tui_user_message_lines(msg, a->cols > 2 ? (size_t)a->cols : 2, a->links, &l);
(void)tui_lines_add(&l, "", 0);
commit_lines(a, &l);
}
static void md_opts(const app *a, tui_md_opts *o) {
o->base = NULL;
o->links = a->links;
o->preserve = 0;
}
/* The uncommitted part of the streamed reply as styled, wrapped lines. */
static void stream_lines(app *a, tui_lines *out) {
tui_md_opts o;
const char *s = a->stream.buf ? a->stream.buf + a->stream_off : "";
md_opts(a, &o);
(void)tui_markdown(s, strlen(s), a->cols > 1 ? (size_t)a->cols : 1, &o, out);
}
/* Commits the first finished block of the reply: up to its blank line. A block
* too long to wait for (no blank line yet) goes a line at a time. 0 when there
* is nothing finished. */
static int commit_head_line(app *a) {
const char *s = a->stream.buf ? a->stream.buf + a->stream_off : "", *nl;
size_t cols = a->cols > 1 ? (size_t)a->cols : 1, n = tui_markdown_block_len(s);
tui_md_opts o;
tui_lines l = {NULL, 0, 0};
md_opts(a, &o);
if (n) {
(void)tui_markdown(s, n, cols, &o, &l);
(void)tui_lines_add(&l, "", 0); /* the blank line between blocks */
commit_lines(a, &l);
a->stream_off += n;
return 1;
}
if (!(nl = strchr(s, '\n'))) {
return 0;
}
(void)tui_markdown_line(s, (size_t)(nl - s), &a->stream_fence, cols, &o, &l);
commit_lines(a, &l);
a->stream_off += (size_t)(nl - s) + 1;
return 1;
}
/* Whether thinking is hidden, read from the saved setting (the settings
* menu, Ctrl+T and other pics may change it at any time). */
static int thinking_hidden(app *a) {
char *hide = pic_setting("hideThinking");
a->hide_thinking = hide && strcmp(hide, "true") == 0;
free(hide);
return a->hide_thinking;
}
/* Commits the reply's thinking: Pi's thinking block, or its one-line marker
* when hidden, after a blank line. */
static void commit_thinking(app *a) {
if (a->thinking.len && a->thinking.buf[strspn(a->thinking.buf, " \t\r\n")]) {
tui_lines l = {NULL, 0, 0};
(void)tui_lines_add(&l, "", 0);
commit_lines(a, &l);
(void)tui_transcript_thinking(a->tr, a->thinking.buf);
(void)tui_thinking_lines(a->thinking.buf, thinking_hidden(a), a->cols > 2 ? (size_t)a->cols : 2, &l);
commit_drawn(a, &l);
(void)tui_lines_add(&l, "", 0); /* Pi's spacer after a thinking run */
commit_lines(a, &l);
}
text_clear(&a->thinking);
}
/* Commits what is left of the streamed reply and starts the next one. */
static void commit_stream(app *a) {
tui_lines l = {NULL, 0, 0};
commit_thinking(a);
if (a->stream.len) { /* kept for /copy */
free(a->last_reply);
a->last_reply = strdup(a->stream.buf);
}
stream_lines(a, &l);
if (l.n) {
commit_lines(a, &l);
}
tui_lines_clear(&l);
text_clear(&a->stream);
text_clear(&a->thinking);
a->stream_off = 0;
a->stream_fence = 0;
}
/* ---- the live area ---------------------------------------------------- */
static void fmt_tokens(long long n, char *out, size_t cap) {
if (n >= 1000000) {
(void)snprintf(out, cap, "%.1fM", (double)n / 1e6);
} else if (n >= 1000) {
(void)snprintf(out, cap, "%.1fk", (double)n / 1e3);
} else {
(void)snprintf(out, cap, "%lld", n);
}
}
static void add_fit(tui_lines *l, const char *style, const char *s, int cols) {
text t = {NULL, 0, 0};
size_t fit = tui_fit(s, strlen(s), cols > 0 ? (size_t)cols : 1);
(void)text_add(&t, style, strlen(style));
(void)text_add(&t, s, fit);
(void)text_add(&t, RESET, strlen(RESET));
(void)tui_lines_add(l, t.buf, t.len);
free(t.buf);
}
/* ---- the thinking level ------------------------------------------------- */
/* Pi's clampThinkingLevel over the model's supported levels: WANT if
* supported, else the nearest supported level above it, else below. */
static const char *clamp_level(const app *a, const char *want) {
int w = pic_thinking_index(want);
if (a->nlvl == 0) {
return "";
}
for (int d = 0; w >= 0 && d < PIC_THINKING_LEVELS; d++) {
for (int i = 0; i < a->nlvl; i++) {
if (pic_thinking_index(a->lvls[i]) == w + d) {
return a->lvls[i];
}
}
}
for (int d = 1; w >= 0 && d < PIC_THINKING_LEVELS; d++) {
for (int i = 0; i < a->nlvl; i++) {
if (pic_thinking_index(a->lvls[i]) == w - d) {
return a->lvls[i];
}
}
}
return a->lvls[a->nlvl - 1];
}
/* The level a request will use, as pic ask works it out (the session's,
* else the model's saved one, else the default, else medium), clamped to what
* the model supports; the levels themselves are cached per model. */
static void refresh_level(app *a) {
pic_model m;
char err[PIC_ERR_CAP], key[320], *saved = NULL;
(void)snprintf(a->lvl_for, sizeof a->lvl_for, "%s", a->model);
if (pic_model_resolve(a->model, &m, err, sizeof err) == 0) {
a->nlvl = pic_model_thinking_levels(&m, a->lvls);
a->window = a->o->context_window >= 0 ? a->o->context_window : m.context_window; /* the footer's percentage before the first request */
} else {
a->nlvl = 0;
}
a->level[0] = '\0';
if (a->nlvl == 0) {
return;
}
if (a->think_level[0]) {
(void)snprintf(a->level, sizeof a->level, "%s", clamp_level(a, a->think_level));
return;
}
(void)snprintf(key, sizeof key, "thinkingLevel:%s", a->model);
saved = pic_setting(key);
if (pic_thinking_index(saved) < 0) {
free(saved);
saved = pic_setting("defaultThinkingLevel");
}
(void)snprintf(a->level, sizeof a->level, "%s", clamp_level(a, pic_thinking_index(saved) >= 0 ? saved : "medium"));
free(saved);
}
static void ensure_level(app *a) {
if (strcmp(a->lvl_for, a->model) != 0 || !a->lvl_for[0]) {
refresh_level(a);
}
}
static void set_level(app *a, const char *level) {
(void)snprintf(a->think_level, sizeof a->think_level, "%s", level);
refresh_level(a);
notice(a, DIM, "thinking level: %s", a->level);
}
/* Shift+Tab: the next level the model supports, wrapping (Pi's cycleThinkingLevel). */
static void cycle_level(app *a) {
int at = 0;
ensure_level(a);
if (a->nlvl <= 1) {
notice(a, DIM, "%s does not support thinking levels", a->model);
return;
}
for (int i = 0; i < a->nlvl; i++) {
at = strcmp(a->lvls[i], a->level) == 0 ? i : at;
}
set_level(a, a->lvls[(at + 1) % a->nlvl]);
}
static void picker_lines(app *a, tui_lines *tail);
static void overlay_lines(app *a, tui_lines *tail);
static void overlay_key(app *a, const tui_key *k);
static void ov_free(app *a);
static void submit(app *a, char *msg);
static void restore_texts(app *a, char *const *texts, int n);
static const pic_prompt *template_for(const app *a, const char *line);
static int skill_for(const app *a, const char *line);
static void pump_refresh(app *a);
static void app_models_free(app *a);
static void menu_lines(app *a, tui_lines *tail);
static void block_lines(const toolblk *b, int expanded, size_t cols, tui_lines *out);
/* Pi colours the editor's border by thinking level, and as bash mode while the line starts with "!". */
static const char *editor_border(app *a) {
const char *cur = tui_editor_text(a->ed);
if (cur[strspn(cur, " \t")] == '!') {
return tui_fg(TUI_T_BASH_MODE);
}
ensure_level(a);
return tui_fg(tui_thinking_token(a->nlvl > 1 ? a->level : "off"));
}
static void draw(app *a) {
static const char *const frames[] = {"\xe2\xa0\x8b", "\xe2\xa0\x99", "\xe2\xa0\xb9", "\xe2\xa0\xb8", "\xe2\xa0\xbc",
"\xe2\xa0\xb4", "\xe2\xa0\xa6", "\xe2\xa0\xa7", "\xe2\xa0\x87", "\xe2\xa0\x8f"};
tui_lines live = {NULL, 0, 0}, tail = {NULL, 0, 0};
int crow = -1, ccol = 0, budget;
char line[1024], mdl[1024];
const char *home = getenv("HOME");
const char *ws = a->o->workspace;
/* Below the reply: status, queue, editor and its menu (or a picker), footer. */
if (a->mp_open) {
picker_lines(a, &tail);
} else if (a->ov) {
overlay_lines(a, &tail);
} else if (a->picking) {
add_fit(&tail, BOLD, "Resume a conversation (up/down, enter, esc):", a->cols);
for (int i = 0; i < a->npick && i < 12; i++) {
int at = a->pick_at < 12 ? i : a->pick_at - 11 + i;
if (at >= a->npick) {
break;
}
(void)snprintf(line, sizeof line, "%s %s", at == a->pick_at ? ">" : " ", a->pick_rows[at]);
add_fit(&tail, at == a->pick_at ? CYAN : "", line, a->cols);
}
if (a->npick > 12) { /* Pi's "(selected/total)" under a long list */
(void)snprintf(line, sizeof line, " (%d/%d)", a->pick_at + 1, a->npick);
add_fit(&tail, DIM, line, a->cols);
}
} else {
const char *bsgr = DIM, *bst = "";
char bbuf[1024];
if (a->flash[0] && now_ms() < a->flash_until) {
bst = a->flash;
} else if (a->working) {
char retry[160];
if (a->retry_n > 0) {
tui_retry_status(a->retry_n, a->retry_max, a->retry_delay, now_ms() - a->retry_at, retry, sizeof retry);
}
(void)snprintf(bbuf, sizeof bbuf, "%s %s", frames[a->spin % 10],
a->interrupted ? "Stopping\xe2\x80\xa6" : a->retry_n > 0 ? retry : a->status[0] ? a->status : "Working\xe2\x80\xa6 (esc to interrupt)");
bst = bbuf;
bsgr = a->retry_n > 0 || a->status[0] ? YELLOW : DIM;
} else if (a->status[0]) {
bst = a->status;
bsgr = YELLOW;
}
if (a->nsteer + a->nfollow + a->nqueue > 0) { /* Pi's pending-messages rows */
(void)tui_lines_add(&tail, "", 0);
for (int i = 0; i < a->nsteer; i++) {
(void)snprintf(line, sizeof line, " Steering: %s", a->steer_q[i]);
add_fit(&tail, DIM, line, a->cols);
}
for (int i = 0; i < a->nfollow; i++) {
(void)snprintf(line, sizeof line, " Follow-up: %s", a->follow_q[i]);
add_fit(&tail, DIM, line, a->cols);
}
for (int i = 0; i < a->nqueue; i++) {
(void)snprintf(line, sizeof line, " Follow-up: %s", a->queue[i]);
add_fit(&tail, DIM, line, a->cols);
}
add_fit(&tail, DIM, " \xe2\x86\xb3 alt+up to edit all queued messages", a->cols);
}
{
size_t before, cols = a->cols > 2 ? (size_t)a->cols : 2;
int er = 0, ec = 0;
const char *bc = editor_border(a);
(void)tui_border_line_in(bc, bsgr, bst, cols, &tail); /* Pi's editor: status in the top border */
before = tail.n;
if (a->hs.on) { /* readline's prompt: the entry found, the query at the cursor */
const char *pre = a->hs.fail ? "(failed reverse-i-search)`" : "(reverse-i-search)`";
const char *m = a->hs.at >= 0 ? tui_editor_history_at(a->ed, (size_t)a->hs.at) : "";
char row[1024];
(void)snprintf(row, sizeof row, "%s%s': %.*s", pre, a->hs.q, (int)strcspn(m, "\n"), m);
add_fit(&tail, "", row, (int)cols);
crow = (int)before;
ccol = (int)tui_width(pre, strlen(pre)) + (int)tui_width(a->hs.q, strlen(a->hs.q));
if (ccol >= (int)cols) {
ccol = (int)cols - 1;
}
} else if (tui_editor_render(a->ed, cols, &tail, &er, &ec) == 0) {
crow = (int)before + er;
ccol = ec;
}
(void)tui_border_line_in(bc, NULL, "", cols, &tail);
}
menu_lines(a, &tail);
}
/* footer: where (cwd, branch, conversation); then tokens, context, model */
tui_footer_where(ws, home, a->branch, a->name[0] ? a->name : a->conversation[0] ? a->conversation : "new conversation",
a->cols > 0 ? (size_t)a->cols : 1, line, sizeof line);
add_fit(&tail, DIM, line, a->cols);
ensure_level(a);
{
tui_footer f = {a->in, a->out, a->cache_read, a->cache_write, a->context, a->window, a->model,
a->nlvl > 1 ? a->level : "", a->expand_tools, a->cost};
tui_footer_stats(&f, a->cols > 0 ? (size_t)a->cols : 1, mdl, sizeof mdl);
(void)tui_lines_add(&tail, mdl, strlen(mdl));
}
/* Above: the reply being written. When it no longer fits, its finished
* lines (ending in a newline) go to the scrollback for good. */
budget = a->rows - 1 - (int)tail.n - 1;
if (budget < 2) {
budget = 2;
}
if (a->stream.len || a->thinking.len || a->nblocks) {
tui_lines s = {NULL, 0, 0};
if (a->stream.len) {
stream_lines(a, &s);
while ((int)s.n > budget && commit_head_line(a)) {
tui_lines_clear(&s);
stream_lines(a, &s);
}
} else if (a->thinking.len) { /* Pi's thinking block as it grows: as much of its end as fits */
tui_lines t = {NULL, 0, 0};
(void)tui_lines_add(&s, "", 0);
(void)tui_thinking_lines(a->thinking.buf, a->hide_thinking, a->cols > 2 ? (size_t)a->cols : 2, &t);
for (size_t i = t.n > (size_t)budget ? t.n - (size_t)budget : 0; i < t.n; i++) {
(void)tui_lines_add(&s, t.lines[i], strlen(t.lines[i]));
}
tui_lines_clear(&t);
}
for (size_t i = 0; i < s.n; i++) {
(void)tui_lines_add(&live, s.lines[i], strlen(s.lines[i]));
}
tui_lines_clear(&s);
for (int i = 0; i < a->nblocks; i++) {
if (i > 0 || live.n > 0 || !a->last_blank) { /* Pi's spacer above a tool block */
(void)tui_lines_add(&live, "", 0);
}
block_lines(&a->blocks[i], a->expand_tools, a->cols > 2 ? (size_t)a->cols : 2, &live);
}
(void)tui_lines_add(&live, "", 0);
}
if (a->bash.running) {
tui_bash b = {a->bash.cmd, a->bash.live ? a->bash.live : "", TUI_BASH_RUNNING, 0, a->bash.no_context};
(void)tui_bash_lines(&b, a->expand_tools, a->cols > 2 ? (size_t)a->cols : 2, &live);
}
size_t split = live.n; /* fullscreen: the transcript's live end, then the dock */
if (crow >= 0) {
crow += (int)live.n;
}
for (size_t i = 0; i < tail.n; i++) {
(void)tui_lines_add(&live, tail.lines[i], strlen(tail.lines[i]));
}
(void)tui_render_draw_split(a->r, (const char *const *)live.lines, live.n, split, crow, ccol, a->rows);
tui_lines_clear(&live);
tui_lines_clear(&tail);
}
/* ---- child processes -------------------------------------------------- */
/* The token that makes this interface the owner of its children's
* conversations for hooks (PIC_HOOK_OWNER): each child fires SessionStart
* once per conversation, and the interface ends them (hook_end). */
static char hook_owner[64];
/* argv for this pic with the journal, workspace and model, then ARGS. commands:
* its stdin is a pipe (c->in) for Pi's RPC lines, else /dev/null. */
static int spawn_in(app *a, child *c, const char *const *args, int commands) {
const char *argv[200];
char exec_s[16], window_s[24];
int n = 0, out[2], err[2], in[2] = {-1, -1}, keyfd;
argv[n++] = a->o->self;
argv[n++] = "--db";
argv[n++] = a->o->db;
argv[n++] = "--workspace";
argv[n++] = a->o->workspace;
argv[n++] = "--model";
argv[n++] = a->model;
(void)snprintf(exec_s, sizeof exec_s, "%d", a->o->exec_seconds);
argv[n++] = "--exec-timeout";
argv[n++] = exec_s;
if (a->o->context_window >= 0) {
(void)snprintf(window_s, sizeof window_s, "%ld", a->o->context_window);
argv[n++] = "--context-window";
argv[n++] = window_s;
}
if (a->o->system_replace) {
argv[n++] = "--system-prompt";
argv[n++] = a->o->system_replace;
}
for (size_t k = 0; k < a->o->system_nappend && n < 150; k++) {
argv[n++] = "--append-system-prompt";
argv[n++] = a->o->system_append[k];
}
if (a->o->tools) {
argv[n++] = "--tools";
argv[n++] = a->o->tools;
}
if (a->o->exclude_tools) {
argv[n++] = "--exclude-tools";
argv[n++] = a->o->exclude_tools;
}
if (a->o->no_tools) {
argv[n++] = "--no-tools";
}
if (a->o->no_builtin_tools) {
argv[n++] = "--no-builtin-tools";
}
ensure_level(a);
if (a->think_level[0] && a->level[0]) { /* the session's choice, clamped to this model */
argv[n++] = "--thinking";
argv[n++] = a->level;
}
for (; *args && n < 199; args++) {
argv[n++] = *args;
}
argv[n] = NULL;
memset(c, 0, sizeof *c);
c->in = c->out = c->err = -1;
if (pipe(out) != 0) {
return -1;
}
if (pipe(err) != 0) {
close(out[0]);
close(out[1]);
return -1;
}
if (commands && pipe(in) != 0) {
close(out[0]);
close(out[1]);
close(err[0]);
close(err[1]);
return -1;
}
/* Our ends must not leak into later children. */
(void)fcntl(out[0], F_SETFD, FD_CLOEXEC);
(void)fcntl(err[0], F_SETFD, FD_CLOEXEC);
if (commands) {
(void)fcntl(in[1], F_SETFD, FD_CLOEXEC);
}
/* The credential store's master key, when this process has unlocked it,
* goes to the child in a pipe it inherits (cred.h, pic_cred_handoff):
* the child has no terminal to ask on, and argv, the environment's
* values, the journal and files must never hold a key. Only this child
* gets the fd (it is close-on-exec until the child clears that), and the
* child closes it before it can start anything of its own. */
keyfd = pic_cred_handoff();
c->pid = fork();
if (c->pid == 0) {
int null = open("/dev/null", O_RDONLY);
if (keyfd >= 0) {
char num[16];
(void)fcntl(keyfd, F_SETFD, 0);
(void)snprintf(num, sizeof num, "%d", keyfd);
(void)setenv("PIC_KEY_FD", num, 1);
}
/* Its own session: no controlling terminal, so nothing it runs can
* read the keyboard from under the interface. */
(void)setsid();
if (commands) {
(void)dup2(in[0], STDIN_FILENO);
close(in[0]);
} else if (null >= 0) {
(void)dup2(null, STDIN_FILENO);
}
(void)dup2(out[1], STDOUT_FILENO);
(void)dup2(err[1], STDERR_FILENO);
close(out[0]);
close(out[1]);
close(err[0]);
close(err[1]);
(void)signal(SIGINT, SIG_DFL);
(void)signal(SIGPIPE, SIG_DFL);
(void)setenv("PIC_HOOK_OWNER", hook_owner, 1);
execv(a->o->self, (char *const *)(void *)argv);
_exit(127);
}
if (keyfd >= 0) {
close(keyfd);
}
close(out[1]);
close(err[1]);
if (commands) {
close(in[0]);
}
if (c->pid < 0) {
close(out[0]);
close(err[0]);
if (commands) {
close(in[1]);
}
return -1;
}
c->in = in[1];
c->out = out[0];
c->err = err[0];
(void)fcntl(c->out, F_SETFL, fcntl(c->out, F_GETFL) | O_NONBLOCK);
(void)fcntl(c->err, F_SETFL, fcntl(c->err, F_GETFL) | O_NONBLOCK);
return 0;
}
static int spawn(app *a, child *c, const char *const *args) { return spawn_in(a, c, args, 0); }
/* Reads what is available; 1 when both pipes are closed. */
static int drain(child *c) {
int fds[2] = {c->out, c->err};
text *bufs[2] = {&c->outbuf, &c->errbuf};
for (int i = 0; i < 2; i++) {
char buf[8192];
ssize_t n = -1; /* read() assigns it whenever the loop condition is reached */
while (fds[i] >= 0 && (n = read(fds[i], buf, sizeof buf)) != 0) {
if (n < 0) {
if (errno == EINTR) {
continue;
}
break; /* EAGAIN: later */
}
(void)text_add(bufs[i], buf, (size_t)n);
}
if (fds[i] >= 0 && n == 0) {
close(fds[i]);
fds[i] = -1;
}
}
c->out = fds[0];
c->err = fds[1];
return c->out < 0 && c->err < 0;
}
/* Runs pic with ARGS to the end; its stdout in *out (malloc'd). The exit
* status, or -1. Stderr lines are shown as notices. */
static int run_sync(app *a, const char *const *args, char **out) {
child c;
int status = 0;
*out = NULL;
if (spawn(a, &c, args) != 0) {
return -1;
}
while (!drain(&c)) {
struct pollfd p[2] = {{c.out, POLLIN, 0}, {c.err, POLLIN, 0}};
(void)poll(p, 2, 100);
}
while (waitpid(c.pid, &status, 0) < 0 && errno == EINTR) {
}
if (c.errbuf.len) {
notice(a, RED, "%.*s", (int)strcspn(c.errbuf.buf, "\n"), c.errbuf.buf);
}
free(c.errbuf.buf);
*out = c.outbuf.buf ? c.outbuf.buf : strdup("");
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}
/* SessionEnd for the conversations this interface's children began, when
* hooks are configured: on leaving them (/new, /resume) and on exit. */
static void hook_end(app *a, const char *reason) {
pic_hooks *h = pic_hooks_load(a->o->workspace, NULL, NULL);
if (h) {
const char *args[] = {"hooks", "end", reason, NULL};
char *out = NULL;
(void)run_sync(a, args, &out);
free(out);
pic_hooks_free(h);
}
}
/* ---- "!" and "!!": a command the user runs ------------------------------ */
/* The command runs as `pic bash`, which journals it as Pi's bashExecution
* message (so it survives a restart and reaches the model with the next
* request unless it is "!!"). Its events are the output so far, then Pi's
* bash response. */
static void bash_settle(app *a) {
free(a->bash.cmd);
free(a->bash.live);
free(a->bash.final);
free(a->bash.c.outbuf.buf);
free(a->bash.c.errbuf.buf);
if (a->bash.running) { /* the fds are only meaningful while it runs (the app starts zeroed) */
if (a->bash.c.out >= 0) {
close(a->bash.c.out);
}
if (a->bash.c.err >= 0) {
close(a->bash.c.err);
}
}
memset(&a->bash, 0, sizeof a->bash);
a->bash.c.in = a->bash.c.out = a->bash.c.err = -1;
}
static int drop_unfinished(app *a);
static int bash_start(app *a, const char *cmd, int no_context) {
const char *args[10];
int n = 0;
bash_settle(a);
if (a->unfinished[0] && drop_unfinished(a) != 0) {
return -1;
}
args[n++] = "--json";
args[n++] = "bash";
if (no_context) {
args[n++] = "--no-context";
}
if (a->conversation[0]) {
args[n++] = "--session";
args[n++] = a->conversation;
}
args[n++] = cmd;
args[n] = NULL;
if (spawn(a, &a->bash.c, args) != 0) {
bash_settle(a);
return -1;
}
a->bash.running = 1;
a->bash.no_context = no_context;
a->bash.cmd = strdup(cmd);
return 0;
}
/* Esc on a running command: SIGINT (pic bash cancels and journals it); Esc
* again, or a grace period, SIGTERM and then SIGKILL. */
static void bash_cancel(app *a) {
if (!a->bash.running) {
return;
}
if (!a->bash.cancelled) {
a->bash.cancelled = 1;
a->bash.kill_at = now_ms() + 5000;
(void)kill(a->bash.c.pid, SIGINT);
} else if (a->bash.kill_level < 2) {
(void)kill(a->bash.c.pid, ++a->bash.kill_level == 1 ? SIGTERM : SIGKILL);
a->bash.kill_at = now_ms() + 2000;
}
}
static void bash_event(app *a, const char *ev) {
char *type = jget(a, ev, "$.type");
if (type && strcmp(type, "bash_execution_update") == 0) {
free(a->bash.live);
a->bash.live = jget(a, ev, "$.output");
} else if (type && strcmp(type, "response") == 0 && jnum(a, ev, "$.success")) {
char *conv = jget(a, ev, "$.data.conversation"), *code = jget(a, ev, "$.data.exitCode");
free(a->bash.final);
a->bash.final = jget(a, ev, "$.data.output");
a->bash.has_exit = code != NULL;
a->bash.exit_code = code ? atoi(code) : 0;
a->bash.cancelled = a->bash.cancelled || jnum(a, ev, "$.data.cancelled") == 1;
a->bash.got_resp = 1;
if (conv && *conv) {
(void)snprintf(a->conversation, sizeof a->conversation, "%s", conv);
}
free(conv);
free(code);
}
free(type);
}
/* Reads the events so far and, when pic bash has exited, commits the block. */
static void bash_pump(app *a) {
int status = 0, code;
tui_bash b;
text *ob = &a->bash.c.outbuf;
size_t used = 0;
if (!a->bash.running) {
return;
}
(void)drain(&a->bash.c);
while (ob->buf && used < ob->len) {
char *nl = memchr(ob->buf + used, '\n', ob->len - used);
if (!nl) {
break;
}
*nl = '\0';
bash_event(a, ob->buf + used);
used = (size_t)(nl - ob->buf) + 1;
}
if (used) {
memmove(ob->buf, ob->buf + used, ob->len - used);
ob->len -= used;
ob->buf[ob->len] = '\0';
}
if (waitpid(a->bash.c.pid, &status, WNOHANG) != a->bash.c.pid) {
if (a->bash.cancelled && a->bash.kill_level < 2 && now_ms() > a->bash.kill_at) {
bash_cancel(a);
}
return;
}
(void)drain(&a->bash.c);
if (ob->len) { /* a last line with no newline */
bash_event(a, ob->buf);
}
if (!a->bash.got_resp) { /* it never answered: nothing was journaled */
if (a->bash.c.errbuf.len) {
notice(a, RED, "%.*s", (int)strcspn(a->bash.c.errbuf.buf, "\n"), a->bash.c.errbuf.buf);
}
if (!a->bash.cancelled) {
notice(a, RED, "pic: the command was not run (exit %d)", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
bash_settle(a);
return;
}
}
code = a->bash.has_exit ? a->bash.exit_code : 0;
b = (tui_bash){a->bash.cmd, a->bash.final ? a->bash.final : a->bash.live ? a->bash.live : "",
a->bash.cancelled ? TUI_BASH_CANCELLED : TUI_BASH_DONE, code, a->bash.no_context};
commit_bash(a, &b);
bash_settle(a);
}
/* A message starting with "!" or "!!": run the rest as a command (Pi's handler
* in interactive-mode.ts). 1 when it was handled. */
static int run_bang(app *a, const char *msg) {
int excluded = msg[0] == '!' && msg[1] == '!';
const char *cmd = msg + (excluded ? 2 : 1);
size_t n;
char *copy;
if (msg[0] != '!') {
return 0;
}
cmd += strspn(cmd, " \t\n");
n = strlen(cmd);
while (n > 0 && strchr(" \t\n", cmd[n - 1])) {
n--;
}
if (n == 0) {
return 0; /* a lone "!" is an ordinary message */
}
if (a->working || a->bash.running) {
notice(a, YELLOW, "Warning: %s", a->working ? "a reply is running: stop it (esc) before running a bash command"
: "A bash command is already running. Press Esc to cancel it first.");
tui_editor_set(a->ed, msg);
return 1;
}
copy = strndup(cmd, n);
if (!copy || bash_start(a, copy, excluded) != 0) {
notice(a, RED, "pic: could not run the command: %s", strerror(errno));
}
free(copy);
return 1;
}
/* ---- requests and their events ----------------------------------------- */
/* A file descriptor holding IM's bytes, at offset 0: an unlinked temporary
* file, so ask's --image reads it as /dev/fd/N and nothing stays on disk. -1
* when it cannot be made. */
static int image_fd(const tui_attachment *im) {
FILE *f = tmpfile();
int fd = -1;
if (!f) {
return -1;
}
if (fwrite(im->data, 1, im->len, f) == im->len && fflush(f) == 0 && (fd = dup(fileno(f))) >= 0 &&
lseek(fd, 0, SEEK_SET) != 0) {
close(fd);
fd = -1;
}
(void)fclose(f);
return fd;
}
static void reset_screen(app *a);
/* The request's key is in the credential store and this process has not
* unlocked it: ask for the passphrase here, on the terminal (the request
* child has none), so the child gets the key by pic_cred_handoff. 0 to go
* on, -1 when it stays locked (the error is shown). */
static int unlock_for(app *a, const char *model) {
pic_model m;
char err[256];
int rc;
if (pic_model_resolve(model, &m, err, sizeof err) != 0 || !pic_cred_needs_unlock(m.provider, m.key_env, m.key_literal)) {
return 0;
}
(void)tui_render_pause(a->r);
tui_term_restore();
printf("The API key for %s is in pic's credential store.\n", m.provider);
(void)fflush(stdout);
rc = pic_cred_unlock(err, sizeof err);
reset_screen(a);
if (rc != 0) {
notice(a, RED, "pic: %s", err);
return -1;
}
return 0;
}
static void request_started(app *a, const char *what);
static void start_request(app *a, const char *msg, const tui_attachment *images, size_t nimages) {
const char *args[4 + 2 * PIC_REQUEST_IMAGES + 2];
char paths[PIC_REQUEST_IMAGES][24];
int fds[PIC_REQUEST_IMAGES], n = 0, nfd = 0, bad = 0;
if (unlock_for(a, a->model) != 0) {
tui_editor_set(a->ed, msg);
return;
}
args[n++] = "--json";
args[n++] = "--commands";
args[n++] = "ask";
if (a->conversation[0]) {
args[n++] = "--session";
args[n++] = a->conversation;
} else if (a->o->new_id) {
args[n++] = "--session-id";
args[n++] = a->o->new_id;
}
for (size_t i = 0; i < nimages && nfd < PIC_REQUEST_IMAGES; i++) {
if ((fds[nfd] = image_fd(&images[i])) < 0) {
bad = 1;
break;
}
(void)snprintf(paths[nfd], sizeof paths[nfd], "/dev/fd/%d", fds[nfd]);
args[n++] = "--image";
args[n++] = paths[nfd++];
}
args[n++] = msg;
args[n] = NULL;
if (bad) {
for (int i = 0; i < nfd; i++) {
close(fds[i]);
}
notice(a, RED, "pic: could not hold the attached images: %s", strerror(errno));
return;
}
if (a->unfinished[0] && drop_unfinished(a) != 0) { /* a new message leaves the interrupted one, as Pi's does */
for (int i = 0; i < nfd; i++) {
close(fds[i]);
}
tui_editor_set(a->ed, msg);
return;
}
commit_user(a, msg);
n = spawn_in(a, &a->run, args, 1);
for (int i = 0; i < nfd; i++) {
close(fds[i]);
}
if (n != 0) {
notice(a, RED, "pic: could not start the request: %s", strerror(errno));
return;
}
{
char what[PATH_MAX + 8];
(void)snprintf(what, sizeof what, "pic --json ask %.200s", msg);
request_started(a, what);
}
}
/* Drops the interrupted request (pic cancel journals it, as Esc's abort
* would have): its prompt stays in the conversation, its reply never comes.
* 0 when dropped. */
static int drop_unfinished(app *a) {
const char *args[] = {"cancel", a->unfinished, NULL};
char *out = NULL;
int rc = run_sync(a, args, &out);
free(out);
if (rc != 0) {
notice(a, RED, "pic: could not drop the interrupted request");
return -1;
}
a->unfinished[0] = '\0';
notice(a, DIM, "interrupted request dropped");
return 0;
}
/* Finishes the interrupted request here, as `pic run --session` does: with
* the model and thinking level it was admitted with, its events shown as a
* request's. */
static void resume_unfinished(app *a) {
const char *args[] = {"--json", "--commands", "run", "--session", a->conversation, NULL};
if (unlock_for(a, a->unfinished_model[0] ? a->unfinished_model : a->model) != 0) { /* its own model's key */
return;
}
if (spawn_in(a, &a->run, args, 1) != 0) {
notice(a, RED, "pic: could not resume the request: %s", strerror(errno));
return;
}
request_started(a, "pic --json run --session");
a->resuming = 1; /* the offer stands until the request has ended */
}
/* Pi's /compact: at once, in a child whose events (compaction_start and
* _end) show it running and its result; Esc stops it as it does a reply. */
static void compact_start(app *a, const char *focus) {
const char *args[] = {"--json", "compact", "--now", a->conversation, *focus ? focus : NULL, NULL};
if (!a->conversation[0]) {
notice(a, RED, "Nothing to compact (session too small)");
return;
}
if (unlock_for(a, a->model) != 0) {
return;
}
if (spawn_in(a, &a->run, args, 0) != 0) {
notice(a, RED, "pic: could not start the compaction: %s", strerror(errno));
return;
}
request_started(a, "pic --json compact --now");
a->compacting = 1;
}
/* The bookkeeping of a request child just started (a->run). */
static void request_started(app *a, const char *what) {
child_pid = a->run.pid;
pic_proc_scope(a->o->workspace, a->conversation);
a->run.proc = pic_proc_start("tui-request", what, (long)a->run.pid, (long)a->run.pid);
a->working = 1;
a->interrupted = a->seen_end = 0;
a->abort_sent = a->clear_sent = a->clear_notice = 0;
a->skip_user = 1;
a->finishing = 0;
a->status[0] = '\0';
a->retried = a->retry_n = 0;
(void)thinking_hidden(a);
}
/* A line of Pi's RPC commands to the running request: 0 when it was written. */
static int send_command(app *a, const char *json) {
size_t n = strlen(json), at = 0;
ssize_t w = 0;
if (a->run.in < 0) {
return -1;
}
/* A line with an image is megabytes: the child reads while this writes. A
* full pipe is a stuck child. */
while (at < n && (w = write(a->run.in, json + at, n - at)) > 0) {
at += (size_t)w;
}
if (at == n) {
w = write(a->run.in, "\n", 1);
}
if (w < 0) {
close(a->run.in);
a->run.in = -1;
return -1;
}
return 0;
}
/* {"type":TYPE,"message":MSG} as a line, MSG JSON-escaped through SQLite. */
static int send_message(app *a, const char *type, const char *msg, const tui_attachment *images, size_t nimages) {
sqlite3_stmt *q = NULL;
text arr = {NULL, 0, 0};
int rc = -1;
if (a->run.in < 0 ||
sqlite3_prepare_v2(a->db, "SELECT json_object('type', ?1, 'message', ?2, 'images', json(?3))", -1, &q, NULL) !=
SQLITE_OK) {
return -1;
}
/* Pi's ImageContent blocks: {"type":"image","data":BASE64,"mimeType":TYPE}; both are plain. */
(void)text_add(&arr, "[", 1);
for (size_t i = 0; i < nimages; i++) {
const char *mime = pic_image_sniff(images[i].data, images[i].len);
char *b64 = malloc(4 * ((images[i].len + 2) / 3) + 1);
if (!b64 || !mime) {
free(b64);
free(arr.buf);
sqlite3_finalize(q);
return -1;
}
(void)pic_base64_encode(images[i].data, images[i].len, b64);
const char *head = i ? ",{\"type\":\"image\",\"data\":\"" : "{\"type\":\"image\",\"data\":\"",
*mid = "\",\"mimeType\":\"", *tail = "\"}";
(void)text_add(&arr, head, strlen(head));
(void)text_add(&arr, b64, strlen(b64));
(void)text_add(&arr, mid, strlen(mid));
(void)text_add(&arr, mime, strlen(mime));
(void)text_add(&arr, tail, strlen(tail));
free(b64);
}
(void)text_add(&arr, "]", 1);
sqlite3_bind_text(q, 1, type, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, msg, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 3, arr.buf ? arr.buf : "[]", -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
rc = send_command(a, (const char *)sqlite3_column_text(q, 0));
}
sqlite3_finalize(q);
free(arr.buf);
return rc;
}
static void block_free(toolblk *b) {
free(b->title);
free(b->diff);
free(b->output);
free(b->content);
memset(b, 0, sizeof *b);
}
static void block_lines(const toolblk *b, int expanded, size_t cols, tui_lines *out) {
tui_tool t = {b->name, b->title ? b->title : "", b->diff, b->output, b->state,
b->state == TUI_TOOL_PENDING ? now_ms() - b->start_ms : b->took_ms, b->content};
(void)tui_tool_lines(&t, expanded, cols > 2 ? cols : 2, out);
}
/* Commits the finished blocks at the front, in the state ctrl+o has now; a
* pending one holds back the rest so the order is kept. force: all of them
* (the request is over: a pending one never finished and is dropped). */
static void blocks_flush(app *a, int force) {
int n = 0;
while (n < a->nblocks && (a->blocks[n].state != TUI_TOOL_PENDING || force)) {
if (a->blocks[n].state != TUI_TOOL_PENDING) {
const toolblk *b = &a->blocks[n];
tui_tool t = {b->name, b->title ? b->title : "", b->diff, b->output, b->state, b->took_ms, b->content};
commit_tool(a, &t);
}
block_free(&a->blocks[n]);
n++;
}
memmove(a->blocks, a->blocks + n, (size_t)(a->nblocks - n) * sizeof *a->blocks);
a->nblocks -= n;
}
/* What a call acts on, from its arguments: bash's command, read's path and
* range, write's path and size, edit's path, the pattern of find and grep. */
static void tool_title(app *a, const char *ev, const char *name, char *out, size_t cap) {
char *cmd = jget(a, ev, "$.args.command"), *path = jget(a, ev, "$.args.path"),
*pattern = jget(a, ev, "$.args.pattern"), *content = jget(a, ev, "$.args.content");
long long offset = jnum(a, ev, "$.args.offset"), limit = jnum(a, ev, "$.args.limit"),
timeout = jnum(a, ev, "$.args.timeout");
size_t n = 0;
out[0] = '\0';
if (strcmp(name, "bash") == 0) {
n = (size_t)snprintf(out, cap, "$ %s", cmd ? cmd : "...");
if (timeout > 0 && n < cap) {
(void)snprintf(out + n, cap - n, " (timeout %llds)", timeout);
}
} else if (strcmp(name, "read") == 0) {
n = (size_t)snprintf(out, cap, "%s", path ? path : "");
if ((offset > 0 || limit > 0) && n < cap) {
if (limit > 0) {
(void)snprintf(out + n, cap - n, ":%lld-%lld", offset > 0 ? offset : 1, (offset > 0 ? offset : 1) + limit - 1);
} else {
(void)snprintf(out + n, cap - n, ":%lld", offset);
}
}
} else if (strcmp(name, "write") == 0) {
size_t len = content ? strlen(content) : 0, lines = 0;
char size[24];
for (size_t i = 0; i < len; i++) {
lines += content[i] == '\n';
}
lines += len > 0 && content[len - 1] != '\n';
tui_fmt_size(len, size, sizeof size);
(void)snprintf(out, cap, "%s (%zu %s, %s)", path ? path : "", lines, lines == 1 ? "line" : "lines", size);
} else if (pattern) {
(void)snprintf(out, cap, "%s%s%s", pattern, path ? " in " : "", path ? path : "");
} else {
(void)snprintf(out, cap, "%s", cmd ? cmd : path ? path : "");
}
free(cmd);
free(path);
free(pattern);
free(content);
}
/* The file an edit touches (workspace-relative paths resolved), up to 8 MB; NULL when unreadable. */
static char *edit_file(app *a, const char *ev) {
char *path = jget(a, ev, "$.args.path"), full[PATH_MAX * 2], *buf = NULL;
FILE *f;
long n;
if (!path) {
return NULL;
}
(void)snprintf(full, sizeof full, "%s%s%s", path[0] == '/' ? "" : a->o->workspace, path[0] == '/' ? "" : "/", path);
free(path);
f = fopen(full, "rb");
if (!f) {
return NULL;
}
if (fseek(f, 0, SEEK_END) == 0 && (n = ftell(f)) >= 0 && n <= 8L << 20 && fseek(f, 0, SEEK_SET) == 0 &&
(buf = malloc((size_t)n + 1)) != NULL) {
if (fread(buf, 1, (size_t)n, f) != (size_t)n) {
free(buf);
buf = NULL;
} else {
buf[n] = '\0';
}
}
(void)fclose(f);
return buf;
}
static long count_lines(const char *s) {
long n = 1;
for (; *s; s++) {
n += *s == '\n';
}
return n;
}
/* The 1-based line of the first occurrence of needle in hay; 0 when absent or empty. */
static long line_of(const char *hay, const char *needle) {
const char *at = *needle ? strstr(hay, needle) : NULL;
long n = 1;
if (!at) {
return 0;
}
for (; hay < at; hay++) {
n += *hay == '\n';
}
return n;
}
/* An edit's diff, one hunk per replacement ({oldText,newText} in edits[], or at the top level),
* with Pi's line numbers when the file can be read: old lines by the file as it was, new lines
* shifted by the earlier replacements. The tool has usually not run yet; when it has, the
* replacement is found by its new text instead. */
static char *edit_diff(app *a, const char *ev) {
text all = {NULL, 0, 0};
char *file = edit_file(a, ev);
long delta = 0, total = 0;
int width = 0;
for (int pass = 0; pass < 2; pass++) {
delta = 0;
for (int i = 0; i < 64; i++) {
char key[2][48], *old, *new_;
(void)snprintf(key[0], sizeof key[0], "$.args.edits[%d].oldText", i);
(void)snprintf(key[1], sizeof key[1], "$.args.edits[%d].newText", i);
old = jget(a, ev, key[0]);
new_ = jget(a, ev, key[1]);
if (i == 0 && !old && !new_) {
old = jget(a, ev, "$.args.oldText");
new_ = jget(a, ev, "$.args.newText");
}
if (old || new_) {
const char *o = old ? old : "", *n = new_ ? new_ : "";
if (pass == 0) {
total += count_lines(n) - count_lines(o);
} else {
long ol = file ? line_of(file, o) : 0, nl;
char *d;
if (file && !ol) { /* already applied: the new text is in the file */
long at = line_of(file, n);
nl = at;
ol = at ? at - delta : 0;
} else {
nl = ol + delta;
}
d = tui_diff_numbered(o, n, ol ? ol : 1, nl ? nl : 1, ol ? width : 0);
if (d && *d) {
if (all.len) {
(void)text_add(&all, "\n \xe2\x80\xa6\n", 6);
}
(void)text_add(&all, d, strlen(d));
}
free(d);
}
delta += count_lines(n) - count_lines(o);
}
free(old);
free(new_);
if (!old && !new_) {
break;
}
}
if (pass == 0) {
long fl = file ? count_lines(file) : 0, big = fl + (total > 0 ? total : 0);
for (width = 1; big >= 10; big /= 10) {
width++;
}
total = 0;
}
}
free(file);
return all.buf;
}
static void tool_start(app *a, const char *ev) {
char *name = jget(a, ev, "$.toolName"), *id = jget(a, ev, "$.toolCallId"), title[1024];
toolblk *grown = realloc(a->blocks, (size_t)(a->nblocks + 1) * sizeof *grown), *b;
if (grown) {
a->blocks = grown;
b = &a->blocks[a->nblocks++];
memset(b, 0, sizeof *b);
(void)snprintf(b->name, sizeof b->name, "%s", name ? name : "tool");
(void)snprintf(b->id, sizeof b->id, "%s", id ? id : "");
tool_title(a, ev, b->name, title, sizeof title);
b->title = strdup(title);
b->diff = strcmp(b->name, "edit") == 0 ? edit_diff(a, ev) : NULL;
b->content = strcmp(b->name, "write") == 0 ? jget(a, ev, "$.args.content") : NULL;
b->start_ms = now_ms();
}
free(name);
free(id);
}
static void tool_end(app *a, const char *ev) {
char *id = jget(a, ev, "$.toolCallId"), *result = jget(a, ev, "$.result.content[0].text");
toolblk *b = NULL;
for (int i = 0; i < a->nblocks; i++) {
if (a->blocks[i].state == TUI_TOOL_PENDING && (!id || !a->blocks[i].id[0] || strcmp(a->blocks[i].id, id) == 0)) {
b = &a->blocks[i];
break;
}
}
if (b) {
b->state = jnum(a, ev, "$.isError") ? TUI_TOOL_ERROR : TUI_TOOL_OK;
b->took_ms = now_ms() - b->start_ms;
free(b->output); /* the live tail */
b->output = result ? result : strdup("");
result = NULL;
}
free(id);
free(result);
}
static void qfree(char **q, int *n) {
for (int i = 0; i < *n; i++) {
free(q[i]);
}
*n = 0;
}
/* The strings of an array at PATH ("$.steering") into q. */
static void qload(app *a, const char *ev, const char *path, char **q, int *n) {
qfree(q, n);
for (int i = 0; i < MAX_QUEUED; i++) {
char key[48], *t;
(void)snprintf(key, sizeof key, "%s[%d]", path, i);
if (!(t = jget(a, ev, key))) {
break;
}
q[(*n)++] = t;
}
}
/* Everything the child still holds (its queue, and what was sent and not yet
* answered) back to the editor, with a note: the request ended without
* running it. Pi puts queued messages back in the editor the same way. */
static void restore_held(app *a, int announce) {
char *all[3 * MAX_QUEUED];
int n = 0;
for (int i = 0; i < a->nsteer && n < 3 * MAX_QUEUED; i++) {
all[n++] = a->steer_q[i];
}
for (int i = 0; i < a->nfollow && n < 3 * MAX_QUEUED; i++) {
all[n++] = a->follow_q[i];
}
for (int i = 0; i < a->nsent && n < 3 * MAX_QUEUED; i++) {
all[n++] = a->sent_q[i];
}
if (n) {
restore_texts(a, all, n);
if (announce) {
notice(a, DIM, "Restored %d queued message%s to editor", n, n > 1 ? "s" : "");
}
}
qfree(a->steer_q, &a->nsteer);
qfree(a->follow_q, &a->nfollow);
qfree(a->sent_q, &a->nsent);
}
static void on_event(app *a, const char *ev) {
char *type = jget(a, ev, "$.type");
if (!type) {
return;
}
if (strcmp(type, "agent_start") == 0) {
char *conv = jget(a, ev, "$.conversation"), *model = jget(a, ev, "$.model");
if (conv) {
(void)snprintf(a->conversation, sizeof a->conversation, "%s", conv);
}
if (model && *model) {
(void)snprintf(a->model, sizeof a->model, "%s", model);
}
a->window = jnum(a, ev, "$.contextWindow");
a->finishing = 0;
free(conv);
free(model);
} else if (strcmp(type, "message_update") == 0) {
char *kind = jget(a, ev, "$.assistantMessageEvent.type"), *delta = jget(a, ev, "$.assistantMessageEvent.delta");
if (kind && delta && (strcmp(kind, "text_delta") == 0 || strcmp(kind, "thinking_delta") == 0)) {
blocks_flush(a, 0); /* the reply goes below the tool calls before it */
a->retry_n = 0;
if (strcmp(kind, "text_delta") == 0 && a->thinking.len) {
commit_thinking(a); /* the thinking is over: it goes above the text it precedes */
}
/* Thinking is always kept; whether it is shown is decided when it is committed. */
(void)text_add(strcmp(kind, "text_delta") == 0 ? &a->stream : &a->thinking, delta, strlen(delta));
}
free(kind);
free(delta);
} else if (strcmp(type, "message_end") == 0) {
char *role = jget(a, ev, "$.message.role"), *stop = jget(a, ev, "$.message.stopReason");
if (role && strcmp(role, "assistant") == 0) {
if (stop && strcmp(stop, "aborted") == 0) {
/* Pi's abort: what streamed stays on screen (agent_end commits it);
* it is not in the context, and nothing is asked again. */
} else if (stop && strcmp(stop, "error") == 0) {
char *err = jget(a, ev, "$.message.errorMessage");
/* The partial reply is dropped. A long one may have had finished
* lines committed already; say so rather than leave them
* unexplained (auto_retry_start says whether it is asked again). */
if (a->stream_off > 0) {
notice(a, YELLOW, "(the reply above was cut off)");
}
text_clear(&a->stream);
text_clear(&a->thinking);
a->stream_off = 0;
a->stream_fence = 0;
(void)snprintf(a->status, sizeof a->status, "reply failed: %s", err ? err : "error");
free(err);
} else {
long long in = jnum(a, ev, "$.message.usage.input"), out = jnum(a, ev, "$.message.usage.output"),
cr = jnum(a, ev, "$.message.usage.cacheRead"), cw = jnum(a, ev, "$.message.usage.cacheWrite");
char *cost = jget(a, ev, "$.message.usage.cost.total");
if (cost) { /* priced models only: nothing shows when absent */
a->cost += strtod(cost, NULL);
free(cost);
}
a->in += in;
a->out += out;
a->cache_read += cr;
a->cache_write += cw;
if (in + cr + cw + out > 0) {
a->context = in + cr + cw + out;
}
commit_stream(a);
a->status[0] = '\0';
a->retry_n = 0;
a->finishing = stop && strcmp(stop, "toolUse") != 0 && a->nsteer == 0 && a->nfollow == 0;
if (stop && (strcmp(stop, "length") == 0 || strcmp(stop, "max_tokens") == 0)) {
notice(a, RED, "Response was truncated before completion.");
}
}
}
free(role);
free(stop);
} else if (strcmp(type, "auto_retry_start") == 0) {
a->retry_n = (int)jnum(a, ev, "$.attempt");
a->retry_max = (int)jnum(a, ev, "$.maxAttempts");
a->retry_delay = (long)jnum(a, ev, "$.delayMs");
a->retry_at = now_ms();
a->retried = a->retry_n;
a->status[0] = '\0'; /* draw shows the live countdown instead */
} else if (strcmp(type, "queue_update") == 0) {
qload(a, ev, "$.steering", a->steer_q, &a->nsteer);
qload(a, ev, "$.followUp", a->follow_q, &a->nfollow);
/* What the child lists is journaled: nothing of ours is in flight any more. */
qfree(a->sent_q, &a->nsent);
} else if (strcmp(type, "queue_returned") == 0) {
/* The request ended without running what it still held. */
qload(a, ev, "$.steering", a->steer_q, &a->nsteer);
qload(a, ev, "$.followUp", a->follow_q, &a->nfollow);
restore_held(a, 1);
} else if (strcmp(type, "message_start") == 0) {
char *role = jget(a, ev, "$.message.role");
if (role && strcmp(role, "user") == 0) {
if (a->skip_user) { /* the request's own text, shown when it was sent */
a->skip_user = 0;
} else { /* steering or a follow-up, delivered where it lands in the reply */
char *t = jget(a, ev, "$.message.content[0].text");
if (t) {
blocks_flush(a, 0);
commit_stream(a);
commit_user(a, t);
free(t);
}
}
}
free(role);
} else if (strcmp(type, "response") == 0) {
char *cmd = jget(a, ev, "$.command");
int ok = jnum(a, ev, "$.success") == 1;
if (cmd && (strcmp(cmd, "steer") == 0 || strcmp(cmd, "follow_up") == 0)) {
if (a->nsent > 0) { /* answered in order: journaled, or refused */
if (!ok) {
char *err = jget(a, ev, "$.error");
notice(a, RED, "%s", err ? err : "the message was not queued");
free(err);
restore_texts(a, a->sent_q, 1);
}
free(a->sent_q[0]);
memmove(a->sent_q, a->sent_q + 1, (size_t)(a->nsent - 1) * sizeof *a->sent_q);
a->nsent--;
}
} else if (cmd && strcmp(cmd, "clear_queue") == 0) {
char *got[2 * MAX_QUEUED + MAX_QUEUED];
int n = 0;
a->clear_sent = 0;
for (int i = 0; ok && i < MAX_QUEUED; i++) {
char key[48];
(void)snprintf(key, sizeof key, "$.data.steering[%d]", i);
if (!(got[n] = jget(a, ev, key))) {
break;
}
n++;
}
for (int i = 0; ok && i < MAX_QUEUED; i++) {
char key[48];
(void)snprintf(key, sizeof key, "$.data.followUp[%d]", i);
if (!(got[n] = jget(a, ev, key))) {
break;
}
n++;
}
for (int i = 0; i < a->nqueue && n < 3 * MAX_QUEUED; i++) {
got[n++] = a->queue[i];
}
if (n) {
restore_texts(a, got, n);
}
if (a->clear_notice) {
if (n) {
notice(a, DIM, "Restored %d queued message%s to editor", n, n > 1 ? "s" : "");
} else {
notice(a, DIM, "No queued messages to restore");
}
}
for (int i = 0; i < n - a->nqueue; i++) {
free(got[i]);
}
for (int i = 0; i < a->nqueue; i++) {
free(a->queue[i]);
}
a->nqueue = 0;
qfree(a->steer_q, &a->nsteer);
qfree(a->follow_q, &a->nfollow);
qfree(a->sent_q, &a->nsent);
a->clear_notice = 0;
}
free(cmd);
} else if (strcmp(type, "tool_execution_update") == 0) {
char *id = jget(a, ev, "$.toolCallId"), *part = jget(a, ev, "$.partialResult.content[0].text");
for (int i = 0; part && i < a->nblocks; i++) {
if (a->blocks[i].state == TUI_TOOL_PENDING && (!id || !a->blocks[i].id[0] || strcmp(a->blocks[i].id, id) == 0)) {
free(a->blocks[i].output);
a->blocks[i].output = part;
part = NULL;
break;
}
}
free(id);
free(part);
} else if (strcmp(type, "tool_execution_start") == 0) {
a->finishing = 0;
commit_stream(a);
tool_start(a, ev);
} else if (strcmp(type, "tool_execution_end") == 0) {
tool_end(a, ev);
} else if (strcmp(type, "compaction_start") == 0) {
(void)snprintf(a->status, sizeof a->status, "Compacting the conversation\xe2\x80\xa6");
} else if (strcmp(type, "compaction_end") == 0) {
char *err = jget(a, ev, "$.errorMessage");
if (a->compacting) {
a->seen_end = 1; /* /compact's result is this */
}
if (err && strcmp(err, "Compaction cancelled") == 0) {
notice(a, RED, "%s", err);
} else if (err) {
notice(a, RED, "compaction failed: %s", err);
} else {
notice(a, DIM, "\xe2\x94\x80 compacted %lld tokens of history into a summary \xe2\x94\x80",
jnum(a, ev, "$.result.tokensBefore"));
}
a->status[0] = '\0';
free(err);
} else if (strcmp(type, "agent_end") == 0) {
char *status = jget(a, ev, "$.status"), *err = jget(a, ev, "$.errorMessage");
blocks_flush(a, 1);
commit_stream(a);
a->seen_end = 1;
if (status && strcmp(status, "failed") == 0) {
if (err && strcmp(err, "cancelled") == 0) {
notice(a, RED, "Operation aborted"); /* Pi's words for an abort */
} else if (a->retried > 0) {
notice(a, RED, "Retry failed after %d attempts: %s", a->retried, err ? err : "Unknown error");
} else {
notice(a, RED, "request failed: %s", err ? err : "");
}
} else if (status && strcmp(status, "stopped") == 0) {
char *why = jget(a, ev, "$.stopReason");
notice(a, YELLOW, "request stopped (%s); send a message to continue", why ? why : "");
free(why);
}
a->status[0] = '\0';
a->retry_n = 0;
(void)tui_git_branch(a->o->workspace, a->branch, sizeof a->branch); /* the agent may have switched it */
free(status);
free(err);
}
free(type);
}
static void app_command(app *a, char *line);
/* Queued commands, then the next message, once nothing holds the journal. */
static void run_queued(app *a) {
while (a->nqueue && !a->working && !a->bash.running && !a->quit) {
char *next = a->queue[0];
memmove(a->queue, a->queue + 1, (size_t)(a->nqueue - 1) * sizeof *a->queue);
a->nqueue--;
if (next[0] == '/' && !template_for(a, next) && !skill_for(a, next)) {
app_command(a, next);
} else {
start_request(a, next, NULL, 0);
}
free(next);
}
}
/* Handles complete event lines; at the end of the child, settles the run. */
static void app_pump(app *a) {
int done = drain(&a->run);
char *s = a->run.outbuf.buf;
size_t used = 0;
while (s && used < a->run.outbuf.len) {
char *nl = memchr(s + used, '\n', a->run.outbuf.len - used);
if (!nl) {
break;
}
*nl = '\0';
on_event(a, s + used);
used = (size_t)(nl - s) + 1;
}
if (used) {
memmove(s, s + used, a->run.outbuf.len - used);
a->run.outbuf.len -= used;
s[a->run.outbuf.len] = '\0';
}
/* Settled when the child has exited (not at end of output: a command it
* started in the background may hold the pipes open). Then read what is
* left and stop listening. */
{
int status = 0;
pid_t w = waitpid(a->run.pid, &status, WNOHANG);
(void)done;
if (w != a->run.pid) {
if (a->stop_at && now_ms() - a->stop_at > STOP_GRACE_MS * a->stop_level && a->stop_level < 3) {
/* Not stopping on SIGINT: SIGTERM, then SIGKILL (the journal recovers). */
a->stop_level++;
(void)kill(a->run.pid, a->stop_level == 2 ? SIGTERM : SIGKILL);
}
return;
}
run_ended(&a->run, status);
(void)drain(&a->run);
if (a->run.outbuf.len) {
(void)text_add(&a->run.outbuf, "\n", 1);
for (char *line = a->run.outbuf.buf, *nl; line && *line; line = nl + 1) {
nl = strchr(line, '\n');
*nl = '\0';
on_event(a, line);
}
}
if (a->run.out >= 0) {
close(a->run.out);
}
if (a->run.err >= 0) {
close(a->run.err);
}
if (a->run.in >= 0) {
close(a->run.in);
}
child_pid = 0;
a->abort_sent = a->clear_sent = a->clear_notice = 0;
a->stop_at = 0;
a->stop_level = 0;
commit_stream(a);
if (a->compacting) { /* Pi's showError: "Nothing to compact (session too small)", "Already compacted" */
const char *e = a->run.errbuf.buf ? a->run.errbuf.buf : "";
size_t n = strlen(e);
while (n && (e[n - 1] == '\n' || e[n - 1] == '\r')) {
n--;
}
if (!a->seen_end && WIFEXITED(status) && WEXITSTATUS(status) != 0 && n) {
notice(a, RED, "%.*s", (int)(strncmp(e, "pic: ", 5) == 0 ? n - 5 : n), strncmp(e, "pic: ", 5) == 0 ? e + 5 : e);
}
a->seen_end = 1;
a->compacting = 0;
}
if (a->resuming) { /* ended: done with it; else the offer stands (no key here, say) */
int ended = a->seen_end;
a->resuming = 0;
if (ended) {
a->unfinished[0] = '\0';
} else {
if (a->run.errbuf.len) {
notice(a, RED, "%s", a->run.errbuf.buf);
}
notice(a, YELLOW, "the last request was interrupted: Enter to resume, Esc to drop it");
a->seen_end = 1;
}
}
if (!a->seen_end) {
if (a->run.errbuf.len) {
notice(a, RED, "%s", a->run.errbuf.buf);
}
if (WIFSIGNALED(status)) {
notice(a, RED, "the request stopped (signal %d)", WTERMSIG(status));
} else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
notice(a, RED, "the request failed (exit %d)", WEXITSTATUS(status));
}
}
free(a->run.outbuf.buf);
free(a->run.errbuf.buf);
memset(&a->run, 0, sizeof a->run);
a->run.in = a->run.out = a->run.err = -1;
a->working = 0;
restore_held(a, 1); /* sent or queued, and never run: back to the editor */
blocks_flush(a, 1);
a->status[0] = '\0';
run_queued(a);
}
}
/* ---- commands ---------------------------------------------------------- */
/* SQL over one JSON argument (?1) giving one text value, malloc'd; NULL when none. */
static char *jsql(app *a, const char *sql, const char *doc) {
sqlite3_stmt *q = NULL;
char *out = NULL;
if (sqlite3_prepare_v2(a->db, sql, -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, doc, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
out = strdup((const char *)sqlite3_column_text(q, 0));
}
}
sqlite3_finalize(q);
return out;
}
/* A journaled reply drawn as it was live: its thinking, text and tool calls
* in order (a call waits in a->blocks for its result). */
static void history_reply(app *a, const char *line) {
for (int i = 0;; i++) {
char key[48], *block, *type;
(void)snprintf(key, sizeof key, "$.content[%d]", i);
if (!(block = jget(a, line, key))) {
break;
}
type = jget(a, block, "$.type");
if (type && strcmp(type, "thinking") == 0) {
char *t = jget(a, block, "$.thinking");
blocks_flush(a, 1);
text_clear(&a->thinking);
(void)text_add(&a->thinking, t ? t : "", t ? strlen(t) : 0);
commit_thinking(a);
free(t);
} else if (type && strcmp(type, "text") == 0) {
char *t = jget(a, block, "$.text");
blocks_flush(a, 1);
if (t && t[strspn(t, " \t\r\n")]) {
text_clear(&a->stream);
(void)text_add(&a->stream, t, strlen(t));
commit_stream(a);
}
free(t);
} else if (type && strcmp(type, "toolCall") == 0) {
char *ev = jsql(a, "SELECT json_object('toolName', json_extract(?1, '$.name'), 'toolCallId', json_extract(?1, '$.id'),"
" 'args', json(coalesce(json_extract(?1, '$.arguments'), '{}')))", block);
if (ev) {
tool_start(a, ev);
}
free(ev);
}
free(type);
free(block);
}
}
/* A journaled tool result completes its call's block, drawn when the calls
* before it are. */
static void history_result(app *a, const char *line) {
char *ev = jsql(a, "SELECT json_object('toolCallId', json_extract(?1, '$.callId'), 'isError', json_extract(?1, '$.isError'),"
" 'result', json_object('content', json_array(json_object('type', 'text', 'text', json_extract(?1, '$.text')))))",
line);
int found = 0;
for (int i = 0; ev && i < a->nblocks; i++) {
found |= a->blocks[i].state == TUI_TOOL_PENDING;
}
if (!found) { /* a result whose call is not on the path: draw it on its own */
char *tool = jget(a, line, "$.tool"), *callid = jget(a, line, "$.callId"), *start;
start = jsql(a, "SELECT json_object('toolName', ?1)", tool ? tool : "tool");
if (start) {
tool_start(a, start);
if (callid) {
(void)snprintf(a->blocks[a->nblocks - 1].id, sizeof a->blocks[0].id, "%s", callid);
}
}
free(start);
free(tool);
free(callid);
}
if (ev) {
tool_end(a, ev);
}
for (int i = 0; i < a->nblocks; i++) {
if (a->blocks[i].state != TUI_TOOL_PENDING) {
a->blocks[i].took_ms = -1; /* not journaled: no "Took" */
}
}
blocks_flush(a, 0);
free(ev);
}
static void app_show_history(app *a) {
const char *args[] = {"log", "--json", a->conversation, NULL};
char *out = NULL;
/* the footer counts the conversation's requests, as Pi's counts its session's */
a->in = a->out = a->cache_read = a->cache_write = a->context = 0;
a->cost = 0;
if (run_sync(a, args, &out) == 0) {
for (char *line = out, *nl; line && *line; line = nl ? nl + 1 : NULL) {
char *kind, *t;
nl = strchr(line, '\n');
if (nl) {
*nl = '\0';
}
kind = jget(a, line, "$.kind");
t = jget(a, line, "$.text");
char *bash_cmd = kind && strcmp(kind, "user") == 0 ? jget(a, line, "$.bash.command") : NULL;
if (!kind || strcmp(kind, "tool_result") != 0) {
blocks_flush(a, 1);
}
if (jget_has(a, line, "$.usage")) {
long long tin = jnum(a, line, "$.usage.pic_tokens.input"), tout = jnum(a, line, "$.usage.pic_tokens.output"),
tcr = jnum(a, line, "$.usage.pic_tokens.cacheRead"), tcw = jnum(a, line, "$.usage.pic_tokens.cacheWrite");
char *cost = jget(a, line, "$.usage.pic_cost.total");
a->in += tin;
a->out += tout;
a->cache_read += tcr;
a->cache_write += tcw;
if (tin + tout + tcr + tcw > 0) {
a->context = tin + tout + tcr + tcw;
}
a->cost += cost ? strtod(cost, NULL) : 0;
free(cost);
}
if (bash_cmd) { /* a "!" command: drawn as it was when it ran */
char *output = jget(a, line, "$.bash.output"), *code = jget(a, line, "$.bash.exitCode");
tui_bash b = {bash_cmd, output ? output : "",
jnum(a, line, "$.bash.cancelled") == 1 ? TUI_BASH_CANCELLED : TUI_BASH_DONE,
code ? atoi(code) : 0, jnum(a, line, "$.bash.excludeFromContext") == 1};
commit_bash(a, &b);
free(output);
free(code);
} else if (kind && strcmp(kind, "user") == 0) {
commit_user(a, t ? t : "");
if (t && *t) { /* Up/Down recalls the conversation's messages, oldest first */
tui_editor_history_add(a->ed, t);
}
} else if (kind && (strcmp(kind, "assistant") == 0 || strcmp(kind, "answer") == 0)) {
if (jget_has(a, line, "$.content")) {
history_reply(a, line);
} else if (t && *t) {
text_clear(&a->stream);
(void)text_add(&a->stream, t, strlen(t));
commit_stream(a);
}
} else if (kind && strcmp(kind, "tool_result") == 0) {
history_result(a, line);
} else if (kind && strcmp(kind, "compaction") == 0) {
notice(a, DIM, "\xe2\x94\x80 compacted history \xe2\x94\x80");
} else if (kind && strcmp(kind, "branch_summary") == 0) { /* Pi's BranchSummaryMessageComponent */
tui_lines shut = {NULL, 0, 0}, open_ = {NULL, 0, 0}, l = {NULL, 0, 0};
tui_md_opts o;
size_t cols = a->cols > 2 ? (size_t)a->cols : 2;
char hint[96];
notice(a, BOLD, "[branch]");
(void)snprintf(hint, sizeof hint, "Branch summary (%sctrl+o%s to expand)", DIM, RESET);
(void)tui_lines_add(&shut, hint, strlen(hint));
(void)tui_lines_add(&open_, BOLD "Branch Summary" RESET, strlen(BOLD "Branch Summary" RESET));
(void)tui_lines_add(&open_, "", 0);
md_opts(a, &o);
(void)tui_markdown(t ? t : "", t ? strlen(t) : 0, cols, &o, &open_);
(void)tui_lines_add(&l, "", 0);
commit_lines(a, &l);
(void)tui_transcript_expandable(a->tr, (const char *const *)shut.lines, shut.n, (const char *const *)open_.lines,
open_.n);
if (a->expand_tools) {
commit_drawn(a, &open_);
} else {
commit_drawn(a, &shut);
}
tui_lines_clear(&shut);
tui_lines_clear(&open_);
}
free(bash_cmd);
free(kind);
free(t);
}
blocks_flush(a, 1);
}
free(out);
}
static void pick_free(app *a) {
for (int i = 0; i < a->npick; i++) {
free(a->pick_ids[i]);
free(a->pick_rows[i]);
}
free(a->pick_ids);
free(a->pick_rows);
a->pick_ids = a->pick_rows = NULL;
a->npick = a->pick_at = a->picking = 0;
}
/* Pi's session selector shows forks under the conversation they came from
* (session-selector.ts: flattenSessionTree, buildTreePrefix): siblings ordered by
* their subtree's latest activity, "\xe2\x94\x9c\xe2\x94\x80 " / "\xe2\x94\x94\xe2\x94\x80 " branches, a "\xe2\x94\x82 " where an ancestor continues.
* ids and rows arrive most recent first, parents[i] is row i's forkedFrom (or NULL);
* both arrays are reordered in place and the prefixes put in front of the rows. */
typedef struct {
int *first, *next, *key, *order, n, out;
char **ids, **rows, **parents;
char **nids, **nrows;
} pick_tree_ctx;
static void pick_walk(pick_tree_ctx *c, int node, int depth, const char *anc, int last) {
char prefix[256] = "", row[1024];
if (depth > 0 && strlen(anc) + 8 < sizeof prefix) {
(void)snprintf(prefix, sizeof prefix, "%s%s", anc, last ? "\xe2\x94\x94\xe2\x94\x80 " : "\xe2\x94\x9c\xe2\x94\x80 ");
}
(void)snprintf(row, sizeof row, "%s%s", prefix, c->rows[node]);
c->nids[c->out] = c->ids[node];
c->nrows[c->out++] = strdup(row);
for (int ch = c->first[node]; ch >= 0; ch = c->next[ch]) {
char sub[256];
/* an ancestor below the root that is not the last child lets its line run down */
(void)snprintf(sub, sizeof sub, "%s%s", anc, depth > 0 && !last ? "\xe2\x94\x82 " : " ");
if (depth < 40) {
pick_walk(c, ch, depth + 1, sub, c->next[ch] < 0);
}
}
}
static void pick_tree(app *a, char **parents) {
int n = a->npick;
pick_tree_ctx c = {0};
int *par = n ? malloc((size_t)n * sizeof *par) : NULL, *tail = n ? malloc((size_t)n * sizeof *tail) : NULL;
int *ord = n ? malloc((size_t)n * sizeof *ord) : NULL;
int roots_first = -1, roots_tail = -1;
c.n = n;
c.first = n ? malloc((size_t)n * sizeof *c.first) : NULL;
c.next = n ? malloc((size_t)n * sizeof *c.next) : NULL;
c.key = n ? malloc((size_t)n * sizeof *c.key) : NULL;
c.nids = n ? malloc((size_t)n * sizeof *c.nids) : NULL;
c.nrows = n ? malloc((size_t)n * sizeof *c.nrows) : NULL;
c.ids = a->pick_ids;
c.rows = a->pick_rows;
if (n && par && tail && ord && c.first && c.next && c.key && c.nids && c.nrows) {
for (int i = 0; i < n; i++) {
par[i] = -1;
for (int j = 0; j < n && parents[i]; j++) {
par[i] = j != i && strcmp(a->pick_ids[j], parents[i]) == 0 ? j : par[i];
}
c.first[i] = c.next[i] = tail[i] = -1;
c.key[i] = i;
}
for (int i = 0; i < n; i++) { /* a subtree sorts by its most recent member (the smallest index) */
int guard = 0;
for (int p = par[i]; p >= 0 && guard++ < n; p = par[p]) {
c.key[p] = c.key[p] < i ? c.key[p] : i;
}
}
for (int i = 0; i < n; i++) {
ord[i] = i;
}
for (int i = 1; i < n; i++) { /* insertion sort by key: stable and cheap for a picker's size */
int v = ord[i], j = i - 1;
for (; j >= 0 && c.key[ord[j]] > c.key[v]; j--) {
ord[j + 1] = ord[j];
}
ord[j + 1] = v;
}
for (int k = 0; k < n; k++) {
int i = ord[k], p = par[i];
if (p < 0) {
if (roots_tail >= 0) {
c.next[roots_tail] = i;
} else {
roots_first = i;
}
roots_tail = i;
} else {
if (tail[p] >= 0) {
c.next[tail[p]] = i;
} else {
c.first[p] = i;
}
tail[p] = i;
}
}
for (int r = roots_first; r >= 0; r = c.next[r]) {
pick_walk(&c, r, 0, "", c.next[r] < 0);
}
if (c.out == n) {
for (int i = 0; i < n; i++) {
free(a->pick_rows[i]);
}
memcpy(a->pick_ids, c.nids, (size_t)n * sizeof *c.nids);
memcpy(a->pick_rows, c.nrows, (size_t)n * sizeof *c.nrows);
} else { /* a cycle left rows out: keep the flat list */
for (int i = 0; i < c.out; i++) {
free(c.nrows[i]);
}
}
}
free(par);
free(tail);
free(ord);
free(c.first);
free(c.next);
free(c.key);
free(c.nids);
free(c.nrows);
}
static void open_picker(app *a) {
const char *args[] = {"sessions", "--json", NULL};
char *out = NULL, **parents = NULL;
pick_free(a);
if (run_sync(a, args, &out) == 0) {
for (char *line = out, *nl; line && *line; line = nl ? nl + 1 : NULL) {
char *id, *name, *first, *forked, row[512], **ids, **rows, **pp;
nl = strchr(line, '\n');
if (nl) {
*nl = '\0';
}
id = jget(a, line, "$.id");
name = jget(a, line, "$.name");
first = jget(a, line, "$.first");
forked = jget(a, line, "$.forkedFrom");
ids = realloc(a->pick_ids, (size_t)(a->npick + 1) * sizeof *ids);
if (ids) {
a->pick_ids = ids;
}
rows = realloc(a->pick_rows, (size_t)(a->npick + 1) * sizeof *rows);
if (rows) {
a->pick_rows = rows;
}
pp = realloc(parents, (size_t)(a->npick + 1) * sizeof *pp);
if (pp) {
parents = pp;
}
if (id && ids && rows && pp) {
(void)snprintf(row, sizeof row, "%s %-16s %lld requests %s", id, name ? name : "-",
jnum(a, line, "$.requests"), first ? first : "");
for (char *c = row; *c; c++) {
*c = *c == '\n' ? ' ' : *c;
}
a->pick_ids[a->npick] = id;
a->pick_rows[a->npick] = strdup(row);
parents[a->npick] = forked;
a->npick++;
id = forked = NULL;
}
free(id);
free(name);
free(first);
free(forked);
}
}
free(out);
pick_tree(a, parents);
for (int i = 0; i < a->npick; i++) {
free(parents[i]);
}
free(parents);
if (a->npick == 0) {
notice(a, DIM, "no conversations yet");
return;
}
a->picking = 1;
}
static void resume(app *a, const char *id) {
const char *args[] = {"sessions", "--json", NULL};
char *out = NULL;
if (a->conversation[0] && strcmp(a->conversation, id) != 0 && !a->working) {
hook_end(a, "other");
}
(void)snprintf(a->conversation, sizeof a->conversation, "%s", id);
a->name[0] = a->unfinished[0] = '\0';
if (run_sync(a, args, &out) == 0) {
for (char *line = out, *nl; line && *line; line = nl ? nl + 1 : NULL) {
char *lid, *name, *pending, *model;
nl = strchr(line, '\n');
if (nl) {
*nl = '\0';
}
lid = jget(a, line, "$.id");
name = jget(a, line, "$.name");
pending = jget(a, line, "$.pending");
model = jget(a, line, "$.pendingModel");
if (lid && strcmp(lid, id) == 0 && name) {
(void)snprintf(a->name, sizeof a->name, "%s", name);
}
if (lid && strcmp(lid, id) == 0 && pending && !a->working) {
(void)snprintf(a->unfinished, sizeof a->unfinished, "%s", pending);
(void)snprintf(a->unfinished_model, sizeof a->unfinished_model, "%s", model ? model : "");
}
free(model);
free(lid);
free(name);
free(pending);
}
}
free(out);
notice(a, DIM, "\xe2\x94\x80 continuing %s \xe2\x94\x80", id);
app_show_history(a);
if (a->unfinished[0]) { /* a crash cut it off: "a run that dies is picked up by the next pic" */
notice(a, YELLOW, "the last request was interrupted: Enter to resume, Esc to drop it");
}
}
/* ---- the model picker (Pi's, see model-selector.ts) ---------------------- */
static void app_models_free(app *a) {
for (int i = 0; i < a->nmodels; i++) {
free(a->mp_models[i]);
free(a->mp_names[i]);
free(a->mp_search[i]);
}
free(a->mp_models);
free(a->mp_names);
free(a->mp_search);
free(a->mp_window);
free(a->mp_order);
a->mp_models = a->mp_names = a->mp_search = NULL;
a->mp_window = NULL;
a->mp_order = NULL;
a->nmodels = 0;
a->mp_n = 0;
}
/* Rank for Pi's order: the current model, then the default, then the rest. */
static int model_rank(const app *a, const char *m) {
return strcmp(m, a->model) == 0 ? 0 : strcmp(m, a->default_model) == 0 ? 1 : 2;
}
/* The models of providers with a key (pic models --json), in Pi's order:
* current, default, then by provider (stable). */
static void load_models_in(app *a, int ranked);
static void load_models(app *a) { load_models_in(a, 1); }
/* RANKED: the picker's order (model_rank); otherwise pic models' own, Pi's
* registry order, which Ctrl+P cycles through. */
static void load_models_in(app *a, int ranked) {
const char *args[] = {"models", "--json", NULL};
char *out = NULL;
int cap = 0;
app_models_free(a);
if (run_sync(a, args, &out) != 0 || !out) {
free(out);
return;
}
for (char *line = out, *nl; *line; line = nl + 1) {
char *m, *name, *provider, *id;
nl = strchr(line, '\n');
if (!nl) {
break;
}
*nl = '\0';
if (a->nmodels == cap) {
int c = cap ? cap * 2 : 128;
char **m1 = realloc(a->mp_models, (size_t)c * sizeof *m1), **m2, **m3;
long *w;
if (m1) {
a->mp_models = m1;
}
m2 = realloc(a->mp_names, (size_t)c * sizeof *m2);
if (m2) {
a->mp_names = m2;
}
m3 = realloc(a->mp_search, (size_t)c * sizeof *m3);
if (m3) {
a->mp_search = m3;
}
w = realloc(a->mp_window, (size_t)c * sizeof *w);
if (w) {
a->mp_window = w;
}
if (!m1 || !m2 || !m3 || !w) {
break;
}
cap = c;
}
m = jget(a, line, "$.model");
name = jget(a, line, "$.name");
provider = jget(a, line, "$.provider");
id = jget(a, line, "$.id");
if (m && name && provider && id) {
char search[1024];
(void)snprintf(search, sizeof search, "%s %s %s %s", id, provider, m, name);
a->mp_models[a->nmodels] = m;
a->mp_names[a->nmodels] = name;
a->mp_search[a->nmodels] = strdup(search);
a->mp_window[a->nmodels] = jnum(a, line, "$.contextWindow");
a->nmodels++;
m = name = NULL;
}
free(m);
free(name);
free(provider);
free(id);
}
free(out);
/* Stable insertion sort by rank (the list is already by provider). */
for (int i = 1; ranked && i < a->nmodels; i++) {
for (int j = i; j > 0 && model_rank(a, a->mp_models[j]) < model_rank(a, a->mp_models[j - 1]); j--) {
char *t;
long w;
t = a->mp_models[j], a->mp_models[j] = a->mp_models[j - 1], a->mp_models[j - 1] = t;
t = a->mp_names[j], a->mp_names[j] = a->mp_names[j - 1], a->mp_names[j - 1] = t;
t = a->mp_search[j], a->mp_search[j] = a->mp_search[j - 1], a->mp_search[j - 1] = t;
w = a->mp_window[j], a->mp_window[j] = a->mp_window[j - 1], a->mp_window[j - 1] = w;
}
}
a->mp_order = malloc(((size_t)a->nmodels + 1) * sizeof *a->mp_order);
}
static void filter_models(app *a) {
a->mp_n = a->mp_order ? tui_fuzzy_filter(a->mp_filter, (const char *const *)a->mp_search, (size_t)a->nmodels, a->mp_order) : 0;
a->mp_sel = 0;
}
static void use_model(app *a, int i, int save) {
(void)snprintf(a->model, sizeof a->model, "%s", a->mp_models[i]);
a->window = a->mp_window[i];
if (save) {
const char *args[] = {"models", "--default", a->model, NULL};
char *out = NULL;
if (run_sync(a, args, &out) == 0) {
(void)snprintf(a->default_model, sizeof a->default_model, "%s", a->model);
notice(a, DIM, "model %s, saved as the default", a->model);
}
free(out);
} else {
notice(a, DIM, "model %s", a->model);
}
}
/* Opens the picker; a fresher catalog is fetched in the background, as Pi
* does when its selector opens. */
/* Starts the background catalog refresh unless one runs or the catalog is
* offline (PIC_MODEL_CATALOG=offline, where the child would do nothing).
* 1 when one is running now. */
static int refresh_catalog(app *a) {
const char *mode = getenv("PIC_MODEL_CATALOG");
if (!a->refreshing && !(mode && strcmp(mode, "offline") == 0)) {
const char *args[] = {"models", "--refresh", "--json", NULL};
if (spawn(a, &a->refresh, args) == 0) {
a->refreshing = 1;
}
}
return a->refreshing;
}
static void open_models(app *a, const char *filter) {
load_models(a);
(void)snprintf(a->mp_filter, sizeof a->mp_filter, "%s", filter ? filter : "");
filter_models(a);
a->mp_open = 1;
(void)refresh_catalog(a);
}
/* The background catalog refresh: when it ends, the open picker reloads. */
static void pump_refresh(app *a) {
int status;
(void)drain(&a->refresh);
if (waitpid(a->refresh.pid, &status, WNOHANG) != a->refresh.pid) {
return;
}
(void)drain(&a->refresh);
if (a->refresh.out >= 0) {
close(a->refresh.out);
}
if (a->refresh.err >= 0) {
close(a->refresh.err);
}
free(a->refresh.outbuf.buf);
free(a->refresh.errbuf.buf);
memset(&a->refresh, 0, sizeof a->refresh);
a->refresh.out = a->refresh.err = -1;
a->refreshing = 0;
if (a->mp_open) {
char *selected = a->mp_n ? strdup(a->mp_models[a->mp_order[a->mp_sel]]) : NULL;
load_models(a);
filter_models(a);
for (size_t i = 0; selected && i < a->mp_n; i++) {
if (strcmp(a->mp_models[a->mp_order[i]], selected) == 0) {
a->mp_sel = (int)i;
}
}
free(selected);
}
}
static void picker_lines(app *a, tui_lines *tail) {
char line[1024];
int first = a->mp_sel < 10 ? 0 : a->mp_sel - 9;
add_fit(tail, BOLD, "Select a model (type to filter \xc2\xb7 enter: use \xc2\xb7 ctrl+s: use and save as default \xc2\xb7 esc)", a->cols);
(void)snprintf(line, sizeof line, "> %s", a->mp_filter);
add_fit(tail, "", line, a->cols);
for (int r = 0; r < 10 && first + r < (int)a->mp_n; r++) {
int i = (int)a->mp_order[first + r];
const char *m = a->mp_models[i], *slash = strchr(m, '/');
char provider[64];
int sel = first + r == a->mp_sel;
(void)snprintf(provider, sizeof provider, "%.*s", slash ? (int)(slash - m) : 0, m);
(void)snprintf(line, sizeof line, "%s %s %s%s%s%s [%s]%s", sel ? "\xe2\x86\x92" : " ",
strcmp(m, a->model) == 0 ? "\xe2\x9c\x93" : " ", slash ? slash + 1 : m,
strcmp(a->mp_names[i], slash ? slash + 1 : m) != 0 ? " (" : "",
strcmp(a->mp_names[i], slash ? slash + 1 : m) != 0 ? a->mp_names[i] : "",
strcmp(a->mp_names[i], slash ? slash + 1 : m) != 0 ? ")" : "", provider,
strcmp(m, a->default_model) == 0 ? " \xc2\xb7 default" : "");
add_fit(tail, sel ? CYAN : "", line, a->cols);
}
if (a->mp_n == 0) {
add_fit(tail, DIM, a->nmodels ? " no model matches" : " no models: no provider has a key (pic models --all lists them)", a->cols);
} else {
(void)snprintf(line, sizeof line, " (%d/%zu)%s", a->mp_sel + 1, a->mp_n,
a->refreshing ? " refreshing the catalog\xe2\x80\xa6" : "");
add_fit(tail, DIM, line, a->cols);
}
add_fit(tail, DIM, "Only models from providers with a key are shown (pic models --all lists every one).", a->cols);
}
static void picker_key(app *a, const tui_key *k) {
size_t len = strlen(a->mp_filter);
switch (k->kind) {
case TUI_KEY_UP:
a->mp_sel = a->mp_n ? (a->mp_sel + (int)a->mp_n - 1) % (int)a->mp_n : 0;
break;
case TUI_KEY_DOWN:
a->mp_sel = a->mp_n ? (a->mp_sel + 1) % (int)a->mp_n : 0;
break;
case TUI_KEY_PAGEUP:
a->mp_sel = a->mp_sel > 10 ? a->mp_sel - 10 : 0;
break;
case TUI_KEY_PAGEDOWN:
a->mp_sel = a->mp_n ? (a->mp_sel + 10 < (int)a->mp_n ? a->mp_sel + 10 : (int)a->mp_n - 1) : 0;
break;
case TUI_KEY_ENTER:
case TUI_KEY_CTRL_S:
if (a->mp_n) {
use_model(a, (int)a->mp_order[a->mp_sel], k->kind == TUI_KEY_CTRL_S);
}
a->mp_open = 0;
break;
case TUI_KEY_ESC:
case TUI_KEY_CTRL_C:
a->mp_open = 0;
break;
case TUI_KEY_BACKSPACE:
while (len > 0 && ((unsigned char)a->mp_filter[len - 1] & 0xC0) == 0x80) {
len--;
}
if (len > 0) {
a->mp_filter[len - 1] = '\0';
}
filter_models(a);
break;
case TUI_KEY_CHAR:
if (len + strlen(k->text) < sizeof a->mp_filter) {
memcpy(a->mp_filter + len, k->text, strlen(k->text) + 1);
}
filter_models(a);
break;
default:
break;
}
}
/* ---- overlays: lists that take the keys until chosen or closed ------------- */
static void ov_free(app *a) {
for (int i = 0; i < a->ov_n; i++) {
free(a->ov_label[i]);
free(a->ov_id[i]);
}
free(a->ov_label);
free(a->ov_id);
free(a->ov_on);
free(a->ov_order);
free(a->ov_data);
a->ov_label = a->ov_id = NULL;
a->ov_on = NULL;
a->ov_order = NULL;
a->ov_data = NULL;
a->ov_n = a->ov_sel = a->ov = 0;
a->ov_m = 0;
a->ov_filter[0] = '\0';
}
static void ov_open(app *a, int kind, const char *title, const char *hint) {
ov_free(a);
a->ov = kind;
(void)snprintf(a->ov_title, sizeof a->ov_title, "%s", title);
(void)snprintf(a->ov_hint, sizeof a->ov_hint, "%s", hint);
}
static void ov_add(app *a, const char *label, const char *id, int on) {
char **l = realloc(a->ov_label, ((size_t)a->ov_n + 1) * sizeof *l), **d;
unsigned char *o;
if (l) {
a->ov_label = l;
}
d = realloc(a->ov_id, ((size_t)a->ov_n + 1) * sizeof *d);
if (d) {
a->ov_id = d;
}
o = realloc(a->ov_on, (size_t)a->ov_n + 1);
if (o) {
a->ov_on = o;
}
if (!l || !d || !o) {
return;
}
a->ov_label[a->ov_n] = strdup(label);
a->ov_id[a->ov_n] = strdup(id);
a->ov_on[a->ov_n] = (unsigned char)(on != 0);
a->ov_n++;
}
static int ov_filterable(const app *a) { return a->ov == OV_SCOPED || a->ov == OV_TREE; }
/* The rows that match the filter, best first (all, in order, with none). */
static void ov_refilter(app *a) {
free(a->ov_order);
a->ov_order = malloc(((size_t)a->ov_n + 1) * sizeof *a->ov_order);
a->ov_m = a->ov_order ? tui_fuzzy_filter(a->ov_filter, (const char *const *)a->ov_label, (size_t)a->ov_n, a->ov_order) : 0;
a->ov_sel = a->ov_m && (size_t)a->ov_sel < a->ov_m ? a->ov_sel : 0;
}
/* The workspace as trust keys it: its real path. */
static const char *trust_path(const app *a, char *out) {
return realpath(a->o->workspace, out) ? out : a->o->workspace;
}
/* ---- Pi's themes and keybindings -------------------------------------- */
static const char *home_dir(void) {
const char *h = getenv("HOME");
return h && *h ? h : NULL;
}
/* Problems found loading themes or keybindings: kept as lines of text, shown by warn_flush (at start, once
* the header is; on /reload, at once). */
static void warn_add(app *a, const char *lines) {
size_t old = a->startup_warn ? strlen(a->startup_warn) : 0, add = lines ? strlen(lines) : 0;
char *g;
if (!add) {
return;
}
if ((g = realloc(a->startup_warn, old + add + 1))) {
memcpy(g + old, lines, add + 1);
a->startup_warn = g;
}
}
static void warn_flush(app *a) {
char *w = a->startup_warn, *nl;
a->startup_warn = NULL;
for (char *line = w; line && *line; line = nl ? nl + 1 : NULL) {
nl = strchr(line, '\n');
if (nl) {
*nl = '\0';
}
notice(a, YELLOW, "%s", line);
}
free(w);
}
/* The theme setting in effect: --theme for this run, else the saved one; malloc'd, NULL when unset. */
static char *theme_setting(const app *a) {
return a->theme_cli[0] ? strdup(a->theme_cli) : pic_setting("theme");
}
/* Makes the theme a setting names (see tui_theme_setting_name) the current one. A name nobody defines falls
* back to the system theme, with a warning. */
static void theme_use(app *a, const char *setting) {
char name[64];
const tui_theme *t;
(void)tui_theme_setting_name(setting, tui_terminal_light(NULL), name, sizeof name);
if (!(t = tui_themeset_find(&a->themes, name))) {
char msg[160];
(void)snprintf(msg, sizeof msg, "Theme \"%s\" not found; using the system theme\n", name);
warn_add(a, msg);
(void)tui_theme_setting_name("system", tui_terminal_light(NULL), name, sizeof name);
t = tui_themeset_find(&a->themes, name);
}
if (t) {
tui_theme_use(t, tui_terminal_truecolor());
}
}
/* (Re)reads the theme files (the user's, and the workspace's when it is trusted) and applies the setting. */
static void themes_load(app *a) {
char real[PATH_MAX], *w = NULL, *set;
tui_themeset_free(&a->themes);
if (tui_themeset_load(&a->themes, home_dir(), a->o->workspace, pic_trust_get(trust_path(a, real)) == 1, &w) != 0) {
warn_add(a, "could not read the themes\n");
}
warn_add(a, w);
free(w);
set = theme_setting(a);
theme_use(a, set);
free(set);
}
/* The first key an action is bound to as Pi's search box shows it ("Shift+Enter", "Option+x" on a Mac), or "Unbound". */
static void key_label(const char *action, const tui_keymap *km, char *out, size_t cap) {
char keys[160];
size_t n = 0;
keys[0] = '\0';
tui_keymap_keys(km, (size_t)tui_keymap_find(action), keys, sizeof keys);
keys[strcspn(keys, ",")] = '\0';
if (!keys[0]) {
(void)snprintf(out, cap, "Unbound");
return;
}
for (const char *p = keys; *p && n + 8 < cap;) {
size_t len = strcspn(p, "+");
char part[24];
(void)snprintf(part, sizeof part, "%.*s", (int)len, p);
#ifdef __APPLE__
if (strcmp(part, "alt") == 0) {
(void)snprintf(part, sizeof part, "option");
}
#endif
part[0] = (char)toupper((unsigned char)part[0]);
n += (size_t)snprintf(out + n, cap - n, "%s%s", n ? "+" : "", part);
p += len + (p[len] == '+' ? 1 : 0);
}
}
/* (Re)reads ~/.pic/keybindings.json over Pi's defaults. */
static void keys_load(app *a) {
char path[1024], *text = NULL, *w = NULL, letters[40];
size_t len = 0;
const char *h = home_dir();
if (!a->km && !(a->km = tui_keymap_new())) {
return;
}
if (h && snprintf(path, sizeof path, "%s/.pic/keybindings.json", h) < (int)sizeof path) {
errno = 0;
text = pic_input_read(path, 1u << 20, 0, &len, NULL);
if (!text && errno != ENOENT) {
warn_add(a, "~/.pic/keybindings.json could not be read; using the default keybindings\n");
}
}
(void)tui_keymap_load(a->km, text, len, "~/.pic/keybindings.json", &w);
warn_add(a, w);
free(text);
free(w);
tui_keymap_alt_letters(a->km, letters);
tui_keys_alt_letters(a->keys, letters);
{
char bottom[120];
tui_keymap_keys(a->km, (size_t)tui_keymap_find("tui.altScreen.bottom"), bottom, sizeof bottom);
tui_render_jump_key(bottom);
}
{
char prev[32], next[32];
key_label("tui.altScreen.searchPrevious", a->km, prev, sizeof prev);
key_label("tui.altScreen.searchNext", a->km, next, sizeof next);
tui_render_search_keys(a->r, prev, next);
}
}
typedef struct {
char **p;
size_t n;
} patterns;
static int add_pattern(void *ctx, const char *pattern) {
patterns *l = ctx;
char **g = realloc(l->p, (l->n + 1) * sizeof *g);
if (g) {
l->p = g;
l->p[l->n++] = strdup(pattern);
}
return 0;
}
static void patterns_free(patterns *l) {
for (size_t i = 0; i < l->n; i++) {
free(l->p[i]);
}
free(l->p);
}
/* Whether PATTERN (a model, or with * and ?) names MODEL ("provider/id"); a
* bare id matches in any provider. Case does not matter. */
static int scope_matches(const char *pattern, const char *model) {
char p[256], m[256];
const char *slash = strchr(model, '/');
size_t i;
for (i = 0; pattern[i] && i + 1 < sizeof p; i++) {
p[i] = (char)tolower((unsigned char)pattern[i]);
}
p[i] = '\0';
for (i = 0; model[i] && i + 1 < sizeof m; i++) {
m[i] = (char)tolower((unsigned char)model[i]);
}
m[i] = '\0';
return fnmatch(p, m, 0) == 0 || (slash && !strchr(p, '/') && fnmatch(p, m + (slash - model) + 1, 0) == 0);
}
static int count_pattern(void *ctx, const char *pattern) {
(void)pattern;
++*(int *)ctx;
return 0;
}
/* Pi's fullscreen settings, as its /settings lists them: the values Enter
* cycles through, the first the default. */
static const struct {
const char *key, *label;
const char *values[8];
} fs_settings[] = {
{"tuiMode", "TUI mode", {"fullscreen", "regular"}},
{"fullscreenExitOutput", "Fullscreen exit output", {"transcript", "resume-hint"}},
{"fullscreenScrollbar", "Fullscreen scrollbar", {"auto", "always", "hidden"}},
{"fullscreenCopyOnSelect", "Fullscreen copy on select", {"true", "false"}},
{"fullscreenWheelScrollLines", "Fullscreen wheel scrolling", {"auto", "1", "2", "3", "5", "10"}},
/* Not a fullscreen setting, but cycled the same way: Pi's toolExecution. */
{"toolExecution", "Tool execution", {"parallel", "sequential"}},
};
/* A fullscreen setting's value as Pi reads it (settings-manager.ts): an
* unknown or missing value is the default. malloc'd. */
static char *fs_setting(const char *key) {
char *v = pic_setting(key), buf[16];
for (size_t i = 0; i < sizeof fs_settings / sizeof fs_settings[0]; i++) {
if (strcmp(fs_settings[i].key, key) != 0) {
continue;
}
if (strcmp(key, "fullscreenWheelScrollLines") == 0) {
int n = tui_wheel_lines(v);
free(v);
if (n == 0) {
return strdup("auto");
}
(void)snprintf(buf, sizeof buf, "%d", n);
return strdup(buf);
}
for (size_t j = 1; fs_settings[i].values[j]; j++) {
if (v && strcmp(v, fs_settings[i].values[j]) == 0) {
return v;
}
}
free(v);
return strdup(fs_settings[i].values[0]);
}
return v;
}
/* Applies the fullscreen settings to the renderer and the input. */
static void fs_apply(app *a) {
char *bar = fs_setting("fullscreenScrollbar"), *out = fs_setting("fullscreenExitOutput"),
*copy = fs_setting("fullscreenCopyOnSelect"), *wheel = fs_setting("fullscreenWheelScrollLines");
int accelerate = 1;
#ifdef __APPLE__
/* Pi's terminalAcceleratesWheel: local macOS terminals already do it */
accelerate = getenv("SSH_CONNECTION") || getenv("SSH_CLIENT") || getenv("SSH_TTY");
#endif
tui_render_options(a->r, tui_scrollbar_mode(bar), !out || strcmp(out, "transcript") == 0);
a->copy_on_select = !copy || strcmp(copy, "false") != 0;
tui_wheel_init(&a->wheel, tui_wheel_lines(wheel), accelerate);
free(bar);
free(out);
free(copy);
free(wheel);
}
/* Enter on a fullscreen setting: its next value, saved; the mode switches at once. */
static void fs_cycle(app *a, const char *key) {
for (size_t i = 0; i < sizeof fs_settings / sizeof fs_settings[0]; i++) {
char *cur;
size_t j = 0, n = 0;
if (strcmp(fs_settings[i].key, key) != 0) {
continue;
}
cur = fs_setting(key);
while (fs_settings[i].values[n]) {
n++;
}
while (j < n && cur && strcmp(cur, fs_settings[i].values[j]) != 0) {
j++;
}
free(cur);
(void)pic_setting_set(key, fs_settings[i].values[(j + 1) % n]);
if (strcmp(key, "tuiMode") == 0) {
int full = strcmp(fs_settings[i].values[(j + 1) % n], "fullscreen") == 0;
(void)tui_render_fullscreen(a->r, full, a->cols, a->rows);
(void)snprintf(a->status, sizeof a->status, "TUI mode: %s", full ? "fullscreen" : "regular");
}
fs_apply(a);
return;
}
}
static void settings_open(app *a, int sel) {
char label[320], *v;
int scoped = 0;
ov_open(a, OV_SETTINGS, "Settings (up/down \xc2\xb7 enter: change \xc2\xb7 esc: close)",
"Kept in ~/.pic/pic.sqlite; a new request picks them up.");
(void)snprintf(label, sizeof label, "%-26s %s", "Default model", a->default_model);
ov_add(a, label, "defaultModel", 0);
v = pic_setting("defaultThinkingLevel");
(void)snprintf(label, sizeof label, "%-26s %s", "Default thinking level", pic_thinking_index(v) >= 0 ? v : "medium");
free(v);
ov_add(a, label, "defaultThinkingLevel", 0);
v = pic_setting("piSessionFiles");
(void)snprintf(label, sizeof label, "%-26s %s", "Pi session files", v && strcmp(v, "1") == 0 ? "true" : "false");
free(v);
ov_add(a, label, "piSessionFiles", 0);
(void)snprintf(label, sizeof label, "%-26s %s", "Hide thinking", a->hide_thinking ? "true" : "false");
ov_add(a, label, "hideThinking", 0);
for (size_t i = 0; i < sizeof fs_settings / sizeof fs_settings[0]; i++) {
char *val = fs_setting(fs_settings[i].key);
(void)snprintf(label, sizeof label, "%-26s %s", fs_settings[i].label, val ? val : "");
free(val);
ov_add(a, label, fs_settings[i].key, 0);
}
{
pic_compaction_settings cs;
pic_compaction_settings_get(a->model, &cs);
(void)snprintf(label, sizeof label, "%-26s %s", "Auto-compact", cs.enabled ? "true" : "false");
ov_add(a, label, "autocompact", 0);
}
(void)pic_scoped_each(count_pattern, &scoped);
if (scoped) {
(void)snprintf(label, sizeof label, "%-26s %d patterns", "Scoped models (Ctrl+P)", scoped);
} else {
(void)snprintf(label, sizeof label, "%-26s every model with a key", "Scoped models (Ctrl+P)");
}
ov_add(a, label, "scopedModels", 0);
v = theme_setting(a);
(void)snprintf(label, sizeof label, "%-26s %s", "Theme", v && *v ? v : "system");
free(v);
ov_add(a, label, "theme", 0);
ov_refilter(a);
a->ov_sel = sel;
}
/* The theme picker: moving over a row previews that theme at once; enter keeps it (saved as the `theme`
* setting), esc puts the earlier one back. */
static void theme_open(app *a) {
char *cur = theme_setting(a);
ov_open(a, OV_THEME, "Theme (up/down: preview \xc2\xb7 enter: choose \xc2\xb7 esc: cancel)",
"system and light/dark follow the terminal (COLORFGBG); themes are read from ~/.pic/themes (and, in a trusted workspace, .pic/themes).");
(void)snprintf(a->theme_prev, sizeof a->theme_prev, "%s", cur && *cur ? cur : "system");
ov_add(a, "system (dark or light, by the terminal)", "system", 0);
ov_add(a, "light/dark (automatic)", "light/dark", 0);
for (size_t i = 0; i < a->themes.n; i++) {
char label[160];
(void)snprintf(label, sizeof label, "%s%s", a->themes.t[i].name, a->themes.t[i].path[0] ? " (custom)" : "");
ov_add(a, label, a->themes.t[i].name, 0);
}
ov_refilter(a);
for (int i = 0; i < a->ov_n; i++) {
if (strcmp(a->ov_id[i], a->theme_prev) == 0) {
a->ov_sel = i;
}
}
free(cur);
}
static void theme_preview(app *a) {
if (a->ov == OV_THEME && a->ov_m) {
theme_use(a, a->ov_id[a->ov_order[a->ov_sel]]);
}
}
static void scoped_open(app *a) {
patterns pl = {NULL, 0};
load_models(a);
ov_open(a, OV_SCOPED, "Scoped models for Ctrl+P (type to filter \xc2\xb7 enter: toggle \xc2\xb7 ctrl+s: save \xc2\xb7 esc)",
"With none chosen, Ctrl+P cycles every model that has a key.");
(void)pic_scoped_each(add_pattern, &pl);
for (int i = 0; i < a->nmodels; i++) {
const char *m = a->mp_models[i], *slash = strchr(m, '/');
char label[320], provider[64];
int on = 0;
for (size_t j = 0; j < pl.n; j++) {
on |= scope_matches(pl.p[j], m);
}
(void)snprintf(provider, sizeof provider, "%.*s", slash ? (int)(slash - m) : 0, m);
(void)snprintf(label, sizeof label, "%s [%s]", slash ? slash + 1 : m, provider);
ov_add(a, label, m, on);
}
patterns_free(&pl);
ov_refilter(a);
}
static void scoped_save(app *a) {
const char **list = malloc(((size_t)a->ov_n + 1) * sizeof *list);
size_t n = 0;
for (int i = 0; list && i < a->ov_n; i++) {
if (a->ov_on[i]) {
list[n++] = a->ov_id[i];
}
}
/* Everything or nothing chosen is no scope at all. */
if (list && pic_scoped_set(list, n == (size_t)a->ov_n ? 0 : n) == 0) {
if (n == 0 || n == (size_t)a->ov_n) {
notice(a, DIM, "no scope: Ctrl+P cycles every model with a key");
} else {
notice(a, DIM, "Ctrl+P cycles %zu models", n);
}
} else {
notice(a, RED, "could not save the scoped models");
}
free(list);
ov_free(a);
}
static void thinking_open(app *a) {
ensure_level(a);
if (a->nlvl <= 1) {
notice(a, DIM, "%s does not support thinking levels", a->model);
return;
}
ov_open(a, OV_THINKING, "Thinking level (up/down \xc2\xb7 enter: use \xc2\xb7 esc)", "For this session; /settings sets the default.");
for (int i = 0; i < a->nlvl; i++) {
ov_add(a, a->lvls[i], a->lvls[i], strcmp(a->lvls[i], a->level) == 0);
}
ov_refilter(a);
for (int i = 0; i < a->nlvl; i++) {
a->ov_sel = a->ov_on[i] ? i : a->ov_sel;
}
}
/* /tree, the request ending at entry SELECT chosen (NULL: the newest on
* the path), as Pi re-shows it after "Summarize branch?" is left. */
static void tree_open(app *a, const char *select) {
const char *args[] = {"tree", "--json", a->conversation, NULL};
char *out = NULL;
int active = 0;
if (run_sync(a, args, &out) != 0 || !out || !*out) {
free(out);
notice(a, DIM, "no conversation tree yet");
return;
}
ov_open(a, OV_TREE, "Conversation tree (type to filter \xc2\xb7 enter: continue from there \xc2\xb7 esc)",
"\xe2\x80\xa2 is the path you are on; indented rows are branches; [id] is a conversation that ends there.");
for (char *line = out, *nl; *line; line = nl ? nl + 1 : line + strlen(line)) {
char *end, *indent, *act, *said, *sessions, label[512], id[160];
int n;
nl = strchr(line, '\n');
if (nl) {
*nl = '\0';
}
end = jget(a, line, "$.end");
indent = jget(a, line, "$.indent");
act = jget(a, line, "$.active");
said = jget(a, line, "$.text");
sessions = jget(a, line, "$.sessions");
if (end && said) {
int depth = indent ? atoi(indent) : 0;
size_t first = strcspn(said, "\n");
n = snprintf(label, sizeof label, "%*s%s %.*s", depth * 2 > 20 ? 20 : depth * 2, "",
act && strcmp(act, "1") == 0 ? "\xe2\x80\xa2" : " ", (int)(first > 100 ? 100 : first), said);
if (sessions && n > 0 && (size_t)n < sizeof label) {
(void)snprintf(label + n, sizeof label - (size_t)n, " [%s]", sessions);
}
(void)snprintf(id, sizeof id, "%s %s", end, sessions ? sessions : "");
ov_add(a, label, id, 0);
if (select ? strcmp(end, select) == 0 : act && strcmp(act, "1") == 0) {
active = a->ov_n - 1;
}
}
free(end);
free(indent);
free(act);
free(said);
free(sessions);
if (!nl) {
break;
}
}
free(out);
ov_refilter(a);
a->ov_sel = active < (int)a->ov_m ? active : 0;
}
/* Pi's "Summarize branch?" after a /tree choice. */
static void summary_open(app *a) {
ov_open(a, OV_SUMMARY, "Summarize branch? (up/down \xc2\xb7 enter \xc2\xb7 esc: back to the tree)",
"A summary of the branch you leave goes into the conversation you continue.");
ov_add(a, "No summary", "none", 0);
ov_add(a, "Summarize", "summarize", 0);
ov_add(a, "Summarize with custom prompt", "custom", 0);
ov_refilter(a);
a->ov_sel = 0;
}
/* Continues from the chosen request: without a summary, in the conversation
* that already ends there or a new fork of this one (Pi's /tree switches the
* leaf; pic's conversations are paths, so the fork is the new leaf); with
* one, in a new conversation that starts with the summary of the branch
* left (pic fork --summarize, Pi's branchWithSummary). */
static void tree_go(app *a, int summarize, const char *instructions) {
const char *args[10];
char *out = NULL;
int n = 0;
if (!summarize && a->branch_sess[0]) {
resume(a, a->branch_sess);
return;
}
args[n++] = "fork";
args[n++] = a->conversation;
args[n++] = "--at";
args[n++] = a->branch_at;
if (summarize) {
args[n++] = "--summarize";
if (instructions && *instructions) {
args[n++] = "--instructions";
args[n++] = instructions;
}
notice(a, DIM, "Summarizing branch...");
draw(a);
}
args[n] = NULL;
if (run_sync(a, args, &out) == 0 && out) {
out[strcspn(out, "\n")] = '\0';
notice(a, DIM, "\xe2\x94\x80 branched: now in %s \xe2\x94\x80", out);
resume(a, out);
}
free(out);
}
/* /fork with no argument: Pi's "Fork from Message" (user-message-selector.ts):
* the earlier user messages, oldest first, the newest selected, two lines
* each. Each row's id is the entry before that message ("0": none) and the
* message's text, which goes back into the editor after the fork. */
static void fork_open(app *a) {
const char *args[] = {"log", "--json", a->conversation, NULL};
char *out = NULL, prev[32] = "0";
if (run_sync(a, args, &out) != 0 || !out) {
free(out);
return;
}
ov_open(a, OV_FORK, "Fork from Message (up/down \xc2\xb7 enter: fork \xc2\xb7 esc)",
"Select a user message to copy the active path up to that point into a new session");
for (char *line = out, *nl; *line; line = nl ? nl + 1 : line + strlen(line)) {
char *kind, *seq, *text, *cmd;
nl = strchr(line, '\n');
if (nl) {
*nl = '\0';
}
kind = jget(a, line, "$.kind");
seq = jget(a, line, "$.seq");
text = jget(a, line, "$.text");
cmd = jget(a, line, "$.bash.command");
if (kind && strcmp(kind, "user") == 0 && !cmd && text) {
size_t n = strlen(text), plen = strlen(prev);
char *row = malloc(plen + n + 2), *one = strdup(text);
if (row && one) {
for (char *c = one; *c; c++) {
*c = *c == '\n' ? ' ' : *c;
}
(void)snprintf(row, plen + n + 2, "%s %s", prev, text);
ov_add(a, one, row, 0);
}
free(row);
free(one);
}
if (seq) {
(void)snprintf(prev, sizeof prev, "%s", seq);
}
free(kind);
free(seq);
free(text);
free(cmd);
if (!nl) {
break;
}
}
free(out);
if (!a->ov_n) {
ov_free(a);
notice(a, DIM, "No messages to fork from");
return;
}
ov_refilter(a);
a->ov_sel = (int)a->ov_m - 1;
}
/* Enter in the picker: a new conversation with the path before that message
* (none: an empty one), its text in the editor (Pi: runtimeHost.fork). */
static void fork_go(app *a) {
char *row = strdup(a->ov_id[a->ov_order[a->ov_sel]]), *text, *out = NULL;
if (!row) {
return;
}
ov_free(a);
text = strchr(row, ' ');
*text++ = '\0';
if (strcmp(row, "0") == 0) {
if (!a->working) {
hook_end(a, "other");
}
a->conversation[0] = a->name[0] = a->unfinished[0] = '\0';
notice(a, DIM, "\xe2\x94\x80 forked: a new conversation \xe2\x94\x80");
} else {
const char *args[] = {"fork", a->conversation, "--at", row, NULL};
if (run_sync(a, args, &out) != 0 || !out) {
free(out);
free(row);
return;
}
out[strcspn(out, "\n")] = '\0';
notice(a, DIM, "\xe2\x94\x80 forked: now in %s \xe2\x94\x80", out);
resume(a, out);
free(out);
}
tui_editor_set(a->ed, text);
free(row);
}
/* Enter on a request: Pi asks whether to summarize the branch left behind
* (unless branchSummary.skipPrompt), then continues from there. */
static void tree_enter(app *a) {
char *id = strdup(a->ov_id[a->ov_order[a->ov_sel]]), *space;
pic_branch_settings bs;
ov_free(a);
if (!id) {
return;
}
space = strchr(id, ' ');
*space = '\0';
(void)snprintf(a->branch_at, sizeof a->branch_at, "%s", id);
a->branch_sess[0] = '\0';
if (space[1]) {
(void)snprintf(a->branch_sess, sizeof a->branch_sess, "%.*s", (int)strcspn(space + 1, ","), space + 1);
}
free(id);
if (strcmp(a->branch_sess, a->conversation) == 0) {
notice(a, DIM, "already on %s", a->branch_sess);
return;
}
pic_branch_settings_get(&bs);
if (bs.skip_prompt) {
tree_go(a, 0, NULL);
} else {
summary_open(a);
}
}
static void trust_open(app *a) {
char real[PATH_MAX], hint[PATH_MAX + 64];
int saved = pic_trust_get(trust_path(a, real));
(void)snprintf(hint, sizeof hint, "%s \xe2\x80\x94 saved decision: %s", real, saved < 0 ? "none" : saved ? "trusted" : "untrusted");
ov_open(a, OV_TRUST, "Workspace trust (up/down \xc2\xb7 enter: save \xc2\xb7 esc)", hint);
ov_add(a, "Trust this workspace", "yes", saved == 1);
ov_add(a, "Do not trust this workspace", "no", saved == 0);
ov_refilter(a);
a->ov_sel = saved == 0;
}
static void trust_save(app *a, int trusted) {
char real[PATH_MAX];
if (pic_trust_set(trust_path(a, real), trusted) == 0) {
notice(a, DIM, "saved trust decision: %s (%s)", trusted ? "trusted" : "untrusted", real);
} else {
notice(a, RED, "could not save the trust decision");
}
}
/* Pipes INPUT to the command ARGV (found on PATH); its stdout in *out. 0 when
* it ran and exited 0. */
static int run_piped(const char *const *argv, const char *input, char **out) {
int in[2], o[2];
pid_t pid;
text got = {NULL, 0, 0};
size_t sent = 0, total = strlen(input);
int status = 0;
*out = NULL;
if (pipe(in) != 0) {
return -1;
}
if (pipe(o) != 0) {
close(in[0]);
close(in[1]);
return -1;
}
pid = fork();
if (pid == 0) {
int null = open("/dev/null", O_WRONLY);
(void)dup2(in[0], STDIN_FILENO);
(void)dup2(o[1], STDOUT_FILENO);
if (null >= 0) {
(void)dup2(null, STDERR_FILENO);
}
close(in[0]);
close(in[1]);
close(o[0]);
close(o[1]);
(void)signal(SIGPIPE, SIG_DFL);
execvp(argv[0], (char *const *)(void *)(uintptr_t)argv);
_exit(127);
}
close(in[0]);
close(o[1]);
if (pid < 0) {
close(in[1]);
close(o[0]);
return -1;
}
(void)fcntl(in[1], F_SETFL, fcntl(in[1], F_GETFL) | O_NONBLOCK);
for (int in_open = 1, out_open = 1; in_open || out_open;) {
struct pollfd p[2] = {{in_open ? in[1] : -1, POLLOUT, 0}, {out_open ? o[0] : -1, POLLIN, 0}};
(void)poll(p, 2, 200);
if (in_open && (p[0].revents & (POLLOUT | POLLERR | POLLHUP))) {
ssize_t w = sent < total ? write(in[1], input + sent, total - sent) : 0;
if (w > 0) {
sent += (size_t)w;
}
if (sent >= total || (w < 0 && errno != EAGAIN && errno != EINTR)) {
close(in[1]);
in_open = 0;
}
}
if (out_open && (p[1].revents & (POLLIN | POLLHUP | POLLERR))) {
char b[4096];
ssize_t r = read(o[0], b, sizeof b);
if (r > 0) {
(void)text_add(&got, b, (size_t)r);
} else if (r == 0 || (errno != EAGAIN && errno != EINTR)) {
close(o[0]);
out_open = 0;
}
}
}
while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {
}
*out = got.buf ? got.buf : strdup("");
return WIFEXITED(status) && WEXITSTATUS(status) == 0 ? 0 : -1;
}
/* /share: the page goes to a secret gist, after a yes. */
static void share_confirm(app *a) {
const char *args[] = {"export", "--html", a->conversation, "-", NULL};
char *html = NULL;
if (run_sync(a, args, &html) != 0 || !html || !*html) {
free(html);
notice(a, RED, "could not build the page to share");
return;
}
ov_open(a, OV_SHARE, "Share this conversation as a secret GitHub gist? (y/N)",
"The whole conversation leaves this machine, as one HTML page, through the gh command. Nothing is sent unless you say yes.");
ov_add(a, "No, keep it here", "no", 0);
ov_add(a, "Yes, create the gist", "yes", 0);
ov_refilter(a);
a->ov_data = html;
}
static void share_run(app *a) {
const char *argv[] = {"gh", "gist", "create", "-", NULL};
char *html = a->ov_data, *out = NULL;
a->ov_data = NULL;
ov_free(a);
if (run_piped(argv, html, &out) == 0 && out && *out) {
out[strcspn(out, "\n")] = '\0';
notice(a, DIM, "shared as a secret gist (only people with the link can open it): %s", out);
} else {
notice(a, RED, "gh could not create the gist (is gh installed and logged in?)");
}
free(out);
free(html);
}
/* Enter on the chosen row. */
static void ov_enter(app *a) {
int row = a->ov_m ? (int)a->ov_order[a->ov_sel] : -1, sel = a->ov_sel;
char id[200];
if (row < 0) {
return;
}
if (a->ov == OV_FORK) {
fork_go(a);
return;
}
(void)snprintf(id, sizeof id, "%s", a->ov_id[row]);
switch (a->ov) {
case OV_SETTINGS:
if (strcmp(id, "defaultModel") == 0) {
ov_free(a);
notice(a, DIM, "pick a model; ctrl+s in the picker saves it as the default");
open_models(a, NULL);
return;
} else if (strcmp(id, "defaultThinkingLevel") == 0) {
char *v = pic_setting("defaultThinkingLevel");
int at = pic_thinking_index(v) >= 0 ? pic_thinking_index(v) : pic_thinking_index("medium");
free(v);
(void)pic_setting_set("defaultThinkingLevel", pic_thinking_names[(at + 1) % PIC_THINKING_LEVELS]);
} else if (strcmp(id, "piSessionFiles") == 0) {
char *v = pic_setting("piSessionFiles");
(void)pic_setting_set("piSessionFiles", v && strcmp(v, "1") == 0 ? "0" : "1");
free(v);
} else if (strcmp(id, "hideThinking") == 0) {
a->hide_thinking = !a->hide_thinking;
(void)pic_setting_set("hideThinking", a->hide_thinking ? "true" : "false");
redraw_transcript(a);
} else if (strcmp(id, "autocompact") == 0) { /* Pi's compaction.enabled */
pic_compaction_settings cs;
pic_compaction_settings_get(a->model, &cs);
(void)pic_setting_set_json("compaction", "$.enabled", cs.enabled ? "false" : "true");
} else if (strcmp(id, "scopedModels") == 0) {
scoped_open(a);
return;
} else if (strcmp(id, "theme") == 0) {
theme_open(a);
return;
} else {
fs_cycle(a, id);
}
a->lvl_for[0] = '\0';
settings_open(a, sel);
break;
case OV_SCOPED:
a->ov_on[row] = (unsigned char)!a->ov_on[row];
break;
case OV_THINKING:
ov_free(a);
set_level(a, id);
break;
case OV_THEME:
a->theme_cli[0] = '\0';
(void)pic_setting_set("theme", id);
theme_use(a, id);
ov_free(a);
notice(a, DIM, "theme: %s", id);
break;
case OV_TREE:
tree_enter(a);
break;
case OV_SUMMARY:
ov_free(a);
if (strcmp(id, "custom") == 0) {
a->branch_custom = 1;
notice(a, DIM, "Custom summarization instructions: type them and press enter (esc goes back)");
} else {
tree_go(a, strcmp(id, "summarize") == 0, NULL);
}
break;
case OV_TRUST:
ov_free(a);
trust_save(a, strcmp(id, "yes") == 0);
break;
default: /* OV_SHARE */
if (strcmp(id, "yes") == 0) {
share_run(a);
} else {
ov_free(a);
notice(a, DIM, "not shared");
}
break;
}
}
static void overlay_lines(app *a, tui_lines *tail) {
char line[1024];
int first = a->ov_sel < 10 ? 0 : a->ov_sel - 9;
add_fit(tail, BOLD, a->ov_title, a->cols);
if (ov_filterable(a)) {
(void)snprintf(line, sizeof line, "> %s", a->ov_filter);
add_fit(tail, "", line, a->cols);
}
for (int r = 0; r < 10 && first + r < (int)a->ov_m; r++) {
int i = (int)a->ov_order[first + r], sel = first + r == a->ov_sel;
const char *mark = a->ov == OV_SCOPED ? (a->ov_on[i] ? "[x] " : "[ ] ")
: (a->ov == OV_THINKING || a->ov == OV_TRUST) ? (a->ov_on[i] ? "\xe2\x9c\x93 " : " ")
: "";
(void)snprintf(line, sizeof line, "%s %s%s", sel ? "\xe2\x86\x92" : " ", mark, a->ov_label[i]);
add_fit(tail, sel ? CYAN : "", line, a->cols);
if (a->ov == OV_FORK) {
(void)snprintf(line, sizeof line, " Message %d of %d", i + 1, a->ov_n);
add_fit(tail, DIM, line, a->cols);
}
}
if (a->ov_m == 0) {
add_fit(tail, DIM, a->ov_n ? " nothing matches" : " nothing to show", a->cols);
} else if (a->ov_m > 10) {
(void)snprintf(line, sizeof line, " (%d/%zu)", a->ov_sel + 1, a->ov_m);
add_fit(tail, DIM, line, a->cols);
}
{
tui_lines h = {NULL, 0, 0}; /* a long hint wraps rather than lose its end */
(void)tui_wrap(a->ov_hint, strlen(a->ov_hint), a->cols > 2 ? (size_t)a->cols : 2, &h);
for (size_t i = 0; i < h.n; i++) {
add_fit(tail, DIM, h.lines[i], a->cols);
}
tui_lines_clear(&h);
}
}
static void overlay_key(app *a, const tui_key *k) {
size_t len = strlen(a->ov_filter);
int moved = k->kind == TUI_KEY_UP || k->kind == TUI_KEY_DOWN || k->kind == TUI_KEY_PAGEUP || k->kind == TUI_KEY_PAGEDOWN;
switch (k->kind) {
case TUI_KEY_UP:
a->ov_sel = a->ov_m ? (a->ov_sel + (int)a->ov_m - 1) % (int)a->ov_m : 0;
break;
case TUI_KEY_DOWN:
a->ov_sel = a->ov_m ? (a->ov_sel + 1) % (int)a->ov_m : 0;
break;
case TUI_KEY_PAGEUP:
a->ov_sel = a->ov_sel > 10 ? a->ov_sel - 10 : 0;
break;
case TUI_KEY_PAGEDOWN:
a->ov_sel = a->ov_m ? (a->ov_sel + 10 < (int)a->ov_m ? a->ov_sel + 10 : (int)a->ov_m - 1) : 0;
break;
case TUI_KEY_ENTER:
ov_enter(a);
break;
case TUI_KEY_CTRL_S:
if (a->ov == OV_SCOPED) {
scoped_save(a);
}
break;
case TUI_KEY_ESC:
case TUI_KEY_CTRL_C:
if (a->ov == OV_THEME) { /* the earlier theme comes back, and Pi's settings list */
theme_use(a, a->theme_prev);
ov_free(a);
settings_open(a, 0);
for (int i = 0; i < (int)a->ov_m; i++) {
if (strcmp(a->ov_id[a->ov_order[i]], "theme") == 0) {
a->ov_sel = i;
}
}
break;
}
if (a->ov == OV_SUMMARY) { /* Pi: back to the tree */
ov_free(a);
tree_open(a, a->branch_at);
break;
}
ov_free(a);
break;
case TUI_KEY_BACKSPACE:
if (ov_filterable(a)) {
while (len > 0 && ((unsigned char)a->ov_filter[len - 1] & 0xC0) == 0x80) {
len--;
}
if (len > 0) {
a->ov_filter[len - 1] = '\0';
}
ov_refilter(a);
}
break;
case TUI_KEY_CHAR:
if (a->ov == OV_SHARE) { /* y / N */
if (k->text[0] == 'y' || k->text[0] == 'Y') {
share_run(a);
} else if (k->text[0] == 'n' || k->text[0] == 'N') {
ov_free(a);
notice(a, DIM, "not shared");
}
} else if (a->ov == OV_SCOPED && k->text[0] == ' ' && a->ov_m) {
a->ov_on[a->ov_order[a->ov_sel]] = (unsigned char)!a->ov_on[a->ov_order[a->ov_sel]];
} else if (ov_filterable(a) && len + strlen(k->text) < sizeof a->ov_filter) {
memcpy(a->ov_filter + len, k->text, strlen(k->text) + 1);
ov_refilter(a);
}
break;
default:
break;
}
if (moved) {
theme_preview(a);
}
}
/* Ctrl+P: the next model. With a scope (/scoped-models) that is the next
* one of it, in its patterns' order (a wildcard's matches alphabetically);
* otherwise the next model with a key, in the picker's order (Pi cycles its
* available models when no scope is set). */
static void cycle_model(app *a, int dir) {
patterns pl = {NULL, 0};
int *list = NULL, n = 0, at = -1;
load_models_in(a, 0); /* one stable order: ranked, the current model would always come first (Pi's _cycleAvailableModel) */
(void)pic_scoped_each(add_pattern, &pl);
list = malloc(((size_t)a->nmodels + 1) * sizeof *list);
for (int i = 0; list && pl.n == 0 && i < a->nmodels; i++) {
list[n++] = i;
}
for (size_t j = 0; list && j < pl.n; j++) {
int from = n;
for (int i = 0; i < a->nmodels; i++) {
int seen = 0;
for (int k = 0; k < n; k++) {
seen |= list[k] == i;
}
if (!seen && scope_matches(pl.p[j], a->mp_models[i])) {
int p = n++;
while (p > from && strcmp(a->mp_models[list[p - 1]], a->mp_models[i]) > 0) {
list[p] = list[p - 1];
p--;
}
list[p] = i;
}
}
}
for (int k = 0; k < n; k++) {
at = strcmp(a->mp_models[list[k]], a->model) == 0 ? k : at;
}
if (n < 2) {
notice(a, DIM, pl.n ? "only one model in the scope (/scoped-models changes it)" : "only one model available");
} else {
use_model(a, list[at < 0 ? (dir < 0 ? n - 1 : 0) : (at + (dir < 0 ? n - 1 : 1)) % n], 0);
}
free(list);
patterns_free(&pl);
}
/* ---- slash commands ------------------------------------------------------ */
static const struct {
const char *name, *hint, *what;
} commands[] = {
{"settings", "", "open the settings menu"},
{"model", "[provider/model]", "select a model"},
{"scoped-models", "", "choose the models Ctrl+P cycles"},
{"thinking", "[level]", "set the thinking level"},
{"tree", "", "navigate the conversation tree (switch branches)"},
{"new", "", "start a new conversation"},
{"resume", "[ID]", "resume another conversation"},
{"name", "NAME", "name this conversation"},
{"session", "", "show this conversation's info and stats"},
{"fork", "[ENTRY]", "pick an earlier message to branch from (or give an ENTRY, see /log)"},
{"clone", "", "duplicate this conversation at its current point"},
{"compact", "[FOCUS]", "summarize the history now"},
{"copy", "", "copy the last reply"},
{"export", "[FILE.html | DIR]", "write this conversation as a web page (or Pi session files into DIR)"},
{"import", "FILE", "import a Pi session file as a conversation"},
{"share", "", "share this conversation as a secret gist"},
{"reload", "", "reload project instructions, skills, prompt templates, the model catalog, keybindings and themes"},
{"trust", "[yes|no]", "save the workspace trust decision"},
{"changelog", "", "show what changed"},
{"bug", "TEXT", "record a bug report (kept locally, sent nowhere)"},
{"login", "[PROVIDER]", "store a provider's API key, sealed (default: the model's provider)"},
{"logout", "[PROVIDER]", "remove a stored API key"},
{"hotkeys", "", "show keyboard shortcuts"},
{"help", "[TOPIC]", "keys and commands, or a topic of the manual (pic help)"},
{"quit", "", "quit pic"},
};
#define NCOMMANDS (sizeof commands / sizeof commands[0])
#define MENU_ROWS 5 /* rows shown at once (Pi's autocompleteMaxVisible) */
#define MENU_MAX 128 /* items kept, scrolled through */
static int is_builtin(const char *name, size_t len) {
if (len == 4 && strncmp(name, "exit", 4) == 0) {
return 1;
}
for (size_t i = 0; i < NCOMMANDS; i++) {
if (strlen(commands[i].name) == len && strncmp(commands[i].name, name, len) == 0) {
return 1;
}
}
return 0;
}
/* The template LINE ("/name ARGS") calls, unless a built-in command has the name. */
static const pic_prompt *template_for(const app *a, const char *line) {
size_t len;
if (line[0] != '/') {
return NULL;
}
len = strcspn(line + 1, " \t\r\n");
if (!len || is_builtin(line + 1, len)) {
return NULL;
}
for (size_t i = 0; i < a->tpl.n; i++) {
if (strlen(a->tpl.v[i].name) == len && strncmp(a->tpl.v[i].name, line + 1, len) == 0) {
return &a->tpl.v[i];
}
}
return NULL;
}
/* Whether LINE ("/skill:name ARGS") names a skill. */
static int skill_for(const app *a, const char *line) {
size_t len;
if (strncmp(line, "/skill:", 7) != 0) {
return 0;
}
len = strcspn(line + 7, " \t\r\n");
for (size_t i = 0; i < a->skl.n; i++) {
if (strlen(a->skl.v[i].name) == len && strncmp(a->skl.v[i].name, line + 7, len) == 0) {
return 1;
}
}
return 0;
}
/* (Re)reads the templates and skills: the user's, and the workspace's when it is trusted. */
static void load_templates(app *a) {
char real[PATH_MAX];
pic_skills_free(&a->skl);
if (pic_skills_load(&a->skl, a->o->workspace, pic_trust_get(trust_path(a, real)) == 1, NULL) != 0) {
notice(a, RED, "could not read the skills");
}
pic_prompts_free(&a->tpl);
if (pic_prompts_load(&a->tpl, a->o->workspace, pic_trust_get(trust_path(a, real)) == 1) != 0) {
notice(a, RED, "could not read the prompt templates");
}
}
/* The @file menu (Pi: files and folders under the workspace for "@" + a
* partial path). Fills labels/values; the list is kept while the token is
* unchanged so a redraw does not walk the tree again. */
static size_t at_items_for(app *a, char labels[][256], char values[][256], size_t cap) {
const char *t = tui_editor_text(a->ed);
char query[512], key[520];
size_t start, n;
int quoted;
if (!atfile_token(t, tui_editor_cursor(a->ed), &start, query, sizeof query, "ed)) {
a->at_valid = 0;
return 0;
}
(void)snprintf(key, sizeof key, "%d%s", quoted, query);
if (!a->at_valid || strcmp(key, a->at_key) != 0) {
a->at_n = atfile_candidates(a->o->workspace, query, quoted, a->at_items, sizeof a->at_items / sizeof *a->at_items);
(void)snprintf(a->at_key, sizeof a->at_key, "%s", key);
a->at_valid = 1;
}
n = a->at_n < cap ? a->at_n : cap;
for (size_t i = 0; i < n; i++) {
(void)snprintf(labels[i], 256, "%s", a->at_items[i].label);
(void)snprintf(values[i], 256, "%s", a->at_items[i].value);
}
return n;
}
/* Puts the chosen completion in place of the token; a folder keeps the
* cursor inside it so the next level completes, a file adds a space (Pi's
* applyCompletion). */
static void at_accept(app *a, size_t sel) {
const char *t = tui_editor_text(a->ed);
char query[512], v[ATFILE_VALUE_MAX + 2];
size_t start, cur = tui_editor_cursor(a->ed), len, end = cur;
int quoted;
const atfile_item *it = &a->at_items[sel];
if (!atfile_token(t, cur, &start, query, sizeof query, "ed)) {
return;
}
len = strlen(it->value);
if (it->value[len - 1] == '"' && t[end] == '"') {
end++; /* the closing quote is already there */
}
(void)snprintf(v, sizeof v, "%s%s", it->value, it->is_dir ? "" : " ");
tui_editor_replace(a->ed, start, end, v, it->is_dir && it->value[len - 1] == '"' ? len - 1 : strlen(v));
a->at_valid = 0;
a->menu_sel = 0;
}
/* The menu for what is typed: commands while the first word is typed after
* "/", model names after "/model ". Fills labels (display) and values (what
* is inserted); returns how many, and whether they are commands. */
static size_t menu_items(app *a, char labels[][256], char values[][256], size_t cap, int *is_command) {
const char *t = tui_editor_text(a->ed), *s = t;
size_t cur = tui_editor_cursor(a->ed), n = 0;
while (*s == ' ') {
s++;
}
*is_command = 0;
if (strcmp(t, a->menu_dismissed) != 0 && (n = at_items_for(a, labels, values, cap)) > 0) {
*is_command = 2;
return n;
}
if (*s != '/' || memchr(t, '\n', cur) || cur < (size_t)(s - t) + 1 || strcmp(t, a->menu_dismissed) == 0) {
return 0;
}
if (!strpbrk(s, " \t")) {
size_t total = NCOMMANDS + a->tpl.n + a->skl.n;
const char **names = malloc(total * sizeof *names);
size_t *ord = malloc(total * sizeof *ord);
char (*skill_names)[80] = malloc((a->skl.n + 1) * sizeof *skill_names);
char query[128];
size_t shown = 0;
if (!names || !ord || !skill_names) {
free(names);
free(ord);
free(skill_names);
return 0;
}
(void)snprintf(query, sizeof query, "%s", s + 1);
for (size_t i = 0; i < NCOMMANDS; i++) {
names[i] = commands[i].name;
}
for (size_t i = 0; i < a->tpl.n; i++) { /* a built-in of the same name hides the template */
names[NCOMMANDS + i] = is_builtin(a->tpl.v[i].name, strlen(a->tpl.v[i].name)) ? "" : a->tpl.v[i].name;
}
for (size_t i = 0; i < a->skl.n; i++) {
(void)snprintf(skill_names[i], sizeof skill_names[i], "skill:%s", a->skl.v[i].name);
names[NCOMMANDS + a->tpl.n + i] = skill_names[i];
}
n = tui_fuzzy_filter(query, names, total, ord);
for (size_t i = 0; i < n && shown < cap; i++) {
const char *name, *hint, *what;
if (ord[i] < NCOMMANDS) {
name = commands[ord[i]].name, hint = commands[ord[i]].hint, what = commands[ord[i]].what;
} else if (ord[i] >= NCOMMANDS + a->tpl.n) {
name = names[ord[i]], hint = "", what = a->skl.v[ord[i] - NCOMMANDS - a->tpl.n].description;
} else if (*names[ord[i]]) {
const pic_prompt *tp = &a->tpl.v[ord[i] - NCOMMANDS];
name = tp->name, hint = tp->hint, what = tp->description;
} else {
continue;
}
(void)snprintf(labels[shown], 256, "/%-13s %s%s%s", name, hint, *hint && *what ? " \xe2\x80\x94 " : "", what);
(void)snprintf(values[shown], 256, "/%s", name);
shown++;
}
free(names);
free(ord);
free(skill_names);
*is_command = 1;
return shown;
}
if (strncmp(s, "/model ", 7) == 0) {
const char *q = s + 7;
size_t *ord;
while (*q == ' ') {
q++;
}
if (!a->nmodels) {
load_models(a);
}
ord = malloc(((size_t)a->nmodels + 1) * sizeof *ord);
if (!ord) {
return 0;
}
{
const char **texts = malloc(((size_t)a->nmodels + 1) * sizeof *texts);
if (texts) {
for (int i = 0; i < a->nmodels; i++) {
texts[i] = a->mp_models[i];
}
n = tui_fuzzy_filter(q, texts, (size_t)a->nmodels, ord);
free(texts);
}
}
for (size_t i = 0; i < n && i < cap; i++) {
const char *m = a->mp_models[ord[i]], *slash = strchr(m, '/');
(void)snprintf(labels[i], 256, "%s [%.*s]", slash ? slash + 1 : m, slash ? (int)(slash - m) : 0, m);
(void)snprintf(values[i], 256, "/model %s", m);
}
free(ord);
return n < cap ? n : cap;
}
return 0;
}
static void menu_lines(app *a, tui_lines *tail) {
char labels[MENU_MAX][256], values[MENU_MAX][256];
int is_command;
size_t n = menu_items(a, labels, values, MENU_MAX, &is_command);
if (a->menu_sel >= (int)n) {
a->menu_sel = 0;
}
/* Pi's SelectList: a window of MENU_ROWS centred on the selection, and
* " (selected/total)" under it when the list is longer. */
size_t from = 0, to = n;
if (n > MENU_ROWS) {
long f = (long)a->menu_sel - MENU_ROWS / 2;
from = f < 0 ? 0 : (size_t)f > n - MENU_ROWS ? n - MENU_ROWS : (size_t)f;
to = from + MENU_ROWS;
}
for (size_t i = from; i < to; i++) {
add_fit(tail, (int)i == a->menu_sel ? CYAN : DIM, labels[i], a->cols);
}
if (n > MENU_ROWS) {
char info[48];
(void)snprintf(info, sizeof info, " (%d/%zu)", a->menu_sel + 1, n);
add_fit(tail, DIM, info, a->cols);
}
}
/* Keys the menu takes while it shows: up/down choose, tab completes, enter
* completes and (for a command) runs it, esc hides it. 1 when taken. */
static int menu_key(app *a, const tui_key *k) {
char labels[MENU_MAX][256], values[MENU_MAX][256];
int is_command;
size_t n;
if (k->kind != TUI_KEY_UP && k->kind != TUI_KEY_DOWN && k->kind != TUI_KEY_TAB && k->kind != TUI_KEY_ENTER &&
k->kind != TUI_KEY_ESC) {
return 0;
}
n = menu_items(a, labels, values, MENU_MAX, &is_command);
if (n == 0) {
return 0;
}
if (a->menu_sel >= (int)n) {
a->menu_sel = 0;
}
if (is_command == 2 && (k->kind == TUI_KEY_TAB || k->kind == TUI_KEY_ENTER)) {
at_accept(a, (size_t)a->menu_sel);
return 1;
}
switch (k->kind) {
case TUI_KEY_UP:
a->menu_sel = (a->menu_sel + (int)n - 1) % (int)n;
return 1;
case TUI_KEY_DOWN:
a->menu_sel = (a->menu_sel + 1) % (int)n;
return 1;
case TUI_KEY_ESC:
(void)snprintf(a->menu_dismissed, sizeof a->menu_dismissed, "%s", tui_editor_text(a->ed));
return 1;
case TUI_KEY_TAB: {
char v[260];
(void)snprintf(v, sizeof v, "%s ", values[a->menu_sel]);
tui_editor_set(a->ed, is_command ? v : values[a->menu_sel]);
a->menu_sel = 0;
return 1;
}
default: /* ENTER */
if (is_command && template_for(a, values[a->menu_sel]) && *template_for(a, values[a->menu_sel])->hint) {
char v[260]; /* a template that takes arguments: complete it, the next Enter sends */
(void)snprintf(v, sizeof v, "%s ", values[a->menu_sel]);
tui_editor_set(a->ed, v);
a->menu_sel = 0;
} else if (is_command) {
char *v = strdup(values[a->menu_sel]);
tui_editor_clear(a->ed);
a->menu_sel = 0;
if (v) {
submit(a, v);
}
free(v);
} else {
tui_editor_set(a->ed, values[a->menu_sel]);
/* the argument is in place; the next Enter runs it, as in Pi */
(void)snprintf(a->menu_dismissed, sizeof a->menu_dismissed, "%s", tui_editor_text(a->ed));
a->menu_sel = 0;
}
return 1;
}
}
/* Copies TEXT: OSC 52 (works over ssh, in most terminals) and, where there
* is one, the system's own clipboard command. */
static void copy_text(const char *t) {
static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
size_t n = strlen(t);
text osc = {NULL, 0, 0};
(void)text_add(&osc, "\x1b]52;c;", 7);
for (size_t i = 0; i < n; i += 3) {
unsigned v = (unsigned)(unsigned char)t[i] << 16 | (i + 1 < n ? (unsigned)(unsigned char)t[i + 1] << 8 : 0) |
(i + 2 < n ? (unsigned char)t[i + 2] : 0);
char q[4] = {b64[v >> 18 & 63], b64[v >> 12 & 63], i + 1 < n ? b64[v >> 6 & 63] : '=', i + 2 < n ? b64[v & 63] : '='};
(void)text_add(&osc, q, 4);
}
(void)text_add(&osc, "\x07", 1);
if (osc.buf) {
ssize_t w = write(STDOUT_FILENO, osc.buf, osc.len);
(void)w;
}
free(osc.buf);
{
const char *tool = !getenv("PIC_NO_NATIVE_CLIPBOARD") && access("/usr/bin/pbcopy", X_OK) == 0 ? "/usr/bin/pbcopy" : NULL;
if (tool) {
int p[2];
pid_t pid = -1;
if (pipe(p) == 0 && (pid = fork()) == 0) {
(void)dup2(p[0], STDIN_FILENO);
close(p[0]);
close(p[1]);
execl(tool, tool, (char *)NULL);
_exit(127);
} else if (pid > 0) {
ssize_t w;
close(p[0]);
w = write(p[1], t, n);
(void)w;
close(p[1]);
(void)waitpid(pid, NULL, 0);
}
}
}
}
static void flash_for(app *a, const char *msg, long ms) {
(void)snprintf(a->flash, sizeof a->flash, "%s", msg);
a->flash_until = now_ms() + ms;
}
static void flash(app *a, const char *msg) {
flash_for(a, msg, 1500);
}
/* Fullscreen: the transcript selection to the clipboard (Pi's
* copySelectionToClipboard), with its "Copied!" flash. 0 when nothing is selected. */
static int copy_selection(app *a) {
char *t = tui_render_selection(a->r);
if (!t) {
return 0;
}
copy_text(t);
free(t);
flash(a, "Copied!");
return 1;
}
static void copy_last(app *a) {
if (a->last_reply && *a->last_reply) {
copy_text(a->last_reply);
notice(a, DIM, "Copied last agent message to clipboard");
} else {
notice(a, RED, "Error: No agent messages to copy yet.");
}
}
/* What /hotkeys adds to the bindings of keybindings.json: input that is not an action. */
static const char hotkeys_extra[] =
"\nOther:\n"
" Esc Esc on an empty editor open /tree\n"
" !cmd run a bash command, recorded in the conversation (the model sees it with your next message)\n"
" !!cmd run a bash command, output stays out of the context Esc cancel it\n"
" Fullscreen: the wheel scrolls the transcript, dragging selects (copied at once, or with the copy key when\n"
" fullscreenCopyOnSelect is false); Ctrl+F searches it (Pi's Ctrl+Shift+F too), elsewhere Ctrl+F is cursor right\n"
" Enter while a reply runs: steer it (Claude Code); Up on the first line pulls queued messages back; Esc Esc clears a draft\n"
" \\ then Enter: a newline (Claude Code) Ctrl+L redraws the screen (Claude Code); the model picker is /model, Alt+P\n"
" Ctrl+D on an empty editor: press twice within 800 ms to exit (Claude Code)\n"
" Ctrl+R: search prompt history; type to filter, Ctrl+R again for an older match, Enter takes it into the editor, Esc cancels\n"
" Fullscreen search: the keys listed under Fullscreen; while the box is open typing goes to the query\n"
"Defaults that differ from Pi are in the README (Mac Terminal and iTerm2 send these without Option as Meta).\n"
"Rebind any action in ~/.pic/keybindings.json (Pi's format); /reload applies it.";
/* /login [PROVIDER]: pic login in this process, on the terminal (key and
* passphrase with echo off), so the unlocked store serves this session's
* requests without asking again. */
static void login(app *a, const char *arg) {
pic_model m;
char provider[64], name[128], key[2 * PIC_CRED_KEY_CAP], prompt[128], err[256] = "";
long n;
int rc = -1;
if (*arg) {
(void)snprintf(provider, sizeof provider, "%s", arg);
} else {
(void)snprintf(provider, sizeof provider, "%.*s", (int)strcspn(a->model, "/"), a->model);
}
(void)snprintf(name, sizeof name, "%s/x", provider);
if (pic_model_resolve(name, &m, err, sizeof err) != 0 || strcmp(m.provider, provider) != 0) {
notice(a, RED, "unknown provider %s (/login PROVIDER; pic models --all lists them)", provider);
return;
}
(void)tui_render_pause(a->r);
tui_term_restore();
(void)snprintf(prompt, sizeof prompt, "API key for %s: ", provider);
n = pic_tty_secret(prompt, key, sizeof key, err, sizeof err);
if (n >= 0) {
rc = pic_cred_login(provider, key, err, sizeof err);
}
pic_cred_wipe(key, sizeof key);
reset_screen(a);
if (rc != 0) {
notice(a, RED, "pic: %s", err);
} else if (m.key_env[0] && getenv(m.key_env) && *getenv(m.key_env)) {
notice(a, DIM, "Saved the API key for %s, sealed, in ~/.pic/pic.sqlite; %s is set and takes precedence.", provider,
m.key_env);
} else {
notice(a, DIM, "Saved the API key for %s, sealed, in ~/.pic/pic.sqlite.", provider);
}
}
static int add_key_name(void *ctx, const char *name, long long created_ms, long long used_ms) {
text *t = ctx;
(void)created_ms;
(void)used_ms;
if (t->len) {
(void)text_add(t, ", ", 2);
}
(void)text_add(t, name, strlen(name));
return 0;
}
/* /logout [PROVIDER]: without one, the stored names (Pi lists them). */
static void logout(app *a, const char *arg) {
if (!*arg) {
text t = {NULL, 0, 0};
(void)pic_cred_each(add_key_name, &t);
if (t.len) {
notice(a, DIM, "Stored keys: %s. /logout PROVIDER removes one.", t.buf);
} else {
notice(a, DIM, "No stored credentials to remove. /logout only removes credentials saved by /login; environment "
"variables and models.json config are unchanged.");
}
free(t.buf);
return;
}
switch (pic_cred_logout(arg)) {
case 1:
notice(a, DIM, "Removed the stored API key for %s. Environment variables and models.json config are unchanged.", arg);
break;
case 0:
notice(a, DIM, "No stored credentials for %s. Environment variables and models.json config are unchanged.", arg);
break;
default:
notice(a, RED, "could not write ~/.pic/pic.sqlite");
}
}
/* CHANGELOG.md, compiled in (src/changelog.inc, made by the Makefile), in
* chunks that /changelog joins. */
static const char *const changelog_parts[] = {
#include "changelog.inc"
};
/* A path the user typed, as a full path: relative ones belong to the
* workspace (Pi's are relative to its working directory, the project), "~/"
* is the home directory. */
static void in_workspace(const app *a, const char *p, char *out, size_t cap) {
char real[PATH_MAX];
const char *home = getenv("HOME");
if (p[0] == '/') {
(void)snprintf(out, cap, "%s", p);
} else if (p[0] == '~' && p[1] == '/' && home) {
(void)snprintf(out, cap, "%s/%s", home, p + 2);
} else {
(void)snprintf(out, cap, "%s/%s", realpath(a->o->workspace, real) ? real : a->o->workspace, p);
}
}
/* /help TOPIC: the manual's topic as markdown between two rules, as
* /changelog shows its text; keys adds the bindings in effect. */
static void help_topic(app *a, const char *name) {
char *md = pic_help_text(name);
tui_lines l = {NULL, 0, 0};
tui_md_opts o;
size_t cols = a->cols > 2 ? (size_t)a->cols : 2;
if (!md) {
text t = {NULL, 0, 0};
for (size_t i = 0; i < pic_help_count(); i++) {
(void)text_add(&t, i ? ", " : "", i ? 2 : 0);
(void)text_add(&t, pic_help_name(i), strlen(pic_help_name(i)));
}
notice(a, RED, "no help topic %s; the topics: %s", name, t.buf ? t.buf : "");
free(t.buf);
return;
}
(void)tui_lines_add(&l, "", 0);
(void)tui_border_line(NULL, NULL, cols, &l);
md_opts(a, &o);
(void)tui_markdown(md, strlen(md), cols, &o, &l);
(void)tui_border_line(NULL, NULL, cols, &l);
commit_lines(a, &l);
free(md);
if (strcmp(name, "keys") == 0) {
char *keys = a->km ? tui_keymap_hotkeys(a->km) : NULL;
notice(a, DIM, "In effect now:\n%s%s", keys ? keys : "", hotkeys_extra);
free(keys);
}
}
static void app_command(app *a, char *line) {
char *arg = line + strcspn(line, " \t");
char *out = NULL;
if (*arg) {
*arg++ = '\0';
arg += strspn(arg, " \t");
}
if (strcmp(line, "/quit") == 0 || strcmp(line, "/exit") == 0) {
a->quit = 1;
} else if (strcmp(line, "/help") == 0 && *arg) {
help_topic(a, arg);
} else if (strcmp(line, "/help") == 0 || strcmp(line, "/hotkeys") == 0) {
{
char *keys = a->km ? tui_keymap_hotkeys(a->km) : NULL;
notice(a, DIM, "%s%s", keys ? keys : "", hotkeys_extra);
free(keys);
}
if (strcmp(line, "/help") == 0) {
text t = {NULL, 0, 0};
for (size_t i = 0; i < NCOMMANDS; i++) {
char row[256];
(void)snprintf(row, sizeof row, "/%-13s %-18s %s\n", commands[i].name, commands[i].hint, commands[i].what);
(void)text_add(&t, row, strlen(row));
}
(void)text_add(&t, "/help TOPIC shows a topic of the manual:", 40);
for (size_t i = 0; i < pic_help_count(); i++) {
(void)text_add(&t, " ", 1);
(void)text_add(&t, pic_help_name(i), strlen(pic_help_name(i)));
}
notice(a, DIM, "%s", t.buf ? t.buf : "");
free(t.buf);
}
} else if (strcmp(line, "/new") == 0) {
if (a->conversation[0] && !a->working) {
hook_end(a, "clear");
}
a->conversation[0] = a->name[0] = a->unfinished[0] = '\0';
a->in = a->out = a->context = 0;
a->cost = 0;
notice(a, DIM, "\xe2\x94\x80 new conversation \xe2\x94\x80");
} else if (strcmp(line, "/resume") == 0) {
if (*arg) {
resume(a, arg);
} else {
open_picker(a);
}
} else if (strcmp(line, "/model") == 0) {
/* An exact provider/model or bare id switches; otherwise the picker
* opens with what was typed as its filter (Pi's /model ARG). */
int found = -1;
if (*arg) {
load_models(a);
for (int i = 0; i < a->nmodels && found < 0; i++) {
const char *m = a->mp_models[i], *slash = strchr(m, '/');
if (strcasecmp(m, arg) == 0 || (slash && strcasecmp(slash + 1, arg) == 0)) {
found = i;
}
}
}
if (found >= 0) {
use_model(a, found, 0);
} else {
open_models(a, arg);
}
} else if (strcmp(line, "/copy") == 0) {
copy_last(a);
} else if (strcmp(line, "/settings") == 0) {
settings_open(a, 0);
} else if (strcmp(line, "/scoped-models") == 0) {
scoped_open(a);
} else if (strcmp(line, "/thinking") == 0) {
ensure_level(a);
if (!*arg) {
thinking_open(a);
} else if (a->nlvl <= 1) {
notice(a, DIM, "%s does not support thinking levels", a->model);
} else {
int ok = 0;
for (int i = 0; i < a->nlvl; i++) {
ok |= strcmp(a->lvls[i], arg) == 0;
}
if (ok) {
set_level(a, arg);
} else {
text t = {NULL, 0, 0};
for (int i = 0; i < a->nlvl; i++) {
(void)text_add(&t, i ? ", " : "", i ? 2 : 0);
(void)text_add(&t, a->lvls[i], strlen(a->lvls[i]));
}
notice(a, RED, "%s does not take thinking level %s (it takes: %s)", a->model, arg, t.buf ? t.buf : "");
free(t.buf);
}
}
} else if (strcmp(line, "/reload") == 0) {
char *ins = pic_project_instructions(a->o->workspace), *def = pic_setting("defaultModel"), *hide = pic_setting("hideThinking");
if (def && *def) {
(void)snprintf(a->default_model, sizeof a->default_model, "%s", def);
}
a->hide_thinking = hide && strcmp(hide, "true") == 0;
a->lvl_for[0] = '\0';
load_models(a);
load_templates(a);
keys_load(a);
themes_load(a);
notice(a, DIM, "reloaded: %s; %zu prompt templates; %zu skills; %d models with a key; keybindings; %zu themes%s",
ins && *ins ? "project instructions found (every request reads them afresh)" : "no project instructions (AGENTS.md, CLAUDE.md)",
a->tpl.n, a->skl.n, a->nmodels, a->themes.n, refresh_catalog(a) ? " (the catalog is refreshing in the background)" : "");
warn_flush(a);
free(ins);
free(def);
free(hide);
} else if (strcmp(line, "/trust") == 0) {
if (*arg && strcmp(arg, "yes") != 0 && strcmp(arg, "no") != 0) {
notice(a, RED, "/trust takes yes or no, or nothing to choose");
} else if (*arg) {
trust_save(a, strcmp(arg, "yes") == 0);
} else {
trust_open(a);
}
} else if (strcmp(line, "/import") == 0) {
if (!*arg) {
notice(a, RED, "/import needs the path of a Pi session file (.jsonl)");
} else if (strcmp(arg, "-") == 0) {
notice(a, RED, "the terminal interface reads the keyboard on stdin; run: pic import - < FILE");
} else {
const char *args[] = {"import", arg, NULL};
if (run_sync(a, args, &out) == 0 && out) {
out[strcspn(out, "\n")] = '\0';
notice(a, DIM, "\xe2\x94\x80 imported %s as conversation %s (the text of its messages) \xe2\x94\x80", arg, out);
resume(a, out);
}
}
} else if (strcmp(line, "/changelog") == 0) {
/* Pi's What's New: the entries oldest first, so the newest is next to
* the editor, as markdown between two rules */
text all = {NULL, 0, 0};
text md = {NULL, 0, 0};
tui_lines l = {NULL, 0, 0};
tui_md_opts o;
size_t cols = a->cols > 2 ? (size_t)a->cols : 2;
const char *top;
for (size_t i = 0; changelog_parts[i]; i++) {
(void)text_add(&all, changelog_parts[i], strlen(changelog_parts[i]));
}
top = all.buf ? strstr(all.buf, "## ") : NULL;
for (const char *end = top ? all.buf + all.len : NULL; top && end > top;) {
const char *start = end - 1;
while (start > top && !(start[-1] == '\n' && strncmp(start, "## ", 3) == 0)) {
start--;
}
if (md.len) {
(void)text_add(&md, "\n\n", 2);
}
(void)text_add(&md, start, (size_t)(end - start));
end = start;
}
(void)tui_lines_add(&l, "", 0);
(void)tui_border_line(NULL, NULL, cols, &l);
commit_lines(a, &l);
notice(a, BOLD, "What's New");
(void)tui_lines_add(&l, "", 0);
md_opts(a, &o);
(void)tui_markdown(md.buf ? md.buf : "No changelog entries found.", md.buf ? md.len : 27, cols, &o, &l);
(void)tui_border_line(NULL, NULL, cols, &l);
commit_lines(a, &l);
free(md.buf);
free(all.buf);
} else if (strcmp(line, "/bug") == 0) {
char real[PATH_MAX];
long long id = *arg ? pic_bug_add(trust_path(a, real), a->conversation, a->model, arg) : -1;
if (!*arg) {
notice(a, RED, "/bug needs a description");
} else if (id < 0) {
notice(a, RED, "could not record the bug report");
} else {
notice(a, DIM, "bug %lld recorded in ~/.pic/pic.sqlite (table picu_bug); nothing was sent", id);
}
} else if (strcmp(line, "/login") == 0) {
login(a, arg);
} else if (strcmp(line, "/logout") == 0) {
logout(a, arg);
} else if (!a->conversation[0]) {
if (strcmp(line, "/compact") == 0) {
compact_start(a, arg); /* Pi's "Nothing to compact (session too small)" */
} else if (strcmp(line, "/name") == 0 || strcmp(line, "/fork") == 0 ||
strcmp(line, "/session") == 0 || strcmp(line, "/clone") == 0 || strcmp(line, "/export") == 0 ||
strcmp(line, "/tree") == 0 || strcmp(line, "/share") == 0) {
notice(a, RED, "%s needs a conversation: send a message first", line);
} else {
notice(a, RED, "unknown command %s (/help lists them)", line);
}
} else if (strcmp(line, "/name") == 0 && *arg) {
const char *args[] = {"name", a->conversation, arg, NULL};
if (run_sync(a, args, &out) == 0) {
(void)snprintf(a->name, sizeof a->name, "%s", arg);
notice(a, DIM, "named %s", arg);
}
} else if (strcmp(line, "/fork") == 0 && !*arg) {
fork_open(a);
} else if (strcmp(line, "/fork") == 0 || strcmp(line, "/clone") == 0) {
int at = strcmp(line, "/fork") == 0 && *arg;
const char *args[] = {"fork", a->conversation, at ? "--at" : NULL, at ? arg : NULL, NULL};
if (run_sync(a, args, &out) == 0 && out) {
out[strcspn(out, "\n")] = '\0';
notice(a, DIM, "\xe2\x94\x80 %s: now in %s \xe2\x94\x80", strcmp(line, "/clone") == 0 ? "cloned" : "forked", out);
if (!a->working) {
hook_end(a, "other");
}
(void)snprintf(a->conversation, sizeof a->conversation, "%s", out);
a->name[0] = '\0';
}
} else if (strcmp(line, "/compact") == 0) {
compact_start(a, arg);
} else if (strcmp(line, "/export") == 0) {
size_t n = strlen(arg);
if (strcmp(arg, "-") == 0) {
notice(a, RED, "the page would land in this terminal; run: pic export --html %s -", a->conversation);
} else if (!*arg || (n > 5 && strcmp(arg + n - 5, ".html") == 0)) {
char dflt[96], path[PATH_MAX + 128];
(void)snprintf(dflt, sizeof dflt, "pic-session-%s.html", a->conversation);
in_workspace(a, *arg ? arg : dflt, path, sizeof path);
const char *args[] = {"export", "--html", a->conversation, path, NULL};
if (run_sync(a, args, &out) == 0) {
notice(a, DIM, "written to %s as one self-contained web page", path);
}
} else {
char path[PATH_MAX + 128];
in_workspace(a, arg, path, sizeof path);
const char *args[] = {"export", "--pi", path, NULL};
if (run_sync(a, args, &out) == 0) {
notice(a, DIM, "written to %s as Pi session files (one per conversation)", path);
}
}
} else if (strcmp(line, "/tree") == 0) {
tree_open(a, NULL);
} else if (strcmp(line, "/share") == 0) {
share_confirm(a);
} else if (strcmp(line, "/session") == 0) {
char a1[16], a2[16], a3[16], a4[16], a5[16];
fmt_tokens(a->in, a1, sizeof a1);
fmt_tokens(a->out, a2, sizeof a2);
fmt_tokens(a->cache_read, a3, sizeof a3);
fmt_tokens(a->cache_write, a4, sizeof a4);
fmt_tokens(a->context, a5, sizeof a5);
notice(a, DIM,
"conversation %s%s%s%s\nmodel %s\ntokens in %s, out %s, cache read %s, cache write %s "
"(this window)\ncontext %s of %ld\njournal %s\nPi rows ~/.pic/pic.sqlite (written after each "
"request, for ctx)",
a->conversation, a->name[0] ? " (" : "", a->name, a->name[0] ? ")" : "", a->model, a1, a2, a3, a4, a5,
a->window, a->o->db);
} else if (strcmp(line, "/name") == 0) {
notice(a, RED, "/name needs a NAME");
} else {
notice(a, RED, "unknown command %s (/help lists them)", line);
}
free(out);
}
/* Enter, or (follow) Alt+Enter. While a reply runs the message goes to it as
* Pi's steer (Enter) or follow_up; /commands wait for it to end (they need the
* journal it holds), as does everything when it takes no commands. */
static void submit_mode(app *a, char *msg, int follow, const tui_attachment *images, size_t nimages) {
if (a->branch_custom) { /* the custom prompt for a branch summary */
a->branch_custom = 0;
tree_go(a, 1, msg);
return;
}
if (run_bang(a, msg)) {
return;
}
if (msg[0] == '/' && !a->working && !template_for(a, msg) && !skill_for(a, msg)) {
app_command(a, msg);
} else if (a->working) {
int plain = msg[0] != '/' || template_for(a, msg) || skill_for(a, msg);
if (plain && !a->interrupted && !a->finishing && a->nsent + a->nsteer + a->nfollow < MAX_QUEUED &&
send_message(a, follow ? "follow_up" : "steer", msg, images, nimages) == 0) {
a->sent_q[a->nsent++] = strdup(msg);
} else if (a->nqueue < MAX_QUEUED) {
a->queue[a->nqueue++] = strdup(msg);
}
} else if (a->bash.running) { /* Pi lets them overlap; here the command holds the journal: after it */
if (a->nqueue < MAX_QUEUED) {
a->queue[a->nqueue++] = strdup(msg);
}
} else {
start_request(a, msg, images, nimages);
}
}
static void submit(app *a, char *msg) { submit_mode(a, msg, 0, NULL, 0); }
/* The texts come back to the editor in front of what is typed there,
* blank-line separated, as Pi's restoreQueuedMessagesToEditor does. */
static void restore_texts(app *a, char *const *texts, int n) {
text t = {NULL, 0, 0};
char *cur;
for (int i = 0; i < n; i++) {
(void)text_add(&t, texts[i], strlen(texts[i]));
if (i + 1 < n) {
(void)text_add(&t, "\n\n", 2);
}
}
cur = tui_editor_expanded(a->ed);
if (cur && cur[strspn(cur, " \t\n")]) {
(void)text_add(&t, "\n\n", 2);
(void)text_add(&t, cur, strlen(cur));
}
free(cur);
tui_editor_set(a->ed, t.buf ? t.buf : "");
free(t.buf);
}
/* The messages the app itself holds (/commands, and what the child could not take)
* back to the editor. Returns how many. */
static int restore_queue(app *a) {
int n = a->nqueue;
if (n == 0) {
return 0;
}
restore_texts(a, a->queue, n);
for (int i = 0; i < n; i++) {
free(a->queue[i]);
}
a->nqueue = 0;
return n;
}
/* Alt+Up, and Esc on a running reply: the queue comes back to the editor. The
* child owns steering and follow-ups, so it is asked (clear_queue) and the
* answer carries them; the rest is local. notify: say how many came back. */
static void dequeue(app *a, int notify) {
if (a->working && a->run.in >= 0 && (a->nsteer + a->nfollow + a->nsent) > 0 && !a->clear_sent &&
send_command(a, "{\"id\":\"dequeue\",\"type\":\"clear_queue\"}") == 0) {
a->clear_sent = 1;
a->clear_notice = notify;
return;
}
{
int n = restore_queue(a);
if (notify) {
if (n) {
notice(a, DIM, "Restored %d queued message%s to editor", n, n > 1 ? "s" : "");
} else {
notice(a, DIM, "No queued messages to restore");
}
}
}
}
/* A fresh renderer over the live area: after the terminal was handed to
* another program and given back. */
static void reset_screen(app *a) {
(void)tui_term_raw(STDIN_FILENO);
tui_term_size(STDOUT_FILENO, &a->cols, &a->rows);
tui_render_size(a->r, a->cols, a->rows);
(void)tui_render_resume(a->r);
a->title[0] = '\0';
}
/* Ctrl+Z: put the terminal back, stop, and come back on SIGCONT. */
static void suspend_ui(app *a) {
(void)tui_render_pause(a->r);
tui_term_restore();
(void)signal(SIGTSTP, SIG_DFL);
(void)raise(SIGTSTP);
reset_screen(a);
}
/* Ctrl+G: the editor's text in a temporary file for $VISUAL / $EDITOR; what
* it holds afterwards replaces the text (Pi's external-editor.ts). */
static void external_editor(app *a) {
const char *cmd = getenv("VISUAL");
char dir[PATH_MAX], file[PATH_MAX + 16], *content, *argv[16], *copy;
const char *tmp = getenv("TMPDIR");
int n = 0, status = 0;
pid_t pid;
FILE *f;
if (!cmd || !*cmd) {
cmd = getenv("EDITOR");
}
if (!cmd || !*cmd) {
notice(a, YELLOW, "No editor configured. Set $VISUAL or $EDITOR environment variable.");
return;
}
(void)snprintf(dir, sizeof dir, "%s/pic-editor-XXXXXX", tmp && *tmp ? tmp : "/tmp");
if (!mkdtemp(dir)) {
notice(a, RED, "could not create a temporary file: %s", strerror(errno));
return;
}
(void)snprintf(file, sizeof file, "%s/prompt.md", dir);
content = tui_editor_expanded(a->ed);
f = fopen(file, "w");
if (!f || !content || fputs(content, f) == EOF) {
notice(a, RED, "could not write %s", file);
if (f) {
(void)fclose(f);
}
free(content);
(void)unlink(file);
(void)rmdir(dir);
return;
}
(void)fclose(f);
free(content);
copy = strdup(cmd);
for (char *w = copy ? strtok(copy, " ") : NULL; w && n < 14; w = strtok(NULL, " ")) {
argv[n++] = w;
}
argv[n++] = file;
argv[n] = NULL;
(void)tui_render_pause(a->r);
tui_term_restore();
printf("Launching external editor: %s\npic will resume when the editor exits.\n", cmd);
(void)fflush(stdout);
pid = n > 1 ? fork() : -1;
if (pid == 0) {
(void)signal(SIGINT, SIG_DFL);
execvp(argv[0], argv);
_exit(127);
}
while (pid > 0 && waitpid(pid, &status, 0) < 0 && errno == EINTR) {
}
reset_screen(a);
if (pid < 0 || (WIFEXITED(status) && WEXITSTATUS(status) == 127)) {
notice(a, YELLOW, "Failed to launch external editor: %s", cmd);
} else if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
notice(a, YELLOW, "External editor exited with %s %d; prompt unchanged", WIFEXITED(status) ? "code" : "signal",
WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status));
} else {
char *got = NULL;
size_t len = 0;
f = fopen(file, "r");
if (f) {
char buf[4096];
size_t k;
text t = {NULL, 0, 0};
while ((k = fread(buf, 1, sizeof buf, f)) > 0) {
(void)text_add(&t, buf, k);
}
(void)fclose(f);
got = t.buf ? t.buf : strdup("");
len = t.len;
}
if (got) {
const char *body = len >= 3 && memcmp(got, "\xEF\xBB\xBF", 3) == 0 ? got + 3 : got;
size_t bl = strlen(body);
char *clean;
if (bl > 0 && body[bl - 1] == '\n') {
bl--;
}
clean = strndup(body, bl);
if (clean) {
tui_editor_set(a->ed, clean);
}
free(clean);
free(got);
}
}
free(copy);
(void)unlink(file);
(void)rmdir(dir);
}
/* Writes the terminal title when it changed: "pic - NAME - DIR". */
static void sync_title(app *a) {
char t[320];
tui_title(a->o->workspace, a->name, t, sizeof t);
if (strcmp(t, a->title) != 0) {
ssize_t w = write(STDOUT_FILENO, t, strlen(t));
(void)w;
(void)snprintf(a->title, sizeof a->title, "%s", t);
}
}
/* ---- keys -------------------------------------------------------------- */
/* Fullscreen mouse input: the wheel scrolls the transcript (Alt: five times
* as far, as Pi's), the left button selects in it. */
static void app_on_mouse(app *a, const tui_key *k) {
if (k->mouse == TUI_MOUSE_WHEEL) {
int lines = tui_wheel_next(&a->wheel, k->button, (double)now_ms());
(void)tui_render_scroll(a->r, (long)k->button * lines * (k->alt ? 5 : 1));
} else if (k->button == 0 && tui_render_mouse(a->r, k->mouse, k->mx, k->my) && a->copy_on_select) {
(void)copy_selection(a);
}
}
/* Pi's tui.altScreen keys: PageUp/PageDown and Ctrl+Home/Ctrl+End move the
* transcript in fullscreen. 1 when the key was one of them. */
static int scroll_key(app *a, const tui_key *k) {
if (!tui_render_is_fullscreen(a->r)) {
return 0;
}
switch (k->kind) {
case TUI_KEY_PAGEUP: (void)tui_render_page(a->r, -1); return 1;
case TUI_KEY_PAGEDOWN: (void)tui_render_page(a->r, 1); return 1;
case TUI_KEY_CTRL_HOME: (void)tui_render_edge(a->r, 0); return 1;
case TUI_KEY_CTRL_END: (void)tui_render_edge(a->r, 1); return 1;
case TUI_KEY_ACTION: { /* Pi's tui.altScreen half-page and line actions */
long half = (a->rows > 4 ? a->rows - 4 : 1) / 2 > 0 ? (a->rows > 4 ? a->rows - 4 : 1) / 2 : 1;
switch (k->action) {
case TUI_ACT_SCROLL_HALF_UP: (void)tui_render_scroll(a->r, -half); return 1;
case TUI_ACT_SCROLL_HALF_DOWN: (void)tui_render_scroll(a->r, half); return 1;
case TUI_ACT_SCROLL_LINE_UP: (void)tui_render_scroll(a->r, -1); return 1;
case TUI_ACT_SCROLL_LINE_DOWN: (void)tui_render_scroll(a->r, 1); return 1;
default: return 0;
}
}
default: return 0;
}
}
/* Text at the editor's cursor as a bracketed paste would put it. */
static void paste_into_editor(app *a, char *t, size_t n) {
tui_key k = {.kind = TUI_KEY_PASTE, .paste = t, .paste_len = n};
(void)tui_editor_key(a->ed, &k);
}
/* Ctrl+V, Pi's handleClipboardPaste: files copied in Finder go in as their
* paths (with a space where they would touch a word), an image is attached
* and shown as "[image #N]", else the clipboard's text is pasted. */
static void clipboard_paste(app *a) {
tui_clip c;
switch (tui_clipboard_read(&c)) {
case TUI_CLIP_FILES: {
const char *cur = tui_editor_text(a->ed);
size_t at = tui_editor_cursor(a->ed), n = strlen(c.text);
char *t;
int lead = at > 0 && !isspace((unsigned char)cur[at - 1]), trail = cur[at] && !isspace((unsigned char)cur[at]);
for (const char *q = c.text; *q; q++) {
if (*q != '\n' && iscntrl((unsigned char)*q)) {
notice(a, RED, "Failed to paste from clipboard: Clipboard file path contains control characters");
tui_clip_free(&c);
return;
}
}
if ((t = malloc(n + 3)) != NULL) {
(void)snprintf(t, n + 3, "%s%s%s", lead ? " " : "", c.text, trail ? " " : "");
paste_into_editor(a, t, strlen(t));
free(t);
}
break;
}
case TUI_CLIP_IMAGE: {
pic_image im = {.mime = NULL, .data = c.image, .len = c.image_len};
char why[160];
if (tui_editor_attached(a->ed) >= PIC_REQUEST_IMAGES) {
notice(a, RED, "Failed to paste from clipboard: at most %d images go with a message", PIC_REQUEST_IMAGES);
} else if (pic_image_check(&im, NULL, why, sizeof why) != PIC_IMAGE_OK) {
notice(a, RED, "Failed to paste from clipboard: %s", why);
} else if (tui_editor_attach(a->ed, c.image, c.image_len) > 0) {
c.image = NULL; /* the editor has it */
}
break;
}
case TUI_CLIP_TEXT:
paste_into_editor(a, c.text, strlen(c.text));
break;
default:
break;
}
tui_clip_free(&c);
}
/* ---- Ctrl+R: reverse search through the prompt history ---------------------- */
static void hs_find(app *a, long from) {
long at = tui_editor_history_find(a->ed, a->hs.q, from);
a->hs.fail = at < 0;
if (at >= 0) {
a->hs.at = at;
}
}
static void hs_open(app *a) {
a->hs.on = 1;
a->hs.q[0] = '\0';
a->hs.at = -1;
hs_find(a, -1);
a->hs.fail = 0;
}
/* Readline's keys: typing filters, Ctrl+R again goes to an older match, Enter accepts the entry into the
* editor (it is not sent), Esc or Ctrl+C cancels. Cursor and Tab keys accept it and then act on the editor.
* 1 when the key was used here. */
static int hs_key(app *a, const tui_key *k) {
size_t n = strlen(a->hs.q);
switch (k->kind) {
case TUI_KEY_CHAR:
if (n + strlen(k->text) < sizeof a->hs.q) {
(void)snprintf(a->hs.q + n, sizeof a->hs.q - n, "%s", k->text);
hs_find(a, a->hs.at);
}
return 1;
case TUI_KEY_PASTE:
for (size_t i = 0; i < k->paste_len && n + 1 < sizeof a->hs.q; i++) {
a->hs.q[n++] = k->paste[i] == '\n' || k->paste[i] == '\t' ? ' ' : k->paste[i];
}
a->hs.q[n] = '\0';
hs_find(a, a->hs.at);
return 1;
case TUI_KEY_BACKSPACE:
while (n > 0 && ((unsigned char)a->hs.q[n - 1] & 0xC0) == 0x80) {
n--;
}
if (n > 0) {
n--;
}
a->hs.q[n] = '\0';
hs_find(a, -1);
return 1;
case TUI_KEY_KILL_START:
case TUI_KEY_DELETE_WORD:
a->hs.q[0] = '\0';
hs_find(a, -1);
return 1;
case TUI_KEY_ACTION:
if (k->action == TUI_ACT_HISTORY_SEARCH) { /* older */
long at = a->hs.at >= 0 ? tui_editor_history_find(a->ed, a->hs.q, a->hs.at - 1) : -1;
a->hs.fail = at < 0 || a->hs.at < 1;
if (!a->hs.fail) {
a->hs.at = at;
}
}
return 1;
case TUI_KEY_ENTER:
a->hs.on = 0;
if (a->hs.at >= 0) {
tui_editor_set(a->ed, tui_editor_history_at(a->ed, (size_t)a->hs.at));
}
return 1;
case TUI_KEY_ESC:
case TUI_KEY_CTRL_C:
a->hs.on = 0;
return 1;
case TUI_KEY_LEFT:
case TUI_KEY_RIGHT:
case TUI_KEY_HOME:
case TUI_KEY_END:
case TUI_KEY_TAB:
a->hs.on = 0;
if (a->hs.at >= 0) {
tui_editor_set(a->ed, tui_editor_history_at(a->ed, (size_t)a->hs.at));
}
return 0;
default:
return 1;
}
}
/* ---- the transcript search (Pi's tui.altScreen.search*) ----------------------- */
/* Appends text to the search query, newlines and tabs as spaces. */
static void search_type(app *a, const char *t, size_t len) {
char q[512];
size_t n = (size_t)snprintf(q, sizeof q, "%s", tui_render_search_query(a->r));
for (size_t i = 0; i < len && n + 1 < sizeof q; i++) {
q[n++] = t[i] == '\n' || t[i] == '\t' || t[i] == '\r' ? ' ' : t[i];
}
q[n] = '\0';
tui_render_search_set(a->r, q);
}
/* While the search box is open it has the keyboard, as Pi's focused overlay does: the search keys, text
* for the query, and the viewport's scroll keys; everything else is dropped. Wheel and mouse go on. Runs on
* the key as decoded, before the keybindings turn it into what the editor wants (Enter, Escape). 1 when used. */
static int search_key(app *a, tui_key *k) {
char q[512];
size_t n;
if (k->kind == TUI_KEY_MOUSE) {
return 0;
}
if (a->km && tui_keymap_has(a->km, "tui.altScreen.search", k)) {
tui_render_search_close(a->r);
return 1;
}
if (a->km ? tui_keymap_has(a->km, "tui.altScreen.searchNext", k) : k->kind == TUI_KEY_ENTER) {
tui_render_search_step(a->r, 1);
return 1;
}
if (a->km && tui_keymap_has(a->km, "tui.altScreen.searchPrevious", k)) {
tui_render_search_step(a->r, -1);
return 1;
}
if (a->km ? tui_keymap_has(a->km, "tui.altScreen.searchClose", k) : k->kind == TUI_KEY_ESC) {
tui_render_search_close(a->r);
return 1;
}
(void)snprintf(q, sizeof q, "%s", tui_render_search_query(a->r));
n = strlen(q);
switch (k->kind) {
case TUI_KEY_CHAR:
search_type(a, k->text, strlen(k->text));
return 1;
case TUI_KEY_PASTE:
search_type(a, k->paste, k->paste_len);
return 1;
case TUI_KEY_BACKSPACE:
while (n > 0 && ((unsigned char)q[n - 1] & 0xC0) == 0x80) {
n--;
}
q[n > 0 ? n - 1 : 0] = '\0';
tui_render_search_set(a->r, q);
return 1;
case TUI_KEY_KILL_START:
tui_render_search_set(a->r, "");
return 1;
case TUI_KEY_DELETE_WORD:
while (n > 0 && q[n - 1] == ' ') {
n--;
}
while (n > 0 && q[n - 1] != ' ') {
n--;
}
q[n] = '\0';
tui_render_search_set(a->r, q);
return 1;
default:
break;
}
if (!a->km || tui_keymap_apply(a->km, k)) {
(void)scroll_key(a, k);
}
return 1;
}
static void on_key(app *a, tui_key *k) {
int follow_next = 0;
tui_key enter = {.kind = TUI_KEY_ENTER};
if (k->kind == TUI_KEY_MOUSE) {
app_on_mouse(a, k);
return;
}
if (a->hs.on && hs_key(a, k)) {
return;
}
if (a->ov) {
overlay_key(a, k);
return;
}
if (a->branch_custom && k->kind == TUI_KEY_ESC) { /* Pi: back to "Summarize branch?" */
a->branch_custom = 0;
summary_open(a);
return;
}
if (a->mp_open) {
picker_key(a, k);
return;
}
if (a->picking) {
if (k->kind == TUI_KEY_UP && a->pick_at > 0) {
a->pick_at--;
} else if (k->kind == TUI_KEY_DOWN && a->pick_at + 1 < a->npick) {
a->pick_at++;
} else if (k->kind == TUI_KEY_ENTER) {
char *id = strdup(a->pick_ids[a->pick_at]);
pick_free(a);
if (id) {
resume(a, id);
}
free(id);
} else if (k->kind == TUI_KEY_ESC || k->kind == TUI_KEY_CTRL_C) {
pick_free(a);
}
return;
}
if (k->kind != TUI_KEY_CTRL_C) {
a->ctrl_c_armed = 0;
}
if (k->kind != TUI_KEY_CTRL_D) {
a->d_at = 0;
}
if (k->kind != TUI_KEY_ESC) {
a->esc_at = 0;
}
if (menu_key(a, k) || scroll_key(a, k)) {
return;
}
if (a->unfinished[0] && !a->working && !a->bash.running && tui_editor_empty(a->ed) &&
(k->kind == TUI_KEY_ENTER || k->kind == TUI_KEY_ESC)) {
if (k->kind == TUI_KEY_ENTER) {
resume_unfinished(a);
} else {
(void)drop_unfinished(a);
}
return;
}
if (k->kind == TUI_KEY_CTRL_HOME || k->kind == TUI_KEY_CTRL_END) { /* regular mode: Home and End, as before */
k->kind = k->kind == TUI_KEY_CTRL_HOME ? TUI_KEY_HOME : TUI_KEY_END;
}
switch (k->kind) {
case TUI_KEY_CTRL_C:
if (a->working && !a->interrupted) { /* Claude Code: Ctrl+C interrupts a running reply; again, it exits */
tui_key esc = {.kind = TUI_KEY_ESC};
on_key(a, &esc);
a->ctrl_c_armed = 1;
return;
}
if (!tui_editor_empty(a->ed)) {
tui_editor_clear(a->ed);
} else if (a->ctrl_c_armed) {
a->quit = 1;
} else {
a->ctrl_c_armed = 1;
(void)snprintf(a->status, sizeof a->status, "press ctrl+c again to quit");
}
return;
case TUI_KEY_CTRL_D:
if (tui_editor_empty(a->ed)) { /* Claude Code: a second press within QUIT_WINDOW_MS */
long now = now_ms();
if (a->d_at && now - a->d_at < QUIT_WINDOW_MS) {
a->quit = 1;
} else {
a->d_at = now;
flash_for(a, "press ctrl+d again to exit", QUIT_WINDOW_MS);
}
} else { /* Pi: delete the character under the cursor */
tui_key del = {.kind = TUI_KEY_DELETE};
(void)tui_editor_key(a->ed, &del);
}
return;
case TUI_KEY_ESC: {
const char *cur = tui_editor_text(a->ed);
if (a->working) { /* interrupt: queued messages come back to the editor, as Pi does */
dequeue(a, 0);
if (!a->interrupted) {
a->interrupted = 1;
a->stop_at = now_ms();
a->stop_level = 1;
/* Pi's abort over the pipe; the signals are the fallback for a child that takes none. */
if (send_command(a, "{\"id\":\"esc\",\"type\":\"abort\"}") == 0) {
a->abort_sent = 1;
} else {
(void)kill(a->run.pid, SIGINT);
}
} else if (a->abort_sent) { /* Esc again: the signal */
a->abort_sent = 0;
a->stop_at = now_ms();
(void)kill(a->run.pid, SIGINT);
} else if (a->stop_level < 3) { /* and again: harder */
a->stop_level++;
(void)kill(a->run.pid, a->stop_level == 2 ? SIGTERM : SIGKILL);
}
} else if (a->bash.running) {
bash_cancel(a);
} else if (cur[strspn(cur, " \t")] == '!') { /* bash mode: Esc clears the line */
tui_editor_clear(a->ed);
} else if (cur[strspn(cur, " \t\n")]) { /* Claude Code: Esc Esc clears the draft */
long now = now_ms();
if (a->esc_at && now - a->esc_at < 500) {
a->esc_at = 0;
tui_editor_clear(a->ed);
} else {
a->esc_at = now;
}
} else { /* Esc Esc on an empty editor: /tree */
long now = now_ms();
if (a->esc_at && now - a->esc_at < 500) {
char tree[] = "/tree";
a->esc_at = 0;
app_command(a, tree);
} else {
a->esc_at = now;
}
}
return;
}
case TUI_KEY_UP: { /* Claude Code: Up from the first line pulls queued messages back into the editor */
const char *t = tui_editor_text(a->ed);
size_t c = tui_editor_cursor(a->ed);
if (a->working && a->nsteer + a->nfollow + a->nqueue + a->nsent > 0 && !memchr(t, '\n', c)) {
dequeue(a, 1);
return;
}
break;
}
case TUI_KEY_ALT_UP: /* Pi's app.message.dequeue */
dequeue(a, 1);
return;
case TUI_KEY_CTRL_G:
external_editor(a);
return;
case TUI_KEY_CTRL_Z:
suspend_ui(a);
return;
case TUI_KEY_CTRL_X: /* Pi's app.message.copy: the selection when it is not copied on select */
if (tui_render_is_fullscreen(a->r) && !a->copy_on_select && copy_selection(a)) {
return;
}
copy_last(a);
return;
case TUI_KEY_CTRL_L: /* Pi's model picker key; while a reply runs it applies from the next request */
open_models(a, NULL);
return;
case TUI_KEY_CTRL_P:
cycle_model(a, 1);
return;
case TUI_KEY_CTRL_P_BACK: /* Shift+Ctrl+P: the previous model */
cycle_model(a, -1);
return;
case TUI_KEY_CTRL_T: /* Pi's toggle for thinking blocks, saved as hideThinking */
a->hide_thinking = !thinking_hidden(a);
(void)pic_setting_set("hideThinking", a->hide_thinking ? "true" : "false");
redraw_transcript(a);
notice(a, DIM, "thinking blocks: %s", a->hide_thinking ? "hidden" : "visible");
return;
case TUI_KEY_BACKTAB: /* Pi's thinking level key */
cycle_level(a);
return;
case TUI_KEY_CTRL_O:
a->expand_tools = !a->expand_tools;
redraw_transcript(a);
return;
case TUI_KEY_CTRL_S: /* Pi's app.thinking.save */
ensure_level(a);
if (a->nlvl > 1 && pic_setting_set("defaultThinkingLevel", a->level) == 0) {
notice(a, DIM, "saved thinking level: %s", a->level);
}
return;
case TUI_KEY_ACTION: { /* Pi's app.session.* actions run their slash commands */
static const char *const cmds[] = {NULL, "/new", "/tree", "/fork", "/resume"};
if (k->action == TUI_ACT_REDRAW) {
tui_render_invalidate(a->r);
return;
}
if (k->action == TUI_ACT_HISTORY_SEARCH) {
hs_open(a);
return;
}
if (k->action == TUI_ACT_SEARCH_TOGGLE) { /* Pi's alt-screen search: fullscreen only */
(void)tui_render_search_toggle(a->r);
return;
}
if (k->action >= TUI_ACT_SEARCH_NEXT && k->action <= TUI_ACT_SEARCH_CLOSE) { /* a key bound to one of them alone */
if (k->action == TUI_ACT_SEARCH_CLOSE) {
tui_render_search_close(a->r);
} else {
tui_render_search_step(a->r, k->action == TUI_ACT_SEARCH_NEXT ? 1 : -1);
}
return;
}
if (k->action >= TUI_ACT_SESSION_NEW && k->action <= TUI_ACT_SESSION_RESUME) {
char cmd[16];
(void)snprintf(cmd, sizeof cmd, "%s", cmds[k->action]);
app_command(a, cmd);
}
return;
}
case TUI_KEY_CTRL_V:
clipboard_paste(a);
return;
default:
break;
}
if (k->kind == TUI_KEY_ENTER) { /* Claude Code: a backslash then Enter is a newline */
const char *t = tui_editor_text(a->ed);
size_t c = tui_editor_cursor(a->ed);
if (c > 0 && t[c - 1] == '\\' && c == strlen(t)) {
tui_key bs = {.kind = TUI_KEY_BACKSPACE}, nl = {.kind = TUI_KEY_NEWLINE};
(void)tui_editor_key(a->ed, &bs);
(void)tui_editor_key(a->ed, &nl);
return;
}
}
if (k->kind == TUI_KEY_ALT_ENTER) { /* Pi's app.message.followUp: Enter's twin that queues a follow-up */
follow_next = 1;
k = &enter;
}
if (tui_editor_key(a->ed, k) == TUI_EDIT_SUBMIT) {
tui_attachment *images = NULL;
size_t nimages = 0;
char *msg;
/* Images go with the message, to a request or to the running one as a steer or follow-up;
* the queues keep only text, so they wait (the editor is left as it is). */
if (tui_editor_attached(a->ed) > 0 &&
(a->bash.running ||
(a->working && (a->interrupted || a->finishing || a->nsent + a->nsteer + a->nfollow >= MAX_QUEUED)))) {
notice(a, RED, "images cannot be queued: send this once the reply has ended");
return;
}
msg = tui_editor_take_attached(a->ed, &images, &nimages);
if (msg) {
if (a->status[0] && !a->working) {
a->status[0] = '\0';
}
(void)tui_render_edge(a->r, 1); /* sending a message follows the end again */
submit_mode(a, msg, follow_next, images, nimages);
}
for (size_t i = 0; i < nimages; i++) {
free(images[i].data);
}
free(images);
free(msg);
}
}
/* ---- the startup header --------------------------------------------------- */
/* A path as Pi lists it: relative to the workspace when inside it, else with
* the home directory as "~". */
static void short_path(const char *real_ws, const char *p, char *out, size_t cap) {
const char *home = getenv("HOME");
size_t wl = strlen(real_ws), hl = home ? strlen(home) : 0;
if (strncmp(p, real_ws, wl) == 0 && p[wl] == '/') {
(void)snprintf(out, cap, "%s", p + wl + 1);
} else if (hl > 1 && strncmp(p, home, hl) == 0 && p[hl] == '/') {
(void)snprintf(out, cap, "~%s", p + hl);
} else {
(void)snprintf(out, cap, "%s", p);
}
}
static void add_section(app *a, const char *name, char **items, size_t n, int sort) {
tui_lines l = {NULL, 0, 0};
if (n == 0) {
return;
}
(void)tui_loaded_section(name, (const char *const *)items, n, sort, a->cols > 2 ? (size_t)a->cols : 2, &l);
(void)tui_lines_add(&l, "", 0);
commit_lines(a, &l);
}
/* Pi's header: the name and model, the key hints, then what was loaded: the
* instruction files, skills and prompt templates. */
static void startup_header(app *a) {
char hints[512], real[PATH_MAX], **items;
tui_lines l = {NULL, 0, 0};
char *ctx = pic_project_instructions(a->o->workspace);
size_t n = 0, cap;
notice(a, BOLD, "pic %s", a->model);
tui_startup_hints(hints, sizeof hints);
(void)tui_wrap(hints, strlen(hints), a->cols > 2 ? (size_t)a->cols : 2, &l);
commit_lines(a, &l);
{
static const char help[] = " \xe2\x80\x94 /help for all keys and commands";
size_t hw = tui_width(help, strlen(help));
char fit[PATH_MAX + 8];
/* a long workspace gives way from the left, so the line does not wrap */
tui_fit_path(a->o->workspace, a->cols > (int)hw + 8 ? (size_t)a->cols - hw : (size_t)-1, fit, sizeof fit);
notice(a, DIM, "%s%s", fit, help);
}
(void)tui_lines_add(&l, "", 0);
commit_lines(a, &l);
if (!realpath(a->o->workspace, real)) {
(void)snprintf(real, sizeof real, "%s", a->o->workspace);
}
cap = 16 + a->skl.n + a->tpl.n;
for (const char *at = ctx; at && (at = strstr(at, "<project_instructions path=\"")); at++) {
cap++;
}
items = calloc(cap, sizeof *items);
if (!items) {
free(ctx);
return;
}
for (const char *at = ctx; at && (at = strstr(at, "<project_instructions path=\"")) && n < cap;) {
const char *from = at + strlen("<project_instructions path=\""), *end = strchr(from, '"');
char path[PATH_MAX], shown[PATH_MAX];
at = from;
if (!end || (size_t)(end - from) >= sizeof path) {
break;
}
(void)snprintf(path, sizeof path, "%.*s", (int)(end - from), from);
short_path(real, path, shown, sizeof shown);
items[n++] = strdup(shown);
}
add_section(a, "Context", items, n, 0);
for (size_t i = 0; i < n; i++) {
free(items[i]);
}
n = 0;
for (size_t i = 0; i < a->skl.n; i++) {
items[n++] = a->skl.v[i].name;
}
add_section(a, "Skills", items, n, 1);
n = 0;
for (size_t i = 0; i < a->tpl.n; i++) {
char name[160];
(void)snprintf(name, sizeof name, "/%s", a->tpl.v[i].name);
items[n++] = strdup(name);
}
add_section(a, "Prompts", items, n, 1);
for (size_t i = 0; i < n; i++) {
free(items[i]);
}
free(items);
free(ctx);
}
/* ---- main loop -------------------------------------------------------- */
int pic_tui_main(const pic_tui_options *o) {
app a;
int rc = 0;
memset(&a, 0, sizeof a);
a.o = o;
(void)snprintf(hook_owner, sizeof hook_owner, "tui-%ld-%lld", (long)getpid(), (long long)pic_platform_get()->wall_ns());
{ /* what on_stop runs, when there are hooks to end conversations for */
pic_hooks *h = pic_hooks_load(o->workspace, NULL, NULL);
if (h) {
const char *argv[] = {o->self, "--db", o->db, "--workspace", o->workspace, "hooks", "end", "other", NULL};
char owner[96];
(void)snprintf(owner, sizeof owner, "PIC_HOOK_OWNER=%s", hook_owner);
(void)pic_host_exec_prepare(&stop_exec, argv, owner);
}
pic_hooks_free(h);
}
a.run.out = a.run.err = -1;
(void)snprintf(a.model, sizeof a.model, "%s", o->model);
(void)snprintf(a.default_model, sizeof a.default_model, "%s", o->default_model ? o->default_model : o->model);
a.refresh.out = a.refresh.err = -1;
{
char *hide = pic_setting("hideThinking");
a.hide_thinking = hide && strcmp(hide, "true") == 0;
free(hide);
}
if (sqlite3_open(":memory:", &a.db) != SQLITE_OK ||
sqlite3_prepare_v2(a.db, "SELECT json_extract(?1, ?2) WHERE json_valid(?1)", -1, &a.get, NULL) != SQLITE_OK ||
!(a.r = tui_render_new(STDOUT_FILENO)) || !(a.tr = tui_transcript_new()) || !(a.ed = tui_editor_new()) ||
!(a.keys = tui_keys_new()) ||
pipe(wake_pipe) != 0 || tui_term_raw(STDIN_FILENO) != 0) {
fprintf(stderr, "pic: cannot start the terminal interface\n");
rc = 1;
goto done;
}
(void)fcntl(wake_pipe[0], F_SETFL, fcntl(wake_pipe[0], F_GETFL) | O_NONBLOCK);
(void)fcntl(wake_pipe[0], F_SETFD, FD_CLOEXEC);
(void)fcntl(wake_pipe[1], F_SETFD, FD_CLOEXEC);
(void)atexit(tui_term_restore);
load_templates(&a);
if (o->theme) {
(void)snprintf(a.theme_cli, sizeof a.theme_cli, "%s", o->theme);
}
keys_load(&a);
themes_load(&a);
(void)signal(SIGSEGV, on_stop);
(void)signal(SIGABRT, on_stop);
(void)signal(SIGBUS, on_stop);
(void)signal(SIGWINCH, on_winch);
(void)signal(SIGTERM, on_stop);
(void)signal(SIGHUP, on_stop);
(void)signal(SIGQUIT, on_stop);
(void)signal(SIGPIPE, SIG_IGN);
(void)signal(SIGINT, SIG_IGN); /* raw mode sends Ctrl+C as a key; a stray SIGINT is ignored */
tui_term_size(STDOUT_FILENO, &a.cols, &a.rows);
fs_apply(&a);
{
char *mode = o->tui_mode ? strdup(o->tui_mode) : fs_setting("tuiMode");
(void)tui_render_fullscreen(a.r, !mode || strcmp(mode, "regular") != 0, a.cols, a.rows);
free(mode);
}
(void)tui_git_branch(o->workspace, a.branch, sizeof a.branch);
a.links = tui_hyperlinks_supported();
startup_header(&a);
warn_flush(&a);
if (o->resume) {
const char *args[] = {"sessions", "--json", NULL};
char *out = NULL;
if (strcmp(o->resume, "latest") == 0) {
if (run_sync(&a, args, &out) == 0 && out && *out) {
char *nl = strchr(out, '\n'), *id;
if (nl) {
*nl = '\0';
}
id = jget(&a, out, "$.id");
if (id) {
resume(&a, id);
}
free(id);
}
free(out);
} else {
resume(&a, o->resume);
}
}
if (o->pick) {
open_picker(&a);
}
while (!a.quit) {
struct pollfd p[6]; /* stdin, wake, the request's two pipes, the catalog refresh, a "!" command */
int n = 0, timeout = -1;
tui_key k;
if (resized) {
resized = 0;
tui_term_size(STDOUT_FILENO, &a.cols, &a.rows);
tui_render_size(a.r, a.cols, a.rows);
tui_render_invalidate(a.r);
}
sync_title(&a);
draw(&a);
p[n++] = (struct pollfd){STDIN_FILENO, POLLIN, 0};
p[n++] = (struct pollfd){wake_pipe[0], POLLIN, 0};
if (a.run.out >= 0) {
p[n++] = (struct pollfd){a.run.out, POLLIN, 0};
}
if (a.run.err >= 0) {
p[n++] = (struct pollfd){a.run.err, POLLIN, 0};
}
if (a.refreshing && a.refresh.out >= 0) {
p[n++] = (struct pollfd){a.refresh.out, POLLIN, 0};
}
if (a.bash.running && a.bash.c.out >= 0) {
p[n++] = (struct pollfd){a.bash.c.out, POLLIN, 0};
}
if (a.refreshing && timeout < 0) {
timeout = 250; /* notice the refresh ending */
}
if (a.working) {
timeout = 80; /* the spinner */
}
if (a.bash.running) {
timeout = 50; /* the command may exit without closing its pipe (a background child) */
}
if (tui_keys_waiting(a.keys)) {
timeout = 50; /* a lone Esc, or the start of a sequence */
}
{
long wake = tui_render_wake(a.r); /* the scrollbar hiding again */
if (a.flash[0] && a.flash_until - now_ms() > 0 && (wake < 0 || a.flash_until - now_ms() < wake)) {
wake = a.flash_until - now_ms() + 1;
}
if (wake >= 0 && (timeout < 0 || wake < timeout)) {
timeout = (int)wake;
}
}
if (poll(p, (nfds_t)n, timeout) < 0 && errno != EINTR) {
rc = 1;
break;
}
a.spin++;
if (p[1].revents) {
char buf[64];
while (read(wake_pipe[0], buf, sizeof buf) > 0) {
}
}
if (p[0].revents & POLLIN) {
char buf[4096];
ssize_t got = read(STDIN_FILENO, buf, sizeof buf);
if (got == 0) {
break; /* the terminal went away */
}
if (got > 0) {
tui_keys_feed(a.keys, buf, (size_t)got);
}
} else if (tui_keys_waiting(a.keys)) {
tui_keys_flush(a.keys);
}
while (tui_keys_next(a.keys, &k)) {
if (tui_render_search_active(a.r) && search_key(&a, &k)) {
free(k.paste);
continue;
}
/* In fullscreen the search key wins over an editor key it shares (ctrl+f, cursor right elsewhere). */
if (a.km && tui_render_is_fullscreen(a.r) && !a.mp_open && !a.ov && !a.picking && !a.hs.on &&
tui_keymap_has(a.km, "tui.altScreen.search", &k)) {
(void)tui_render_search_toggle(a.r);
free(k.paste);
continue;
}
if (!a.km || tui_keymap_apply(a.km, &k)) { /* Pi's keybindings: a key bound to nothing is dropped */
on_key(&a, &k);
}
free(k.paste);
}
if (a.working && a.run.pid > 0) {
app_pump(&a);
}
if (a.bash.running) {
bash_pump(&a);
run_queued(&a);
}
if (a.refreshing) {
pump_refresh(&a);
}
}
if (a.bash.running) { /* quitting under a "!" command: it does not outlive pic */
long t0 = now_ms();
int level = 0;
(void)kill(a.bash.c.pid, SIGINT); /* pic bash cancels the command and journals it */
while (waitpid(a.bash.c.pid, NULL, WNOHANG) == 0) {
(void)poll(NULL, 0, 20);
if (now_ms() - t0 > 3000 * (level + 1) && level < 2) {
(void)kill(a.bash.c.pid, ++level == 1 ? SIGTERM : SIGKILL);
}
}
}
if (a.working && a.run.pid > 0) { /* quitting mid-reply: cancel it, firmly if it must be */
long t0 = now_ms();
int level = 1, status = 0;
(void)kill(a.run.pid, SIGINT);
while (waitpid(a.run.pid, &status, WNOHANG) == 0) {
struct pollfd p[2] = {{a.run.out, POLLIN, 0}, {a.run.err, POLLIN, 0}};
(void)poll(p, 2, 100);
(void)drain(&a.run);
if (now_ms() - t0 > STOP_GRACE_MS * level && level < 3) {
level++;
(void)kill(a.run.pid, level == 2 ? SIGTERM : SIGKILL);
}
}
run_ended(&a.run, status);
child_pid = 0;
free(a.run.outbuf.buf);
free(a.run.errbuf.buf);
if (a.run.in >= 0) {
close(a.run.in);
}
}
if (a.refreshing && a.refresh.pid > 0) { /* the catalog refresh: not worth waiting long for */
long t0 = now_ms();
(void)kill(a.refresh.pid, SIGTERM);
while (waitpid(a.refresh.pid, NULL, WNOHANG) == 0) {
if (now_ms() - t0 > 2000) {
(void)kill(a.refresh.pid, SIGKILL);
(void)waitpid(a.refresh.pid, NULL, 0);
break;
}
(void)poll(NULL, 0, 20);
}
free(a.refresh.outbuf.buf);
free(a.refresh.errbuf.buf);
}
if (a.r) {
hook_end(&a, "prompt_input_exit");
}
(void)tui_render_finish(a.r);
done:
tui_term_restore();
if (a.conversation[0] && rc == 0) { /* first, and flushed: what follows may be slow on a busy machine */
printf("pic: conversation %s (pic chat --session %s, or pic tui -c)\n", a.conversation, a.conversation);
(void)fflush(stdout);
}
pick_free(&a);
ov_free(&a);
app_models_free(&a);
free(a.last_reply);
bash_settle(&a);
qfree(a.steer_q, &a.nsteer);
qfree(a.follow_q, &a.nfollow);
qfree(a.sent_q, &a.nsent);
pic_prompts_free(&a.tpl);
pic_skills_free(&a.skl);
for (int i = 0; i < a.nqueue; i++) {
free(a.queue[i]);
}
free(a.stream.buf);
free(a.thinking.buf);
for (int i = 0; i < a.nblocks; i++) {
block_free(&a.blocks[i]);
}
free(a.blocks);
if (a.keys) {
tui_keys_free(a.keys);
}
tui_keymap_free(a.km);
tui_themeset_free(&a.themes);
free(a.startup_warn);
if (a.ed) {
tui_editor_free(a.ed);
}
if (a.r) {
tui_render_free(a.r);
}
tui_transcript_free(a.tr);
sqlite3_finalize(a.get);
sqlite3_close(a.db);
return rc;
}