Skip to content
pi-c Documentation
Login

Documentation

/* 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 ... ask` (stdin /dev/null, events on its stdout, notices on its
 * stderr); Esc sends it SIGINT, which pic turns into a clean cancel. */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#include "sqlite3.h"
#include "tui/editor.h"
#include "tui/render.h"
#include "tui/term.h"
#include "tui/tui.h"
#include "tui/width.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 TOOL_PREVIEW_LINES 6
#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 child pic process: a request (events) or a short command (output). */
typedef struct {
    pid_t pid;
    int out, err; /* read ends; -1 once closed */
    text outbuf, errbuf;
} child;

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_done;   /* wrapped stream lines already committed */
    char status[256];     /* retry / compaction notices */
    char tool[512];       /* the running tool call's header */
    int spin;
    /* tokens over this session of the UI */
    long long in, out, cache_read, cache_write, context;
    int expand_tools;
    char *queue[MAX_QUEUED];
    int nqueue;
    int ctrl_c_armed; /* a second Ctrl-C quits */
    /* /resume picker */
    char **pick_ids, **pick_rows;
    int npick, pick_at, picking;
    int quit;
} app;

static volatile sig_atomic_t resized;
static int wake_pipe[2] = {-1, -1};

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;
    }
}

static void on_stop(int sig) {
    tui_term_restore();
    (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);
}

/* Light markdown for one logical line: headings bold, fences and code dim
 * cyan, `code` cyan, **bold** bold, "- " bullets as "• ". */
static void md_line(const char *line, int *fence, text *out) {
    const char *p = line;
    if (strncmp(line, "```", 3) == 0) {
        *fence = !*fence;
        (void)text_add(out, DIM, strlen(DIM));
        (void)text_add(out, line, strlen(line));
        (void)text_add(out, RESET, strlen(RESET));
        return;
    }
    if (*fence) {
        (void)text_add(out, CYAN, strlen(CYAN));
        (void)text_add(out, line, strlen(line));
        (void)text_add(out, RESET, strlen(RESET));
        return;
    }
    if (*p == '#') {
        while (*p == '#') {
            p++;
        }
        while (*p == ' ') {
            p++;
        }
        (void)text_add(out, BOLD, strlen(BOLD));
        (void)text_add(out, p, strlen(p));
        (void)text_add(out, RESET, strlen(RESET));
        return;
    }
    {
        size_t lead = strspn(p, " ");
        if ((p[lead] == '-' || p[lead] == '*') && p[lead + 1] == ' ') {
            (void)text_add(out, p, lead);
            (void)text_add(out, "\xe2\x80\xa2 ", 4);
            p += lead + 2;
        }
    }
    for (int code = 0, bold = 0; *p; p++) {
        if (*p == '`') {
            code = !code;
            (void)text_add(out, code ? CYAN : RESET, strlen(code ? CYAN : RESET));
            if (!code && bold) {
                (void)text_add(out, BOLD, strlen(BOLD));
            }
        } else if (!code && p[0] == '*' && p[1] == '*') {
            bold = !bold;
            (void)text_add(out, bold ? BOLD : RESET, strlen(bold ? BOLD : RESET));
            p++;
        } else {
            (void)text_add(out, p, 1);
        }
        if (!p[1] && (code || bold)) {
            (void)text_add(out, RESET, strlen(RESET));
        }
    }
}

/* The streamed reply as styled, wrapped lines. */
static void stream_lines(app *a, tui_lines *out) {
    int fence = 0;
    const char *s = a->stream.buf ? a->stream.buf : "";
    size_t cols = a->cols > 1 ? (size_t)a->cols : 1;
    while (*s) {
        size_t n = strcspn(s, "\n");
        char *line = strndup(s, n);
        text styled = {NULL, 0, 0};
        if (line) {
            md_line(line, &fence, &styled);
            (void)tui_wrap(styled.buf ? styled.buf : "", styled.len, cols, out);
        }
        free(line);
        free(styled.buf);
        s += n;
        if (*s == '\n') {
            s++;
            if (!*s) {
                (void)tui_lines_add(out, "", 0);
            }
        }
    }
}

/* 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}, rest = {NULL, 0, 0};
    stream_lines(a, &l);
    for (size_t i = a->stream_done; i < l.n; i++) {
        (void)tui_lines_add(&rest, l.lines[i], strlen(l.lines[i]));
    }
    if (rest.n) {
        commit_lines(a, &rest);
    }
    tui_lines_clear(&l);
    text_clear(&a->stream);
    text_clear(&a->thinking);
    a->stream_done = 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);
}

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], a1[16], a2[16], a3[16], a4[16];
    const char *home = getenv("HOME");
    const char *ws = a->o->workspace;
    /* Below the reply: status, queue, editor (or picker), footer. */
    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 {
        if (a->working) {
            (void)snprintf(line, sizeof line, "%s %s", frames[a->spin % 10],
                           a->interrupted ? "Stopping\xe2\x80\xa6" : a->status[0] ? a->status : "Working\xe2\x80\xa6 (esc to interrupt)");
            add_fit(&tail, a->status[0] ? YELLOW : DIM, line, a->cols);
        } else if (a->status[0]) {
            add_fit(&tail, YELLOW, a->status, a->cols);
        }
        for (int i = 0; i < a->nqueue; i++) {
            (void)snprintf(line, sizeof line, "queued: %s", a->queue[i]);
            add_fit(&tail, DIM, line, a->cols);
        }
        {
            size_t before = tail.n;
            int er = 0, ec = 0;
            if (tui_editor_render(a->ed, a->cols > 2 ? (size_t)a->cols : 2, &tail, &er, &ec) == 0) {
                crow = (int)before + er;
                ccol = ec;
            }
        }
    }
    /* footer: where, which conversation; tokens, context, model */
    if (home && *home && strncmp(ws, home, strlen(home)) == 0) {
        (void)snprintf(line, sizeof line, "~%s  %s", ws + strlen(home),
                       a->name[0] ? a->name : a->conversation[0] ? a->conversation : "new conversation");
    } else {
        (void)snprintf(line, sizeof line, "%s  %s", ws, a->name[0] ? a->name : a->conversation[0] ? a->conversation : "new conversation");
    }
    add_fit(&tail, DIM, line, a->cols);
    fmt_tokens(a->in, a1, sizeof a1);
    fmt_tokens(a->out, a2, sizeof a2);
    fmt_tokens(a->context, a3, sizeof a3);
    fmt_tokens(a->window, a4, sizeof a4);
    if (a->window > 0) {
        (void)snprintf(line, sizeof line, "\xe2\x86\x91%s \xe2\x86\x93%s  %.1f%%/%s  %s%s", a1, a2,
                       100.0 * (double)a->context / (double)a->window, a4, a->model,
                       a->expand_tools ? "  (tool output expanded)" : "");
    } else {
        (void)snprintf(line, sizeof line, "\xe2\x86\x91%s \xe2\x86\x93%s  %s  %s%s", a1, a2, a3, a->model,
                       a->expand_tools ? "  (tool output expanded)" : "");
    }
    add_fit(&tail, DIM, line, a->cols);
    /* Above: the reply being written; lines that no longer fit go to the
     * scrollback for good (only the last wrapped line can still change). */
    budget = a->rows - 1 - (int)tail.n - 1;
    if (a->stream.len || a->thinking.len || a->tool[0]) {
        tui_lines s = {NULL, 0, 0};
        if (a->stream.len) {
            stream_lines(a, &s);
        } else if (a->thinking.len) {
            const char *t = a->thinking.buf, *last = strrchr(t, '\n');
            add_fit(&s, DIM, last && last[1] ? last + 1 : t, a->cols);
        }
        if (a->stream.len && s.n > a->stream_done + 1 && (int)(s.n - a->stream_done) > (budget > 2 ? budget : 2)) {
            size_t keep = budget > 2 ? (size_t)budget : 2, upto = s.n - keep;
            tui_lines c = {NULL, 0, 0};
            for (size_t i = a->stream_done; i < upto; i++) {
                (void)tui_lines_add(&c, s.lines[i], strlen(s.lines[i]));
            }
            commit_lines(a, &c);
            a->stream_done = upto;
        }
        for (size_t i = a->stream.len ? a->stream_done : 0; i < s.n; i++) {
            (void)tui_lines_add(&live, s.lines[i], strlen(s.lines[i]));
        }
        tui_lines_clear(&s);
        if (a->tool[0]) {
            add_fit(&live, CYAN, a->tool, a->cols);
        }
        (void)tui_lines_add(&live, "", 0);
    }
    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(a->r, (const char *const *)live.lines, live.n, crow, ccol, a->rows);
    tui_lines_clear(&live);
    tui_lines_clear(&tail);
}

/* ---- child processes -------------------------------------------------- */

/* argv for this pic with the journal, workspace and model, then ARGS. */
static int spawn(app *a, child *c, const char *const *args) {
    const char *argv[32];
    char exec_s[16], window_s[24];
    int n = 0, out[2], err[2];
    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;
    }
    for (; *args && n < 31; args++) {
        argv[n++] = *args;
    }
    argv[n] = NULL;
    memset(c, 0, sizeof *c);
    c->out = c->err = -1;
    if (pipe(out) != 0 || pipe(err) != 0) {
        return -1;
    }
    c->pid = fork();
    if (c->pid == 0) {
        int null = open("/dev/null", O_RDONLY);
        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);
        execv(a->o->self, (char *const *)(void *)argv);
        _exit(127);
    }
    close(out[1]);
    close(err[1]);
    if (c->pid < 0) {
        close(out[0]);
        close(err[0]);
        return -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;
}

/* 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;
        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;
}

/* ---- requests and their events ----------------------------------------- */

static void start_request(app *a, const char *msg) {
    const char *args[6];
    int n = 0;
    args[n++] = "--json";
    args[n++] = "ask";
    if (a->conversation[0]) {
        args[n++] = "--session";
        args[n++] = a->conversation;
    }
    args[n++] = msg;
    args[n] = NULL;
    notice(a, BOLD, "> %s", msg);
    if (spawn(a, &a->run, args) != 0) {
        notice(a, RED, "pic: could not start the request: %s", strerror(errno));
        return;
    }
    a->working = 1;
    a->interrupted = a->seen_end = 0;
    a->status[0] = a->tool[0] = '\0';
}

static void show_tool_end(app *a, const char *ev) {
    char *name = jget(a, ev, "$.toolName"), *result = jget(a, ev, "$.result.content[0].text");
    int err = (int)jnum(a, ev, "$.isError");
    const char *r = result ? result : "";
    size_t lines = 0;
    text preview = {NULL, 0, 0};
    for (const char *p = r; *p; p++) {
        lines += *p == '\n';
    }
    lines += *r && r[strlen(r) - 1] != '\n';
    notice(a, err ? RED : GREEN, "%s %s", err ? "\xe2\x9c\x97" : "\xe2\x9c\x93", a->tool[0] ? a->tool : name ? name : "tool");
    if (a->expand_tools || lines <= TOOL_PREVIEW_LINES) {
        (void)text_add(&preview, r, strlen(r));
    } else {
        const char *p = r;
        for (int i = 0; i < TOOL_PREVIEW_LINES && *p; i++) {
            size_t n = strcspn(p, "\n");
            (void)text_add(&preview, p, n + (p[n] == '\n'));
            p += n + (p[n] == '\n');
        }
        {
            char more[96];
            (void)snprintf(more, sizeof more, "\xe2\x80\xa6 +%zu lines (ctrl+o expands later results)",
                           lines - TOOL_PREVIEW_LINES);
            (void)text_add(&preview, more, strlen(more));
        }
    }
    if (preview.len) {
        commit_text(a, DIM, preview.buf);
    }
    free(preview.buf);
    free(name);
    free(result);
    a->tool[0] = '\0';
}

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");
        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) {
            (void)text_add(&a->stream, delta, strlen(delta));
        } else if (kind && delta && strcmp(kind, "thinking_delta") == 0) {
            (void)text_add(&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 was only ever in the live area: drop it. */
                text_clear(&a->stream);
                text_clear(&a->thinking);
                a->stream_done = 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");
                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';
            }
        }
        free(role);
        free(stop);
    } else if (strcmp(type, "auto_retry_start") == 0) {
        char *err = jget(a, ev, "$.errorMessage");
        (void)snprintf(a->status, sizeof a->status, "Retrying (%lld/%lld): %s", jnum(a, ev, "$.attempt"),
                       jnum(a, ev, "$.maxAttempts"), err ? err : "");
        free(err);
    } else if (strcmp(type, "tool_execution_start") == 0) {
        char *name = jget(a, ev, "$.toolName"), *cmd = jget(a, ev, "$.args.command"), *path = jget(a, ev, "$.args.path");
        commit_stream(a);
        (void)snprintf(a->tool, sizeof a->tool, "%s %s", name ? name : "tool", cmd ? cmd : path ? path : "");
        free(name);
        free(cmd);
        free(path);
    } else if (strcmp(type, "tool_execution_end") == 0) {
        show_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");
        commit_stream(a);
        a->seen_end = 1;
        if (status && strcmp(status, "failed") == 0) {
            notice(a, RED, err && strcmp(err, "cancelled") == 0 ? "request cancelled" : "request failed: %s", err ? err : "");
        }
        a->status[0] = '\0';
        free(status);
        free(err);
    }
    free(type);
}

static void command(app *a, char *line);

/* 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';
    }
    if (done) {
        int status = 0;
        while (waitpid(a->run.pid, &status, 0) < 0 && errno == EINTR) {
        }
        commit_stream(a);
        if (!a->seen_end && a->run.errbuf.len) {
            notice(a, RED, "%s", a->run.errbuf.buf);
        }
        free(a->run.outbuf.buf);
        free(a->run.errbuf.buf);
        memset(&a->run, 0, sizeof a->run);
        a->run.out = a->run.err = -1;
        a->working = 0;
        a->tool[0] = '\0';
        a->status[0] = '\0';
        while (a->nqueue && !a->working && !a->quit) { /* queued commands, then the next message */
            char *next = a->queue[0];
            memmove(a->queue, a->queue + 1, (size_t)(a->nqueue - 1) * sizeof *a->queue);
            a->nqueue--;
            if (next[0] == '/') {
                command(a, next);
            } else {
                start_request(a, next);
            }
            free(next);
        }
    }
}

/* ---- 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");
            if (kind && strcmp(kind, "user") == 0) {
                notice(a, BOLD, "> %s", t ? 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");
            }
            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  %.60s", 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;
    (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);
}

static const char help[] =
    "Enter sends; Ctrl+J or Alt+Enter adds a line. While a reply runs, Enter queues the message and Esc interrupts.\n"
    "Ctrl+C clears the editor (twice quits), Ctrl+D quits on an empty editor, Ctrl+O expands later tool output,\n"
    "Ctrl+L redraws.\n"
    "/new  /resume [ID]  /name NAME  /fork [ENTRY]  /compact [FOCUS]  /model [NAME]  /help  /quit";

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) {
        notice(a, DIM, "%s", help);
    } else if (strcmp(line, "/new") == 0) {
        a->conversation[0] = a->name[0] = '\0';
        a->in = a->out = a->context = 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) {
        if (*arg) {
            (void)snprintf(a->model, sizeof a->model, "%s", arg);
            a->window = 0;
        }
        notice(a, DIM, "model %s%s", a->model, *arg ? " (from the next message)" : "");
    } else if (!a->conversation[0] &&
               (strcmp(line, "/name") == 0 || strcmp(line, "/fork") == 0 || strcmp(line, "/compact") == 0)) {
        notice(a, RED, "%s needs a conversation: send a message first", 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) {
        const char *args[] = {"fork", a->conversation, *arg ? "--at" : NULL, *arg ? arg : NULL, NULL};
        if (run_sync(a, args, &out) == 0 && out) {
            out[strcspn(out, "\n")] = '\0';
            notice(a, DIM, "\xe2\x94\x80 forked: now in %s \xe2\x94\x80", out);
            (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 {
        notice(a, RED, "unknown command %s (/help lists them)", line);
    }
    free(out);
}

static void submit(app *a, char *msg) {
    /* While a reply runs, messages and commands queue (commands need the
     * journal, which the running request holds). */
    if (msg[0] == '/' && !a->working) {
        command(a, msg);
    } else if (a->working) {
        if (a->nqueue < MAX_QUEUED) {
            a->queue[a->nqueue++] = strdup(msg);
        }
    } else {
        start_request(a, msg);
    }
}

/* ---- keys -------------------------------------------------------------- */

static void on_key(app *a, tui_key *k) {
    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;
    }
    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;
        }
        return;
    case TUI_KEY_ESC:
        if (a->working && !a->interrupted) {
            a->interrupted = 1;
            (void)kill(a->run.pid, SIGINT);
        }
        if (a->nqueue) { /* queued messages come back to the editor, as Pi does */
            text t = {NULL, 0, 0};
            for (int i = 0; i < a->nqueue; i++) {
                (void)text_add(&t, a->queue[i], strlen(a->queue[i]));
                if (i + 1 < a->nqueue) {
                    (void)text_add(&t, "\n", 1);
                }
                free(a->queue[i]);
            }
            a->nqueue = 0;
            tui_editor_set(a->ed, t.buf ? t.buf : "");
            free(t.buf);
        }
        return;
    case TUI_KEY_CTRL_L:
        tui_render_invalidate(a->r);
        return;
    case TUI_KEY_CTRL_O:
        a->expand_tools = !a->expand_tools;
        return;
    default:
        break;
    }
    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(a, msg);
        }
        free(msg);
    }
}

/* ---- main loop -------------------------------------------------------- */

int pic_tui_main(const pic_tui_options *o) {
    app a;
    int rc = 0;
    memset(&a, 0, sizeof a);
    a.o = o;
    a.run.out = a.run.err = -1;
    (void)snprintf(a.model, sizeof a.model, "%s", o->model);
    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)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);
    notice(&a, BOLD, "pic %s", a.model);
    notice(&a, DIM, "%s  \xe2\x80\x94  /help for keys and commands", o->workspace);
    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[4];
        int n = 0, timeout = -1;
        tui_key k;
        if (resized) {
            resized = 0;
            tui_term_size(STDOUT_FILENO, &a.cols, &a.rows);
            tui_render_invalidate(a.r);
        }
        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.working) {
            timeout = 80; /* the spinner */
        }
        if (tui_keys_waiting(a.keys)) {
            timeout = 50; /* a lone Esc, or the start of a sequence */
        }
        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.working && a.run.pid > 0) { /* quitting mid-reply: cancel it cleanly */
        (void)kill(a.run.pid, SIGINT);
        while (!drain(&a.run)) {
            struct pollfd p[2] = {{a.run.out, POLLIN, 0}, {a.run.err, POLLIN, 0}};
            (void)poll(p, 2, 100);
        }
        (void)waitpid(a.run.pid, NULL, 0);
        free(a.run.outbuf.buf);
        free(a.run.errbuf.buf);
    }
    (void)tui_render_finish(a.r);
done:
    tui_term_restore();
    pick_free(&a);
    for (int i = 0; i < a.nqueue; i++) {
        free(a.queue[i]);
    }
    free(a.stream.buf);
    free(a.thinking.buf);
    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);
    if (a.conversation[0] && rc == 0) {
        printf("pic: conversation %s (pic chat --session %s, or pic tui -c)\n", a.conversation, a.conversation);
    }
    return rc;
}