/* 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "compact.h" #include "hooks.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/fuzzy.h" #include "tui/markdown.h" #include "tui/render.h" #include "tui/term.h" #include "tui/tui.h" #include "tui/view.h" #include "tui/viewport.h" #include "tui/width.h" #include "userdb.h" #define DIM "\x1b[2m" #define BOLD "\x1b[1m" #define CYAN "\x1b[36m" #define GREEN "\x1b[32m" #define RED "\x1b[31m" #define YELLOW "\x1b[33m" #define RESET "\x1b[0m" #define THINK_STYLE "\x1b[2;3m" /* dim italic: Pi's thinking text */ #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; 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 */ 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 */ /* /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 */ 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; } 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 enum { OV_NONE, OV_SETTINGS, OV_SCOPED, OV_THINKING, OV_TREE, OV_TRUST, OV_SHARE, OV_SUMMARY }; 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 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_render_commit(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 msg[1024]; va_list ap; va_start(ap, fmt); (void)vsnprintf(msg, sizeof msg, fmt, ap); va_end(ap); commit_text(a, style, 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: dim italic text, or Pi's one-line marker when hidden. */ static void commit_thinking(app *a) { if (a->thinking.len) { if (thinking_hidden(a)) { commit_text(a, THINK_STYLE, "Thinking..."); } else { size_t n = a->thinking.len; while (n > 0 && (a->thinking.buf[n - 1] == '\n' || a->thinking.buf[n - 1] == ' ')) { n--; } a->thinking.buf[n] = '\0'; commit_text(a, THINK_STYLE, a->thinking.buf); } } 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 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); 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); } } else { const char *bsgr = DIM, *bst = ""; char bbuf[1024]; 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->flash[0] && now_ms() < a->flash_until) { bst = a->flash; } 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; (void)tui_border_line(bsgr, bst, cols, &tail); /* Pi's editor: status in the top border */ before = tail.n; if (tui_editor_render(a->ed, cols, &tail, &er, &ec) == 0) { crow = (int)before + er; ccol = ec; } (void)tui_border_line(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", 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) { const char *t = a->thinking.buf, *last = strrchr(t, '\n'); if (a->hide_thinking) { add_fit(&s, THINK_STYLE, "Thinking...", a->cols); } else { add_fit(&s, THINK_STYLE, last && last[1] ? last + 1 : t, a->cols); } } 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++) { 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[34]; char exec_s[16], window_s[24]; int n = 0, out[2], err[2], in[2] = {-1, -1}; 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; } 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 < 33; 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); } c->pid = fork(); if (c->pid == 0) { int null = open("/dev/null", O_RDONLY); /* 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); } 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 bash_start(app *a, const char *cmd, int no_context) { const char *args[10]; int n = 0; bash_settle(a); 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; tui_lines l = {NULL, 0, 0}; 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}; (void)tui_bash_lines(&b, a->expand_tools, a->cols > 2 ? (size_t)a->cols : 2, &l); commit_lines(a, &l); 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 ----------------------------------------- */ static void start_request(app *a, const char *msg) { const char *args[7]; int n = 0; args[n++] = "--json"; args[n++] = "--commands"; args[n++] = "ask"; if (a->conversation[0]) { args[n++] = "--session"; args[n++] = a->conversation; } args[n++] = msg; args[n] = NULL; commit_user(a, msg); if (spawn_in(a, &a->run, args, 1) != 0) { notice(a, RED, "pic: could not start the request: %s", strerror(errno)); return; } child_pid = a->run.pid; { char what[PATH_MAX + 8]; (void)snprintf(what, sizeof what, "pic --json ask %.200s", msg); 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); ssize_t w; if (a->run.in < 0) { return -1; } /* Whole lines are far below the pipe's atomic size; a full pipe is a stuck child. */ w = write(a->run.in, json, n); if (w == (ssize_t)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) { sqlite3_stmt *q = NULL; int rc = -1; if (a->run.in < 0 || sqlite3_prepare_v2(a->db, "SELECT json_object('type', ?1, 'message', ?2)", -1, &q, NULL) != SQLITE_OK) { return -1; } sqlite3_bind_text(q, 1, type, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, msg, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { rc = send_command(a, (const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); return rc; } static void block_free(toolblk *b) { free(b->title); free(b->diff); free(b->output); 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}; (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) { tui_lines l = {NULL, 0, 0}; block_lines(&a->blocks[n], a->expand_tools, a->cols > 2 ? (size_t)a->cols : 2, &l); commit_lines(a, &l); } 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); } /* An edit's diff, one hunk per replacement ({oldText,newText} in edits[], or at the top level). */ static char *edit_diff(app *a, const char *ev) { text all = {NULL, 0, 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_) { char *d = tui_diff_text(old ? old : "", new_ ? new_ : ""); 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); } free(old); free(new_); if (!old && !new_) { break; } } 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->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; /* 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, "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. */ if (a->stream_off > 0) { notice(a, YELLOW, "(the reply above was cut off; it is requested again)"); } 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 (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, "request cancelled"); } 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 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)) { command(a, next); } else { start_request(a, next); } free(next); } } /* Handles complete event lines; at the end of the child, settles the run. */ static void 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->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 ---------------------------------------------------------- */ static void show_history(app *a) { const char *args[] = {"log", "--json", a->conversation, NULL}; char *out = NULL; 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 (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_lines l = {NULL, 0, 0}; 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}; (void)tui_bash_lines(&b, 0, a->cols > 2 ? (size_t)a->cols : 2, &l); commit_lines(a, &l); 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) && 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) { char *tool = jget(a, line, "$.tool"); notice(a, DIM, " %s: %.*s", tool ? tool : "tool", (int)strcspn(t ? t : "", "\n"), t ? t : ""); free(tool); } 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 collapsed BranchSummaryMessageComponent */ notice(a, BOLD, "[branch]"); notice(a, "", "Branch summary"); } free(bash_cmd); free(kind); free(t); } } 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; } static void open_picker(app *a) { const char *args[] = {"sessions", "--json", NULL}; char *out = 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, row[512], **ids, **rows; nl = strchr(line, '\n'); if (nl) { *nl = '\0'; } id = jget(a, line, "$.id"); name = jget(a, line, "$.name"); first = jget(a, line, "$.first"); 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; } if (id && ids && rows) { (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); a->npick++; id = NULL; } free(id); free(name); free(first); } } free(out); 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] = '\0'; if (run_sync(a, args, &out) == 0) { for (char *line = out, *nl; line && *line; line = nl ? nl + 1 : NULL) { char *lid, *name; nl = strchr(line, '\n'); if (nl) { *nl = '\0'; } lid = jget(a, line, "$.id"); name = jget(a, line, "$.name"); if (lid && strcmp(lid, id) == 0 && name) { (void)snprintf(a->name, sizeof a->name, "%s", name); } free(lid); free(name); } } free(out); notice(a, DIM, "\xe2\x94\x80 continuing %s \xe2\x94\x80", id); show_history(a); } /* ---- the model picker (Pi's, see model-selector.ts) ---------------------- */ static void 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(app *a) { const char *args[] = {"models", "--json", NULL}; char *out = NULL; int cap = 0; 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; 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; } 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"}}, }; /* 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 ? "on" : "off"); free(v); ov_add(a, label, "piSessionFiles", 0); (void)snprintf(label, sizeof label, "%-26s %s", "Hide thinking", a->hide_thinking ? "on" : "off"); 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); ov_refilter(a); a->ov_sel = 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); } /* 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; } (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"); } 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 { 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_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_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); } add_fit(tail, DIM, a->ov_hint, a->cols); } static void overlay_key(app *a, const tui_key *k) { size_t len = strlen(a->ov_filter); 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_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; } } /* 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(a); (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]", "branch this conversation (from ENTRY, see /log)"}, {"clone", "", "duplicate this conversation at its current point"}, {"compact", "[FOCUS]", "summarize the history before the next message"}, {"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 and the model catalog"}, {"trust", "[yes|no]", "save the workspace trust decision"}, {"changelog", "", "show what changed"}, {"bug", "TEXT", "record a bug report (kept locally, sent nowhere)"}, {"login", "", "configure provider authentication"}, {"logout", "", "remove provider authentication"}, {"hotkeys", "", "show keyboard shortcuts"}, {"quit", "", "quit pic"}, }; #define NCOMMANDS (sizeof commands / sizeof commands[0]) #define MENU_ROWS 5 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_ROWS][256], values[MENU_ROWS][256]; int is_command; size_t n = menu_items(a, labels, values, MENU_ROWS, &is_command); if (a->menu_sel >= (int)n) { a->menu_sel = 0; } for (size_t i = 0; i < n; i++) { add_fit(tail, (int)i == a->menu_sel ? CYAN : DIM, labels[i], 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_ROWS][256], values[MENU_ROWS][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_ROWS, &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(app *a, const char *msg) { (void)snprintf(a->flash, sizeof a->flash, "%s", msg); a->flash_until = now_ms() + 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."); } } static const char hotkeys[] = "Enter send (while a reply runs: steer it) Ctrl+J / Shift+Enter new line\n" "Alt+Enter queue a follow-up for after the reply\n" "Esc interrupt the reply (again: stop it harder; restores queued messages)\n" "Esc Esc on an empty editor open /tree Alt+Up restore queued messages\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" "Ctrl+L model picker Ctrl+P / Shift+Ctrl+P next / previous model\n" "Ctrl+O expand tool output (calls still in view and later ones) Ctrl+T show/hide thinking\n" "Ctrl+C clear the editor (twice: quit) Ctrl+D quit on an empty editor\n" "Ctrl+K / Ctrl+U / Ctrl+W / Alt+D kill (delete into the kill ring) Ctrl+Y yank Alt+Y yank-pop\n" "Ctrl+- undo Ctrl+] jump to a character (Ctrl+Alt+] backward)\n" "Ctrl+G edit in $VISUAL / $EDITOR Ctrl+X copy the last reply Ctrl+Z suspend\n" "Up/Down history Tab complete a /command or a model name\n" "Fullscreen: PageUp/PageDown scroll the transcript, Ctrl+Home/Ctrl+End its top/bottom, the wheel scrolls,\n" " dragging selects (copied at once, or with Ctrl+X when fullscreenCopyOnSelect is false)"; static void 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 || strcmp(line, "/hotkeys") == 0) { notice(a, DIM, "%s", hotkeys); 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)); } if (t.buf) { notice(a, DIM, "%s", 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] = '\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); notice(a, DIM, "reloaded: %s; %zu prompt templates; %d models with a key%s", ins && *ins ? "project instructions found (every request reads them afresh)" : "no project instructions (AGENTS.md, CLAUDE.md)", a->tpl.n, a->nmodels, refresh_catalog(a) ? " (the catalog is refreshing in the background)" : ""); 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) { notice(a, DIM, "no changelog yet: pic does not ship one"); } 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 || strcmp(line, "/logout") == 0) { notice(a, DIM, "%s is not available yet", line); } else if (!a->conversation[0]) { if (strcmp(line, "/name") == 0 || strcmp(line, "/fork") == 0 || strcmp(line, "/compact") == 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 || 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) { const char *args[] = {"compact", a->conversation, *arg ? arg : NULL, NULL}; if (run_sync(a, args, &out) == 0) { notice(a, DIM, "the history is summarized before the next message"); } } 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]; (void)snprintf(dflt, sizeof dflt, "pic-session-%s.html", a->conversation); const char *args[] = {"export", "--html", a->conversation, *arg ? arg : dflt, NULL}; if (run_sync(a, args, &out) == 0) { notice(a, DIM, "written to %s as one self-contained web page", args[3]); } } else { const char *args[] = {"export", "--pi", arg, NULL}; if (run_sync(a, args, &out) == 0) { notice(a, DIM, "written to %s as Pi session files (one per conversation)", arg); } } } 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) { 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)) { 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) == 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); } } static void submit(app *a, char *msg) { submit_mode(a, msg, 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 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; default: return 0; } } 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) { on_mouse(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_ESC) { a->esc_at = 0; } if (menu_key(a, k) || scroll_key(a, k)) { 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 (!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)) { a->quit = 1; } 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")]) { /* 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; command(a, tree); } else { a->esc_at = now; } } return; } 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"); 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; return; default: break; } 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) { char *msg = tui_editor_take(a->ed); if (msg) { if (a->status[0] && !a->working) { a->status[0] = '\0'; } submit_mode(a, msg, follow_next); } 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); notice(a, DIM, "%s \xe2\x80\x94 /help for all keys and commands", a->o->workspace); (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, "= 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.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); (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); 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); } } 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)) { on_key(&a, &k); free(k.paste); } if (a.working && a.run.pid > 0) { 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); 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); } if (a.ed) { tui_editor_free(a.ed); } if (a.r) { tui_render_free(a.r); } sqlite3_finalize(a.get); sqlite3_close(a.db); return rc; }