Skip to content
pi-c Documentation
Login

Documentation

/* pic --mode rpc: Pi's RPC mode (packages/coding-agent/src/modes/rpc in Pi;
 * docs/rpc.md and docs/rpc-commands.md). Commands arrive as JSON lines on
 * stdin; each gets Pi's response line, and Pi's events stream between them.
 *
 * The process holds the journal only while it works: per command when idle,
 * and for the length of a request, a compaction or a bash command. While one
 * of those runs, stdin is read whenever pic waits (net.h's side descriptor):
 * steering and queries are answered at once, a compact or a session change
 * aborts the request (journaled as Ctrl-C's cancel) and runs once it has
 * stopped, and anything else waits its turn. */
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "commands.h"
#include "cred.h"
#include "hooks.h"
#include "net.h"
#include "platform.h"
#include "policy.h"
#include "rpc.h"
#include "userdb.h"

#define LINE_CAP (16u << 20) /* a longer line is answered with a parse error and dropped */

enum phase { IDLE, RUN, BASH, COMPACT };

typedef struct {
    char **v;
    size_t head, n, cap;
} rpc_lines;

/* A steer or follow-up sent while idle: Pi holds it for the next run. */
typedef struct {
    char *line, *kind, *text;
} held;

static struct {
    const pic_rpc_host *h;
    sqlite3 *mem; /* JSON work, whatever the journal is doing */
    pic_events ev;
    char model[256], thinking[16];
    char sid[64]; /* the conversation; it may not be in the journal yet */
    int steer_all, follow_up_all, no_retry;
    enum phase phase;
    pic_store *cur; /* the journal, while not idle */
    char *buf;
    size_t len, cap;
    int overlong, eof, pumping;
    rpc_lines inbox, deferred;
    held *held;
    size_t nheld;
    const char *bash_id; /* the bash command's id, for its updates */
    char *bash_seen;     /* what its updates have sent */
    volatile sig_atomic_t term;
} R;

/* ---- JSON ------------------------------------------------------------------ */

static void out_line(const char *json) {
    fputs(json, stdout);
    fputc('\n', stdout);
    fflush(stdout);
}

/* The first column of SQL with A and B bound as text (NULL: null), malloc'd. */
static char *sqlv_on(sqlite3 *db, const char *sql, const char *a, const char *b) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(db, sql, -1, &q, NULL) != SQLITE_OK) {
        fprintf(stderr, "pic: rpc: %s\n", sqlite3_errmsg(db));
        return NULL;
    }
    if (a) {
        sqlite3_bind_text(q, 1, a, -1, SQLITE_STATIC);
    }
    if (b) {
        sqlite3_bind_text(q, 2, b, -1, SQLITE_STATIC);
    }
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        out = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}

static char *sqlv(const char *sql, const char *a, const char *b) { return sqlv_on(R.mem, sql, a, b); }

/* LINE's string at PATH ("$.type"), malloc'd, or NULL when it is not a string. */
static char *jtext(const char *line, const char *path) {
    return sqlv("SELECT CASE WHEN json_valid(?1) AND json_type(?1, ?2) = 'text' THEN json_extract(?1, ?2) END", line, path);
}

/* 1 or 0 for a boolean at PATH, -1 for anything else. */
static int jbool(const char *line, const char *path) {
    char *t = sqlv("SELECT CASE WHEN json_valid(?1) THEN json_type(?1, ?2) END", line, path);
    int v = t && strcmp(t, "true") == 0 ? 1 : t && strcmp(t, "false") == 0 ? 0 : -1;
    free(t);
    return v;
}

static int has_field(const char *line, const char *path) {
    char *t = sqlv("SELECT CASE WHEN json_valid(?1) THEN json_type(?1, ?2) END", line, path);
    int v = t != NULL;
    free(t);
    return v;
}

/* An images field that is neither an array nor null. */
static int bad_images(const char *line) {
    char *t = sqlv("SELECT CASE WHEN json_valid(?1) THEN json_type(?1, '$.images') END", line, NULL);
    int bad = t && strcmp(t, "array") != 0 && strcmp(t, "null") != 0;
    free(t);
    return bad;
}

static char *quote(const char *text) { return sqlv("SELECT json_quote(?1)", text, NULL); }

/* Pi's response: the command's id when it had one, then type, command,
 * success, and data (JSON; "null" is kept) or error. */
static void rpc_respond(const char *line, const char *command, const char *data, const char *error) {
    sqlite3_stmt *q = NULL;
    sqlite3_str *t;
    char *head = NULL, *res;
    if (sqlite3_prepare_v2(R.mem,
                           "SELECT json_patch('{}', json_object('id', CASE WHEN json_valid(?1) AND json_type(?1) = 'object'"
                           " THEN json_extract(?1, '$.id') END, 'type', 'response', 'command', ?2,"
                           " 'success', json(iif(?3, 'true', 'false'))))",
                           -1, &q, NULL) != SQLITE_OK) {
        return;
    }
    sqlite3_bind_text(q, 1, line ? line : "", -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, command, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 3, error == NULL);
    if (sqlite3_step(q) == SQLITE_ROW) {
        head = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    if (!head) {
        return;
    }
    t = sqlite3_str_new(NULL);
    sqlite3_str_append(t, head, (int)strlen(head) - 1);
    if (error) {
        char *e = quote(error);
        sqlite3_str_appendf(t, ",\"error\":%s", e ? e : "\"\"");
        free(e);
    } else if (data) {
        sqlite3_str_appendf(t, ",\"data\":%s", data);
    }
    sqlite3_str_appendchar(t, 1, '}');
    res = sqlite3_str_finish(t);
    if (res) {
        out_line(res);
    }
    sqlite3_free(res);
    free(head);
}

static void ok(const char *line, const char *command, const char *data) { rpc_respond(line, command, data, NULL); }
static void fail(const char *line, const char *command, const char *error) { rpc_respond(line, command, NULL, error); }

/* ---- line queues ------------------------------------------------------------- */

static void rpc_push(rpc_lines *l, const char *line) {
    char *copy = strdup(line);
    if (!copy) {
        return;
    }
    if (l->head + l->n == l->cap) {
        if (l->head > 0) {
            memmove(l->v, l->v + l->head, l->n * sizeof *l->v);
            l->head = 0;
        }
        if (l->n == l->cap) {
            size_t ncap = l->cap ? l->cap * 2 : 16;
            char **v = realloc(l->v, ncap * sizeof *v);
            if (!v) {
                free(copy);
                return;
            }
            l->v = v;
            l->cap = ncap;
        }
    }
    l->v[l->head + l->n++] = copy;
}

static char *pop(rpc_lines *l) {
    char *line;
    if (l->n == 0) {
        return NULL;
    }
    line = l->v[l->head++];
    if (--l->n == 0) {
        l->head = 0;
    }
    return line;
}

/* Reads what stdin has (blocking when BLOCK and nothing is buffered); each
 * complete line goes to the inbox. -1 at its end, else 0. */
static int fill(void) {
    ssize_t n;
    size_t start = 0;
    if (R.eof) {
        return -1;
    }
    if (R.cap - R.len < 4097) {
        size_t ncap = R.cap ? R.cap * 2 : 8192;
        char *b = R.len + 4097 > LINE_CAP ? NULL : realloc(R.buf, ncap);
        if (!b) { /* too long (or no memory): drop what is buffered of this line */
            R.len = 0;
            R.overlong = 1;
        } else {
            R.buf = b;
            R.cap = ncap;
        }
    }
    if (!R.buf) {
        R.eof = 1;
        return -1;
    }
    n = read(STDIN_FILENO, R.buf + R.len, R.cap - R.len - 1);
    if (n < 0 && (errno == EINTR || errno == EAGAIN)) {
        return 0;
    }
    if (n > 0) {
        R.len += (size_t)n;
    } else {
        R.eof = 1;
    }
    for (;;) {
        char *nl = memchr(R.buf + start, '\n', R.len - start);
        size_t end;
        if (!nl && !(R.eof && start < R.len)) {
            break;
        }
        end = nl ? (size_t)(nl - R.buf) : R.len;
        R.buf[end] = '\0';
        if (end > start && R.buf[end - 1] == '\r') {
            R.buf[end - 1] = '\0';
        }
        if (R.overlong) {
            fail(NULL, "parse", "Failed to parse command: the line is too long");
            R.overlong = 0;
        } else if (R.buf[start]) {
            rpc_push(&R.inbox, R.buf + start);
        }
        start = nl ? end + 1 : R.len;
    }
    memmove(R.buf, R.buf + start, R.len - start);
    R.len -= start;
    return R.eof ? -1 : 0;
}

/* ---- the conversation and the journal -------------------------------------- */

static int open_journal(pic_store *s) {
    if (R.h->open(s, R.h->db) != 0) {
        return -1;
    }
    s->events = &R.ev;
    s->steer_all = R.steer_all;
    s->follow_up_all = R.follow_up_all;
    s->no_retry = R.no_retry;
    return 0;
}

/* A fresh conversation id, as the journal makes them; not journaled until
 * the conversation has something in it. */
static void fresh_sid(pic_store *s) {
    for (;;) {
        unsigned char r[4];
        sqlite3_stmt *q = NULL;
        int taken = 0;
        if (pic_platform_get()->entropy(r, sizeof r) != 0) {
            r[0] = (unsigned char)getpid();
            r[1] = (unsigned char)(getpid() >> 8);
            r[2] = (unsigned char)rand();
            r[3] = (unsigned char)rand();
        }
        (void)snprintf(R.sid, sizeof R.sid, "%02x%02x%02x%02x", r[0], r[1], r[2], r[3]);
        if (s && sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, R.sid, -1, SQLITE_STATIC);
            taken = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0) != 0;
        }
        sqlite3_finalize(q);
        if (!taken) {
            return;
        }
    }
}

static int sid_exists(pic_store *s) {
    sqlite3_stmt *q = NULL;
    int yes = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, R.sid, -1, SQLITE_STATIC);
        yes = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0) != 0;
    }
    sqlite3_finalize(q);
    return yes;
}

/* The conversation's row, made now when it has none (a bash command or a
 * name before the first prompt). */
static int ensure_sid(pic_store *s) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (sid_exists(s)) {
        return 0;
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    rc = sqlite3_prepare_v2(s->db,
                            "INSERT INTO pic_session(id, created_ms, updated_ms) VALUES(?1, CAST(unixepoch('subsec') * 1000 AS INTEGER),"
                            " CAST(unixepoch('subsec') * 1000 AS INTEGER))",
                            -1, &q, NULL) == SQLITE_OK;
    if (rc) {
        sqlite3_bind_text(q, 1, R.sid, -1, SQLITE_STATIC);
        rc = sqlite3_step(q) == SQLITE_DONE;
    }
    sqlite3_finalize(q);
    if (!rc || pic_commit(s) != 0) {
        (void)snprintf(s->err, sizeof s->err, "cannot record conversation %s: %s", R.sid, sqlite3_errmsg(s->db));
        pic_rollback(s);
        return -1;
    }
    return 0;
}

/* The conversation's path as Pi entries (malloc'd JSON array; "[]" when it
 * has none yet). */
static char *rpc_entries(pic_store *s) {
    if (!sid_exists(s)) {
        return strdup("[]");
    }
    return pic_pi_entries(s, R.sid);
}

static char *leaf_id(pic_store *s) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(s->db, "SELECT json_quote(CAST(head_seq AS TEXT)) FROM pic_session WHERE id = ?", -1, &q, NULL) ==
        SQLITE_OK) {
        sqlite3_bind_text(q, 1, R.sid, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out ? out : strdup("null");
}

#define MS_OF(v) "CAST(round((julianday(json_extract(" v ", '$.timestamp')) - 2440587.5) * 86400000) AS INTEGER)"

/* Pi's session.messages: the context after the latest compaction (its
 * summary, the entries it kept, what followed), as AgentMessages. */
static char *messages_of(const char *entries_json) { return pic_rpc_messages(R.mem, entries_json); }

char *pic_rpc_messages(sqlite3 *db, const char *entries_json) {
    return sqlv_on(db, 
        "WITH e(i, v) AS (SELECT key, value FROM json_each(?1)),"
        " c(ci) AS (SELECT max(i) FROM e WHERE json_extract(v, '$.type') = 'compaction'),"
        " ck(ci, fk) AS (SELECT c.ci, (SELECT CAST(json_extract(v, '$.firstKeptEntryId') AS INTEGER) FROM e WHERE i = c.ci) FROM c)"
        " SELECT coalesce(json_group_array(json(m)), '[]') FROM (SELECT CASE WHEN e.i = ck.ci THEN -1 ELSE e.i END o,"
        " CASE json_extract(v, '$.type')"
        "  WHEN 'message' THEN json_extract(v, '$.message')"
        "  WHEN 'custom_message' THEN json_object('role', 'custom', 'customType', json_extract(v, '$.customType'),"
        "   'content', json_extract(v, '$.content'), 'display', json(iif(json_extract(v, '$.display'), 'true', 'false')),"
        "   'timestamp', " MS_OF("v") ")"
        "  WHEN 'branch_summary' THEN json_object('role', 'branchSummary', 'summary', json_extract(v, '$.summary'),"
        "   'fromId', json_extract(v, '$.fromId'), 'timestamp', " MS_OF("v") ")"
        "  WHEN 'compaction' THEN CASE WHEN e.i = ck.ci THEN json_object('role', 'compactionSummary',"
        "   'summary', json_extract(v, '$.summary'), 'tokensBefore', json_extract(v, '$.tokensBefore'),"
        "   'timestamp', " MS_OF("v") ") END"
        " END m FROM e, ck WHERE ck.ci IS NULL OR e.i >= ck.ci OR CAST(json_extract(v, '$.id') AS INTEGER) >= ck.fk"
        " ORDER BY o) WHERE m IS NOT NULL",
        entries_json, NULL);
}

/* A user message entry's text (Pi's extractUserMessageText): its text blocks joined. */
#define USER_TEXT(o)                                                                                                   \
    "CASE json_type(" o ".value, '$.message.content') WHEN 'text' THEN json_extract(" o ".value, '$.message.content')"  \
    " ELSE (SELECT coalesce(group_concat(json_extract(b.value, '$.text'), ''), '') FROM json_each(" o ".value,"         \
    " '$.message.content') b WHERE json_extract(b.value, '$.type') = 'text') END"

static char *messages(pic_store *s) {
    char *e = rpc_entries(s), *m = e ? messages_of(e) : NULL;
    free(e);
    return m;
}

/* ---- models and thinking --------------------------------------------------- */

typedef struct {
    char **names, **objects;
    size_t n;
} model_list;

/* Pi's Model object for NAME ("provider/id"); DISPLAY its name (NULL: the id). */
char *pic_rpc_model_json(const char *name, const char *display) {
    pic_model m;
    char err[PIC_ERR_CAP];
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (!R.mem || pic_model_resolve(name, &m, err, sizeof err) != 0) {
        return NULL;
    }
    if (sqlite3_prepare_v2(R.mem,
                           "SELECT json_object('id', ?1, 'name', ?2, 'api', ?3, 'provider', ?4, 'baseUrl', ?5,"
                           " 'reasoning', json(iif(?6, 'true', 'false')), 'input', json(iif(?7, '[\"text\",\"image\"]', '[\"text\"]')),"
                           " 'contextWindow', ?8, 'maxTokens', ?9, 'cost', json_object('input', ?10, 'output', ?11,"
                           " 'cacheRead', ?12, 'cacheWrite', ?13))",
                           -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_text(q, 1, m.id, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, display && *display ? display : m.id, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, pic_api_name(m.api), -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 4, m.provider, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 5, m.base_url, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 6, m.reasoning);
    sqlite3_bind_int(q, 7, m.image_input);
    sqlite3_bind_int64(q, 8, m.context_window);
    sqlite3_bind_int64(q, 9, m.max_tokens);
    sqlite3_bind_double(q, 10, m.price.base.input);
    sqlite3_bind_double(q, 11, m.price.base.output);
    sqlite3_bind_double(q, 12, m.price.base.cache_read);
    sqlite3_bind_double(q, 13, m.price.base.cache_write);
    if (sqlite3_step(q) == SQLITE_ROW) {
        out = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}

static const pic_rpc_command *component_command(const char *type);
static int component_call(const pic_rpc_command *c, pic_store *s, const char *line, pic_rpc_call *call);

/* The available models, as the registry's get_available_models answers
 * them; none when no component does. */
static void models_load(model_list *l) {
    const pic_rpc_command *c = component_command("get_available_models");
    pic_rpc_call call;
    sqlite3_stmt *q = NULL;
    memset(l, 0, sizeof *l);
    memset(&call, 0, sizeof call);
    if (!c || (c->flags & PIC_RPC_JOURNAL_FREE) == 0 ||
        component_call(c, NULL, "{\"type\": \"get_available_models\"}", &call) != 0 || !call.data) {
        free(call.data);
        return;
    }
    if (sqlite3_prepare_v2(R.mem,
                           "SELECT json_extract(value, '$.provider') || '/' || json_extract(value, '$.id'), value"
                           " FROM json_each(?1, '$.models')",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, call.data, -1, SQLITE_STATIC);
        while (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            char **nv = realloc(l->names, (l->n + 1) * sizeof *nv), **ov;
            if (!nv) {
                break;
            }
            l->names = nv;
            ov = realloc(l->objects, (l->n + 1) * sizeof *ov);
            if (!ov) {
                break;
            }
            l->objects = ov;
            l->names[l->n] = strdup((const char *)sqlite3_column_text(q, 0));
            l->objects[l->n] = strdup((const char *)sqlite3_column_text(q, 1));
            if (!l->names[l->n] || !l->objects[l->n]) {
                free(l->names[l->n]);
                free(l->objects[l->n]);
                break;
            }
            l->n++;
        }
    }
    sqlite3_finalize(q);
    free(call.data);
}

/* The policy's estimate of the context SUBMISSION's next request sends;
 * 0 tokens with no policy. */
static int context_tokens(pic_store *s, sqlite3_int64 submission, long *tokens) {
    *tokens = 0;
    return s->policy && s->policy->tokens ? s->policy->tokens(s->db, submission, tokens) : 0;
}

static void models_free(model_list *l) {
    for (size_t i = 0; i < l->n; i++) {
        free(l->names[i]);
        free(l->objects[i]);
    }
    free(l->names);
    free(l->objects);
}

static char *current_model(void) {
    model_list l;
    char *out = NULL;
    models_load(&l);
    for (size_t i = 0; i < l.n && !out; i++) {
        if (strcmp(l.names[i], R.model) == 0) {
            out = strdup(l.objects[i]);
        }
    }
    models_free(&l);
    return out ? out : pic_rpc_model_json(R.model, NULL);
}

static void level_changed(void) {
    char *q = quote(R.thinking), line[96];
    (void)snprintf(line, sizeof line, "{\"type\":\"thinking_level_changed\",\"level\":%s}", q ? q : "\"\"");
    free(q);
    out_line(line);
}

/* Pi's setThinkingLevel: LEVEL clamped to what the model takes; the change
 * is announced when there is one. */
static void rpc_set_level(const char *level) {
    pic_model m;
    char err[PIC_ERR_CAP];
    const char *want = level;
    if (pic_model_resolve(R.model, &m, err, sizeof err) == 0) {
        want = pic_model_thinking_clamp(&m, level);
    }
    if (strcmp(want, R.thinking) != 0) {
        (void)snprintf(R.thinking, sizeof R.thinking, "%s", want);
        level_changed();
    }
}

/* Pi's model switch: the model's saved level (thinkingLevel:provider/id),
 * else the current one, clamped. */
static void rpc_use_model(const char *name) {
    char key[320], *saved;
    (void)snprintf(R.model, sizeof R.model, "%s", name);
    (void)snprintf(key, sizeof key, "thinkingLevel:%s", name);
    saved = pic_setting(key);
    rpc_set_level(saved && pic_thinking_index(saved) >= 0 ? saved : R.thinking);
    free(saved);
}

static int levels_json(char *out, size_t cap) {
    pic_model m;
    char err[PIC_ERR_CAP];
    const char *levels[PIC_THINKING_LEVELS];
    int n;
    size_t used = 0;
    if (pic_model_resolve(R.model, &m, err, sizeof err) != 0) {
        n = PIC_THINKING_LEVELS;
        for (int i = 0; i < n; i++) {
            levels[i] = pic_thinking_names[i];
        }
    } else {
        n = pic_model_thinking_levels(&m, levels);
    }
    used += (size_t)snprintf(out, cap, "[");
    for (int i = 0; i < n && used < cap; i++) {
        used += (size_t)snprintf(out + used, cap - used, "%s\"%s\"", i ? "," : "", levels[i]);
    }
    if (used < cap) {
        (void)snprintf(out + used, cap - used, "]");
    }
    return n;
}

/* ---- scoped models (Ctrl+P's scope, as the terminal cycles it) -------------- */

typedef struct {
    char **p;
    size_t n;
} rpc_patterns;

static int rpc_add_pattern(void *ctx, const char *pattern) {
    rpc_patterns *pl = ctx;
    char **v = realloc(pl->p, (pl->n + 1) * sizeof *v);
    if (v) {
        pl->p = v;
        pl->p[pl->n] = strdup(pattern);
        if (pl->p[pl->n]) {
            pl->n++;
        }
    }
    return 0;
}

/* A scope pattern (fnmatch, any case) matches "provider/model", or a bare id. */
static int rpc_scope_matches(const char *pattern, const char *model) {
    char *r = sqlv("SELECT lower(?2) GLOB lower(?1) OR (instr(?1, '/') = 0 AND"
                   " substr(lower(?2), instr(?2, '/') + 1) GLOB lower(?1))",
                   pattern, model);
    int yes = r && strcmp(r, "1") == 0;
    free(r);
    return yes;
}

/* ---- commands ---------------------------------------------------------------- */

static void get_state(pic_store *s, const char *line) {
    char *model = current_model(), *msgs = messages(s), *name = NULL, *data;
    sqlite3_stmt *q = NULL;
    long pending = 0;
    int automatic = s->policy && s->policy->automatic && s->policy->automatic(R.model);
    if (sqlite3_prepare_v2(s->db, "SELECT name FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, R.sid, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            name = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    if (R.phase == RUN &&
        sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_queued WHERE submission_id = ? AND state = 'queued'", -1, &q,
                           NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, s->running);
        pending = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int(q, 0) : 0;
        sqlite3_finalize(q);
    } else {
        pending = (long)R.nheld;
    }
    {
        sqlite3_stmt *b = NULL;
        data = NULL;
        if (sqlite3_prepare_v2(R.mem,
                               "SELECT json_patch(json_object('model', json(?1)), json_object('thinkingLevel', ?2,"
                               " 'isStreaming', json(iif(?3, 'true', 'false')), 'isCompacting', json(iif(?4, 'true', 'false')),"
                               " 'steeringMode', ?5, 'followUpMode', ?6, 'sessionId', ?7, 'sessionName', ?8,"
                               " 'autoCompactionEnabled', json(iif(?9, 'true', 'false')), 'messageCount', json_array_length(?10),"
                               " 'pendingMessageCount', ?11))",
                               -1, &b, NULL) == SQLITE_OK) {
            if (model) {
                sqlite3_bind_text(b, 1, model, -1, SQLITE_STATIC);
            }
            sqlite3_bind_text(b, 2, R.thinking, -1, SQLITE_STATIC);
            sqlite3_bind_int(b, 3, R.phase == RUN);
            sqlite3_bind_int(b, 4, R.phase == COMPACT);
            /* while a request runs, commands.c keeps the modes on its journal */
            sqlite3_bind_text(b, 5, (R.phase == RUN ? s->steer_all : R.steer_all) ? "all" : "one-at-a-time", -1, SQLITE_STATIC);
            sqlite3_bind_text(b, 6, (R.phase == RUN ? s->follow_up_all : R.follow_up_all) ? "all" : "one-at-a-time", -1,
                              SQLITE_STATIC);
            sqlite3_bind_text(b, 7, R.sid, -1, SQLITE_STATIC);
            if (name) {
                sqlite3_bind_text(b, 8, name, -1, SQLITE_STATIC);
            }
            sqlite3_bind_int(b, 9, automatic);
            sqlite3_bind_text(b, 10, msgs ? msgs : "[]", -1, SQLITE_STATIC);
            sqlite3_bind_int64(b, 11, pending);
            if (sqlite3_step(b) == SQLITE_ROW) {
                data = strdup((const char *)sqlite3_column_text(b, 0));
            }
        }
        sqlite3_finalize(b);
    }
    if (data) {
        ok(line, "get_state", data);
    } else {
        fail(line, "get_state", "cannot read the state");
    }
    free(data);
    free(model);
    free(msgs);
    free(name);
}

/* Pi's getSessionStats over the conversation's path: message counts, the
 * tokens and cost of its replies and summaries, and the context in use. */
static void session_stats(pic_store *s, const char *line) {
    char *e = rpc_entries(s), *base = NULL, *data = NULL, usage[160] = "";
    pic_model m;
    char err[PIC_ERR_CAP];
    if (!e) {
        fail(line, "get_session_stats", s->err);
        return;
    }
    base = sqlv("WITH e(i, v) AS (SELECT key, value FROM json_each(?1)),"
                " m(r, msg) AS (SELECT json_extract(v, '$.message.role'), json_extract(v, '$.message') FROM e"
                "   WHERE json_extract(v, '$.type') = 'message'),"
                " u(x) AS (SELECT json_extract(msg, '$.usage') FROM m WHERE r = 'assistant' UNION ALL"
                "   SELECT json_extract(v, '$.usage') FROM e WHERE json_extract(v, '$.type') IN ('branch_summary', 'compaction')"
                "   AND json_type(v, '$.usage') = 'object')"
                " SELECT json_object('sessionId', ?2,"
                " 'userMessages', (SELECT count(*) FROM m WHERE r = 'user'),"
                " 'assistantMessages', (SELECT count(*) FROM m WHERE r = 'assistant'),"
                " 'toolCalls', (SELECT coalesce(sum((SELECT count(*) FROM json_each(msg, '$.content')"
                "   WHERE json_extract(value, '$.type') = 'toolCall')), 0) FROM m WHERE r = 'assistant'),"
                " 'toolResults', (SELECT count(*) FROM m WHERE r = 'toolResult'),"
                " 'totalMessages', (SELECT count(*) FROM m),"
                " 'tokens', json_object('input', coalesce(sum(json_extract(x, '$.input')), 0),"
                "   'output', coalesce(sum(json_extract(x, '$.output')), 0),"
                "   'cacheRead', coalesce(sum(json_extract(x, '$.cacheRead')), 0),"
                "   'cacheWrite', coalesce(sum(json_extract(x, '$.cacheWrite')), 0),"
                "   'total', coalesce(sum(json_extract(x, '$.input')), 0) + coalesce(sum(json_extract(x, '$.output')), 0)"
                "     + coalesce(sum(json_extract(x, '$.cacheRead')), 0) + coalesce(sum(json_extract(x, '$.cacheWrite')), 0)),"
                " 'cost', coalesce(sum(json_extract(x, '$.cost.total')), 0)) FROM u",
                e, R.sid);
    /* contextUsage: unknown (null) after a compaction until a reply comes back. */
    if (pic_model_resolve(R.model, &m, err, sizeof err) == 0 && m.context_window > 0) {
        char *fresh = sqlv("WITH e(i, v) AS (SELECT key, value FROM json_each(?1)),"
                           " c(ci) AS (SELECT max(i) FROM e WHERE json_extract(v, '$.type') = 'compaction')"
                           " SELECT (SELECT ci FROM c) IS NULL OR EXISTS (SELECT 1 FROM e, c WHERE e.i > c.ci"
                           "  AND json_extract(v, '$.message.role') = 'assistant'"
                           "  AND coalesce(json_extract(v, '$.message.stopReason'), '') NOT IN ('aborted', 'error')"
                           "  AND coalesce(json_extract(v, '$.message.usage.totalTokens'), 0) > 0)",
                           e, NULL);
        long tokens = 0;
        sqlite3_int64 own = 0;
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db, "SELECT coalesce(max(id), 0) FROM pic_submission WHERE session_id = ?", -1, &q, NULL) ==
            SQLITE_OK) {
            sqlite3_bind_text(q, 1, R.sid, -1, SQLITE_STATIC);
            own = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int64(q, 0) : 0;
        }
        sqlite3_finalize(q);
        if (own && context_tokens(s, own, &tokens) != 0) {
            tokens = 0;
        }
        if (fresh && strcmp(fresh, "1") == 0) {
            (void)snprintf(usage, sizeof usage, "{\"tokens\":%ld,\"contextWindow\":%ld,\"percent\":%.17g}", tokens,
                           m.context_window, (double)tokens * 100.0 / (double)m.context_window);
        } else {
            (void)snprintf(usage, sizeof usage, "{\"tokens\":null,\"contextWindow\":%ld,\"percent\":null}", m.context_window);
        }
        free(fresh);
    }
    if (base && usage[0]) {
        data = sqlv("SELECT json_set(?1, '$.contextUsage', json(?2))", base, usage);
    }
    ok(line, "get_session_stats", data ? data : base ? base : "{}");
    free(data);
    free(base);
    free(e);
}

static void get_entries(pic_store *s, const char *line) {
    char *e = rpc_entries(s), *since = jtext(line, "$.since"), *leaf = leaf_id(s), *data = NULL;
    if (!e) {
        fail(line, "get_entries", s->err);
    } else if (has_field(line, "$.since") && !since) {
        fail(line, "get_entries", "since must be a string");
    } else {
        char *found = since ? sqlv("SELECT key FROM json_each(?1) WHERE json_extract(value, '$.id') = ?2", e, since) : NULL;
        if (since && !found) {
            char msg[160];
            (void)snprintf(msg, sizeof msg, "Entry not found: %.100s", since);
            fail(line, "get_entries", msg);
        } else {
            char *after = sqlv("SELECT json_group_array(json(value)) FROM (SELECT value FROM json_each(?1)"
                               " WHERE key > coalesce(CAST(?2 AS INTEGER), -1) ORDER BY key)",
                               e, found);
            data = after ? sqlv("SELECT json_object('entries', json(?1), 'leafId', json(?2))", after, leaf) : NULL;
            free(after);
            ok(line, "get_entries", data ? data : "{\"entries\":[],\"leafId\":null}");
        }
        free(found);
    }
    free(e);
    free(since);
    free(leaf);
    free(data);
}

/* Pi's getTree: nodes {entry, children}; a conversation is one path. */
static void get_tree(pic_store *s, const char *line) {
    char *e = rpc_entries(s), *leaf = leaf_id(s), *res;
    sqlite3_stmt *q = NULL;
    sqlite3_str *t = sqlite3_str_new(NULL);
    long depth = 0;
    sqlite3_str_appendall(t, "{\"tree\":[");
    if (e && sqlite3_prepare_v2(R.mem, "SELECT value FROM json_each(?1) ORDER BY key", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, e, -1, SQLITE_STATIC);
        while (sqlite3_step(q) == SQLITE_ROW) {
            sqlite3_str_appendf(t, "{\"entry\":%s,\"children\":[", (const char *)sqlite3_column_text(q, 0));
            depth++;
        }
        sqlite3_finalize(q);
    }
    for (; depth > 0; depth--) {
        sqlite3_str_appendall(t, "]}");
    }
    sqlite3_str_appendf(t, "],\"leafId\":%s}", leaf);
    res = sqlite3_str_finish(t);
    ok(line, "get_tree", res ? res : "{\"tree\":[],\"leafId\":null}");
    sqlite3_free(res);
    free(e);
    free(leaf);
}

static void get_fork_messages(pic_store *s, const char *line) {
    char *e = rpc_entries(s), *list = NULL, *data = NULL;
    if (e) {
        list = sqlv("SELECT coalesce(json_group_array(json_object('entryId', id, 'text', text)), '[]') FROM"
                    " (SELECT json_extract(o.value, '$.id') id, " USER_TEXT("o") " text"
                    " FROM json_each(?1) o WHERE json_extract(o.value, '$.type') = 'message'"
                    " AND json_extract(o.value, '$.message.role') = 'user' ORDER BY o.key) WHERE text != ''",
                    e, NULL);
    }
    data = list ? sqlv("SELECT json_object('messages', json(?1))", list, NULL) : NULL;
    ok(line, "get_fork_messages", data ? data : "{\"messages\":[]}");
    free(e);
    free(list);
    free(data);
}

static void last_assistant_text(pic_store *s, const char *line) {
    char *m = messages(s), *text = NULL, *data;
    if (m) {
        text = sqlv("SELECT json_quote(nullif(trim(t, ' ' || char(9, 10, 13)), '')) FROM (SELECT (SELECT coalesce(group_concat(json_extract(b.value, '$.text'), ''), '')"
                    "  FROM json_each(o.value, '$.content') b WHERE json_extract(b.value, '$.type') = 'text') t, o.key k,"
                    "  coalesce(json_extract(o.value, '$.stopReason'), 'stop') stop"
                    " FROM json_each(?1) o WHERE json_extract(o.value, '$.role') = 'assistant') x"
                    " WHERE stop = 'stop' OR trim(t, ' ' || char(9, 10, 13)) != '' ORDER BY k DESC LIMIT 1",
                    m, NULL);
    }
    data = sqlite3_mprintf("{\"text\":%s}", text ? text : "null");
    ok(line, "get_last_assistant_text", data);
    sqlite3_free(data);
    free(text);
    free(m);
}

static void set_model(const char *line) {
    char *provider = jtext(line, "$.provider"), *id = jtext(line, "$.modelId"), name[320];
    model_list l;
    int found = -1;
    if (!provider || !id) {
        fail(line, "set_model", "provider and modelId must be strings");
        free(provider);
        free(id);
        return;
    }
    (void)snprintf(name, sizeof name, "%s/%s", provider, id);
    models_load(&l);
    for (size_t i = 0; i < l.n && found < 0; i++) {
        found = strcmp(l.names[i], name) == 0 ? (int)i : -1;
    }
    if (found < 0) {
        char msg[400];
        (void)snprintf(msg, sizeof msg, "Model not found: %s", name);
        fail(line, "set_model", msg);
    } else {
        rpc_use_model(name);
        ok(line, "set_model", l.objects[found]);
    }
    models_free(&l);
    free(provider);
    free(id);
}

/* Pi's cycleModel: the next model of the scope (pic scoped-models) when one
 * is set, else of the available models; null data when there is no other. */
static void rpc_cycle_model(const char *line) {
    model_list l;
    rpc_patterns pl = {NULL, 0};
    size_t *order, n = 0;
    int at = -1;
    models_load(&l);
    (void)pic_scoped_each(rpc_add_pattern, &pl);
    order = malloc((l.n + 1) * sizeof *order);
    for (size_t i = 0; order && pl.n == 0 && i < l.n; i++) {
        order[n++] = i;
    }
    for (size_t j = 0; order && j < pl.n; j++) {
        size_t from = n;
        for (size_t i = 0; i < l.n; i++) {
            int seen = 0;
            for (size_t k = 0; k < n; k++) {
                seen |= order[k] == i;
            }
            if (!seen && rpc_scope_matches(pl.p[j], l.names[i])) {
                size_t p = n++;
                while (p > from && strcmp(l.names[order[p - 1]], l.names[i]) > 0) {
                    order[p] = order[p - 1];
                    p--;
                }
                order[p] = i;
            }
        }
    }
    for (size_t k = 0; k < n; k++) {
        at = strcmp(l.names[order[k]], R.model) == 0 ? (int)k : at;
    }
    if (n < 2) {
        ok(line, "cycle_model", "null");
    } else {
        size_t next = order[at < 0 ? 0 : ((size_t)at + 1) % n];
        char *data, *lv;
        rpc_use_model(l.names[next]);
        lv = quote(R.thinking);
        data = sqlite3_mprintf("{\"model\":%s,\"thinkingLevel\":%s,\"isScoped\":%s}", l.objects[next], lv ? lv : "\"off\"",
                               pl.n ? "true" : "false");
        ok(line, "cycle_model", data);
        sqlite3_free(data);
        free(lv);
    }
    free(order);
    for (size_t j = 0; j < pl.n; j++) {
        free(pl.p[j]);
    }
    free(pl.p);
    models_free(&l);
}

static void set_thinking_level(const char *line) {
    char *level = jtext(line, "$.level");
    if (!level || pic_thinking_index(level) < 0) {
        char msg[160];
        (void)snprintf(msg, sizeof msg, "Invalid thinking level: %.40s (off, minimal, low, medium, high, xhigh, max)",
                       level ? level : "(not a string)");
        fail(line, "set_thinking_level", msg);
    } else {
        rpc_set_level(level);
        ok(line, "set_thinking_level", NULL);
    }
    free(level);
}

static void cycle_thinking_level(const char *line) {
    pic_model m;
    char err[PIC_ERR_CAP], data[64];
    const char *levels[PIC_THINKING_LEVELS];
    int n, at = 0;
    if (pic_model_resolve(R.model, &m, err, sizeof err) != 0 || !m.reasoning) {
        ok(line, "cycle_thinking_level", "null");
        return;
    }
    n = pic_model_thinking_levels(&m, levels);
    for (int i = 0; i < n; i++) {
        at = strcmp(levels[i], R.thinking) == 0 ? i : at;
    }
    rpc_set_level(levels[(at + 1) % n]);
    (void)snprintf(data, sizeof data, "{\"level\":\"%s\"}", R.thinking);
    ok(line, "cycle_thinking_level", data);
}

static void set_mode(const char *line, const char *type, int *all) {
    char *mode = jtext(line, "$.mode");
    if (mode && (strcmp(mode, "all") == 0 || strcmp(mode, "one-at-a-time") == 0)) {
        *all = strcmp(mode, "all") == 0;
        if (R.cur) {
            R.cur->steer_all = R.steer_all;
            R.cur->follow_up_all = R.follow_up_all;
        }
        ok(line, type, NULL);
    } else {
        fail(line, type, "mode must be \"all\" or \"one-at-a-time\"");
    }
    free(mode);
}

/* Pi's set_auto_compaction and set_auto_retry: compaction.enabled and
 * retry.enabled in the user's settings, as Pi saves them. */
static void set_enabled(const char *line, const char *type, const char *key) {
    int enabled = jbool(line, "$.enabled");
    if (enabled < 0) {
        fail(line, type, "enabled must be a boolean");
    } else if (pic_setting_set_json(key, "$.enabled", enabled ? "true" : "false") != 0) {
        fail(line, type, "cannot write ~/.pic/pic.sqlite");
    } else {
        if (strcmp(key, "retry") == 0) {
            R.no_retry = !enabled;
            if (R.cur) {
                R.cur->no_retry = R.no_retry;
            }
        }
        ok(line, type, NULL);
    }
}

/* ---- credentials -------------------------------------------------------------------- */

/* login {provider}: the provider's subscription sign-in. stdout carries the
 * protocol, so the sign-in's messages (the URL) go to stderr, the browser
 * opens, and the redirect alone completes it (nothing is pasted); a locked
 * store is opened with unlock first, since nothing here asks on a terminal.
 * A provider without one is an error: an API key is stored with `pic login`. */
static void rpc_auth_login(const char *line) {
    char *provider = jtext(line, "$.provider"), err[512];
    if (!provider || !*provider) {
        fail(line, "login", "login needs a provider");
    } else if (!pic_cred_oauth_label(provider)) {
        (void)snprintf(err, sizeof err, "%.64s has no subscription sign-in: store its API key with `pic login %.64s`", provider,
                       provider);
        fail(line, "login", err);
    } else if (pic_cred_oauth_login(provider, PIC_CRED_NO_TERMINAL, err, sizeof err) != 0) {
        fail(line, "login", err);
    } else {
        char *q = quote(provider), *data = sqlite3_mprintf("{\"provider\":%s,\"type\":\"%s\"}", q ? q : "\"\"", "oauth");
        ok(line, "login", data);
        sqlite3_free(data);
        free(q);
    }
    free(provider);
}

/* logout {provider}: removes its stored sign-in or key; data.removed says whether there was one. */
static void rpc_auth_logout(const char *line) {
    char *provider = jtext(line, "$.provider");
    int rc = provider && *provider ? pic_cred_logout(provider) : -2;
    if (rc == -2) {
        fail(line, "logout", "logout needs a provider");
    } else if (rc < 0) {
        fail(line, "logout", "cannot write ~/.pic/pic.sqlite");
    } else {
        ok(line, "logout", rc ? "{\"removed\":true}" : "{\"removed\":false}");
    }
    free(provider);
}

static int rpc_auth_row(void *ctx, const char *name, const char *kind, long long created_ms, long long used_ms) {
    sqlite3_str *out = ctx;
    const char *label = pic_cred_oauth_label(name);
    char *q = quote(name), *l = label ? quote(label) : NULL;
    sqlite3_str_appendf(out, "%s{\"provider\":%s,\"type\":\"%s\"%s%s,\"createdAt\":%lld,\"lastUsedAt\":%lld}",
                        sqlite3_str_length(out) > 16 ? "," : "", q ? q : "\"\"", strcmp(kind, "oauth") == 0 ? "oauth" : "api_key",
                        l && strcmp(kind, "oauth") == 0 ? ",\"label\":" : "", l && strcmp(kind, "oauth") == 0 ? l : "",
                        created_ms, used_ms);
    free(q);
    free(l);
    return 0;
}

/* get_auth_status: each stored credential's provider, type and dates; never a value. */
static void rpc_auth_status(const char *line) {
    sqlite3_str *out = sqlite3_str_new(NULL);
    char *data;
    sqlite3_str_appendall(out, "{\"credentials\":[");
    if (pic_cred_each(rpc_auth_row, out) != 0) {
        sqlite3_free(sqlite3_str_finish(out));
        fail(line, "get_auth_status", "cannot read ~/.pic/pic.sqlite");
        return;
    }
    sqlite3_str_appendall(out, "]}");
    data = sqlite3_str_finish(out);
    ok(line, "get_auth_status", data);
    sqlite3_free(data);
}

static void set_session_name(pic_store *s, const char *line) {
    char *name = jtext(line, "$.name"), *trimmed = name ? sqlv("SELECT trim(?1, ' ' || char(9, 10, 13))", name, NULL) : NULL;
    if (!trimmed || !*trimmed) {
        fail(line, "set_session_name", "Session name cannot be empty");
    } else if (ensure_sid(s) != 0 || pic_session_name(s, R.sid, trimmed) != 0) {
        fail(line, "set_session_name", s->err);
    } else {
        char *q = quote(trimmed), *ev = sqlite3_mprintf("{\"type\":\"session_info_changed\",\"name\":%s}", q ? q : "\"\"");
        out_line(ev);
        sqlite3_free(ev);
        free(q);
        ok(line, "set_session_name", NULL);
    }
    free(name);
    free(trimmed);
}

static void export_html(pic_store *s, const char *line) {
    char *path = jtext(line, "$.outputPath"), deflt[PATH_MAX], *data;
    const char *to = path;
    FILE *f;
    sqlite3_stmt *q = NULL;
    int any = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT head_seq IS NOT NULL FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, R.sid, -1, SQLITE_STATIC);
        any = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
    }
    sqlite3_finalize(q);
    if (!any) {
        fail(line, "export_html", "Nothing to export yet - start a conversation first");
        free(path);
        return;
    }
    if (!to || !*to) {
        (void)snprintf(deflt, sizeof deflt, "%s/pic-session-%s.html", R.h->workspace, R.sid);
        to = deflt;
    }
    if (!(f = fopen(to, "w"))) {
        char msg[PATH_MAX + 64];
        (void)snprintf(msg, sizeof msg, "cannot write %s: %s", to, strerror(errno));
        fail(line, "export_html", msg);
    } else {
        int rc = pic_export_html(s, R.sid, f);
        if (fclose(f) != 0 && rc == 0) {
            (void)snprintf(s->err, sizeof s->err, "cannot write %s: %s", to, strerror(errno));
            rc = -1;
        }
        if (rc != 0) {
            fail(line, "export_html", s->err);
        } else {
            char *qp = quote(to);
            data = sqlite3_mprintf("{\"path\":%s}", qp ? qp : "\"\"");
            ok(line, "export_html", data);
            sqlite3_free(data);
            free(qp);
        }
    }
    free(path);
}

/* ---- busy phases --------------------------------------------------------------- */

static void command(const char *line);
static void catch_signals(void);

/* Every complete line read so far, handled as the phase allows. */
static void pump(void) {
    char *line;
    if (R.pumping) {
        return;
    }
    R.pumping = 1;
    while ((line = pop(&R.inbox)) != NULL) {
        if (R.phase == RUN) {
            pic_commands_line(line); /* steering, the queues, abort; the rest comes back to busy_other */
        } else {
            command(line);
        }
        free(line);
    }
    R.pumping = 0;
}

static void side_ready(void) {
    if (fill() < 0) {
        pic_side_fd = -1;
    }
    pump();
}

static void side_on(void) {
    pic_side_fd = R.eof ? -1 : STDIN_FILENO;
    pic_side_ready = side_ready;
}

static void side_off(void) {
    pic_side_fd = -1;
    pic_side_ready = NULL;
}

/* Answered whatever runs. */
static int immediate(const char *type) {
    static const char *const names[] = {"get_state", "get_messages", "get_session_stats",
                                        "get_available_thinking_levels", "get_fork_messages", "get_last_assistant_text",
                                        "get_entries", "get_tree", "set_model", "cycle_model",
                                        "set_thinking_level", "cycle_thinking_level", "set_steering_mode",
                                        "set_follow_up_mode", "set_auto_compaction", "set_auto_retry", "abort_retry",
                                        "set_session_name", "export_html", "login", "logout", "unlock", "extension_ui_response"};
    const pic_rpc_command *c = component_command(type);
    for (size_t i = 0; i < sizeof names / sizeof names[0]; i++) {
        if (strcmp(type, names[i]) == 0) {
            return 1;
        }
    }
    return c && (c->flags & PIC_RPC_IMMEDIATE) != 0;
}

/* While a request, compaction or bash command runs: 1 when the command was
 * taken care of here (answered, or kept for when it ends), 0 to answer it now. */
static int busy(const char *line, const char *type) {
    int replaces = strcmp(type, "compact") == 0 || strcmp(type, "new_session") == 0 || strcmp(type, "switch_session") == 0 ||
                   strcmp(type, "fork") == 0 || strcmp(type, "clone") == 0;
    if (immediate(type)) {
        return 0;
    }
    if (strcmp(type, "abort_bash") == 0) {
        if (R.phase == BASH && !pic_interrupted) {
            pic_interrupted = 2;
        }
        ok(line, "abort_bash", NULL);
        return 1;
    }
    if (R.phase == RUN && strcmp(type, "prompt") == 0) {
        char *behavior = jtext(line, "$.streamingBehavior"), *message = jtext(line, "$.message");
        if (!message) {
            fail(line, "prompt", "message must be a string");
        } else if (!behavior || (strcmp(behavior, "steer") != 0 && strcmp(behavior, "followUp") != 0)) {
            fail(line, "prompt", "Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
        } else {
            (void)pic_commands_enqueue(line, "prompt", strcmp(behavior, "steer") == 0 ? "steer" : "follow_up", message);
        }
        free(behavior);
        free(message);
        return 1;
    }
    /* A compaction or a session change ends a request or compaction first, as
     * Pi's abort does: journaled as Ctrl-C's cancel. */
    if ((replaces && R.phase != BASH) || (strcmp(type, "abort") == 0 && R.phase == COMPACT)) {
        if (!pic_interrupted) {
            pic_interrupted = 2;
        }
    }
    rpc_push(&R.deferred, line);
    return 1;
}

/* commands.c's fallback while a request runs. */
static int busy_other(void *ctx, const char *line, const char *type) {
    (void)ctx;
    if (!busy(line, type)) {
        command(line);
    }
    return 1;
}

/* ---- idle commands that run work ------------------------------------------------ */

static int bash_store_entry(pic_store *s, sqlite3_int64 *seq) {
    sqlite3_stmt *q = NULL;
    *seq = 0;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT max(b.entry_seq) FROM pic_bash b JOIN pic_entry e ON e.seq = b.entry_seq"
                           " JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = ?",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, R.sid, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            *seq = sqlite3_column_int64(q, 0);
        }
    }
    sqlite3_finalize(q);
    return *seq ? 0 : -1;
}

static void bash_live(void *ctx, const char *text) {
    size_t seen = R.bash_seen ? strlen(R.bash_seen) : 0;
    const char *delta = text;
    sqlite3_stmt *q = NULL;
    (void)ctx;
    if (R.bash_seen && strncmp(text, R.bash_seen, seen) == 0) {
        delta = text + seen;
    }
    if (*delta && sqlite3_prepare_v2(R.mem,
                                     "SELECT json_patch('{}', json_object('type', 'bash_execution_update', 'id', ?1, 'delta', ?2))",
                                     -1, &q, NULL) == SQLITE_OK) {
        if (R.bash_id) {
            sqlite3_bind_text(q, 1, R.bash_id, -1, SQLITE_STATIC);
        }
        sqlite3_bind_text(q, 2, delta, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            out_line((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    free(R.bash_seen);
    R.bash_seen = strdup(text);
}

/* Pi's bash: run in the workspace, journaled as a bashExecution message
 * (pic bash's), reaching the model with the next prompt unless excluded. */
static void run_bash(pic_store *s, const char *line) {
    char *command_text = jtext(line, "$.command"), *id = jtext(line, "$.id"), joined[64];
    int exclude = jbool(line, "$.excludeFromContext") == 1, rc;
    pic_bash_msg m;
    if (!command_text || !*command_text) {
        fail(line, "bash", "command must be a non-empty string");
        free(command_text);
        free(id);
        return;
    }
    if (ensure_sid(s) != 0) {
        fail(line, "bash", s->err);
        free(command_text);
        free(id);
        return;
    }
    R.phase = BASH;
    R.cur = s;
    R.bash_id = id;
    side_on();
    rc = pic_bash_run(s, R.h->workspace, R.sid, command_text, exclude, R.h->exec_seconds, bash_live, NULL, &m, joined,
                      sizeof joined);
    side_off();
    pic_interrupted = 0;
    R.phase = IDLE;
    R.cur = NULL;
    R.bash_id = NULL;
    free(R.bash_seen);
    R.bash_seen = NULL;
    if (rc != 0) {
        fail(line, "bash", s->err);
    } else {
        char path[PATH_MAX] = "", *data = NULL;
        sqlite3_int64 seq = 0;
        sqlite3_stmt *q = NULL;
        if (m.truncated && bash_store_entry(s, &seq) == 0 &&
            sqlite3_prepare_v2(s->db, "SELECT sqlar_uncompress(full, full_sz) FROM pic_bash WHERE entry_seq = ? AND full IS NOT NULL",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_int64(q, 1, seq);
            if (sqlite3_step(q) == SQLITE_ROW) {
                const char *tmp = getenv("TMPDIR");
                FILE *f;
                (void)snprintf(path, sizeof path, "%s/pic-bash-%s-%lld.log", tmp && *tmp ? tmp : "/tmp", R.sid, (long long)seq);
                if ((f = fopen(path, "w")) != NULL) {
                    (void)fwrite(sqlite3_column_blob(q, 0), 1, (size_t)sqlite3_column_bytes(q, 0), f);
                    if (fclose(f) != 0) {
                        path[0] = '\0';
                    }
                } else {
                    path[0] = '\0';
                }
            }
        }
        sqlite3_finalize(q);
        if (sqlite3_prepare_v2(R.mem,
                               "SELECT json_patch('{}', json_object('output', ?1, 'exitCode', CASE WHEN ?2 THEN ?3 END,"
                               " 'cancelled', json(iif(?4, 'true', 'false')), 'truncated', json(iif(?5, 'true', 'false')),"
                               " 'fullOutputPath', nullif(?6, '')))",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, m.output, -1, SQLITE_STATIC);
            sqlite3_bind_int(q, 2, m.has_exit && !m.cancelled);
            sqlite3_bind_int(q, 3, m.exit_code);
            sqlite3_bind_int(q, 4, m.cancelled);
            sqlite3_bind_int(q, 5, m.truncated);
            sqlite3_bind_text(q, 6, path, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                data = strdup((const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
        ok(line, "bash", data ? data : "{}");
        free(data);
        free((void *)(uintptr_t)m.output);
        {
            const char *pi = getenv("PIC_PI_EXPORT");
            if (!(pi && strcmp(pi, "0") == 0) && pic_export_pi(s, R.h->workspace, NULL, R.sid) != 0) {
                fprintf(stderr, "pic: warning: Pi session file: %s\n", s->err);
            }
        }
    }
    free(command_text);
    free(id);
}

/* The model's credential is sealed and the store locked: credential_locked names the provider
 * (the client asks for the passphrase and sends unlock), and COMMAND fails at once. 1 when it
 * failed. Nothing here ever asks on a terminal. */
static int key_locked(const char *line, const char *command) {
    char provider[128] = "", err[PIC_ERR_CAP];
    int rc = R.h->key_ready ? R.h->key_ready(R.model, provider, sizeof provider, err, sizeof err) : 0;
    if (rc == 1) {
        char *q = quote(provider), *ev = sqlite3_mprintf("{\"type\":\"credential_locked\",\"provider\":%s}", q ? q : "\"\"");
        out_line(ev);
        sqlite3_free(ev);
        free(q);
    }
    if (rc != 0) {
        fail(line, command, err);
        return 1;
    }
    return 0;
}

/* unlock {passphrase}: opens the credential store with PASSPHRASE (a new store is made with
 * it); RPC never asks on a terminal, so this is how a client opens a store that is locked. */
static void rpc_unlock(const char *line) {
    char *pass = jtext(line, "$.passphrase"), err[PIC_ERR_CAP];
    int created = 0;
    if (!pass || !*pass) {
        fail(line, "unlock", "unlock needs a passphrase");
    } else if (pic_cred_unlock_with(pass, strlen(pass), &created, err, sizeof err) != 0) {
        fail(line, "unlock", err);
    } else {
        ok(line, "unlock", created ? "{\"created\":true}" : NULL);
    }
    if (pass) {
        pic_cred_wipe(pass, strlen(pass));
    }
    free(pass);
}

/* Pi's compact: aborts what runs (done before this runs), then compacts now. */
static void compact(pic_store *s, const char *line) {
    char *instructions = jtext(line, "$.customInstructions"), err[PIC_ERR_CAP];
    pic_provider provider;
    sqlite3_int64 seq = 0;
    memset(&provider, 0, sizeof provider);
    if (!sid_exists(s)) {
        fail(line, "compact", "Nothing to compact (session too small)");
        free(instructions);
        return;
    }
    if (R.h->provider(&provider, R.model, R.thinking, err, sizeof err) != 0) {
        fail(line, "compact", err);
        if (provider.free) {
            provider.free(&provider);
        }
        free(instructions);
        return;
    }
    if (key_locked(line, "compact")) {
        provider.free(&provider);
        free(instructions);
        return;
    }
    R.phase = COMPACT;
    R.cur = s;
    side_on();
    if (pic_compact_now(s, &provider, R.sid, instructions, &seq) != 0) {
        side_off();
        fail(line, "compact", s->err);
    } else {
        sqlite3_stmt *q = NULL;
        char *data = NULL;
        long after = 0;
        sqlite3_int64 owner = 0;
        side_off();
        if (sqlite3_prepare_v2(s->db, "SELECT submission_id FROM pic_entry WHERE seq = ?", -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_int64(q, 1, seq);
            owner = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int64(q, 0) : 0;
        }
        sqlite3_finalize(q);
        if (owner && context_tokens(s, owner, &after) != 0) {
            after = 0;
        }
        if (sqlite3_prepare_v2(
                s->db,
                "SELECT json_object('summary', e.body, 'firstKeptEntryId', CAST(e.first_kept_seq AS TEXT),"
                " 'tokensBefore', coalesce(e.tokens_before, 0), 'estimatedTokensAfter', ?2,"
                " 'usage', json_object('input', coalesce(json_extract(g.usage, '$.pic_tokens.input'), json_extract(g.usage, '$.input_tokens'), 0),"
                "   'output', coalesce(json_extract(g.usage, '$.pic_tokens.output'), json_extract(g.usage, '$.output_tokens'), 0),"
                "   'cacheRead', coalesce(json_extract(g.usage, '$.pic_tokens.cacheRead'), json_extract(g.usage, '$.cache_read_input_tokens'), 0),"
                "   'cacheWrite', coalesce(json_extract(g.usage, '$.pic_tokens.cacheWrite'), json_extract(g.usage, '$.cache_creation_input_tokens'), 0),"
                "   'totalTokens', coalesce(json_extract(g.usage, '$.pic_tokens.totalTokens'), coalesce(json_extract(g.usage, '$.input_tokens'), 0)"
                "     + coalesce(json_extract(g.usage, '$.output_tokens'), 0)),"
                "   'cost', json(coalesce(json_extract(g.usage, '$.pic_cost'), '{\"input\":0,\"output\":0,\"cacheRead\":0,\"cacheWrite\":0,\"total\":0}'))),"
                " 'details', json_object('readFiles', json(coalesce(json_extract(e.native, '$.readFiles'), '[]')),"
                "   'modifiedFiles', json(coalesce(json_extract(e.native, '$.modifiedFiles'), '[]'))))"
                " FROM pic_entry e LEFT JOIN pic_generation g ON g.entry_seq = e.seq AND g.state = 'done' WHERE e.seq = ?1",
                -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_int64(q, 1, seq);
            sqlite3_bind_int64(q, 2, after);
            if (sqlite3_step(q) == SQLITE_ROW) {
                data = strdup((const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
        ok(line, "compact", data ? data : "{}");
        free(data);
    }
    pic_interrupted = 0;
    R.phase = IDLE;
    R.cur = NULL;
    provider.free(&provider);
    free(instructions);
}

typedef struct {
    pic_store *s;
    const char *line;
    int admitted;
} prompt_ctx;

static void hold_free(void) {
    for (size_t i = 0; i < R.nheld; i++) {
        free(R.held[i].line);
        free(R.held[i].kind);
        free(R.held[i].text);
    }
    free(R.held);
    R.held = NULL;
    R.nheld = 0;
}

/* The prompt is in the journal: answered now, then what was held while idle
 * joins its queues, and commands are read while it runs. */
static void admitted(void *p) {
    prompt_ctx *c = p;
    c->admitted = 1;
    ok(c->line, "prompt", "{\"disposition\":\"started\"}");
    for (size_t i = 0; i < R.nheld; i++) {
        char *message = jtext(R.held[i].line, "$.message");
        if (message) {
            (void)pic_commands_enqueue(R.held[i].line, NULL, R.held[i].kind, message);
        }
        free(message);
    }
    if (R.nheld) {
        pic_queue_event(c->s);
    }
    hold_free();
    side_on();
    pump();
}

static void prompt(pic_store *s, const char *line) {
    char *message = jtext(line, "$.message"), err[PIC_ERR_CAP];
    pic_image *images = NULL;
    unsigned char *bytes = NULL;
    size_t n = 0;
    const char *error = NULL;
    pic_provider provider;
    prompt_ctx c = {s, line, 0};
    int exists, rc, aborted;
    if (!message) {
        fail(line, "prompt", "message must be a string");
        return;
    }
    if (bad_images(line)) {
        fail(line, "prompt", "images must be an array");
        free(message);
        return;
    }
    if (pic_images_from_json(R.mem, line, "$.images", 1, &images, &n, &bytes, &error) != 0) {
        fail(line, "prompt", error ? error : "images must be an array of image content");
        free(message);
        return;
    }
    memset(&provider, 0, sizeof provider);
    if (R.h->provider(&provider, R.model, R.thinking, err, sizeof err) != 0) { /* before anything is journaled */
        if (provider.free) {
            provider.free(&provider);
        }
        fail(line, "prompt", err);
        free(images);
        free(bytes);
        free(message);
        return;
    }
    provider.free(&provider);
    if (key_locked(line, "prompt")) {
        free(images);
        free(bytes);
        free(message);
        return;
    }
    exists = sid_exists(s);
    R.phase = RUN;
    R.cur = s;
    pic_commands_start(s, -1, R.h->expand, (void *)(uintptr_t)R.h->workspace);
    pic_commands_other(busy_other, NULL);
    s->events = &R.ev;
    rc = R.h->prompt(s, R.model, R.thinking, exists ? R.sid : NULL, exists ? NULL : R.sid, message, images, n, admitted, &c);
    catch_signals();
    aborted = rc != 0 && strcmp(s->err, "cancelled") == 0;
    side_off();
    pic_commands_stop();
    R.steer_all = s->steer_all;
    R.follow_up_all = s->follow_up_all;
    pic_interrupted = 0;
    R.phase = IDLE;
    R.cur = NULL;
    if (!c.admitted) {
        fail(line, "prompt", s->err[0] ? s->err : "the prompt was not accepted");
    } else {
        out_line(aborted ? "{\"type\":\"agent_settled\",\"aborted\":true}" : "{\"type\":\"agent_settled\",\"aborted\":false}");
    }
    free(images);
    free(bytes);
    free(message);
}

/* ---- idle commands ------------------------------------------------------------------ */

static void hold(const char *line, const char *type) {
    char *message = jtext(line, "$.message"), *expanded = NULL;
    held *v;
    if (!message) {
        fail(line, type, "message must be a string");
        return;
    }
    if (bad_images(line)) {
        fail(line, type, "images must be an array");
        free(message);
        return;
    }
    if (message[0] == '/' && R.h->expand) {
        expanded = R.h->expand((void *)(uintptr_t)R.h->workspace, message);
    }
    v = realloc(R.held, (R.nheld + 1) * sizeof *v);
    if (!v) {
        fail(line, type, "out of memory");
        free(message);
        free(expanded);
        return;
    }
    R.held = v;
    R.held[R.nheld].line = strdup(line);
    R.held[R.nheld].kind = strdup(type);
    R.held[R.nheld].text = expanded ? expanded : strdup(message);
    R.nheld++;
    free(message);
    ok(line, type, "{\"disposition\":\"queued\"}");
    {
        sqlite3_str *t = sqlite3_str_new(NULL);
        char *res;
        for (int pass = 0; pass < 2; pass++) {
            int first = 1;
            sqlite3_str_appendall(t, pass ? "],\"followUp\":[" : "{\"type\":\"queue_update\",\"steering\":[");
            for (size_t i = 0; i < R.nheld; i++) {
                if ((strcmp(R.held[i].kind, "steer") == 0) == (pass == 0)) {
                    char *q = quote(R.held[i].text);
                    sqlite3_str_appendf(t, "%s%s", first ? "" : ",", q ? q : "\"\"");
                    first = 0;
                    free(q);
                }
            }
        }
        sqlite3_str_appendall(t, "]}");
        res = sqlite3_str_finish(t);
        if (res) {
            out_line(res);
        }
        sqlite3_free(res);
    }
}

static void clear_held(const char *line) {
    sqlite3_str *t = sqlite3_str_new(NULL);
    char *res;
    for (int pass = 0; pass < 2; pass++) {
        int first = 1;
        sqlite3_str_appendall(t, pass ? "],\"followUp\":[" : "{\"steering\":[");
        for (size_t i = 0; i < R.nheld; i++) {
            if ((strcmp(R.held[i].kind, "steer") == 0) == (pass == 0)) {
                char *q = quote(R.held[i].text);
                sqlite3_str_appendf(t, "%s%s", first ? "" : ",", q ? q : "\"\"");
                first = 0;
                free(q);
            }
        }
    }
    sqlite3_str_appendall(t, "]}");
    res = sqlite3_str_finish(t);
    hold_free();
    ok(line, "clear_queue", res ? res : "{\"steering\":[],\"followUp\":[]}");
    sqlite3_free(res);
    if (res) {
        out_line("{\"type\":\"queue_update\",\"steering\":[],\"followUp\":[]}");
    }
}

/* A conversation id from Pi's sessionPath: an id (or a unique prefix), or
 * a session file pic exported (..._<id>.jsonl). */
static void session_from_path(const char *path, char *out, size_t cap) {
    const char *base = strrchr(path, '/'), *us;
    size_t n;
    base = base ? base + 1 : path;
    n = strlen(base);
    if (n > 6 && strcmp(base + n - 6, ".jsonl") == 0 && (us = strrchr(base, '_')) != NULL) {
        (void)snprintf(out, cap, "%.*s", (int)(base + n - 6 - us - 1), us + 1);
    } else {
        (void)snprintf(out, cap, "%s", path);
    }
}

static void end_owned(pic_store *s, const char *reason) {
    if (s->hooks && pic_hooks_end_owned(s, reason) != 0) {
        fprintf(stderr, "pic: warning: SessionEnd hooks: %s\n", s->err);
    }
}

static void session_change(pic_store *s, const char *line, const char *type) {
    if (strcmp(type, "new_session") == 0) {
        end_owned(s, "clear");
        fresh_sid(s);
        ok(line, type, "{\"cancelled\":false}");
    } else if (strcmp(type, "switch_session") == 0) {
        char *path = jtext(line, "$.sessionPath"), want[256], id[64];
        if (!path) {
            fail(line, type, "sessionPath must be a string");
        } else {
            session_from_path(path, want, sizeof want);
            if (pic_session_resolve(s, want, id, sizeof id) != 0) {
                fail(line, type, s->err);
            } else {
                if (strcmp(id, R.sid) != 0) {
                    end_owned(s, "other");
                }
                (void)snprintf(R.sid, sizeof R.sid, "%s", id);
                ok(line, type, "{\"cancelled\":false}");
            }
        }
        free(path);
    } else if (strcmp(type, "clone") == 0) {
        char made[64];
        sqlite3_stmt *q = NULL;
        int head = 0;
        if (sqlite3_prepare_v2(s->db, "SELECT head_seq IS NOT NULL FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, R.sid, -1, SQLITE_STATIC);
            head = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
        }
        sqlite3_finalize(q);
        if (!head) {
            fail(line, type, "Cannot clone session: no current entry selected");
        } else if (pic_fork(s, R.sid, 0, made, sizeof made) != 0) {
            fail(line, type, s->err);
        } else {
            end_owned(s, "other");
            (void)snprintf(R.sid, sizeof R.sid, "%s", made);
            ok(line, type, "{\"cancelled\":false}");
        }
    } else { /* fork: from the user message ENTRYID, without it */
        char *entry = jtext(line, "$.entryId"), *e = rpc_entries(s), *found = NULL;
        if (entry && e) {
            found = sqlv("SELECT json_array(coalesce(json_extract(o.value, '$.parentId'), ''), " USER_TEXT("o") ")"
                         " FROM json_each(?1) o WHERE json_extract(o.value, '$.id') = ?2 AND json_extract(o.value, '$.type') = 'message'"
                         " AND json_extract(o.value, '$.message.role') = 'user'",
                         e, entry);
        }
        if (!found) {
            fail(line, type, "Invalid entry ID for forking");
        } else {
            char *parent = jtext(found, "$[0]"), *text = jtext(found, "$[1]"), made[64] = "";
            int rc = 0;
            if (parent && *parent) {
                rc = pic_fork(s, R.sid, strtoll(parent, NULL, 10), made, sizeof made);
            }
            if (rc != 0) {
                fail(line, type, s->err);
            } else {
                char *qt = quote(text ? text : ""), *data;
                end_owned(s, "other");
                if (made[0]) {
                    (void)snprintf(R.sid, sizeof R.sid, "%s", made);
                } else {
                    fresh_sid(s); /* the first message: a new, empty conversation */
                }
                data = sqlite3_mprintf("{\"text\":%s,\"cancelled\":false}", qt ? qt : "\"\"");
                ok(line, type, data);
                sqlite3_free(data);
                free(qt);
            }
            free(parent);
            free(text);
        }
        free(found);
        free(e);
        free(entry);
    }
}

/* Needs nothing of the journal. */
static int journal_free(const char *type) {
    static const char *const names[] = {"get_available_thinking_levels", "set_model", "cycle_model", "set_thinking_level", "cycle_thinking_level", "set_steering_mode",
                                        "set_follow_up_mode", "set_auto_compaction", "set_auto_retry", "abort_retry",
                                        "abort", "abort_bash", "steer", "follow_up", "clear_queue", "login", "logout", "unlock", "get_auth_status",
                                        "extension_ui_response"};
    const pic_rpc_command *c = component_command(type);
    for (size_t i = 0; i < sizeof names / sizeof names[0]; i++) {
        if (strcmp(type, names[i]) == 0) {
            return 1;
        }
    }
    return c && (c->flags & PIC_RPC_JOURNAL_FREE) != 0;
}

/* A component's command (pic_rpc_host's), or NULL. */
static const pic_rpc_command *component_command(const char *type) {
    for (size_t i = 0; R.h && i < R.h->ncommands; i++) {
        if (strcmp(R.h->commands[i]->type, type) == 0) {
            return R.h->commands[i];
        }
    }
    return NULL;
}

/* Runs C's answer for LINE with the journal S (NULL for a journal-free
 * command); CALL holds its outputs, with err set on -1. */
static int component_call(const pic_rpc_command *c, pic_store *s, const char *line, pic_rpc_call *call) {
    memset(call, 0, sizeof *call);
    call->s = s;
    call->session = R.sid;
    call->model = R.model;
    call->workspace = R.h->workspace;
    call->line = line;
    if (s) {
        s->err[0] = '\0';
    }
    if (c->answer(call) == 0) {
        return 0;
    }
    if (!call->err[0]) {
        (void)snprintf(call->err, sizeof call->err, "%s", s && s->err[0] ? s->err : "failed");
    }
    return -1;
}

static void component_answer(pic_store *s, const char *line, const char *type, const pic_rpc_command *c) {
    pic_rpc_call call;
    if (component_call(c, s, line, &call) != 0) {
        fail(line, type, call.err);
    } else {
        if (call.switched && s) {
            end_owned(s, "other");
            if (call.next[0]) {
                (void)snprintf(R.sid, sizeof R.sid, "%s", call.next);
            } else {
                fresh_sid(s);
            }
        }
        ok(line, type, call.data);
    }
    free(call.data);
}

static void with_journal(const char *line, const char *type) {
    const pic_rpc_command *cmd = component_command(type);
    pic_store own, *s = R.cur;
    if (!s) {
        if (open_journal(&own) != 0) {
            fail(line, type, own.err);
            pic_close(&own);
            return;
        }
        s = &own;
    }
    if (strcmp(type, "get_state") == 0) {
        get_state(s, line);
    } else if (strcmp(type, "get_messages") == 0) {
        char *m = messages(s), *data = m ? sqlite3_mprintf("{\"messages\":%s}", m) : NULL;
        if (data) {
            ok(line, type, data);
        } else {
            fail(line, type, s->err);
        }
        sqlite3_free(data);
        free(m);
    } else if (strcmp(type, "get_session_stats") == 0) {
        session_stats(s, line);
    } else if (strcmp(type, "get_fork_messages") == 0) {
        get_fork_messages(s, line);
    } else if (strcmp(type, "get_last_assistant_text") == 0) {
        last_assistant_text(s, line);
    } else if (strcmp(type, "get_entries") == 0) {
        get_entries(s, line);
    } else if (strcmp(type, "get_tree") == 0) {
        get_tree(s, line);
    } else if (strcmp(type, "set_session_name") == 0) {
        set_session_name(s, line);
    } else if (strcmp(type, "export_html") == 0) {
        export_html(s, line);
    } else if (strcmp(type, "prompt") == 0) {
        prompt(s, line);
    } else if (strcmp(type, "bash") == 0) {
        run_bash(s, line);
    } else if (strcmp(type, "compact") == 0) {
        compact(s, line);
    } else if (strcmp(type, "new_session") == 0 || strcmp(type, "switch_session") == 0 || strcmp(type, "fork") == 0 ||
               strcmp(type, "clone") == 0) {
        session_change(s, line, type);
    } else if (cmd) {
        component_answer(s, line, type, cmd);
    } else {
        char msg[160];
        (void)snprintf(msg, sizeof msg, "Unknown command: %.100s", type);
        fail(line, type, msg);
    }
    if (s == &own) {
        pic_close(&own);
    }
}

static void command(const char *line) {
    char *valid = sqlv("SELECT json_valid(?1) AND json_type(?1) = 'object'", line, NULL), *type;
    if (!valid || strcmp(valid, "1") != 0) {
        free(valid);
        fail(NULL, "parse", "Failed to parse command: not a JSON object");
        return;
    }
    free(valid);
    type = jtext(line, "$.type");
    if (!type) {
        fail(line, "", "Unknown command: ");
        return;
    }
    if (R.phase != IDLE && busy(line, type)) {
        free(type);
        return;
    }
    if (!journal_free(type)) {
        with_journal(line, type);
    } else if (strcmp(type, "get_available_thinking_levels") == 0) {
        char levels[160], data[192];
        (void)levels_json(levels, sizeof levels);
        (void)snprintf(data, sizeof data, "{\"levels\":%s}", levels);
        ok(line, type, data);
    } else if (strcmp(type, "set_model") == 0) {
        set_model(line);
    } else if (strcmp(type, "cycle_model") == 0) {
        rpc_cycle_model(line);
    } else if (strcmp(type, "set_thinking_level") == 0) {
        set_thinking_level(line);
    } else if (strcmp(type, "cycle_thinking_level") == 0) {
        cycle_thinking_level(line);
    } else if (strcmp(type, "set_steering_mode") == 0) {
        set_mode(line, type, &R.steer_all);
    } else if (strcmp(type, "set_follow_up_mode") == 0) {
        set_mode(line, type, &R.follow_up_all);
    } else if (strcmp(type, "set_auto_compaction") == 0) {
        set_enabled(line, type, "compaction");
    } else if (strcmp(type, "set_auto_retry") == 0) {
        set_enabled(line, type, "retry");
    } else if (strcmp(type, "abort_retry") == 0) {
        if (R.cur) {
            R.cur->abort_retry = 1;
        }
        ok(line, type, NULL);
    } else if (strcmp(type, "abort") == 0 || strcmp(type, "abort_bash") == 0) {
        ok(line, type, NULL); /* nothing runs: idle already */
    } else if (strcmp(type, "steer") == 0 || strcmp(type, "follow_up") == 0) {
        hold(line, type);
    } else if (strcmp(type, "clear_queue") == 0) {
        clear_held(line);
    } else if (strcmp(type, "login") == 0) {
        rpc_auth_login(line);
    } else if (strcmp(type, "logout") == 0) {
        rpc_auth_logout(line);
    } else if (strcmp(type, "unlock") == 0) {
        rpc_unlock(line);
    } else if (strcmp(type, "get_auth_status") == 0) {
        rpc_auth_status(line);
    } else if (strcmp(type, "extension_ui_response") == 0) {
        fail(line, type, "pic has no extensions, so there is no extension UI to answer");
    } else {
        component_answer(NULL, line, type, component_command(type));
    }
    free(type);
}

/* ---- the process ---------------------------------------------------------------------- */

static void on_signal(int sig) {
    R.term = sig;
    if (!pic_interrupted) {
        pic_interrupted = 2;
    }
}

/* SIGTERM, SIGHUP and SIGINT: what runs is cancelled (durably, as Ctrl-C's
 * cancel), then the process ends. A request installs Ctrl-C's own handler
 * while it runs; this one comes back after. */
static void catch_signals(void) {
    struct sigaction sa;
    memset(&sa, 0, sizeof sa);
    sa.sa_handler = on_signal; /* no SA_RESTART: an idle read ends */
    sigemptyset(&sa.sa_mask);
    (void)sigaction(SIGTERM, &sa, NULL);
    (void)sigaction(SIGHUP, &sa, NULL);
    (void)sigaction(SIGINT, &sa, NULL);
}

int pic_rpc_main(const pic_rpc_host *h, const char *model, const char *session) {
    char err[PIC_ERR_CAP];
    int status = 0;
    memset(&R, 0, sizeof R);
    R.h = h;
    pic_tty_forbid(); /* stdin and stdout are the protocol; a terminal, if any, is the client's */
    if (sqlite3_open(":memory:", &R.mem) != SQLITE_OK) {
        fputs("pic: rpc: cannot open an in-memory database\n", stderr);
        return 1;
    }
    pic_events_init(&R.ev, stdout, stderr, 1, 0);
    (void)snprintf(R.model, sizeof R.model, "%s", model);
    if (h->level(model, R.thinking, sizeof R.thinking, err, sizeof err) != 0) {
        fprintf(stderr, "pic: %s\n", err);
        sqlite3_close(R.mem);
        return 2;
    }
    {
        char *retry = pic_setting("retry"), *enabled = retry ? sqlv("SELECT json_extract(?1, '$.enabled')", retry, NULL) : NULL;
        R.no_retry = enabled && strcmp(enabled, "0") == 0;
        free(enabled);
        free(retry);
    }
    {
        pic_store s;
        if (open_journal(&s) != 0) {
            fprintf(stderr, "pic: %s\n", s.err);
            pic_close(&s);
            sqlite3_close(R.mem);
            return 1;
        }
        if (session) {
            if (pic_session_resolve(&s, session, R.sid, sizeof R.sid) != 0) {
                fprintf(stderr, "pic: %s\n", s.err);
                pic_close(&s);
                sqlite3_close(R.mem);
                return 1;
            }
        } else {
            fresh_sid(&s);
        }
        pic_close(&s);
    }
    catch_signals();
    for (;;) {
        char *line;
        if (R.term) {
            break;
        }
        if ((line = pop(&R.deferred)) != NULL || (line = pop(&R.inbox)) != NULL) {
            command(line);
            free(line);
            continue;
        }
        if (R.eof) {
            break;
        }
        (void)fill();
    }
    if (R.term) {
        status = R.term == SIGHUP ? 129 : R.term == SIGINT ? 130 : 143;
    }
    h->end(h->db, "other");
    hold_free();
    while (R.inbox.n) {
        free(pop(&R.inbox));
    }
    while (R.deferred.n) {
        free(pop(&R.deferred));
    }
    free(R.inbox.v);
    free(R.deferred.v);
    free(R.buf);
    sqlite3_close(R.mem);
    return status;
}