Skip to content
pi-c Artifact [3c08ba17fd]
Login

Artifact [3c08ba17fd]

Artifact 3c08ba17fd51f865c94b2613c720bd02d6a057f67d05f53a870c6e72d80ca915:


/* pic command line: ask for work, run it durably, inspect the journal. */
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include <stdint.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

#include "commands.h"
#include "cred.h"
#include "hooks.h"
#include "input.h"
#include "net.h"
#include "catalog.h"
#include "userdb.h"
#include "pic.h"
#include "procs.h"
#include "prompts.h"
#include "rpc.h"
#include "skills.h"
#include "platform.h"
#include "tui/tui.h"
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif

/* --context-window: replaces the model's window for automatic compaction (-1: keep). */
static long context_window = -1;
/* --thinking: the thinking level asked for on the command line (NULL: the settings). */
static const char *thinking_opt;
/* --json: Pi-style events on stdout; --stream: stream reply text even when
 * stdout is not a terminal. */
static int json_events, force_stream;
/* --commands: Pi's RPC command lines on stdin steer ask and run (with --json). */
static int commands;
/* The line mode: ask prints the conversation it joined only when it changes. */
static int quiet;
static char last_session[64]; /* the line mode's conversation, set by ask */
static pic_events events;
/* --mode rpc (rpc.c): a new conversation's id, chosen before its first
 * prompt, and what runs once ask has admitted a prompt. */
static const char *ask_new_id;
static void (*ask_admitted)(void *ctx);
static void *ask_admitted_ctx;
/* The command hooks (hooks.h), loaded once the workspace and journal are known. */
static pic_hooks *hooks;
/* PIC_HOOK_OWNER, taken from the environment so tools and hooks never see it. */
static char hook_owner[96];

/* For benchmarks: the trial arm and request cap kept on each request this
 * process admits, and lapse compaction (--trial, --max-requests, --lapse,
 * --lapse-seconds, --lapse-floor; else PIC_TRIAL, PIC_MAX_REQUESTS,
 * PIC_LAPSE, PIC_LAPSE_SECONDS, PIC_LAPSE_FLOOR; else the settings
 * lapseCompaction, lapseSeconds, lapseFloorTokens). */
static const char *trial_opt, *max_requests_opt, *lapse_opt, *lapse_seconds_opt, *lapse_floor_opt;
static struct {
    const char *trial;
    long max_requests, lapse_seconds, lapse_floor;
    int lapse;
} bench = {NULL, 0, -1, 20000, 0};

/* Opens the journal with the hooks attached. */
static int open_store(pic_store *s, const char *db) {
    int rc = pic_open(s, db);
    s->hooks = hooks;
    s->trial = bench.trial;
    s->max_requests = bench.max_requests;
    s->lapse = bench.lapse;
    s->lapse_seconds = bench.lapse_seconds;
    s->lapse_floor = bench.lapse_floor;
    return rc;
}

/* The flag, else the environment variable, else the setting (*owned is the
 * malloc'd setting, for the caller to free), else NULL. */
static const char *bench_value(const char *flag, const char *env, const char *key, char **owned) {
    const char *e = getenv(env);
    *owned = NULL;
    if (flag) {
        return flag;
    }
    if (e && *e) {
        return e;
    }
    return key ? (*owned = pic_setting(key)) : NULL;
}

/* A whole number from MIN up, or -1. */
static long whole(const char *v, long min) {
    char *end = NULL;
    long n;
    errno = 0;
    n = v && *v ? strtol(v, &end, 10) : -1;
    return errno || !end || *end || n < min ? -1 : n;
}

/* Resolves the benchmark options; -1 with a message for a bad value. */
static int bench_options(void) {
    char *owned;
    const char *v = bench_value(trial_opt, "PIC_TRIAL", NULL, &owned);
    if (v) {
        size_t n = strlen(v);
        for (size_t k = 0; k < n; k++) {
            if (v[k] < 0x20 || v[k] > 0x7e) {
                n = 0;
            }
        }
        if (n == 0 || n > 64) {
            fputs("pic: a trial label is 1 to 64 printable characters (--trial, PIC_TRIAL)\n", stderr);
            return -1;
        }
        bench.trial = v;
    }
    if ((v = bench_value(max_requests_opt, "PIC_MAX_REQUESTS", NULL, &owned)) &&
        (bench.max_requests = whole(v, 1)) < 0) {
        fprintf(stderr, "pic: --max-requests takes a number of requests from 1 up, not %s\n", v);
        return -1;
    }
    v = bench_value(lapse_opt, "PIC_LAPSE", "lapseCompaction", &owned);
    if (v && strcmp(v, "on") != 0 && strcmp(v, "off") != 0) {
        fprintf(stderr, "pic: lapse compaction is on or off, not %s (--lapse, PIC_LAPSE, lapseCompaction)\n", v);
        free(owned);
        return -1;
    }
    bench.lapse = v && strcmp(v, "on") == 0;
    free(owned);
    v = bench_value(lapse_seconds_opt, "PIC_LAPSE_SECONDS", "lapseSeconds", &owned);
    if (v && (bench.lapse_seconds = whole(v, 1)) < 0) {
        fprintf(stderr, "pic: the lapse lifetime is seconds from 1 up, not %s (--lapse-seconds, PIC_LAPSE_SECONDS, lapseSeconds)\n", v);
        free(owned);
        return -1;
    }
    free(owned);
    v = bench_value(lapse_floor_opt, "PIC_LAPSE_FLOOR", "lapseFloorTokens", &owned);
    if (v && (bench.lapse_floor = whole(v, 0)) < 0) {
        fprintf(stderr, "pic: the lapse floor is tokens from 0 up, not %s (--lapse-floor, PIC_LAPSE_FLOOR, lapseFloorTokens)\n", v);
        free(owned);
        return -1;
    }
    free(owned);
    return 0;
}

/* Ctrl-C: the first cancels the running request (pic_run settles it in the
 * journal), a second exits at once and the journal recovers on the next run. */
static void on_interrupt(int sig) {
    if (pic_interrupted == 1) { /* 2 is an abort command's: this is still the first Ctrl-C */
        (void)signal(sig, SIG_DFL);
        (void)raise(sig);
    }
    pic_interrupted = 1;
}

static void catch_interrupt(void) {
    struct sigaction sa;
    memset(&sa, 0, sizeof sa);
    sa.sa_handler = on_interrupt; /* no SA_RESTART: blocked waits return */
    sigemptyset(&sa.sa_mask);
    (void)sigaction(SIGINT, &sa, NULL);
}

/* ---- models and settings ------------------------------------------------ */

static int usage(void);

/* A setting (malloc'd), or NULL: picu_setting in ~/.pic/pic.sqlite. */
static char *setting(const char *key) { return pic_setting(key); }

/* Sets KEY to VALUE in picu_setting. */
static int set_setting(const char *key, const char *value) { return pic_setting_set(key, value); }

static int print_project(void *ctx, const pic_project *p) {
    (void)ctx;
    printf("%s\t%s\t%s\t%s\n", p->name, p->kind, p->state, p->remote);
    return 0;
}

static int print_setting(void *ctx, const char *key, const char *value) {
    (void)ctx;
    printf("%s=%s\n", key, value);
    return 0;
}

static void level_names(char *out, size_t cap, const char *const *names, int n) {
    size_t used = 0;
    out[0] = '\0';
    for (int i = 0; i < n && used < cap; i++) {
        used += (size_t)snprintf(out + used, cap - used, "%s%s", i ? ", " : "", names[i]);
    }
}

typedef struct {
    sqlite3_stmt *q;
    int json, all, available;
    char provider[64];
} listing;

static int list_model(void *ctx, const char *provider, const char *json) {
    listing *l = ctx;
    char levels[96];
    if (strcmp(provider, l->provider) != 0) {
        (void)snprintf(l->provider, sizeof l->provider, "%s", provider);
        l->available = pic_model_available(provider);
    }
    if (!l->all && !l->available) {
        return 0;
    }
    sqlite3_bind_text(l->q, 1, json, -1, SQLITE_STATIC);
    sqlite3_bind_text(l->q, 2, provider, -1, SQLITE_STATIC);
    sqlite3_bind_int(l->q, 3, l->available);
    pic_model_thinking_json(json, levels, sizeof levels);
    sqlite3_bind_text(l->q, 4, levels, -1, SQLITE_STATIC);
    if (sqlite3_step(l->q) == SQLITE_ROW) {
        printf("%s\n", (const char *)sqlite3_column_text(l->q, l->json ? 0 : 1));
    }
    sqlite3_reset(l->q);
    return 0;
}

/* pic models: the catalog (Pi's) plus the models file, for providers with a
 * key unless --all; --refresh fetches fresher lists first. */
static int models_command(int argc, char **argv) {
    listing l;
    sqlite3 *db = NULL;
    int refresh = 0;
    memset(&l, 0, sizeof l);
    for (int i = 0; i < argc; i++) {
        if (strcmp(argv[i], "--json") == 0) {
            l.json = 1;
        } else if (strcmp(argv[i], "--all") == 0) {
            l.all = 1;
        } else if (strcmp(argv[i], "--refresh") == 0) {
            refresh = 1;
        } else if (strcmp(argv[i], "--default") == 0 && i + 1 < argc) {
            pic_model m;
            char err[PIC_ERR_CAP];
            if (pic_model_resolve(argv[i + 1], &m, err, sizeof err) != 0) {
                fprintf(stderr, "pic: %s\n", err);
                return 1;
            }
            if (set_setting("defaultModel", argv[i + 1]) != 0) {
                fprintf(stderr, "pic: cannot save the setting in ~/.pic/pic.sqlite\n");
                return 1;
            }
            printf("default model: %s\n", argv[i + 1]);
            return 0;
        } else if (strcmp(argv[i], "--thinking-default") == 0 && i + 1 < argc) {
            if (pic_thinking_index(argv[i + 1]) < 0) {
                char list[128];
                level_names(list, sizeof list, pic_thinking_names, PIC_THINKING_LEVELS);
                fprintf(stderr, "pic: unknown thinking level %s (%s)\n", argv[i + 1], list);
                return 1;
            }
            if (set_setting("defaultThinkingLevel", argv[i + 1]) != 0) {
                fprintf(stderr, "pic: cannot save the setting in ~/.pic/pic.sqlite\n");
                return 1;
            }
            printf("default thinking level: %s\n", argv[i + 1]);
            return 0;
        } else {
            return usage();
        }
    }
    if (refresh) {
        char err[PIC_ERR_CAP];
        if (pic_catalog_refresh(1, err, sizeof err) != 0) {
            fprintf(stderr, "pic: model catalog: %s (showing what is stored)\n", err);
        }
    }
    if (sqlite3_open(":memory:", &db) != SQLITE_OK ||
        sqlite3_prepare_v2(db,
                           "SELECT json_object('model', ?2 || '/' || json_extract(?1, '$.id'), 'provider', ?2,"
                           " 'id', json_extract(?1, '$.id'), 'name', coalesce(json_extract(?1, '$.name'), json_extract(?1, '$.id')),"
                           " 'contextWindow', json_extract(?1, '$.contextWindow'),"
                           " 'reasoning', json(iif(json_extract(?1, '$.reasoning'), 'true', 'false')), 'thinkingLevels', json(?4),"
                           " 'cost', json(coalesce(json_extract(?1, '$.cost'),"
                           "   '{\"input\":0,\"output\":0,\"cacheRead\":0,\"cacheWrite\":0}')),"
                           " 'available', json(iif(?3, 'true', 'false'))),"
                           " printf('%-48s %s', ?2 || '/' || json_extract(?1, '$.id'),"
                           "   coalesce(json_extract(?1, '$.name'), '') || CASE WHEN ?3 THEN '' ELSE '  (no key)' END)",
                           -1, &l.q, NULL) != SQLITE_OK) {
        sqlite3_close(db);
        return 1;
    }
    (void)pic_catalog_each(list_model, &l);
    l.provider[0] = '\0';
    (void)pic_models_each_user(list_model, &l);
    sqlite3_finalize(l.q);
    sqlite3_close(db);
    return 0;
}

/* This executable's path, for the TUI's child processes. */
static void self_path(const char *argv0, char *out, size_t cap) {
#ifdef __APPLE__
    uint32_t size = (uint32_t)cap;
    char raw[PATH_MAX];
    if (_NSGetExecutablePath(raw, &size) == 0 && realpath(raw, out)) {
        return;
    }
#else
    ssize_t n = readlink("/proc/self/exe", out, cap - 1);
    if (n > 0) {
        out[n] = '\0';
        return;
    }
#endif
    if (!realpath(argv0, out)) {
        (void)snprintf(out, cap, "%s", argv0);
    }
}

static void print_usage(FILE *out) {
    fputs("usage: pic [--workspace DIR] [--db PATH] [--model MODEL] ask [-c | --session ID] [--image PATH]... TEXT\n"
          "           run TEXT in the workspace (default: the current directory) and print the answer;\n"
          "           a new session, or -c to continue the latest, --session to continue that one;\n"
          "           --image attaches an image file (png, jpeg, gif, webp) after the text\n"
          "           the journal defaults to WORKSPACE/.pic/journal.sqlite\n"
          "       pic [options] -p [TEXT] [@FILE]... [TEXT]...   Pi's print mode: run one prompt and print the answer;\n"
          "           --print too; piped stdin comes first in the prompt, then the @files (text as <file name=\"PATH\">,\n"
          "           images attached), then the first TEXT; each further TEXT continues the conversation;\n"
          "           -c or --continue joins the latest conversation, --session ID that one (an unknown ID is an error);\n"
          "           -- ends the options (what follows is TEXT and @FILE, even with a leading - or @)\n"
          "       options: --system-prompt TEXT|FILE replaces the system prompt; --append-system-prompt TEXT|FILE adds to it\n"
          "           (repeat it), as ~/.pic/SYSTEM.md and APPEND_SYSTEM.md do, and the trusted workspace's .pic/ ones\n"
          "       pic [options] [tui [-c | --session ID]]   the terminal interface (plain pic in a terminal);\n"
          "           -c continues the latest conversation (the first in pic sessions), --session that one\n"
          "       pic [options] chat [-c | --session ID]   a plain line prompt for one conversation\n"
          "       pic [options] --mode rpc [-c | --continue | --session ID]   Pi's RPC mode: Pi's JSONL commands on stdin\n"
          "           (prompt, steer, follow_up, abort, compact, bash, fork, get_state and the rest), responses and Pi's\n"
          "           events on stdout; the journal is held only while a command, request, compaction or bash runs\n"
          "       pic [options] settings [KEY [VALUE] | --unset KEY]   settings kept in ~/.pic/pic.sqlite\n"
          "           cacheRetention: short (default), long (1 hour; OpenAI 24h) or none, as Pi's (PI_CACHE_RETENTION=long too)\n"
          "           toolExecution: parallel (default: a reply's tool calls run at once) or sequential, as Pi's\n"
          "       pic projects   the projects kept in ~/.pic/pic.sqlite: name, kind, state, remote\n"
          "       pic login PROVIDER   store PROVIDER's API key (typed with echo off, or piped on stdin) in ~/.pic/pic.sqlite,\n"
          "           sealed with ChaCha20-Poly1305 under a key from a passphrase (asked once per process, when a stored key\n"
          "           is needed); PROVIDER's variable (ANTHROPIC_API_KEY and the like) still wins when set\n"
          "       pic logout PROVIDER   remove the stored key\n"
          "       pic keys   the stored keys' names and dates, never values\n"
          "       pic [options] models [--json] [--all] [--refresh] | models --default NAME | models --thinking-default LEVEL\n"
          "           models from Pi's catalog (and models.json) whose provider has a key; --all every one\n"
          "       pic [options] sessions [--json] | log [--json] [ID] | name ID NAME | fork ID [--at ENTRY]\n"
          "       pic [options] bash [--no-context] [-c | --session ID] COMMAND   run COMMAND in the workspace and journal it as\n"
          "           Pi's bashExecution message (what \"!COMMAND\" does in the terminal): it reaches the model with the\n"
          "           conversation's next request, unless --no-context (\"!!\"); exits with the command's status; with --json,\n"
          "           bash_execution_update events and Pi's bash response (output, exitCode, cancelled, truncated, conversation)\n"
          "       pic [options] tree --json [ID]   the requests of ID's conversation tree, branches included\n",
          out);
    /* Two literals: one would pass the length C11 compilers must accept. */
    fputs("       pic [options] fork ID --at ENTRY --summarize [--instructions TEXT] [--script FILE | --api-url URL]\n"
          "           Pi's /tree with a summary: a new conversation from ENTRY with a summary of what ID leaves behind\n"
          "       pic [options] export --html ID [PATH | -]   a conversation as one self-contained HTML page (default -)\n"
          "       pic [options] import PATH | -   a Pi v3 session JSONL as a new conversation (the text of its messages)\n"
          "       pic [options] import --claude PATH [--until UUID] [--workspace DIR] [--count]   a Claude Code transcript as a new\n"
          "           conversation in its cwd's workspace (or DIR), its main thread before the record UUID; prints its id,\n"
          "           counts, pic's estimate of the next request's context and the transcript's own at the cut; --count\n"
          "           also counts pic's first request on it (system prompt, tools, messages) by the provider's counter\n"
          "       pic [options] trust [yes | no] | scoped-models [--clear | --set PATTERN...] | bug [--list | TEXT]\n"
          "           the workspace's trust, the models Ctrl+P cycles, a bug report kept in ~/.pic/pic.sqlite (sent nowhere)\n"
          "       pic [options] prompts [--json]   the prompt templates (~/.pic/prompts, and the trusted workspace's .pic/prompts):\n"
          "           /NAME ARGS in a message sends the template with $1, $@, ${@:2} and the like filled in\n"
          "       pic [options] skills [--json]   the skills (~/.pic/skills, and the trusted workspace's .pic/skills; symlinks followed):\n"
          "           listed in the system prompt; /skill:NAME ARGS in a message sends the skill's instructions and ARGS\n"
          ,
          out);
    fputs("       pic ps [--all] [--json] | ps --kill ID|--all   the processes pic started that are still running (hooks,\n"
          "           bash and \"!\" commands, the terminal's request children); --all adds recent finished ones; --kill\n"
          "           stops one (or all) by process group. Processes a hook script starts on its own are not tracked.\n",
          out);
    fputs("       pic [options] hooks   the command hooks of ~/.pic/hooks.json (and the trusted workspace's .pic/hooks.json),\n"
          "           Claude Code's shape and events (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact,\n"
          "           Stop, SessionEnd); pic dump lists their runs. hooks end REASON: SessionEnd for what PIC_HOOK_OWNER began\n"
          "       pic [options] compact [ID [INSTRUCTIONS]]   summarize the conversation before its next request\n"
          "       pic [options] compact --now [ID [INSTRUCTIONS]]   summarize it now (Pi's /compact)\n"
          "       pic [options] export [--since ENTRY]   finished entries as JSON lines\n"
          "       pic [options] export --pi [DIR | -]   conversations as Pi session lines: rows in ~/.pic/pic.sqlite\n"
          "           (for ctx; ask, chat and the terminal write them after each request unless PIC_PI_EXPORT=0),\n"
          "           and ~/.pic/sessions files only with piSessionFiles=1; DIR writes files there, - to stdout\n"
          "       pic [options] submit KEY TEXT [--session ID] | cancel KEY\n"
          "       pic [options] run --script FILE\n"
          "       pic [options] run [--session ID] [--provider anthropic] [--api-url URL]   finish unfinished requests, each\n"
          "           with the model and thinking level it was admitted with; --session: only that conversation's\n"
          "       pic [options] dump | check | result CALL_ID\n"
          "       pic [options] usage --by-trial [--json]   requests, tokens (cache reads and writes too) and cost by trial\n"
          "       pic [options] prune [--dry-run]   drop the bytes of images no request sends any more (compacted\n"
          "           away) or older than imageRetentionDays (setting, default 30, 0 never); also at open, hourly\n"
          "options: --workspace DIR  --db PATH  --model MODEL  --exec-timeout SECONDS (bash default, 600)\n"
          "         --tools, -t LIST (comma list of read, bash, edit, write, grep, find, ls: only these; * patterns; or only\n"
          "           +name/-name entries to change the default four)  --exclude-tools, -xt LIST  --no-tools, -nt\n"
          "           --no-builtin-tools, -nbt  (setting defaultTools: a comma list, same entries; default read,bash,edit,write)\n"
          "         --tui-mode MODE (the terminal interface: fullscreen, the default, or regular; setting tuiMode)\n"
          "         --theme NAME (the colour theme for this run: dark, light, a file in ~/.pic/themes, or light/dark; setting theme)\n"
          "         --thinking LEVEL (off, minimal, low, medium, high, xhigh, max; the model's supported ones;\n"
          "           default: settings thinkingLevel:MODEL / defaultThinkingLevel, else medium)\n"
          "         --json (events on stdout, as Pi's JSON mode)  --stream (stream the reply even when piped)\n"
          "         --context-window TOKENS (compact past this minus 16384; default: the model's, 0 never)\n"
          "         --lapse on|off (PIC_LAPSE; setting lapseCompaction, default off): compact before a request when the\n"
          "           conversation has been idle past the prompt cache's lifetime and its context is above the floor\n"
          "         --lapse-seconds N (PIC_LAPSE_SECONDS; setting lapseSeconds; default the cache's: 300, 3600 with\n"
          "           cacheRetention long, OpenAI 86400)  --lapse-floor TOKENS (PIC_LAPSE_FLOOR; lapseFloorTokens; 20000)\n"
          "         --trial LABEL (PIC_TRIAL): a benchmark arm (1-64 printable bytes) kept on each request admitted\n"
          "         --max-requests N (PIC_MAX_REQUESTS): a request stops cleanly (request_cap) before its (N+1)th\n"
          "           reply request, retries not counted; pic ask -c continues it\n"
          "         --commands (with --json, for ask and run: Pi's RPC command lines on stdin steer the running\n"
          "           request: steer, follow_up, clear_queue, abort, set_steering_mode, set_follow_up_mode;\n"
          "           each is journaled as it arrives. While a request runs its process owns the journal, so\n"
          "           this is the only way to steer it: there is no separate steer command)\n",
          out);
}

static int usage(void) {
    print_usage(stderr);
    return 2;
}

static const char default_model[] = "anthropic/claude-opus-5-5";

/* Pi's defaultModelPerProvider (model-resolver.ts), in its order: with no
 * usable saved default, the first of these whose provider has a key. */
static const char *const default_per_provider[][2] = {
    {"amazon-bedrock", "us.anthropic.claude-opus-5-5"},
    {"ant-ling", "Ring-2.6-1T"},
    {"anthropic", "claude-opus-5-5"},
    {"openai", "gpt-6.2-sol"},
    {"azure", "gpt-6.2-sol"},
    {"openai-codex", "gpt-6.2-sol"},
    {"radius", "balanced"},
    {"nvidia", "nvidia/nemotron-3.5-super-vl-120b-a12b"},
    {"deepseek", "deepseek-v4-pro"},
    {"google", "gemini-4-argon"},
    {"google-vertex", "gemini-4-argon"},
    {"github-copilot", "gpt-6.1-sol"},
    {"openrouter", "moonshotai/kimi-k2.7-code"},
    {"vercel-ai-gateway", "zai/glm-5.3"},
    {"xai", "grok-4.7"},
    {"groq", "openai/gpt-oss-120b"},
    {"cerebras", "gpt-oss-120b"},
    {"zai", "glm-5.3"},
    {"zai-coding-cn", "glm-5.3"},
    {"mistral", "devstral-medium-latest"},
    {"minimax", "MiniMax-M3"},
    {"minimax-cn", "MiniMax-M3"},
    {"moonshotai", "kimi-k2.7-code"},
    {"moonshotai-cn", "kimi-k2.7-code"},
    {"huggingface", "moonshotai/Kimi-K2.7-Code"},
    {"fireworks", "accounts/fireworks/models/kimi-k3"},
    {"together", "moonshotai/Kimi-K3"},
    {"baseten", "zai-org/GLM-5.3"},
    {"opencode", "kimi-k2.7-code"},
    {"opencode-go", "kimi-k3.1-pro"},
    {"kimi-coding", "kimi-for-coding"},
    {"meta", "muse-spark-1.3"},
    {"cloudflare-workers-ai", "@cf/moonshotai/kimi-k2.7-code"},
    {"cloudflare-ai-gateway", "workers-ai/@cf/moonshotai/kimi-k2.7-code"},
    {"qwen-token-plan", "qwen3.8-max"},
    {"qwen-token-plan-cn", "qwen3.8-max"},
    {"qwen-token-plan-individual", "qwen3.8-max"},
    {"qwen-token-plan-individual-cn", "qwen3.8-max"},
    {"xiaomi", "mimo-v2.6-pro"},
    {"xiaomi-token-plan-cn", "mimo-v2.6-pro"},
    {"xiaomi-token-plan-ams", "mimo-v2.6-pro"},
    {"xiaomi-token-plan-sgp", "mimo-v2.6-pro"},
};

typedef struct {
    sqlite3_stmt *id; /* json_extract(?1, '$.id') */
    char provider[64];
    int available;
    char *out;
    size_t cap;
} first_model;

static int first_available(void *ctx, const char *provider, const char *json) {
    first_model *f = ctx;
    if (strcmp(provider, f->provider) != 0) {
        (void)snprintf(f->provider, sizeof f->provider, "%s", provider);
        f->available = pic_model_available(provider);
    }
    if (!f->available) {
        return 0;
    }
    sqlite3_bind_text(f->id, 1, json, -1, SQLITE_STATIC);
    if (sqlite3_step(f->id) == SQLITE_ROW && sqlite3_column_text(f->id, 0)) {
        (void)snprintf(f->out, f->cap, "%s/%s", provider, (const char *)sqlite3_column_text(f->id, 0));
    }
    sqlite3_reset(f->id);
    return f->out[0] != '\0';
}

/* The model to start on, as Pi's findInitialModel picks it: the saved
 * default when its provider has a key; else Pi's default for the first
 * provider with one; else the first model with a key (catalog, then the
 * models file); else pic's own default, whose error then names the key. */
static void initial_model(char *out, size_t cap) {
    char *def = setting("defaultModel");
    pic_model m;
    char err[PIC_ERR_CAP];
    if (def && *def && pic_model_resolve(def, &m, err, sizeof err) == 0 && pic_model_available(m.provider)) {
        (void)snprintf(out, cap, "%s", def);
        free(def);
        return;
    }
    free(def);
    for (size_t i = 0; i < sizeof default_per_provider / sizeof default_per_provider[0]; i++) {
        char *found;
        if (!pic_model_available(default_per_provider[i][0]) ||
            !(found = pic_catalog_find(default_per_provider[i][0], default_per_provider[i][1]))) {
            continue;
        }
        free(found);
        (void)snprintf(out, cap, "%s/%s", default_per_provider[i][0], default_per_provider[i][1]);
        return;
    }
    {
        sqlite3 *db = NULL;
        first_model f;
        memset(&f, 0, sizeof f);
        out[0] = '\0';
        f.out = out;
        f.cap = cap;
        if (sqlite3_open(":memory:", &db) == SQLITE_OK &&
            sqlite3_prepare_v2(db, "SELECT json_extract(?1, '$.id') WHERE json_valid(?1)", -1, &f.id, NULL) == SQLITE_OK) {
            (void)pic_catalog_each(first_available, &f);
            f.provider[0] = '\0';
            if (!out[0]) {
                (void)pic_models_each_user(first_available, &f);
            }
        }
        sqlite3_finalize(f.id);
        sqlite3_close(db);
    }
    if (!out[0]) {
        (void)snprintf(out, cap, "%s", default_model);
    }
}

/* WORKSPACE/.pic/journal.sqlite, creating .pic if needed. */
static int default_db(const char *workspace, char *out, size_t cap) {
    char dir[PATH_MAX];
    if (snprintf(dir, sizeof dir, "%s/.pic", workspace) >= (int)sizeof dir ||
        snprintf(out, cap, "%s/journal.sqlite", dir) >= (int)cap) {
        return -1;
    }
    if (mkdir(dir, 0700) != 0 && errno != EEXIST) {
        return -1;
    }
    return 0;
}

/* pic trust [yes|no] | scoped-models [--clear | --set PATTERN...] | bug [--list | TEXT]:
 * the user-level state the terminal's /trust, /scoped-models and /bug keep
 * in ~/.pic/pic.sqlite. */
static int print_pattern(void *ctx, const char *pattern) {
    (void)ctx;
    puts(pattern);
    return 0;
}

static int print_bug(void *ctx, long long id, long long ms, const char *workspace, const char *description) {
    (void)ctx;
    printf("%lld\t%lld\t%s\t%s\n", id, ms, workspace, description);
    return 0;
}

/* The user's templates, and the workspace's when it is trusted. */
static int load_prompts(pic_prompts *p, const char *workspace) {
    char real[PATH_MAX];
    return pic_prompts_load(p, workspace, pic_trust_get(realpath(workspace, real) ? real : workspace) == 1);
}

/* The user's skills, and the workspace's when it is trusted. */
static int load_skills(pic_skills *s, const char *workspace, FILE *warn) {
    char real[PATH_MAX];
    return pic_skills_load(s, workspace, pic_trust_get(realpath(workspace, real) ? real : workspace) == 1, warn);
}

/* pic login PROVIDER: the key from the terminal with echo off, or from
 * stdin when it is not a terminal, sealed into the credential store (asking
 * for the store's passphrase, or a new one the first time). Pi's
 * `pi auth login PROVIDER --api-key`, without OAuth. */
static int login_command(const char *provider) {
    char key[2 * PIC_CRED_KEY_CAP], err[256], name[128];
    pic_model m;
    long n;
    int rc;
    (void)snprintf(name, sizeof name, "%s/x", provider);
    if (pic_model_resolve(name, &m, err, sizeof err) != 0 || strcmp(m.provider, provider) != 0) {
        fprintf(stderr, "pic: unknown provider %s (pic models --all lists them)\n", provider);
        return 1;
    }
    if (isatty(STDIN_FILENO)) {
        char prompt[160];
        (void)snprintf(prompt, sizeof prompt, "API key for %s: ", provider);
        n = pic_tty_secret(prompt, key, sizeof key, err, sizeof err);
    } else {
        /* read(2), not stdio: no copy of the key is left in a FILE buffer. */
        size_t got = 0;
        char c;
        ssize_t r;
        while (got < sizeof key && ((r = read(STDIN_FILENO, &c, 1)) > 0 || (r < 0 && errno == EINTR))) {
            if (r < 0) {
                continue;
            }
            if (c == '\n') {
                break;
            }
            key[got++] = c;
        }
        c = 0;
        n = got < sizeof key ? (long)got : -1;
        if (n < 0) {
            (void)snprintf(err, sizeof err, "the key is longer than %zu bytes", sizeof key - 1);
        } else {
            while (n > 0 && (key[n - 1] == '\r' || key[n - 1] == ' ' || key[n - 1] == '\t')) {
                n--;
            }
            key[n] = '\0';
        }
    }
    if (n < 0) {
        pic_cred_wipe(key, sizeof key);
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    rc = pic_cred_login(provider, key, err, sizeof err);
    pic_cred_wipe(key, sizeof key);
    if (rc != 0) {
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    printf("Saved the API key for %s, sealed, in ~/.pic/pic.sqlite.\n", provider);
    if (m.key_env[0] && getenv(m.key_env) && *getenv(m.key_env)) {
        printf("%s is set in this environment and takes precedence over the stored key.\n", m.key_env);
    }
    return 0;
}

static int print_key(void *ctx, const char *name, long long created_ms, long long used_ms) {
    char added[32], used[32];
    time_t t = (time_t)(created_ms / 1000);
    struct tm tm;
    int *n = ctx;
    (void)strftime(added, sizeof added, "%Y-%m-%d %H:%M", localtime_r(&t, &tm));
    t = (time_t)(used_ms / 1000);
    if (used_ms) {
        (void)strftime(used, sizeof used, "%Y-%m-%d %H:%M", localtime_r(&t, &tm));
    }
    printf("%-20s added %s  %s%s\n", name, added, used_ms ? "last used " : "never used", used_ms ? used : "");
    (*n)++;
    return 0;
}

static int user_command(int argc, char **argv, const char *workspace) {
    char real[PATH_MAX];
    const char *ws = realpath(workspace, real) ? real : workspace;
    if (strcmp(argv[0], "login") == 0 && argc == 2) {
        return login_command(argv[1]);
    }
    if (strcmp(argv[0], "logout") == 0 && argc == 2) {
        int rc = pic_cred_logout(argv[1]);
        if (rc < 0) {
            fputs("pic: cannot write ~/.pic/pic.sqlite\n", stderr);
            return 1;
        }
        printf(rc ? "Removed the stored API key for %s. Environment variables and models.json config are unchanged.\n"
                  : "No stored credentials for %s. Environment variables and models.json config are unchanged.\n",
               argv[1]);
        return 0;
    }
    if (strcmp(argv[0], "keys") == 0 && argc == 1) {
        int n = 0;
        if (pic_cred_each(print_key, &n) != 0) {
            fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr);
            return 1;
        }
        if (n == 0) {
            puts("No stored keys (pic login PROVIDER stores one).");
        }
        return 0;
    }
    if (strcmp(argv[0], "prompts") == 0 && (argc == 1 || (argc == 2 && strcmp(argv[1], "--json") == 0))) {
        pic_prompts p;
        if (load_prompts(&p, workspace) != 0) {
            fputs("pic: out of memory\n", stderr);
            return 1;
        }
        pic_prompts_print(&p, stdout, argc == 2);
        pic_prompts_free(&p);
        return 0;
    }
    if (strcmp(argv[0], "skills") == 0 && (argc == 1 || (argc == 2 && strcmp(argv[1], "--json") == 0))) {
        pic_skills k;
        if (load_skills(&k, workspace, stderr) != 0) {
            fputs("pic: out of memory\n", stderr);
            return 1;
        }
        pic_skills_print(&k, stdout, argc == 2);
        pic_skills_free(&k);
        return 0;
    }
    if (strcmp(argv[0], "trust") == 0 && argc <= 2) {
        if (argc == 2) {
            if (strcmp(argv[1], "yes") != 0 && strcmp(argv[1], "no") != 0) {
                return usage();
            }
            if (pic_trust_set(ws, strcmp(argv[1], "yes") == 0) != 0) {
                fputs("pic: cannot write ~/.pic/pic.sqlite\n", stderr);
                return 1;
            }
        }
        {
            int t = pic_trust_get(ws);
            puts(t < 0 ? "undecided" : t ? "trusted" : "untrusted");
        }
        return 0;
    }
    if (strcmp(argv[0], "scoped-models") == 0) {
        if (argc == 1) {
            return pic_scoped_each(print_pattern, NULL) == 0 ? 0 : 1;
        }
        if (argc == 2 && strcmp(argv[1], "--clear") == 0) {
            return pic_scoped_set(NULL, 0) == 0 ? 0 : 1;
        }
        if (argc >= 3 && strcmp(argv[1], "--set") == 0) {
            return pic_scoped_set((const char *const *)(void *)(argv + 2), (size_t)argc - 2) == 0 ? 0 : 1;
        }
        return usage();
    }
    if (strcmp(argv[0], "bug") == 0 && argc == 2) {
        if (strcmp(argv[1], "--list") == 0) {
            return pic_bugs_each(print_bug, NULL) == 0 ? 0 : 1;
        }
        {
            long long id = pic_bug_add(ws, NULL, NULL, argv[1]);
            if (id < 0) {
                fputs("pic: cannot write ~/.pic/pic.sqlite\n", stderr);
                return 1;
            }
            printf("bug %lld recorded in ~/.pic/pic.sqlite (table picu_bug); nothing was sent\n", id);
        }
        return 0;
    }
    return usage();
}

static int print_result(pic_store *s, const char *id) {
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (sqlite3_prepare_v2(s->db, "SELECT is_error, result FROM pic_effect WHERE id=?", -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    sqlite3_bind_int64(q, 1, strtoll(id, NULL, 10));
    if (sqlite3_step(q) == SQLITE_ROW) {
        printf("error=%d\n%s\n", sqlite3_column_int(q, 0),
               sqlite3_column_text(q, 1) ? (const char *)sqlite3_column_text(q, 1) : "");
        rc = 0;
    } else {
        (void)snprintf(s->err, sizeof s->err, "no tool call %s", id);
    }
    sqlite3_finalize(q);
    return rc;
}

/* The thinking level for model M, as Pi picks it: --thinking (an unsupported
 * level is an error naming the supported ones), else the model's saved level
 * (setting thinkingLevel:provider/id), else defaultThinkingLevel,
 * else medium; a saved level the model does not take is clamped. */
static int thinking_level(const pic_model *m, char *out, size_t cap, char *err, size_t errcap) {
    const char *levels[PIC_THINKING_LEVELS];
    char key[320], list[128], *saved = NULL;
    int n = pic_model_thinking_levels(m, levels);
    if (thinking_opt) {
        int ok = 0;
        for (int i = 0; i < n; i++) {
            ok |= strcmp(levels[i], thinking_opt) == 0;
        }
        if (!ok) {
            level_names(list, sizeof list, levels, n);
            (void)snprintf(err, errcap, "thinking level %s is not supported by %s/%s (supported: %s)", thinking_opt,
                           m->provider, m->id, list);
            return -1;
        }
        (void)snprintf(out, cap, "%s", thinking_opt);
        return 0;
    }
    if (snprintf(key, sizeof key, "thinkingLevel:%s/%s", m->provider, m->id) < (int)sizeof key) {
        saved = setting(key);
    }
    if (pic_thinking_index(saved) < 0) {
        free(saved);
        saved = setting("defaultThinkingLevel");
    }
    (void)snprintf(out, cap, "%s", pic_model_thinking_clamp(m, pic_thinking_index(saved) >= 0 ? saved : "medium"));
    free(saved);
    return 0;
}

/* What model_provider last made a provider for: the model ("provider/id"),
 * its thinking level, the endpoint and the workspace. */
static char built_model[200], built_thinking[16];
static const char *built_url, *built_workspace;

/* A provider for a model name ("provider/model") from the registry; url,
 * when not NULL, replaces the model's endpoint. */
static int model_provider(pic_provider *p, const char *name, const char *url, const char *workspace, char *err,
                          size_t errcap) {
    pic_model m;
    char level[16];
    if (pic_model_resolve(name, &m, err, errcap) != 0 || thinking_level(&m, level, sizeof level, err, errcap) != 0 ||
        pic_provider_for_model(p, &m, level, url, workspace, err, errcap) != 0) {
        return -1;
    }
    (void)snprintf(built_model, sizeof built_model, "%s/%s", m.provider, m.id);
    (void)snprintf(built_thinking, sizeof built_thinking, "%s", level);
    built_url = url;
    built_workspace = workspace;
    return 0;
}

/* pic_store.provider_for: *P, made by model_provider, remade for a request
 * admitted with another model or thinking level (a request finishes with
 * its own, whoever runs it); the endpoint (--api-url) stays. */
static int provider_for(pic_store *s, pic_provider *p, const char *model, const char *thinking) {
    pic_provider next;
    const char *saved = thinking_opt;
    int rc;
    if (strcmp(p->model, built_model) == 0 && strcmp(model, built_model) == 0 &&
        strcmp(thinking ? thinking : "", built_thinking) == 0) {
        return 0;
    }
    memset(&next, 0, sizeof next);
    { /* a model with no key here is not this run's to finish (nor to fail) */
        pic_model m;
        if (pic_model_resolve(model, &m, s->err, sizeof s->err) != 0) {
            return -1;
        }
        if (!pic_model_available(m.provider)) {
            (void)snprintf(s->err, sizeof s->err, "its model %s needs a key: set %s or run `pic login %s`", model,
                           m.key_env[0] ? m.key_env : "the provider's key variable", m.provider);
            return -1;
        }
    }
    thinking_opt = thinking && *thinking ? thinking : NULL;
    rc = model_provider(&next, model, built_url, built_workspace, s->err, sizeof s->err);
    thinking_opt = saved;
    if (rc != 0) {
        if (next.free) {
            next.free(&next);
        }
        return -1;
    }
    if (context_window >= 0) {
        next.context_window = context_window;
    }
    p->free(p);
    *p = next;
    return 0;
}

/* What TEXT expands to: a skill (/skill:name ARGS) or a prompt template
 * (/name ARGS), or NULL. For steering and follow-ups, where a skill that
 * has gone simply leaves the text as typed. */
static char *expand_template(void *workspace, const char *text) {
    pic_prompts templates;
    char *expanded = NULL;
    if (strncmp(text, "/skill:", 7) == 0) {
        pic_skills skills;
        char err[256];
        if (load_skills(&skills, workspace, NULL) == 0) {
            if (pic_skills_expand(&skills, text, &expanded, err, sizeof err) < 0) {
                expanded = NULL;
            }
            pic_skills_free(&skills);
        }
        return expanded;
    }
    if (text[0] == '/' && load_prompts(&templates, workspace) == 0) {
        expanded = pic_prompts_expand(&templates, text);
        pic_prompts_free(&templates);
    }
    return expanded;
}

/* pic_run, reading --commands from stdin meanwhile when asked to. */
static int run_with_commands(pic_store *s, const char *workspace, pic_provider *provider, int exec_seconds) {
    int rc;
    if (commands) {
        pic_commands_start(s, STDIN_FILENO, expand_template, (void *)(uintptr_t)workspace);
    }
    rc = pic_run(s, workspace, provider, exec_seconds);
    if (commands) {
        pic_commands_stop();
    }
    return rc;
}

/* submit under a fresh key, run with the model's provider, print the answer. */
/* SessionStart and UserPromptSubmit for a prompt to SESSION (NULL: a new
 * conversation, whose id is chosen now, so hooks see it, and *fresh set).
 * The conversation's id goes to sid; the prompt's first UserPromptSubmit
 * run to *first, for its admission to claim. A conversation still busy
 * with a request is refused before any hook runs. 0 to go on; -1 when the
 * prompt is rejected or on an error (s->err). */
static int hook_conversation(pic_store *s, const char *session, char sid[64], int *fresh, const char *text, int64_t *first) {
    *fresh = !session;
    *first = 0;
    if (session) {
        sqlite3_stmt *q = NULL;
        int busy = 0;
        /* One another pic is working is refused before any hook runs, naming it. */
        if (pic_session_resolve(s, session, sid, 64) != 0 || pic_lease(s, sid, PIC_LEASE_WAIT_MS) != 0) {
            sid[0] = '\0';
            return -1;
        }
        if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_submission WHERE session_id = ? AND status = 'admitted'", -1, &q,
                               NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
            busy = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0) > 0;
        }
        sqlite3_finalize(q);
        if (busy) {
            (void)snprintf(s->err, sizeof s->err, "session %s is still working on a request (pic run finishes it)", sid);
            sid[0] = '\0';
            return -1;
        }
    } else if (ask_new_id) {
        (void)snprintf(sid, 64, "%s", ask_new_id);
    } else {
        for (;;) { /* a fresh id, as the journal makes them */
            unsigned char r[4];
            sqlite3_stmt *q = NULL;
            int taken = 1;
            if (pic_platform_get()->entropy(r, sizeof r) != 0) {
                (void)snprintf(s->err, sizeof s->err, "no randomness for a conversation id");
                return -1;
            }
            (void)snprintf(sid, 64, "%02x%02x%02x%02x", r[0], r[1], r[2], r[3]);
            if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
                sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
                taken = sqlite3_step(q) != SQLITE_ROW || sqlite3_column_int(q, 0) != 0;
            }
            sqlite3_finalize(q);
            if (!taken) {
                break;
            }
        }
    }
    if (pic_hooks_session_start(s, sid, session ? "resume" : "startup") != 0) {
        return -1;
    }
    return pic_hooks_prompt(s, sid, text, first) == 0 ? 0 : -1;
}

/* A standalone process (not the line mode, not a terminal's child) ends the
 * conversation it started on its way out. */
static void end_own(pic_store *s, const char *sid) {
    if (s->hooks && sid[0] && !quiet && !pic_hooks_owned(s->hooks)) {
        char saved[PIC_ERR_CAP];
        (void)snprintf(saved, sizeof saved, "%s", s->err);
        if (pic_hooks_session_end(s, sid, "other") != 0) {
            fprintf(stderr, "pic: warning: SessionEnd hooks: %s\n", s->err);
        }
        (void)snprintf(s->err, sizeof s->err, "%s", saved);
    }
}

static int ask(pic_store *s, const char *workspace, const char *model, const char *url, int exec_seconds,
               const char *session, const char *text, pic_image *images, size_t nimages) {
    char key[64], joined[64] = "", sid[64] = "";
    int fresh = 0;
    int64_t first = 0;
    pic_provider provider;
    char *expanded = NULL;
    int duplicate = 0, rc;
    int64_t now = pic_platform_get()->wall_ns();
    (void)snprintf(key, sizeof key, "ask-%lld-%09ld-%ld", (long long)(now / 1000000000), (long)(now % 1000000000),
                   (long)getpid());
    memset(&provider, 0, sizeof provider);
    /* The provider first: a model that cannot be had leaves nothing admitted. */
    if (model_provider(&provider, model, url, workspace, s->err, sizeof s->err) != 0) {
        if (provider.free) {
            provider.free(&provider);
        }
        return -1;
    }
    if (strncmp(text, "/skill:", 7) == 0) { /* a skill: submit its instructions and the arguments */
        pic_skills skills;
        int found = 0;
        if (load_skills(&skills, workspace, NULL) == 0) {
            found = pic_skills_expand(&skills, text, &expanded, s->err, sizeof s->err);
            pic_skills_free(&skills);
        }
        if (found < 0) {
            provider.free(&provider);
            return -1;
        }
    } else {
        expanded = expand_template((void *)(uintptr_t)workspace, text); /* a prompt template */
    }
    /* Hooks see the conversation before the prompt is admitted, so a new one
     * gets its id now; UserPromptSubmit may reject the prompt. */
    if (s->hooks && hook_conversation(s, session, sid, &fresh, text, &first) != 0) {
        free(expanded);
        end_own(s, sid);
        provider.free(&provider);
        return -1;
    }
    { /* images that cannot go inline become notes after the text, as Pi's */
        char *with_notes = pic_image_prepare(expanded ? expanded : text, images, &nimages, s->err, sizeof s->err);
        s->model = built_model; /* the request keeps its model and level, to finish with them */
        s->thinking = built_thinking;
        rc = with_notes ? pic_submit_hooked(s, key, with_notes, images, nimages, fresh ? NULL : sid[0] ? sid : session,
                                            fresh ? sid : !session ? ask_new_id : NULL, first, &duplicate, joined,
                                            sizeof joined)
                        : -1;
        s->model = s->thinking = NULL;
        free(with_notes);
    }
    free(expanded);
    if (rc != 0) {
        end_own(s, sid);
        provider.free(&provider);
        return -1;
    }
    { /* this request runs first, and commands steer it, whatever else the journal holds */
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_submission WHERE request_key = ?", -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                s->running = sqlite3_column_int64(q, 0);
            }
        }
        sqlite3_finalize(q);
    }
    if (ask_admitted) {
        ask_admitted(ask_admitted_ctx);
    }
    if (!quiet) {
        fprintf(stderr, "pic: session %s, request %s (pic cancel %s to stop it)\n", joined, key, key);
    }
    if (session != joined && joined[0] && quiet) {
        (void)snprintf(last_session, sizeof last_session, "%s", joined);
    }
    s->provider_for = provider_for;
    s->session_only = 1; /* its own conversation's requests: another's unfinished one is left to it */
    pic_events_init(&events, stdout, stderr, json_events, !json_events && (force_stream || isatty(STDOUT_FILENO)));
    s->events = &events;
    if (context_window >= 0) {
        provider.context_window = context_window;
    }
    catch_interrupt();
    rc = run_with_commands(s, workspace, &provider, exec_seconds);
    provider.free(&provider);
    /* A pic ask on its own ends the conversation it started; the line mode
     * and the terminal (which owns its children's) end theirs on exit. */
    end_own(s, sid);
    /* The conversation as a Pi session file, for ctx (PIC_PI_EXPORT=0: off). */
    {
        const char *pi = getenv("PIC_PI_EXPORT");
        char saved[PIC_ERR_CAP];
        (void)snprintf(saved, sizeof saved, "%s", s->err);
        if (!(pi && strcmp(pi, "0") == 0) && joined[0] && pic_export_pi(s, workspace, NULL, joined) != 0) {
            fprintf(stderr, "pic: warning: Pi session file: %s\n", s->err);
        }
        (void)snprintf(s->err, sizeof s->err, "%s", saved);
    }
    { /* a request that stopped short of its answer says why, on stderr */
        sqlite3_stmt *q = NULL;
        if (rc == 0 && sqlite3_prepare_v2(s->db, "SELECT stop_reason, max_requests FROM pic_submission WHERE request_key = ?"
                                                 " AND status = 'stopped'", -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                fprintf(stderr, "pic: stopped (%s: %lld provider requests); pic ask -c continues the conversation\n",
                        (const char *)sqlite3_column_text(q, 0), (long long)sqlite3_column_int64(q, 1));
                sqlite3_finalize(q);
                return 0;
            }
        }
        sqlite3_finalize(q);
    }
    /* Streamed or sent as events already; otherwise the answer now. */
    if (rc == 0 && !json_events && !events.streamed) {
        char *answer = pic_answer_text(s, key);
        puts(answer && *answer ? answer : "(no text in the answer)");
        free(answer);
    }
    return rc;
}

/* --mode rpc: the host side of rpc.c, over ask and the model registry. */
static const char *rpc_workspace;
static int rpc_exec_seconds;

static int rpc_prompt(pic_store *s, const char *model, const char *thinking, const char *session, const char *new_id,
                      const char *text, pic_image *images, size_t n, void (*admitted)(void *ctx), void *ctx) {
    const char *saved = thinking_opt;
    int rc;
    thinking_opt = thinking;
    ask_new_id = new_id;
    ask_admitted = admitted;
    ask_admitted_ctx = ctx;
    rc = ask(s, rpc_workspace, model, NULL, rpc_exec_seconds, session, text, images, n);
    thinking_opt = saved;
    ask_new_id = NULL;
    ask_admitted = NULL;
    ask_admitted_ctx = NULL;
    return rc;
}

static int rpc_provider(pic_provider *p, const char *model, const char *thinking, char *err, size_t errcap) {
    const char *saved = thinking_opt;
    int rc;
    thinking_opt = thinking;
    rc = model_provider(p, model, NULL, rpc_workspace, err, errcap);
    thinking_opt = saved;
    if (rc == 0 && context_window >= 0) {
        p->context_window = context_window;
    }
    return rc;
}

static int rpc_level(const char *model, char *out, size_t cap, char *err, size_t errcap) {
    pic_model m;
    if (pic_model_resolve(model, &m, err, errcap) != 0) { /* the first prompt reports it */
        (void)snprintf(out, cap, "%s", thinking_opt ? thinking_opt : "medium");
        return 0;
    }
    return thinking_level(&m, out, cap, err, errcap);
}

/* ask [-c | --session ID] [--image PATH]... TEXT: each image read through
 * the input reader and sniffed as Pi's read does. 2 for a usage error. */
static int ask_command(pic_store *s, const char *workspace, const char *model, int exec_seconds, int argc, char **argv) {
    const char *session = NULL;
    pic_image *images = NULL;
    char **bytes = NULL;
    size_t n = 0;
    int rc = -1, i;
    if (argc < 1 || !(images = calloc((size_t)argc, sizeof *images)) || !(bytes = calloc((size_t)argc, sizeof *bytes))) {
        free(images);
        return argc < 1 ? 2 : -1;
    }
    for (i = 0; i < argc - 1; i++) {
        if (strcmp(argv[i], "-c") == 0 && !session) {
            session = "latest";
        } else if (strcmp(argv[i], "--session") == 0 && !session && i + 2 < argc) {
            session = argv[++i];
        } else if (strcmp(argv[i], "--image") == 0 && i + 2 < argc) {
            const char *path = argv[++i];
            size_t len = 0;
            if (!(bytes[n] = pic_input_read(path, 256u << 20, 0, &len, NULL))) {
                (void)snprintf(s->err, sizeof s->err, "cannot read image %s: %s", path, strerror(errno));
                goto done;
            }
            images[n].data = (const unsigned char *)bytes[n];
            images[n].len = len;
            images[n].mime = NULL; /* whatever the data is */
            n++;
            {
                char why[160];
                int bad = pic_image_check(&images[n - 1], NULL, why, sizeof why);
                if (bad != PIC_IMAGE_OK && bad != PIC_IMAGE_UNSUPPORTED) {
                    (void)snprintf(s->err, sizeof s->err, "image %s: %s", path, why);
                    goto done;
                }
            }
        } else {
            rc = 2;
            goto done;
        }
    }
    rc = ask(s, workspace, model, NULL, exec_seconds, session, argv[argc - 1], images, n);
done:
    for (size_t k = 0; k < n; k++) {
        free(bytes[k]);
    }
    free(bytes);
    free(images);
    return rc;
}

/* -p / --print, Pi's print mode: the messages and @files from the command
 * line, then run them as ask does. */
static int print_mode;
static char *print_messages[256];
static size_t print_nmessages;
static char *print_files[256];
static size_t print_nfiles;

static int print_add(char **list, size_t *n, char *arg) {
    if (*n >= 256) {
        fputs("pic: too many arguments\n", stderr);
        return -1;
    }
    list[(*n)++] = arg;
    return 0;
}

/* Piped stdin, trimmed as Pi's readPipedStdin does; NULL when stdin is a
 * terminal or holds only whitespace. */
static char *read_piped_stdin(void) {
    size_t len = 0, cap = 4096, start = 0;
    char *buf = malloc(cap);
    if (!buf || isatty(STDIN_FILENO)) {
        free(buf);
        return NULL;
    }
    for (;;) {
        ssize_t n;
        if (len + 1 >= cap) {
            char *bigger = realloc(buf, cap * 2);
            if (!bigger) {
                free(buf);
                return NULL;
            }
            buf = bigger;
            cap *= 2;
        }
        n = read(STDIN_FILENO, buf + len, cap - len - 1);
        if (n < 0 && errno == EINTR) {
            continue;
        }
        if (n <= 0) {
            break;
        }
        len += (size_t)n;
    }
    while (len > 0 && isspace((unsigned char)buf[len - 1])) {
        len--;
    }
    while (start < len && isspace((unsigned char)buf[start])) {
        start++;
    }
    if (start == len) {
        free(buf);
        return NULL;
    }
    memmove(buf, buf + start, len - start);
    buf[len - start] = '\0';
    return buf;
}

static int grow_text(char **buf, size_t *len, size_t *cap, const char *s, size_t n) {
    if (*len + n + 1 > *cap) {
        size_t c = *cap ? *cap : 4096;
        char *p;
        while (c < *len + n + 1) {
            c *= 2;
        }
        if (!(p = realloc(*buf, c))) {
            return -1;
        }
        *buf = p;
        *cap = c;
    }
    memcpy(*buf + *len, s, n);
    *len += n;
    (*buf)[*len] = '\0';
    return 0;
}

/* Pi's processFileArguments: each file as <file name="PATH">, its text
 * between newlines, or for an image the empty tag and the image attached.
 * Empty files are skipped; a file that cannot be read ends the run. */
static int attach_files(const char *workspace, char **text, size_t *len, size_t *cap, pic_image *images, char **bytes,
                        size_t *nimages) {
    char real[PATH_MAX];
    const char *base = realpath(workspace, real) ? real : workspace;
    for (size_t k = 0; k < print_nfiles; k++) {
        const char *arg = print_files[k], *home = getenv("HOME");
        char path[PATH_MAX], *data;
        size_t n = 0;
        int ok;
        if (arg[0] == '/') {
            ok = snprintf(path, sizeof path, "%s", arg) < (int)sizeof path;
        } else if (arg[0] == '~' && (arg[1] == '/' || !arg[1]) && home) {
            ok = snprintf(path, sizeof path, "%s%s", home, arg + 1) < (int)sizeof path;
        } else {
            ok = snprintf(path, sizeof path, "%s/%s", base, arg) < (int)sizeof path;
        }
        if (!ok) {
            fprintf(stderr, "pic: Error: File not found: %s\n", arg);
            return -1;
        }
        if (!(data = pic_input_read(path, 256u << 20, 0, &n, NULL))) {
            if (errno == ENOENT) {
                fprintf(stderr, "pic: Error: File not found: %s\n", path);
            } else {
                fprintf(stderr, "pic: Error: Could not read file %s: %s\n", path, strerror(errno));
            }
            return -1;
        }
        if (n == 0) {
            free(data);
            continue;
        }
        if (pic_image_sniff((const unsigned char *)data, n)) {
            bytes[*nimages] = data;
            images[*nimages].data = (const unsigned char *)data;
            images[*nimages].len = n;
            images[*nimages].mime = NULL;
            (*nimages)++;
            ok = grow_text(text, len, cap, "<file name=\"", 12) == 0 && grow_text(text, len, cap, path, strlen(path)) == 0 &&
                 grow_text(text, len, cap, "\"></file>\n", 10) == 0;
        } else {
            const char *body = n >= 3 && memcmp(data, "\xEF\xBB\xBF", 3) == 0 ? data + 3 : data;
            ok = grow_text(text, len, cap, "<file name=\"", 12) == 0 && grow_text(text, len, cap, path, strlen(path)) == 0 &&
                 grow_text(text, len, cap, "\">\n", 3) == 0 && grow_text(text, len, cap, body, strlen(body)) == 0 &&
                 grow_text(text, len, cap, "\n</file>\n", 9) == 0;
            free(data);
        }
        if (!ok) {
            fputs("pic: out of memory\n", stderr);
            return -1;
        }
    }
    return 0;
}

/* pic -p: stdin, the @files and the first message make one prompt, joined as
 * Pi's buildInitialMessage joins them (no separator); each further message
 * continues the conversation. Nothing to send is not an error, as in Pi. */
static int print_command(pic_store *s, const char *workspace, const char *model, int exec_seconds, const char *session) {
    pic_image images[256];
    char *bytes[256], *text = NULL, *stdin_text = commands ? NULL : read_piped_stdin();
    size_t len = 0, cap = 0, nimages = 0, first = 0;
    int rc = 0;
    memset(images, 0, sizeof images);
    memset(bytes, 0, sizeof bytes);
    if (stdin_text && grow_text(&text, &len, &cap, stdin_text, strlen(stdin_text)) != 0) {
        rc = -1;
    }
    free(stdin_text);
    if (rc == 0 && attach_files(workspace, &text, &len, &cap, images, bytes, &nimages) != 0) {
        rc = 125; /* already reported on stderr: exit 1 without the journal's message */
    }
    if (rc == 0 && print_nmessages > 0) {
        first = 1;
        rc = grow_text(&text, &len, &cap, print_messages[0], strlen(print_messages[0]));
    }
    if (rc == 0 && text) {
        rc = ask(s, workspace, model, NULL, exec_seconds, session, text, images, nimages);
    }
    for (size_t k = first; rc == 0 && k < print_nmessages; k++) {
        rc = ask(s, workspace, model, NULL, exec_seconds, "latest", print_messages[k], NULL, 0);
    }
    for (size_t k = 0; k < nimages; k++) {
        free(bytes[k]);
    }
    free(text);
    return rc;
}

/* Whether CMD ("/name") names a prompt template, or ("/skill:name") a skill. */
static int is_template(const char *workspace, const char *cmd) {
    pic_prompts p;
    int found = 0;
    if (strncmp(cmd, "/skill:", 7) == 0) {
        pic_skills k;
        if (load_skills(&k, workspace, NULL) == 0) {
            found = pic_skills_find(&k, cmd + 7) != NULL;
            pic_skills_free(&k);
        }
        return found;
    }
    if (load_prompts(&p, workspace) == 0) {
        found = pic_prompts_find(&p, cmd + 1) != NULL;
        pic_prompts_free(&p);
    }
    return found;
}

static const char repl_help[] =
    "Type a message to continue the conversation (a line ending in \\ continues on the next).\n"
    "  /new                 start a new conversation\n"
    "  /resume ID           continue another conversation (/sessions lists them)\n"
    "  /sessions            list conversations\n"
    "  /log                 this conversation so far\n"
    "  /name NAME           name this conversation\n"
    "  /fork [ENTRY]        branch this conversation (from ENTRY, see /log)\n"
    "  /compact [FOCUS]     summarize the history now\n"
    "  /model [NAME]        show or change the model (provider/model)\n"
    "  /NAME [ARGS]         a prompt template (pic prompts lists them)\n"
    "  /skill:NAME [ARGS]   a skill (pic skills lists them)\n"
    "  /help  /quit         Ctrl-C cancels a running reply; Ctrl-D quits\n";

/* Reads one message: lines ending in a backslash continue it. NULL at EOF;
 * an empty string after a Ctrl-C at the prompt. */
static char *read_input(void) {
    char line[8192], *all = NULL;
    size_t len = 0;
    for (;;) {
        size_t n;
        char *grown;
        fputs(all ? ". " : "> ", stdout);
        fflush(stdout);
        if (!fgets(line, sizeof line, stdin)) {
            if (ferror(stdin) && errno == EINTR) {
                clearerr(stdin);
                pic_interrupted = 0;
                fputc('\n', stdout);
                free(all);
                all = malloc(1);
                if (all) {
                    all[0] = '\0';
                }
                return all;
            }
            if (all) {
                return all; /* EOF after a continued line: send what there is */
            }
            return NULL;
        }
        n = strcspn(line, "\n");
        line[n] = '\0';
        grown = realloc(all, len + n + 2);
        if (!grown) {
            free(all);
            return NULL;
        }
        all = grown;
        memcpy(all + len, line, n + 1);
        len += n;
        if (n > 0 && line[n - 1] == '\\') {
            all[len - 1] = '\n';
            all[len] = '\0';
            continue;
        }
        return all;
    }
}

/* SessionEnd for the conversations this process started (the line mode,
 * which opens the journal only while it handles an input). */
static void end_conversations(const char *db, const char *reason) {
    pic_store s;
    if (!hooks) {
        return;
    }
    if (open_store(&s, db) != 0 || pic_hooks_end_owned(&s, reason) != 0) {
        fprintf(stderr, "pic: warning: SessionEnd hooks: %s\n", s.err);
    }
    pic_close(&s);
}

/* pic with no command, in a terminal: a prompt that continues one
 * conversation. The journal is open only while an input is handled, so
 * other pic commands can use it between messages. */
static int repl(const char *db, const char *workspace, const char *model, int exec_seconds, const char *resume) {
    char current[64] = "", modelbuf[128];
    char *in;
    (void)snprintf(modelbuf, sizeof modelbuf, "%s", model);
    quiet = 1;
    catch_interrupt();
    if (resume) { /* -c: the latest conversation; --session ID: that one */
        pic_store s;
        int rc = open_store(&s, db) != 0 ? -1 : pic_session_resolve(&s, resume, current, sizeof current);
        if (rc != 0) {
            fprintf(stderr, "pic: %s\n", s.err);
        }
        pic_close(&s);
        if (rc != 0) {
            return 1;
        }
    }
    printf("pic: %s in %s, %s%s (/help for commands)\n", modelbuf, workspace, current[0] ? "continuing " : "a new conversation",
           current);
    while ((in = read_input()) != NULL) {
        char *cmd = in, *arg;
        pic_store s;
        int rc = 0;
        while (*cmd == ' ' || *cmd == '\t') {
            cmd++;
        }
        if (!*cmd) {
            free(in);
            continue;
        }
        arg = cmd[0] == '/' ? cmd + strcspn(cmd, " \t") : NULL;
        if (arg) {
            if (*arg) {
                *arg++ = '\0';
            }
            while (*arg == ' ' || *arg == '\t') {
                arg++;
            }
        }
        if (arg && (strcmp(cmd, "/quit") == 0 || strcmp(cmd, "/exit") == 0)) {
            free(in);
            break;
        }
        if (arg && strcmp(cmd, "/help") == 0) {
            fputs(repl_help, stdout);
            free(in);
            continue;
        }
        if (arg && strcmp(cmd, "/new") == 0) {
            end_conversations(db, "clear");
            current[0] = '\0';
            puts("pic: the next message starts a new conversation");
            free(in);
            continue;
        }
        if (arg && strcmp(cmd, "/model") == 0) {
            pic_model m;
            char err[PIC_ERR_CAP];
            if (*arg && pic_model_resolve(arg, &m, err, sizeof err) != 0) {
                fprintf(stderr, "pic: %s\n", err);
            } else if (*arg) {
                (void)snprintf(modelbuf, sizeof modelbuf, "%s", arg);
            }
            printf("pic: model %s\n", modelbuf);
            free(in);
            continue;
        }
        if (open_store(&s, db) != 0) {
            fprintf(stderr, "pic: %s\n", s.err);
            pic_close(&s);
            free(in);
            continue;
        }
        if (!arg) {
            last_session[0] = '\0';
            rc = ask(&s, workspace, modelbuf, NULL, exec_seconds, current[0] ? current : NULL, in, NULL, 0);
            if (last_session[0] && strcmp(last_session, current) != 0) {
                (void)snprintf(current, sizeof current, "%s", last_session);
            }
        } else if (strcmp(cmd, "/sessions") == 0) {
            rc = pic_sessions(&s, stdout);
        } else if (strcmp(cmd, "/log") == 0) {
            rc = pic_session_log(&s, *arg ? arg : current[0] ? current : "latest", stdout);
        } else if (strcmp(cmd, "/resume") == 0 && *arg) {
            char id[64];
            rc = pic_session_resolve(&s, arg, id, sizeof id);
            if (rc == 0 && strcmp(id, current) != 0 && hooks) {
                rc = pic_hooks_end_owned(&s, "other");
            }
            if (rc == 0) {
                (void)snprintf(current, sizeof current, "%s", id);
                printf("pic: now in %s\n", id);
            }
        } else if (strcmp(cmd, "/name") == 0 && *arg && current[0]) {
            rc = pic_session_name(&s, current, arg);
        } else if (strcmp(cmd, "/fork") == 0 && current[0]) {
            char made[64];
            rc = pic_fork(&s, current, *arg ? strtoll(arg, NULL, 10) : 0, made, sizeof made);
            if (rc == 0 && hooks) {
                rc = pic_hooks_end_owned(&s, "other");
            }
            if (rc == 0) {
                (void)snprintf(current, sizeof current, "%s", made);
                printf("pic: now in %s, a fork\n", made);
            }
        } else if (strcmp(cmd, "/compact") == 0 && current[0]) {
            char id[64];
            rc = pic_compact_request(&s, current, *arg ? arg : NULL, id, sizeof id);
            if (rc == 0) {
                puts("pic: the history is summarized before the next message");
            }
        } else if (strcmp(cmd, "/sessions") != 0 && strcmp(cmd, "/log") != 0 && strcmp(cmd, "/resume") != 0 &&
                   strcmp(cmd, "/name") != 0 && strcmp(cmd, "/fork") != 0 && strcmp(cmd, "/compact") != 0) {
            size_t cap = strlen(cmd) + strlen(arg) + 2;
            char *line = is_template(workspace, cmd) ? malloc(cap) : NULL;
            if (line) { /* a prompt template: the model gets what it expands to */
                (void)snprintf(line, cap, "%s %s", cmd, arg);
                last_session[0] = '\0';
                rc = ask(&s, workspace, modelbuf, NULL, exec_seconds, current[0] ? current : NULL, line, NULL, 0);
                if (last_session[0] && strcmp(last_session, current) != 0) {
                    (void)snprintf(current, sizeof current, "%s", last_session);
                }
                free(line);
            } else {
                fprintf(stderr, "pic: unknown command %s (/help lists them)\n", cmd);
                rc = 0;
            }
        } else {
            fprintf(stderr, "pic: %s needs %s (/help)\n", cmd,
                    current[0] || strcmp(cmd, "/resume") == 0 || strcmp(cmd, "/name") == 0 ? "an argument"
                                                                                           : "a conversation first");
        }
        if (rc != 0) {
            fprintf(stderr, "pic: %s\n", s.err);
        }
        pic_close(&s);
        free(in);
    }
    if (!in) {
        fputc('\n', stdout);
    }
    end_conversations(db, "prompt_input_exit");
    return 0;
}

/* pic bash: see bash.c. */
static int bash_live_json(pic_store *s, const char *text) {
    sqlite3_stmt *q = NULL;
    if (sqlite3_prepare_v2(s->db, "SELECT json_object('type', 'bash_execution_update', 'output', ?1)", -1, &q, NULL) ==
        SQLITE_OK) {
        sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            pic_ev_line(s, (const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return 0;
}

static pic_store *bash_store;
static void bash_live(void *ctx, const char *text) {
    (void)ctx;
    (void)bash_live_json(bash_store, text);
}

static int bash_command(pic_store *s, const char *workspace, int exec_seconds, int argc, char **argv, int *status) {
    const char *session = NULL, *command = NULL;
    int exclude = 0;
    char joined[64] = "";
    pic_bash_msg m;
    int rc;
    for (int j = 0; j < argc; j++) {
        if (strcmp(argv[j], "--no-context") == 0) {
            exclude = 1;
        } else if (strcmp(argv[j], "-c") == 0) {
            session = "latest";
        } else if (strcmp(argv[j], "--session") == 0 && j + 1 < argc) {
            session = argv[++j];
        } else if (!command) {
            command = argv[j];
        } else {
            goto usage_err;
        }
    }
    if (!command || !command[0]) {
        goto usage_err;
    }
    if (json_events) {
        pic_events_init(&events, stdout, stderr, 1, 0);
        s->events = &events;
    }
    bash_store = s;
    catch_interrupt();
    rc = pic_bash_run(s, workspace, session, command, exclude, exec_seconds, json_events ? bash_live : NULL, NULL, &m,
                      joined, sizeof joined);
    if (rc != 0) {
        return rc;
    }
    {
        const char *pi = getenv("PIC_PI_EXPORT");
        char saved[PIC_ERR_CAP];
        (void)snprintf(saved, sizeof saved, "%s", s->err);
        if (!(pi && strcmp(pi, "0") == 0) && pic_export_pi(s, workspace, NULL, joined) != 0) {
            fprintf(stderr, "pic: warning: Pi session file: %s\n", s->err);
        }
        (void)snprintf(s->err, sizeof s->err, "%s", saved);
    }
    if (json_events) {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db,
                               "SELECT json_patch('{}', json_object('type', 'response', 'command', 'bash', 'success', json('true'),"
                               " 'data', json_object('output', ?1, 'exitCode', CASE WHEN ?2 THEN ?3 END,"
                               " 'cancelled', json(iif(?4, 'true', 'false')), 'truncated', json(iif(?5, 'true', 'false')),"
                               " 'conversation', ?6)))",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, m.output, -1, SQLITE_STATIC);
            sqlite3_bind_int(q, 2, m.has_exit);
            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, joined, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                pic_ev_line(s, (const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
    } else {
        if (m.output[0]) {
            puts(m.output);
        }
        if (!session) {
            fprintf(stderr, "pic: conversation %s\n", joined);
        }
    }
    *status = m.cancelled ? 130 : m.has_exit ? m.exit_code & 0xff : 1;
    free((void *)(uintptr_t)m.output);
    return 0;
usage_err:
    (void)snprintf(s->err, sizeof s->err, "usage: pic bash [--no-context] [-c | --session ID] COMMAND");
    return -1;
}

/* Pi's tool selection options: --no-tools (-nt) 1, --no-builtin-tools (-nbt) 2 take no value;
 * --tools (-t) 1 and --exclude-tools (-xt) 2 take a comma list. */
static int tool_switch(const char *a) {
    return strcmp(a, "--no-tools") == 0 || strcmp(a, "-nt") == 0 ? 1
           : strcmp(a, "--no-builtin-tools") == 0 || strcmp(a, "-nbt") == 0 ? 2
                                                                             : 0;
}

static int tool_option(const char *a) {
    return strcmp(a, "--tools") == 0 || strcmp(a, "-t") == 0 ? 1 : strcmp(a, "--exclude-tools") == 0 || strcmp(a, "-xt") == 0 ? 2 : 0;
}

int main(int argc, char **argv) {
    const char *db = NULL, *workspace = NULL, *model = NULL, *tui_mode = NULL, *theme = NULL;
    char cwd[PATH_MAX], db_path[PATH_MAX], claude_cwd[PATH_MAX];
    const char *claude_path = NULL, *claude_until = NULL, *claude_url = NULL;
    int claude_count = 0;
    int exec_seconds = 600;
    struct stat st;
    pic_store s;
    int i = 1, rc = 0, dashdash = 0, rpc_mode = 0;
    const char *rpc_session = NULL;
    const char *system_replace = NULL, *system_append[PIC_SYSTEM_APPEND_MAX];
    size_t system_nappend = 0;
    char *print_argv[] = {"ask", NULL};
    const char *tools_opt = NULL, *exclude_opt = NULL;
    int no_tools_opt = 0, no_builtin_opt = 0;
    /* A reader that goes away (a closed pipe) does not stop a run. */
    (void)signal(SIGPIPE, SIG_IGN);
    { /* the terminal's token for its children: theirs alone, not their tools' */
        const char *owner = getenv("PIC_HOOK_OWNER");
        (void)snprintf(hook_owner, sizeof hook_owner, "%s", owner ? owner : "");
        (void)unsetenv("PIC_HOOK_OWNER");
    }
    pic_cred_adopt(); /* the master key a parent pic handed over, before anything can spawn */
    for (int h = 1; h < argc; h++) { /* --help anywhere among the options */
        if (strcmp(argv[h], "--help") == 0 || strcmp(argv[h], "-h") == 0) {
            print_usage(stdout);
            return 0;
        }
        if (argv[h][0] != '-') {
            break;
        }
    }
    while (i < argc && (strcmp(argv[i], "--json") == 0 || strcmp(argv[i], "--stream") == 0 ||
                        strcmp(argv[i], "--commands") == 0 || tool_switch(argv[i]))) {
        if (strcmp(argv[i], "--json") == 0 || strcmp(argv[i], "--stream") == 0 || strcmp(argv[i], "--commands") == 0) {
            *(strcmp(argv[i], "--json") == 0 ? &json_events : strcmp(argv[i], "--stream") == 0 ? &force_stream : &commands) = 1;
        } else if (tool_switch(argv[i]) == 1) {
            no_tools_opt = 1;
        } else {
            no_builtin_opt = 1;
        }
        i++;
    }
    while (i < argc && (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "-c") == 0 || strncmp(argv[i], "--", 2) == 0 || tool_option(argv[i]) || tool_switch(argv[i])) &&
           (i + 1 < argc || strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--print") == 0 || strcmp(argv[i], "-c") == 0 ||
            strcmp(argv[i], "--continue") == 0 || strcmp(argv[i], "--") == 0 ||
            tool_switch(argv[i]))) {
        if (strcmp(argv[i], "--") == 0) { /* what follows is messages and files, whatever it looks like */
            i++;
            dashdash = 1;
            break;
        }
        if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--continue") == 0) { /* Pi: the latest session */
            if (!rpc_session) {
                rpc_session = "latest";
            }
            i++;
            continue;
        }
        if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--print") == 0) { /* Pi: a message may follow */
            print_mode = 1;
            i++;
            if (i < argc && argv[i][0] != '@' && (argv[i][0] != '-' || strncmp(argv[i], "---", 3) == 0)) {
                if (print_add(print_messages, &print_nmessages, argv[i++]) != 0) {
                    return 2;
                }
            }
            continue;
        }
        if (strcmp(argv[i], "--json") == 0 || strcmp(argv[i], "--stream") == 0 || strcmp(argv[i], "--commands") == 0) {
            *(strcmp(argv[i], "--json") == 0 ? &json_events : strcmp(argv[i], "--stream") == 0 ? &force_stream : &commands) = 1;
            i++;
            continue;
        }
        if (tool_switch(argv[i])) {
            *(tool_switch(argv[i]) == 1 ? &no_tools_opt : &no_builtin_opt) = 1;
            i++;
            continue;
        }
        if (tool_option(argv[i]) == 1) {
            tools_opt = argv[i + 1];
            i += 2;
            continue;
        }
        if (tool_option(argv[i]) == 2) {
            exclude_opt = argv[i + 1];
            i += 2;
            continue;
        }
        if (strcmp(argv[i], "--db") == 0) {
            db = argv[i + 1];
        } else if (strcmp(argv[i], "--workspace") == 0) {
            workspace = argv[i + 1];
        } else if (strcmp(argv[i], "--model") == 0) {
            model = argv[i + 1];
        } else if (strcmp(argv[i], "--thinking") == 0) {
            if (pic_thinking_index(argv[i + 1]) < 0) {
                char list[128];
                level_names(list, sizeof list, pic_thinking_names, PIC_THINKING_LEVELS);
                fprintf(stderr, "pic: unknown thinking level %s (%s)\n", argv[i + 1], list);
                return 2;
            }
            thinking_opt = argv[i + 1];
        } else if (strcmp(argv[i], "--context-window") == 0) {
            char *end = NULL;
            long v = strtol(argv[i + 1], &end, 10);
            if (!end || *end || v < 0) {
                return usage();
            }
            context_window = v;
        } else if (strcmp(argv[i], "--trial") == 0) {
            trial_opt = argv[i + 1];
        } else if (strcmp(argv[i], "--max-requests") == 0) {
            max_requests_opt = argv[i + 1];
        } else if (strcmp(argv[i], "--lapse") == 0) {
            lapse_opt = argv[i + 1];
        } else if (strcmp(argv[i], "--lapse-seconds") == 0) {
            lapse_seconds_opt = argv[i + 1];
        } else if (strcmp(argv[i], "--lapse-floor") == 0) {
            lapse_floor_opt = argv[i + 1];
        } else if (strcmp(argv[i], "--system-prompt") == 0) {
            system_replace = argv[i + 1];
        } else if (strcmp(argv[i], "--append-system-prompt") == 0) {
            if (system_nappend >= PIC_SYSTEM_APPEND_MAX) {
                fputs("pic: too many --append-system-prompt\n", stderr);
                return 2;
            }
            system_append[system_nappend++] = argv[i + 1];
        } else if (strcmp(argv[i], "--mode") == 0) {
            if (strcmp(argv[i + 1], "rpc") != 0) {
                fprintf(stderr, "pic: unknown mode %s (rpc is the only one; text is the default)\n", argv[i + 1]);
                return 2;
            }
            rpc_mode = 1;
        } else if (strcmp(argv[i], "--session") == 0) {
            rpc_session = argv[i + 1];
        } else if (strcmp(argv[i], "--tui-mode") == 0) {
            if (strcmp(argv[i + 1], "regular") != 0 && strcmp(argv[i + 1], "fullscreen") != 0) {
                fprintf(stderr, "pic: Invalid TUI mode \"%s\". Valid values: regular, fullscreen\n", argv[i + 1]);
                return 2;
            }
            tui_mode = argv[i + 1];
        } else if (strcmp(argv[i], "--theme") == 0 || strcmp(argv[i], "--use-theme") == 0) {
            theme = argv[i + 1]; /* a name, or light/dark; a theme nobody defines is reported and system is used */
        } else if (strcmp(argv[i], "--exec-timeout") == 0) {
            char *end = NULL;
            long v = strtol(argv[i + 1], &end, 10);
            if (!end || *end || v < 1 || v > 86400) {
                return usage();
            }
            exec_seconds = (int)v;
        } else {
            fprintf(stderr, "pic: unknown option %s\n", argv[i]);
            return usage();
        }
        i += 2;
    }
    /* A leftover option (an unknown one, or one missing its value) is an error
     * before anything is opened: a typo must not create a journal here. */
    if (print_mode) { /* the rest are messages and @files (and the output flags), in any order */
        for (; i < argc; i++) {
            if (!dashdash && (strcmp(argv[i], "--json") == 0 || strcmp(argv[i], "--stream") == 0)) {
                *(argv[i][2] == 'j' ? &json_events : &force_stream) = 1;
            } else if (!dashdash && argv[i][0] == '-' && argv[i][1]) {
                fprintf(stderr, "pic: unknown option %s\n", argv[i]);
                return usage();
            } else if (print_add(argv[i][0] == '@' ? print_files : print_messages, argv[i][0] == '@' ? &print_nfiles : &print_nmessages,
                                 argv[i][0] == '@' ? argv[i] + 1 : argv[i]) != 0) {
                return 2;
            }
        }
        if (commands) {
            fputs("pic: --commands takes Pi's command lines on stdin for ask or run, with --json\n", stderr);
            return usage();
        }
        argv = print_argv; /* from here on it is the ask command */
        argc = 1;
        i = 0;
    } else if (rpc_mode) { /* pic --mode rpc [-c | --continue] */
        if (i < argc && (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--continue") == 0) && !rpc_session) {
            rpc_session = "latest";
            i++;
        }
        if (i < argc || commands) {
            fputs("pic: --mode rpc takes no command: Pi's RPC commands come on stdin\n", stderr);
            return usage();
        }
        json_events = 1;
    } else if (rpc_session) {
        fputs("pic: --session and -c before a command are for -p and --mode rpc (ask --session ID continues one)\n", stderr);
        return usage();
    } else if (i < argc && argv[i][0] == '-') {
        fprintf(stderr, "pic: unknown option %s\n", argv[i]);
        return usage();
    }
    pic_system_prompt_args(system_replace, system_append, system_nappend);
    if (bench_options() != 0) {
        return 2;
    }
    { /* Pi's tool selection: --tools, --exclude-tools, --no-tools, --no-builtin-tools, the defaultTools setting */
        char *saved = setting("defaultTools"), err[256];
        int bad = pic_toolset_configure(tools_opt, exclude_opt, no_tools_opt, no_builtin_opt, saved, err, sizeof err);
        free(saved);
        if (bad) {
            fprintf(stderr, "pic: %s\n", err);
            return 2;
        }
    }
    if (commands && (!json_events || i >= argc || (strcmp(argv[i], "ask") != 0 && strcmp(argv[i], "run") != 0))) {
        fputs("pic: --commands takes Pi's command lines on stdin for ask or run, with --json\n", stderr);
        return usage();
    }
    /* The model: --model, else the default saved with pic models --default (or
     * Ctrl+S in the model picker), else pic's own. */
    static char default_saved[256];
    {
        char *def = setting("defaultModel");
        (void)snprintf(default_saved, sizeof default_saved, "%s", def && *def ? def : default_model);
        free(def);
    }
    if (!model) {
        static char saved[256];
        initial_model(saved, sizeof saved);
        model = saved;
    }
    if (i < argc && strcmp(argv[i], "ps") == 0) { /* picu_proc in ~/.pic/pic.sqlite */
        return pic_ps_command(argc - i - 1, argv + i + 1);
    }
    pic_proc_sink_set(&pic_procs_sink);
    pic_procs_init(!json_events);
    if (i < argc && strcmp(argv[i], "models") == 0) {
        return models_command(argc - i - 1, argv + i + 1);
    }
    if (i < argc && strcmp(argv[i], "projects") == 0) { /* picu_project in ~/.pic/pic.sqlite */
        if (argc - i != 1) {
            return usage();
        }
        if (pic_projects_each(print_project, NULL) != 0) {
            fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr);
            return 1;
        }
        return 0;
    }
    if (i < argc && strcmp(argv[i], "settings") == 0) { /* stored in ~/.pic/pic.sqlite */
        if (argc - i == 1) {
            return pic_settings_each(print_setting, NULL) == 0 ? 0 : 1;
        }
        if (argc - i == 2 && argv[i + 1][0] != '-') {
            char *v = setting(argv[i + 1]);
            if (v) {
                puts(v);
            }
            free(v);
            return v ? 0 : 1;
        }
        if (argc - i == 3 && strcmp(argv[i + 1], "--unset") == 0) {
            return set_setting(argv[i + 2], NULL) == 0 ? 0 : 1;
        }
        if (argc - i == 3) {
            return set_setting(argv[i + 1], argv[i + 2]) == 0 ? 0 : 1;
        }
        return usage();
    }
    /* No command: the line mode, when a person is at a terminal. */
    if (i >= argc && !rpc_mode && !(isatty(STDIN_FILENO) && isatty(STDOUT_FILENO))) {
        return usage();
    }
    /* import --claude: the transcript's cwd is the workspace unless one is named. */
    if (i < argc && strcmp(argv[i], "import") == 0 && argc - i >= 3 && strcmp(argv[i + 1], "--claude") == 0) {
        claude_path = argv[i + 2];
        for (int k = i + 3; k < argc; k += 2) {
            if (strcmp(argv[k], "--count") == 0) {
                claude_count = 1;
                k--;
            } else if (k + 1 >= argc) {
                return usage();
            } else if (strcmp(argv[k], "--api-url") == 0) {
                claude_url = argv[k + 1];
            } else if (strcmp(argv[k], "--until") == 0) {
                claude_until = argv[k + 1];
            } else if (strcmp(argv[k], "--workspace") == 0) {
                workspace = argv[k + 1];
            } else {
                return usage();
            }
        }
        if (!workspace) {
            char err[PATH_MAX + 64];
            if (pic_claude_cwd(claude_path, claude_until, claude_cwd, sizeof claude_cwd, err, sizeof err) != 0) {
                fprintf(stderr, "pic: %s\n", err);
                return 1;
            }
            workspace = claude_cwd;
        }
    }
    if (!workspace) {
        if (!getcwd(cwd, sizeof cwd)) {
            fprintf(stderr, "pic: cannot read the current directory\n");
            return 1;
        }
        workspace = cwd;
    }
    /* A missing workspace would otherwise be recorded as a permanent tool error. */
    if (stat(workspace, &st) != 0 || !S_ISDIR(st.st_mode)) {
        fprintf(stderr, "pic: workspace is not a directory: %s\n", workspace);
        return 1;
    }
    if (i < argc && (strcmp(argv[i], "trust") == 0 || strcmp(argv[i], "scoped-models") == 0 || strcmp(argv[i], "bug") == 0 ||
                       strcmp(argv[i], "prompts") == 0 || strcmp(argv[i], "skills") == 0 || strcmp(argv[i], "login") == 0 ||
                       strcmp(argv[i], "logout") == 0 || strcmp(argv[i], "keys") == 0)) {
        return user_command(argc - i, argv + i, workspace);
    }
    if (!db) {
        if (default_db(workspace, db_path, sizeof db_path) != 0) {
            fprintf(stderr, "pic: cannot create %s/.pic\n", workspace);
            return 1;
        }
        db = db_path;
    }
    if (i < argc && strcmp(argv[i], "hooks") == 0 && argc - i == 1) {
        return pic_hooks_list(workspace, stdout) == 0 ? 0 : 1;
    }
    hooks = pic_hooks_load(workspace, hook_owner[0] ? hook_owner : NULL, stderr);
    if (i < argc && strcmp(argv[i], "hooks") == 0 && argc - i == 3 && strcmp(argv[i + 1], "end") == 0 && !hooks) {
        return 0; /* nothing configured: nothing to end */
    }
    if (rpc_mode) {
        pic_rpc_host h;
        memset(&h, 0, sizeof h);
        quiet = 1; /* conversations end when the process does */
        rpc_workspace = workspace;
        rpc_exec_seconds = exec_seconds;
        h.db = db;
        h.workspace = workspace;
        h.exec_seconds = exec_seconds;
        h.open = open_store;
        h.prompt = rpc_prompt;
        h.provider = rpc_provider;
        h.level = rpc_level;
        h.expand = expand_template;
        h.end = end_conversations;
        rc = pic_rpc_main(&h, model, rpc_session);
        pic_hooks_free(hooks);
        return rc;
    }
    if (i >= argc || (strcmp(argv[i], "tui") == 0 && argc - i <= 3)) {
        char self[PATH_MAX];
        pic_tui_options t;
        const char *resume = NULL;
        if (i < argc && argc - i == 2 && strcmp(argv[i + 1], "-c") == 0) {
            resume = "latest";
        } else if (i < argc && argc - i == 3 && strcmp(argv[i + 1], "--session") == 0) {
            resume = argv[i + 2];
        } else if (i < argc && argc - i != 1) {
            return usage();
        }
        self_path(argv[0], self, sizeof self);
        t.self = self;
        t.db = db;
        t.workspace = workspace;
        t.model = model;
        t.default_model = default_saved;
        t.exec_seconds = exec_seconds;
        t.context_window = context_window;
        t.resume = resume;
        t.tui_mode = tui_mode;
        t.theme = theme;
        t.system_replace = system_replace;
        t.system_append = system_append;
        t.system_nappend = system_nappend;
        t.tools = tools_opt;
        t.exclude_tools = exclude_opt;
        t.no_tools = no_tools_opt;
        t.no_builtin_tools = no_builtin_opt;
        return pic_tui_main(&t);
    }
    if (strcmp(argv[i], "chat") == 0 && argc - i == 1) {
        return repl(db, workspace, model, exec_seconds, NULL);
    }
    if (strcmp(argv[i], "chat") == 0 && argc - i == 2 && strcmp(argv[i + 1], "-c") == 0) {
        return repl(db, workspace, model, exec_seconds, "latest");
    }
    if (strcmp(argv[i], "chat") == 0 && argc - i == 3 && strcmp(argv[i + 1], "--session") == 0) {
        return repl(db, workspace, model, exec_seconds, argv[i + 2]);
    }
    if (open_store(&s, db) != 0) {
        fprintf(stderr, "pic: %s\n", s.err);
        pic_close(&s);
        return 1;
    }
    {
        char real[PATH_MAX];
        const char *ws = realpath(workspace, real) ? real : workspace;
        (void)pic_workspace_touch(ws, db);
        pic_proc_scope(ws, NULL);
    }
    if (print_mode) {
        rc = print_command(&s, workspace, model, exec_seconds, rpc_session);
        if (rc == 125) { /* the message is out already */
            pic_close(&s);
            return 1;
        }
    } else if (strcmp(argv[i], "ask") == 0) {
        rc = ask_command(&s, workspace, model, exec_seconds, argc - i - 1, argv + i + 1);
        if (rc == 2) {
            pic_close(&s);
            return usage();
        }
    } else if (strcmp(argv[i], "submit") == 0 && (argc - i == 3 || (argc - i == 5 && strcmp(argv[i + 3], "--session") == 0))) {
        int duplicate = 0, fresh = 0;
        int64_t first = 0;
        char joined[64], sid[64] = "";
        const char *session = argc - i == 5 ? argv[i + 4] : NULL;
        rc = s.hooks && hook_conversation(&s, session, sid, &fresh, argv[i + 2], &first) != 0
                 ? -1
                 : pic_submit_hooked(&s, argv[i + 1], argv[i + 2], NULL, 0, fresh ? NULL : sid[0] ? sid : session,
                                     fresh ? sid : NULL, first, &duplicate, joined, sizeof joined);
        if (rc == 0) {
            puts(duplicate ? "duplicate: already admitted" : "admitted");
        }
        end_own(&s, sid);
    } else if (strcmp(argv[i], "compact") == 0 && argc - i >= 2 && argc - i <= 4 && strcmp(argv[i + 1], "--now") == 0) {
        /* Pi's /compact: at once, with this model (its events with --json). */
        pic_provider provider;
        sqlite3_int64 seq = 0;
        memset(&provider, 0, sizeof provider);
        rc = model_provider(&provider, model, NULL, workspace, s.err, sizeof s.err);
        if (rc == 0) {
            if (context_window >= 0) {
                provider.context_window = context_window;
            }
            if (json_events) {
                pic_events_init(&events, stdout, stderr, 1, 0);
                s.events = &events;
            }
            catch_interrupt();
            rc = pic_compact_now(&s, &provider, argc - i >= 3 ? argv[i + 2] : "latest", argc - i == 4 ? argv[i + 3] : NULL,
                                 &seq);
            s.events = NULL;
        }
        if (provider.free) {
            provider.free(&provider);
        }
        if (rc == 0 && !json_events) {
            sqlite3_stmt *q = NULL;
            if (sqlite3_prepare_v2(s.db, "SELECT coalesce(tokens_before, 0) FROM pic_entry WHERE seq = ?", -1, &q, NULL) ==
                SQLITE_OK) {
                sqlite3_bind_int64(q, 1, seq);
                if (sqlite3_step(q) == SQLITE_ROW) {
                    printf("compacted %lld tokens of history into a summary\n", (long long)sqlite3_column_int64(q, 0));
                }
            }
            sqlite3_finalize(q);
        }
    } else if (strcmp(argv[i], "compact") == 0 && argc - i <= 3) {
        char id[64];
        rc = pic_compact_request(&s, argc - i >= 2 ? argv[i + 1] : "latest", argc - i == 3 ? argv[i + 2] : NULL, id,
                                 sizeof id);
        if (rc == 0) {
            printf("%s will be compacted before its next request\n", id);
        }
    } else if (strcmp(argv[i], "export") == 0 && argc - i >= 3 && argc - i <= 4 && strcmp(argv[i + 1], "--html") == 0) {
        const char *path = argc - i == 4 ? argv[i + 3] : "-";
        FILE *f = strcmp(path, "-") == 0 ? stdout : fopen(path, "w");
        if (!f) {
            (void)snprintf(s.err, sizeof s.err, "cannot write %s: %s", path, strerror(errno));
            rc = -1;
        } else {
            rc = pic_export_html(&s, argv[i + 2], f);
            if (f != stdout && fclose(f) != 0 && rc == 0) {
                (void)snprintf(s.err, sizeof s.err, "cannot write %s: %s", path, strerror(errno));
                rc = -1;
            }
        }
    } else if (strcmp(argv[i], "tree") == 0 && argc - i >= 2 && argc - i <= 3 && strcmp(argv[i + 1], "--json") == 0) {
        rc = pic_tree_json(&s, argc - i == 3 ? argv[i + 2] : "latest", stdout);
    } else if (claude_path) {
        pic_claude_import made_by;
        char made[64];
        FILE *f = fopen(claude_path, "r");
        if (!f) {
            (void)snprintf(s.err, sizeof s.err, "cannot read %s: %s", claude_path, strerror(errno));
            rc = -1;
        } else {
            rc = pic_import_claude(&s, f, claude_until, made, sizeof made, &made_by);
            fclose(f);
        }
        if (rc == 0) {
            printf("%s\nrequests %ld, tool calls %ld structured, %ld as text\n"
                   "context %ld tokens (pic estimate: chars/4 of the messages)\n",
                   made, made_by.requests, made_by.calls, made_by.text_calls, made_by.context_tokens);
            if (made_by.usage >= 0) {
                printf("transcript usage %lld tokens (input + cache read + cache write of the last reply)\n", made_by.usage);
            } else {
                puts("transcript usage none recorded");
            }
        }
        /* --count: the first request pic would send, its system prompt and
         * tools frozen as that request freezes them, by the provider's counter. */
        if (rc == 0 && claude_count) {
            pic_provider provider;
            long counted = 0;
            if (pic_begin(&s) != 0) {
                rc = -1;
            } else if (pic_sync_session(&s, workspace, made_by.last) != 0 || pic_commit(&s) != 0) {
                pic_rollback(&s);
                rc = -1;
            } else if (model_provider(&provider, model, claude_url, workspace, s.err, sizeof s.err) != 0) {
                rc = -1;
            } else {
                if (!provider.count) {
                    printf("counted: %.*s has no token-counting endpoint; the estimate stands\n",
                           (int)strcspn(provider.model, "/"), provider.model);
                } else {
                    s.err[0] = '\0';
                    rc = provider.count(&provider, &s, made_by.last, &counted, s.err, sizeof s.err);
                    if (rc == 0) {
                        printf("counted %ld tokens (anthropic count_tokens: system prompt, tools and messages)\n", counted);
                    }
                }
                provider.free(&provider);
            }
        }
    } else if (strcmp(argv[i], "import") == 0 && argc - i == 2) {
        char made[64];
        long turns = 0;
        FILE *f = strcmp(argv[i + 1], "-") == 0 ? stdin : fopen(argv[i + 1], "r");
        if (!f) {
            (void)snprintf(s.err, sizeof s.err, "cannot read %s: %s", argv[i + 1], strerror(errno));
            rc = -1;
        } else {
            rc = pic_import_pi(&s, f, made, sizeof made, &turns);
            if (f != stdin) {
                fclose(f);
            }
            if (rc == 0) {
                printf("%s\n", made);
            }
        }
    } else if (strcmp(argv[i], "export") == 0 && argc - i <= 3 && argc - i >= 2 && strcmp(argv[i + 1], "--pi") == 0) {
        rc = pic_export_pi(&s, workspace, argc - i == 3 ? argv[i + 2] : NULL, NULL);
    } else if (strcmp(argv[i], "export") == 0 && (argc - i == 1 || (argc - i == 3 && strcmp(argv[i + 1], "--since") == 0))) {
        char real[PATH_MAX];
        rc = pic_export(&s, realpath(workspace, real) ? real : workspace, argc - i == 3 ? strtoll(argv[i + 2], NULL, 10) : 0,
                        stdout);
    } else if (strcmp(argv[i], "sessions") == 0 && argc - i == 2 && strcmp(argv[i + 1], "--json") == 0) {
        rc = pic_sessions_json(&s, stdout);
    } else if (strcmp(argv[i], "log") == 0 && argc - i >= 2 && argc - i <= 3 && strcmp(argv[i + 1], "--json") == 0) {
        rc = pic_session_log_json(&s, argc - i == 3 ? argv[i + 2] : "latest", stdout);
    } else if (strcmp(argv[i], "sessions") == 0 && argc - i == 1) {
        rc = pic_sessions(&s, stdout);
    } else if (strcmp(argv[i], "log") == 0 && argc - i <= 2) {
        rc = pic_session_log(&s, argc - i == 2 ? argv[i + 1] : "latest", stdout);
    } else if (strcmp(argv[i], "name") == 0 && argc - i == 3) {
        rc = pic_session_name(&s, argv[i + 1], argv[i + 2]);
    } else if (strcmp(argv[i], "fork") == 0 && argc - i >= 5 && strcmp(argv[i + 2], "--at") == 0 &&
               strcmp(argv[i + 4], "--summarize") == 0) {
        /* Pi's /tree with a summary of the branch left behind: its request
         * goes to the model, or to --script / --api-url as pic run's would. */
        const char *instructions = NULL, *script = NULL, *url = NULL;
        pic_provider provider;
        char made[64];
        memset(&provider, 0, sizeof provider);
        for (int j = i + 5; j < argc; j += 2) {
            if (j + 1 >= argc) {
                pic_close(&s);
                return usage();
            }
            if (strcmp(argv[j], "--instructions") == 0) {
                instructions = argv[j + 1];
            } else if (strcmp(argv[j], "--script") == 0) {
                script = argv[j + 1];
            } else if (strcmp(argv[j], "--api-url") == 0) {
                url = argv[j + 1];
            } else {
                pic_close(&s);
                return usage();
            }
        }
        rc = script ? pic_provider_script(&provider, script) : model_provider(&provider, model, url, workspace, s.err, sizeof s.err);
        if (rc == 0) {
            if (context_window >= 0) {
                provider.context_window = context_window;
            }
            catch_interrupt();
            rc = pic_branch_summarize(&s, &provider, argv[i + 1], strtoll(argv[i + 3], NULL, 10), instructions, made, sizeof made);
            if (rc == 0) {
                puts(made);
            }
        }
        if (provider.free) {
            provider.free(&provider);
        }
    } else if (strcmp(argv[i], "fork") == 0 && (argc - i == 2 || (argc - i == 4 && strcmp(argv[i + 2], "--at") == 0))) {
        char made[64];
        rc = pic_fork(&s, argv[i + 1], argc - i == 4 ? strtoll(argv[i + 3], NULL, 10) : 0, made, sizeof made);
        if (rc == 0) {
            puts(made);
        }
    } else if (strcmp(argv[i], "bash") == 0) {
        int status = 0;
        rc = bash_command(&s, workspace, exec_seconds, argc - i - 1, argv + i + 1, &status);
        if (rc == 0) {
            pic_close(&s);
            return json_events ? 0 : status;
        }
    } else if (strcmp(argv[i], "cancel") == 0 && argc - i == 2) {
        rc = pic_cancel(&s, argv[i + 1]);
        if (rc == 0) {
            puts("cancelled");
        }
    } else if (strcmp(argv[i], "run") == 0) {
        const char *provider_name = NULL, *script = NULL, *url = NULL, *only = NULL;
        pic_provider provider;
        memset(&provider, 0, sizeof provider);
        for (int j = i + 1; j < argc; j += 2) {
            if (j + 1 >= argc) {
                pic_close(&s);
                return usage();
            }
            if (strcmp(argv[j], "--session") == 0) {
                only = argv[j + 1];
            } else if (strcmp(argv[j], "--script") == 0) {
                script = argv[j + 1];
            } else if (strcmp(argv[j], "--provider") == 0) {
                provider_name = argv[j + 1];
            } else if (strcmp(argv[j], "--model") == 0) {
                model = argv[j + 1];
            } else if (strcmp(argv[j], "--api-url") == 0) {
                url = argv[j + 1];
            } else {
                pic_close(&s);
                return usage();
            }
        }
        if (script && provider_name) {
            pic_close(&s);
            return usage();
        } else if (script) {
            rc = pic_provider_script(&provider, script);
        } else if (!script) {
            rc = model_provider(&provider, model, url, workspace, s.err, sizeof s.err);
            s.provider_for = provider_for; /* each request finishes with its own model */
        } else {
            pic_close(&s);
            return usage();
        }
        if (rc == 0 && only) { /* only that conversation's requests, its unfinished one first */
            char sid[64];
            sqlite3_stmt *q = NULL;
            rc = pic_session_resolve(&s, only, sid, sizeof sid);
            if (rc == 0 && sqlite3_prepare_v2(s.db, "SELECT coalesce(min(id), 0) FROM pic_submission WHERE session_id = ?"
                                                    " AND status = 'admitted'", -1, &q, NULL) == SQLITE_OK) {
                sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
                if (sqlite3_step(q) == SQLITE_ROW) {
                    s.running = sqlite3_column_int64(q, 0);
                }
                sqlite3_finalize(q);
            }
            s.session_only = 1;
            if (rc == 0 && !s.running) {
                (void)snprintf(s.err, sizeof s.err, "conversation %s has no unfinished request", sid);
                rc = -1;
            }
        }
        if (rc == 0) {
            if (context_window >= 0) {
                provider.context_window = context_window;
            }
            if (json_events || force_stream) {
                pic_events_init(&events, stdout, stderr, json_events, !json_events);
                s.events = &events;
            }
            catch_interrupt();
            rc = run_with_commands(&s, workspace, &provider, exec_seconds);
        }
        if (provider.free) {
            provider.free(&provider);
        }
    } else if (strcmp(argv[i], "hooks") == 0 && argc - i == 3 && strcmp(argv[i + 1], "end") == 0) {
        rc = pic_hooks_end_owned(&s, argv[i + 2]); /* the terminal, on exit: PIC_HOOK_OWNER names it */
    } else if (strcmp(argv[i], "dump") == 0 && argc - i == 1) {
        rc = pic_dump(&s);
    } else if (strcmp(argv[i], "usage") == 0 && argc - i >= 2 && strcmp(argv[i + 1], "--by-trial") == 0 &&
               (argc - i == 2 || (argc - i == 3 && strcmp(argv[i + 2], "--json") == 0))) {
        rc = pic_usage_by_trial(&s, argc - i == 3, stdout);
    } else if (strcmp(argv[i], "result") == 0 && argc - i == 2) {
        rc = print_result(&s, argv[i + 1]);
    } else if (strcmp(argv[i], "check") == 0 && argc - i == 1) {
        rc = pic_check_deep(&s);
        if (rc == 0) {
            puts("check: ok");
        }
    } else if (strcmp(argv[i], "prune") == 0 && (argc - i == 1 || (argc - i == 2 && strcmp(argv[i + 1], "--dry-run") == 0))) {
        long long count = 0, bytes = 0;
        int dry = argc - i == 2;
        rc = pic_prune(&s, dry, &count, &bytes);
        if (rc == 0) {
            printf("%s %lld image%s, %lld bytes\n", dry ? "would prune" : "pruned", count, count == 1 ? "" : "s", bytes);
        }
    } else {
        pic_close(&s);
        fprintf(stderr, "pic: unknown %s %s\n", strncmp(argv[i], "-", 1) == 0 ? "option" : "command or arguments:", argv[i]);
        return usage();
    }
    if (rc != 0) {
        fprintf(stderr, "pic: %s\n", s.err);
    }
    pic_close(&s);
    pic_hooks_free(hooks);
    return rc == 0 ? 0 : 1;
}