Skip to content
pi-c Documentation
Login

Documentation

/* pic command line: ask for work, run it durably, inspect the journal. */
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.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 "anthropic.h"
#include "attach.h"
#include "commands.h"
#include "gemini.h"
#include "openai_chat.h"
#include "openai_responses.h"
#include "compact.h"
#include "cred.h"
#include "endpoints.h"
#include "keyhealth.h"
#include "keyprobe.h"
#include "help.h"
#include "hooks.h"
#include "inbox.h"
#include "peer.h"
#include "listings.h"
#include "input.h"
#include "net.h"
#include "oauth.h"
#include "catalog.h"
#include "userdb.h"
#include "verify.h"
#include "pic.h"
#include "procs.h"
#include "provider_http.h"
#include "prompts.h"
#include "rewind.h"
#include "rpc.h"
#include "settings.h"
#include "skills.h"
#include "platform.h"
#include "tui/remote.h"
#include "remote.h"
#include "doctor.h"
#include "tui/tui.h"

/* --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 main_commands;
/* --hold-key-failures: a reply refused for its key leaves its request
 * unfinished (the terminal's swap prompt); --key LABEL: the model's provider
 * uses its key LABEL for this run. */
static int hold_key_failures_opt;
static const char *key_opt;
/* 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;
static char *verify_command; /* the trusted workspace's verify command (verify.h), or NULL */
/* PIC_HOOK_OWNER, taken from the environment so tools and hooks never see it. */
static char main_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), handed to the context
 * policy (compact.c), which owns them. Lapse compaction is on by default
 * above 100000 tokens; PIC_LAPSE_HOLDOUT, lapseHoldout and lapseMode are
 * only checked here (compact.c reads them). */
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, PIC_LAPSE_FLOOR, 1};

static int valid_session_id(const char *id);

/* Opens the journal with the hooks and the context policy attached. */
static int open_store(pic_store *s, const char *db) {
    int rc = pic_open(s, db);
    s->hooks = hooks;
    s->verify = verify_command;
    s->trial = bench.trial;
    s->max_requests = bench.max_requests;
    s->policy = &pic_compact_policy;
    s->hold_key_failures = hold_key_failures_opt;
    pic_lapse_configure(bench.lapse, bench.lapse_seconds, 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);
    v = bench_value(NULL, "PIC_LAPSE_HOLDOUT", "lapseHoldout", &owned); /* compact.c reads it at each lapse */
    if (v) {
        char *end = NULL;
        double h = strtod(v, &end);
        if (!*v || !end || *end || !(h >= 0.0 && h <= 1.0)) {
            fprintf(stderr, "pic: the lapse holdout is a share from 0 to 1, not %s (PIC_LAPSE_HOLDOUT, lapseHoldout)\n", v);
            free(owned);
            return -1;
        }
    }
    free(owned);
    v = bench_value(NULL, "", "lapseMode", &owned);
    if (v && strcmp(v, "trim") != 0 && strcmp(v, "summary") != 0) {
        fprintf(stderr, "pic: lapseMode is trim or summary, not %s\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);
}

/* catch_interrupt, and SIGTERM the same way: a standalone request that is stopped while its hooks
 * run (before it is admitted) still ends its conversation. */
static void catch_interrupt_and_term(void) {
    struct sigaction sa;
    catch_interrupt();
    memset(&sa, 0, sizeof sa);
    sa.sa_handler = on_interrupt;
    sigemptyset(&sa.sa_mask);
    (void)sigaction(SIGTERM, &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], key[16];
} main_listing;

/* How PROVIDER's key stands, as a request would use it: KEY_WORKS when its
 * last reply came back, KEY_UNTRIED when nothing is known, KEY_FAILED when it
 * was refused, is out of credit or limited, KEY_NONE when it has none. HOW
 * says where the key comes from ("OPENROUTER_API_KEY is set"); WHAT, for a
 * failed one, how ("was refused"); SIGNED_IN, whether it is a subscription's
 * sign-in rather than a key. */
enum { KEY_NONE, KEY_FAILED, KEY_UNTRIED, KEY_WORKS };

typedef struct {
    char name[PIC_CRED_NAME_CAP], env[128], kind[16];
    int found;
} active_cred;

static int note_active(void *ctx, const pic_cred_entry *e) {
    active_cred *c = ctx;
    if (!e->active) {
        return 0;
    }
    (void)snprintf(c->name, sizeof c->name, "%s", e->name ? e->name : "");
    (void)snprintf(c->env, sizeof c->env, "%s", e->env ? e->env : "");
    (void)snprintf(c->kind, sizeof c->kind, "%s", e->kind ? e->kind : "");
    c->found = 1;
    return 1;
}

static int key_standing(const char *provider, char *how, size_t howcap, char *what, size_t whatcap, int *signed_in) {
    char name[128], err[256];
    pic_model m;
    active_cred c;
    pic_key_health h;
    if (how && howcap) {
        how[0] = '\0';
    }
    if (what && whatcap) {
        what[0] = '\0';
    }
    if (signed_in) {
        *signed_in = 0;
    }
    (void)snprintf(name, sizeof name, "%s/x", provider);
    if (pic_model_resolve(name, &m, err, sizeof err) != 0 || !pic_model_available(provider)) {
        return KEY_NONE;
    }
    if (!m.key_env[0] && !m.key_literal[0]) {
        if (how && howcap) {
            (void)snprintf(how, howcap, "%s needs no key", provider);
        }
        return KEY_UNTRIED;
    }
    memset(&c, 0, sizeof c);
    (void)pic_cred_entries(provider, m.key_env, m.key_literal, note_active, &c);
    if (!c.found) {
        return KEY_UNTRIED;
    }
    if (how && howcap) {
        if (strcmp(c.kind, "env") == 0) {
            (void)snprintf(how, howcap, "%s is set", c.env);
        } else if (strcmp(c.kind, "file") == 0) {
            (void)snprintf(how, howcap, "the models file has a key for %s", provider);
        } else if (strcmp(c.kind, "oauth") == 0) {
            (void)snprintf(how, howcap, "you are signed in to %s", provider);
        } else {
            (void)snprintf(how, howcap, "a key for %s is stored", provider);
        }
    }
    if (signed_in) {
        *signed_in = strcmp(c.kind, "oauth") == 0;
    }
    if (pic_cred_health_of(c.name, &h) != 1) {
        return KEY_UNTRIED;
    }
    if (pic_cred_key_bad(&h, pic_platform_get()->wall_ns() / 1000000)) {
        if (what && whatcap) {
            (void)snprintf(what, whatcap, "%s", h.state == PIC_KEY_INVALID  ? "was refused"
                                                : h.state == PIC_KEY_CREDIT ? "is out of credit"
                                                                            : "is rate-limited");
        }
        return KEY_FAILED;
    }
    return h.state == PIC_KEY_OK ? KEY_WORKS : KEY_UNTRIED;
}

static int list_model(void *ctx, const char *provider, const char *json) {
    main_listing *l = ctx;
    char levels[96];
    if (strcmp(provider, l->provider) != 0) {
        char what[64];
        int signed_in, standing;
        (void)snprintf(l->provider, sizeof l->provider, "%s", provider);
        l->available = pic_model_available(provider);
        standing = key_standing(provider, NULL, 0, what, sizeof what, &signed_in);
        (void)snprintf(l->key, sizeof l->key, "%s",
                       standing == KEY_NONE                                ? "none"
                       : standing == KEY_FAILED                            ? (strstr(what, "refused") ? "refused"
                                                                              : strstr(what, "credit") ? "no credit"
                                                                                                       : "limited")
                       : signed_in && (strcmp(provider, "openai") == 0 ||
                                       strcmp(provider, "openai-codex") == 0) ? "ChatGPT plan"
                       : signed_in                                         ? "signed in"
                       : standing == KEY_WORKS                             ? "ok"
                                                                           : "unknown");
    }
    if (!l->all && !l->available) {
        return 0;
    }
    sqlite3_bind_text(l->q, 5, l->key, -1, SQLITE_STATIC);
    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_use(int argc, char **argv);

static int models_command(int argc, char **argv) {
    main_listing l;
    sqlite3 *db = NULL;
    int refresh = 0;
    if (argc >= 1 && strcmp(argv[0], "use") == 0) {
        return models_use(argc - 1, argv + 1);
    }
    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 || strcmp(argv[i], "--last") == 0) && i + 1 < argc) {
            pic_model m;
            int last = strcmp(argv[i], "--last") == 0;
            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;
            }
            int bad = last ? pic_model_remember(argv[i + 1])
                           : (set_setting("defaultModel", argv[i + 1]) != 0 || set_setting("lastModel", NULL) != 0);
            if (bad) {
                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 iif(e IS NULL, o, json_set(o, '$.endpoint', e)), t FROM (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')), 'key', ?5) AS o,"
                           " json_extract(?1, '$.endpoint') AS e,"
                           " printf('%-48s %s', ?2 || '/' || json_extract(?1, '$.id'),"
                           "   coalesce(json_extract(?1, '$.name'), 'from ' || json_extract(?1, '$.endpoint'), '')"
                           "   || CASE WHEN ?3 THEN '' ELSE '  (no key)' END) AS t)",
                           -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);
    l.provider[0] = '\0';
    (void)pic_endpoint_models_each(list_model, &l);
    sqlite3_finalize(l.q);
    sqlite3_close(db);
    return 0;
}

/* ---- pic endpoints: saved model endpoints (endpoints.h) --------------------- */

static long read_key(const char *prompt, char *key, size_t cap, char *err, size_t errcap);

static int print_endpoint(void *ctx, const pic_endpoint *e) {
    char when[32] = "never fetched";
    int *n = ctx;
    if (e->fetched_ms) {
        time_t t = (time_t)(e->fetched_ms / 1000);
        struct tm tm;
        if (localtime_r(&t, &tm)) {
            (void)strftime(when, sizeof when, "fetched %Y-%m-%d %H:%M", &tm);
        }
    }
    printf("%-16s %s  %d model%s, %s%s\n", e->name, e->url, e->count, e->count == 1 ? "" : "s", when,
           pic_cred_stored(e->name) ? ", key stored" : "");
    if (e->error) {
        printf("%-16s the last refresh failed, so this list is older: %s\n", "", e->error);
    }
    ++*n;
    return 0;
}

static int endpoint_name(void *ctx, const pic_endpoint *e) {
    char *out = ctx;
    size_t used = strlen(out);
    (void)snprintf(out + used, 4096 - used, "%s\n", e->name);
    return 0;
}

/* pic endpoints [list] | add NAME URL [--key] | remove NAME | refresh [NAME]. */
static int endpoints_command(int argc, char **argv) {
    char err[PIC_ERR_CAP];
    int count = 0;
    if (argc == 0 || (argc == 1 && strcmp(argv[0], "list") == 0)) {
        int n = 0;
        if (pic_endpoints_each(print_endpoint, &n) != 0) {
            fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr);
            return 1;
        }
        if (n == 0) {
            puts("No saved endpoints (pic endpoints add NAME URL saves one).");
        }
        return 0;
    }
    if (strcmp(argv[0], "add") == 0 && (argc == 3 || (argc == 4 && strcmp(argv[3], "--key") == 0))) {
        char key[2 * PIC_CRED_KEY_CAP], prompt[160], norm[PIC_ENDPOINT_URL_CAP];
        int rc;
        if (pic_endpoint_name_check(argv[1], err, sizeof err) != 0 ||
            pic_endpoint_url_check(argv[2], norm, sizeof norm, err, sizeof err) != 0) {
            fprintf(stderr, "pic: %s\n", err);
            return 2;
        }
        if (argc == 4) {
            (void)snprintf(prompt, sizeof prompt, "API key for %s: ", argv[1]);
            if (read_key(prompt, key, sizeof key, err, sizeof err) < 0) {
                pic_cred_wipe(key, sizeof key);
                fprintf(stderr, "pic: %s\n", err);
                return 1;
            }
        }
        rc = pic_endpoint_add(argv[1], norm, argc == 4 ? key : NULL, &count, err, sizeof err);
        pic_cred_wipe(key, sizeof key);
        if (rc < 0) {
            fprintf(stderr, "pic: %s\n", err);
            return 1;
        }
        printf("Saved the endpoint %s (%s)%s.\n", argv[1], norm, argc == 4 ? " with its key, sealed in ~/.pic/pic.sqlite" : "");
        if (rc == 1) {
            fprintf(stderr, "pic: its models could not be fetched: %s (pic endpoints refresh %s tries again)\n", err, argv[1]);
            return 1;
        }
        printf("%d model%s, in /model as %s/MODEL. pic has not checked that each one answers.\n", count,
               count == 1 ? "" : "s", argv[1]);
        return 0;
    }
    if (strcmp(argv[0], "remove") == 0 && argc == 2) {
        int r = pic_endpoint_remove(argv[1]);
        if (r < 0) {
            fputs("pic: cannot remove the endpoint from ~/.pic/pic.sqlite\n", stderr);
            return 1;
        }
        if (r == 0) {
            fprintf(stderr, "pic: no endpoint is saved as %s (pic endpoints list)\n", argv[1]);
            return 1;
        }
        printf("Removed the endpoint %s and any key stored for it.\n", argv[1]);
        return 0;
    }
    if (strcmp(argv[0], "refresh") == 0 && argc <= 2) {
        char names[4096] = "";
        int failed = 0;
        if (argc == 2) {
            (void)snprintf(names, sizeof names, "%s\n", argv[1]);
        } else {
            (void)pic_endpoints_each(endpoint_name, names);
        }
        for (char *name = names, *nl; (nl = strchr(name, '\n')); name = nl + 1) {
            *nl = '\0';
            if (pic_endpoint_refresh(name, &count, err, sizeof err) != 0) {
                fprintf(stderr, "pic: %s: %s (the list it had is kept)\n", name, err);
                failed = 1;
            } else {
                printf("%s: %d model%s\n", name, count, count == 1 ? "" : "s");
            }
        }
        if (!names[0]) {
            puts("No saved endpoints (pic endpoints add NAME URL saves one).");
        }
        return failed;
    }
    return usage();
}

/* This executable's path, for the TUI's child processes. */
static void self_path(const char *argv0, char *out, size_t cap) {
    const pic_platform *p = pic_platform_get();
    if (p->self_path && p->self_path(out, cap) == 0) {
        return;
    }
    if (!realpath(argv0, out)) {
        (void)snprintf(out, cap, "%s", argv0);
    }
}

/* A synopsis; every command and flag is in docs/reference/cli.md (pic help cli). */
static void print_usage(FILE *out) {
    fputs("usage: pic [options] [COMMAND]\n"
          "\n"
          "  pic                        the terminal interface in the current directory (tui)\n"
          "  pic tui [-c | --session ID]   continue the latest conversation, or that one\n"
          "  pic ask [-c] TEXT          run TEXT and print the answer\n"
          "  pic -p TEXT [@FILE]...     Pi's print mode: one prompt, the answer on stdout\n"
          "  pic chat                   a plain line prompt\n"
          "  pic --mode rpc             Pi's RPC mode: JSONL commands on stdin\n"
          "  pic bash COMMAND           run and journal a command, as ! does in the terminal\n"
          "  pic attach [-i] [-c | --session ID] [--format text]   watch (and steer) a running conversation\n"
          "  pic send [--session ID] steer TEXT   steer a conversation run elsewhere (or follow_up, abort)\n"
          "  pic remote-control | rc [--session ID] [--ssh | --link]   open it on a paired phone (or over ssh)\n"
          "  pic remote [pair | devices | status | stop | install | unpair ID | ...]   phones, the relay\n"
          "\n"
          "  pic sessions | log [ID] | name ID NAME | fork ID --at ENTRY | compact [ID]\n"
          "  pic export --html ID | export --pi [DIR] | import PATH | import --claude PATH\n"
          "  pic models [--all] | models --default NAME | scoped-models --set PATTERN...\n"
          "  pic endpoints | endpoints add NAME URL [--key] | endpoints refresh | endpoints remove NAME\n"
          "  pic auth login PROVIDER [--api-key] [--no-browser] | auth logout PROVIDER | auth status [--check]\n"
          "  pic auth rekey SOURCE      move the store's key: keychain, file or passphrase\n"
          "  pic login PROVIDER | logout PROVIDER | keys | auth reset [--yes]\n"
          "  pic settings [KEY [VALUE] | --unset KEY] | trust [yes | no]\n"
          "  pic prompts | skills | hooks | ps [--all] | usage --by-trial|--by-tool|--lapse | prune | bug TEXT\n"
          "  pic help [TOPIC]           the manual and reference: pic help lists the topics\n"
          "\n"
          "options:\n"
          "  --model MODEL              provider/id, e.g. anthropic/claude-opus-5-5\n"
          "  --thinking LEVEL           off, minimal, low, medium, high, xhigh, max\n"
          "  --workspace DIR            the workspace (default: the current directory)\n"
          "  --json                     Pi's JSON events on stdout\n"
          "  --system-prompt TEXT|FILE  replace the system prompt (--append-system-prompt adds)\n"
          "  --tools LIST               only these tools, or +name/-name to change the default\n"
          "\n"
          "Every command and flag: pic help cli. Settings: pic help settings. Keys: pic help keys.\n",
          out);
}

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

static const char default_model[] = "anthropic/claude-sonnet-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 that
 * worked, else one not known to fail, else any. Where Pi starts on a costly
 * coding model (OpenRouter, Moonshot) or its provider's dearest (DeepSeek, Anthropic),
 * pic starts on an inexpensive general one (docs/manual/differences-from-pi.md). */
static const char *const default_per_provider[][2] = {
    {"amazon-bedrock", "us.anthropic.claude-opus-5-5"},
    {"ant-ling", "Ring-2.6-1T"},
    {"anthropic", "claude-sonnet-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-flash"},
    {"google", "gemini-4-argon"},
    {"google-vertex", "gemini-4-argon"},
    {"github-copilot", "gpt-6.1-sol"},
    {"openrouter", "deepseek/deepseek-v4.1-flash"},
    {"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.6"},
    {"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 whose key worked, else one not known to fail, else any with a
 * key; else the first model with a key (catalog, then the models file);
 * else pic's own default, whose error then names the key. WHY says which,
 * in a few words ("OPENROUTER_API_KEY is set; anthropic's key was refused"). */
static void initial_model(char *out, size_t cap, char *why, size_t whycap) {
    char *def = setting("defaultModel");
    pic_model m;
    char err[PIC_ERR_CAP], how[160], what[64], skipped[200] = "";
    size_t best = (size_t)-1;
    int best_standing = KEY_NONE;
    why[0] = '\0';
    if (def && *def && pic_model_resolve(def, &m, err, sizeof err) == 0 && pic_model_available(m.provider)) {
        (void)snprintf(out, cap, "%s", def);
        char *last = setting("lastModel");
        const char *source = last && strcmp(last, def) == 0 ? "your last choice" : "your saved default";
        if (key_standing(m.provider, how, sizeof how, what, sizeof what, NULL) == KEY_FAILED) {
            (void)snprintf(why, whycap, "%s; its key %s last time", source, what);
        } else {
            (void)snprintf(why, whycap, "%s", source);
        }
        free(last);
        free(def);
        return;
    }
    free(def);
    for (size_t i = 0; i < sizeof default_per_provider / sizeof default_per_provider[0] && best_standing != KEY_WORKS; i++) {
        char *found;
        int standing = key_standing(default_per_provider[i][0], NULL, 0, what, sizeof what, NULL);
        if (standing <= best_standing || !(found = pic_catalog_find(default_per_provider[i][0], default_per_provider[i][1]))) {
            if (standing == KEY_FAILED && !skipped[0]) {
                (void)snprintf(skipped, sizeof skipped, "; %s's key %s", default_per_provider[i][0], what);
            }
            continue;
        }
        free(found);
        if (standing == KEY_FAILED && !skipped[0]) {
            (void)snprintf(skipped, sizeof skipped, "; %s's key %s", default_per_provider[i][0], what);
        }
        best = i;
        best_standing = standing;
    }
    if (best != (size_t)-1) {
        (void)snprintf(out, cap, "%s/%s", default_per_provider[best][0], default_per_provider[best][1]);
        (void)key_standing(default_per_provider[best][0], how, sizeof how, what, sizeof what, NULL);
        if (best_standing == KEY_FAILED) { /* every key failed: this one anyway, and said */
            (void)snprintf(why, whycap, "%s; its key %s last time", how, what);
        } else {
            (void)snprintf(why, whycap, "%s%s", how, skipped);
        }
        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]) {
        char *slash = strchr(out, '/');
        char provider[PIC_CRED_PROVIDER_CAP];
        (void)snprintf(provider, sizeof provider, "%.*s", slash ? (int)(slash - out) : 0, out);
        (void)key_standing(provider, how, sizeof how, what, sizeof what, NULL);
        (void)snprintf(why, whycap, "%s", how[0] ? how : "the first model with a key");
        return;
    }
    (void)snprintf(out, cap, "%s", default_model);
    (void)snprintf(why, whycap, "no key yet");
}

/* Why this run's model is the one it is (initial_model's words, or "from --model"). */
static char model_why[320];

/* MODEL as provider/id, when its provider has a key: 1, else 0. */
static int model_with_key(const char *model, char *out, size_t cap) {
    pic_model m;
    char err[PIC_ERR_CAP];
    if (pic_model_resolve(model, &m, err, sizeof err) != 0 || !pic_model_available(m.provider)) {
        return 0;
    }
    (void)snprintf(out, cap, "%s/%s", m.provider, m.id);
    return 1;
}

/* ask and -p: the model and why, on stderr, when pic chose it; nothing for
 * --model (the person named it), JSON or a terminal's child, and nothing when
 * its provider has no key (the request's own error says how to get one). */
static void model_notice(const char *model) {
    char name[256];
    if (json_events || main_commands || strcmp(model_why, "from --model") == 0 ||
        !model_with_key(model, name, sizeof name)) {
        return;
    }
    fprintf(stderr, "pic: model %s (%s; --model or pic models --default to change)\n", name, model_why);
}

/* --key: the provider MODEL resolves to uses that key for this run, or nothing runs. 0, or -1 said. */
static int apply_key_opt(const char *model) {
    pic_model km;
    char why[256];
    if (pic_model_resolve(model, &km, why, sizeof why) != 0) {
        fprintf(stderr, "pic: --key: %s\n", why);
        return -1;
    }
    if (!pic_cred_has(km.provider, key_opt, km.key_env, km.key_literal)) {
        fprintf(stderr, "pic: no key \"%s\" for %s (pic auth status lists its keys)\n", key_opt, km.provider);
        return -1;
    }
    if (pic_cred_override(km.provider, key_opt) != 0) {
        fprintf(stderr, "pic: --key: cannot keep \"%s\" for %s\n", key_opt, km.provider);
        return -1;
    }
    return 0;
}

static const char *model_flag; /* --model, as given; NULL without one */

/* -p and ask going on with SESSION (NULL: a new conversation): with no --model, the conversation's
 * own model, key and thinking level, said on stderr; a model or key that cannot be had now stops
 * the run with one line naming it and the way on, never another model in its place. Then --key,
 * and the notice of a model pic chose. 0, or -1 said. */
static int resume_choice(pic_store *s, const char *session, const char **model) {
    static char own[200], level[16];
    char label[PIC_CRED_LABEL_CAP], why[400], named[PIC_CRED_LABEL_CAP + 16] = "";
    int found = model_flag || !session ? 0 : pic_session_choice(s, session, own, sizeof own, level, sizeof level, label, sizeof label);
    if (found < 0) {
        fprintf(stderr, "pic: %s\n", s->err);
        return -1;
    }
    if (found == 1) {
        pic_model m;
        char err[PIC_ERR_CAP];
        pic_cred_used inuse;
        int bad = pic_model_usable(own, key_opt ? NULL : label, why, sizeof why);
        if (bad != PIC_MODEL_USABLE) {
            fprintf(stderr, "pic: %s; %s\n", why,
                    bad == PIC_MODEL_KEY_GONE ? "pic auth status lists its keys, or --key LABEL goes on with another"
                    : bad == PIC_MODEL_NO_KEY ? "pic auth login adds one, or --model NAME goes on with another"
                                              : "--model NAME goes on with another");
            return -1;
        }
        *model = own;
        (void)snprintf(model_why, sizeof model_why, "this conversation's own");
        if (!thinking_opt && level[0]) {
            thinking_opt = level;
        }
        if (!key_opt && label[0] && pic_model_resolve(own, &m, err, sizeof err) == 0) {
            /* named when it is not the one the provider would use anyway */
            if (pic_cred_active(m.provider, m.key_env, m.key_literal, &inuse) != 0 || strcmp(inuse.label, label) != 0) {
                (void)snprintf(named, sizeof named, ", key \"%s\"", label);
            }
            if (pic_cred_override(m.provider, label) != 0) {
                fprintf(stderr, "pic: cannot keep the key \"%s\" for %s\n", label, m.provider);
                return -1;
            }
        }
    }
    if (key_opt && !model_flag && apply_key_opt(*model) != 0) {
        return -1;
    }
    if (found != 1) {
        model_notice(*model);
    } else if (!json_events && !main_commands) {
        fprintf(stderr, "pic: model %s%s (%s; --model to change)\n", *model, named, model_why);
    }
    return 0;
}

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

/* On stderr, once, what the skill listing's budget cuts for a model with WINDOW
 * tokens of context: nothing when it all fits. The terminal's children are
 * silent (the terminal shows it itself, as a notice). */
static void skills_budget_warning(const char *workspace, long window) {
    static int done;
    pic_skills skills;
    char *listing, *warning = NULL;
    if (done || main_commands) {
        return;
    }
    done = 1;
    if (load_skills(&skills, workspace, NULL) == 0) {
        listing = pic_skills_prompt(&skills, window, &warning);
        if (warning) {
            fprintf(stderr, "pic: %s\n", warning);
        }
        free(listing);
        free(warning);
        pic_skills_free(&skills);
    }
}

/* PROVIDER resolved as a provider pic knows into m: 0, or 1 with the error printed. */
static int known_provider(const char *provider, pic_model *m) {
    char err[256], name[128];
    (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;
    }
    return 0;
}

/* A key typed with echo off after PROMPT on a terminal, else a line of stdin: its length, or
 * -1 with err. */
static long read_key(const char *prompt, char *key, size_t cap, char *err, size_t errcap) {
    long n;
    if (isatty(STDIN_FILENO)) {
        n = pic_tty_secret(prompt, key, cap, err, errcap);
    } 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 < cap && ((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 < cap ? (long)got : -1;
        if (n < 0) {
            (void)snprintf(err, errcap, "the key is longer than %zu bytes", cap - 1);
        } else {
            while (n > 0 && (key[n - 1] == '\r' || key[n - 1] == ' ' || key[n - 1] == '\t')) {
                n--;
            }
            key[n] = '\0';
        }
    }
    return n;
}

/* 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`. */
static int add_key(const char *provider, const char *label, const char *key, int use, int *changed, int *in_use, char *err,
                   size_t errcap);
static char *added_json(const char *provider, const char *label, int changed, int in_use);
static char *credentials_json(const char *only, int checked);
static int run_checks(const char *only, int active_only);
static void active_label(const pic_model *m, char *out, size_t cap);
static void json_text(FILE *out, const char *v);
/* --json on an auth command: one JSON object on stdout instead of the sentences. */
static int auth_json;

static int key_login(const char *provider, const char *label, const pic_model *mp) {
    char key[2 * PIC_CRED_KEY_CAP], err[256], prompt[160];
    pic_model m = *mp;
    long n;
    int rc;
    if (label) {
        (void)snprintf(prompt, sizeof prompt, "API key \"%s\" for %s: ", label, provider);
    } else {
        (void)snprintf(prompt, sizeof prompt, "API key for %s: ", provider);
    }
    n = read_key(prompt, key, sizeof key, err, sizeof err);
    if (n < 0) {
        pic_cred_wipe(key, sizeof key);
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    if (auth_json) { /* the same key again changes nothing, and says so */
        int changed, in_use;
        char *json;
        rc = add_key(provider, label, key, 0, &changed, &in_use, err, sizeof err);
        pic_cred_wipe(key, sizeof key);
        if (rc != 0 || !(json = added_json(provider, label, changed, in_use))) {
            fprintf(stderr, "pic: %s\n", rc ? err : "out of memory");
            return 1;
        }
        puts(json);
        free(json);
        return 0;
    }
    rc = pic_cred_login_as(provider, label, key, err, sizeof err);
    pic_cred_wipe(key, sizeof key);
    if (rc != 0) {
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    if (label) {
        pic_cred_used now;
        printf("Saved the API key \"%s\" for %s, sealed, in ~/.pic/pic.sqlite.\n", label, provider);
        if (pic_cred_active(provider, m.key_env, m.key_literal, &now) == 0 && strcmp(now.label, label) != 0) {
            printf("Requests use \"%s\"; pic auth use %s %s makes this one active.\n", now.label, provider, label);
        }
    } else {
        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 also set; the stored key is used (pic auth use %s env picks the variable).\n", m.key_env, provider);
    }
    return 0;
}

/* SIGTERM and SIGINT for the terminal interface's sign-in child: the wait
 * gives up, the callback listener is closed and the child exits. */
static void on_cancel(int sig) {
    (void)sig;
    pic_interrupted = 1;
}

/* PROVIDER's subscription sign-in on this terminal (FLAGS: PIC_CRED_NO_BROWSER),
 * or through pipes for the terminal interface (PIC_CRED_PIPE). */
static int sign_in(const char *provider, const pic_model *m, int flags) {
    char err[512];
    if (flags & PIC_CRED_PIPE) {
        struct sigaction sa;
        memset(&sa, 0, sizeof sa);
        sa.sa_handler = on_cancel; /* no SA_RESTART: blocked waits return */
        sigemptyset(&sa.sa_mask);
        (void)sigaction(SIGTERM, &sa, NULL);
        (void)sigaction(SIGINT, &sa, NULL);
    } else if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO)) {
        fprintf(stderr, "pic: signing in to %s needs a terminal (pic auth login %s --api-key reads a key from stdin)\n",
                provider, provider);
        return 1;
    }
    if (pic_cred_oauth_login(provider, flags, err, sizeof err) != 0) {
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    printf("Signed in to %s (%s). The sign-in is sealed in ~/.pic/pic.sqlite.\n", provider, pic_cred_oauth_label(provider));
    if (m->key_env[0] && getenv(m->key_env) && *getenv(m->key_env)) {
        printf("%s is also set; the sign-in is used (pic auth use %s env picks the variable).\n", m->key_env, provider);
    }
    return 0;
}

/* A key's label from --as: checked, or NULL with the error shown. */
static const char *as_label(const char *label) {
    char err[200];
    if (strcmp(label, "default") == 0) {
        return NULL;
    }
    if (pic_cred_label_check(label, err, sizeof err) != 0) {
        fprintf(stderr, "pic: --as: %s\n", err);
        return "";
    }
    return label;
}

/* pic login PROVIDER [--as LABEL]: on a terminal, a provider with a
 * subscription sign-in offers it beside an API key; otherwise the key. */
static int login_command(int argc, char **argv) {
    pic_model m;
    const char *label, *provider = argc >= 1 ? argv[0] : NULL, *as = NULL;
    if (argc == 3 && strcmp(argv[1], "--as") == 0) {
        if ((as = as_label(argv[2])) && !*as) {
            return 2;
        }
    } else if (argc != 1) {
        fputs("usage: pic login PROVIDER [--as LABEL]\n", stderr);
        return 2;
    }
    if (known_provider(provider, &m) != 0) {
        return 1;
    }
    label = pic_cred_oauth_label(provider);
    if (label && !as && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
        char answer[16], err[128];
        printf("How do you want to log in to %s?\n  1. %s\n  2. Paste an API key\n", provider, label);
        for (;;) {
            long n;
            printf("Select 1-2: ");
            (void)fflush(stdout);
            if (!fgets(answer, sizeof answer, stdin)) {
                return 1;
            }
            n = strtol(answer, NULL, 10);
            if (n == 1) {
                return sign_in(provider, &m, 0);
            }
            if (n == 2) {
                return key_login(provider, NULL, &m);
            }
            (void)snprintf(err, sizeof err, "Enter 1 or 2.");
            puts(err);
        }
    }
    return key_login(provider, as, &m);
}

/* pic auth login PROVIDER [--api-key] [--as LABEL] [--no-browser], as Pi's:
 * account sign-in unless --api-key asks for a key; a provider without one
 * takes a key. --as names an extra API key. */
static int auth_login(int argc, char **argv) {
    const char *provider = NULL, *as = NULL;
    int api_key = 0, flags = 0, named = 0;
    pic_model m;
    for (int k = 0; k < argc; k++) {
        if (strcmp(argv[k], "--api-key") == 0) {
            api_key = 1;
        } else if (strcmp(argv[k], "--json") == 0) {
            auth_json = 1;
        } else if (strcmp(argv[k], "--no-browser") == 0) {
            flags |= PIC_CRED_NO_BROWSER;
        } else if (strcmp(argv[k], "--pipe") == 0) {
            flags |= PIC_CRED_PIPE;
        } else if (strcmp(argv[k], "--as") == 0 && k + 1 < argc) {
            named = 1;
            if ((as = as_label(argv[++k])) && !*as) {
                return 2;
            }
        } else if (argv[k][0] == '-' || provider) {
            provider = NULL;
            break;
        } else {
            provider = argv[k];
        }
    }
    if (!provider) {
        fputs("usage: pic auth login PROVIDER [--api-key] [--as LABEL] [--no-browser]\n", stderr);
        return 2;
    }
    if (api_key && (flags & PIC_CRED_NO_BROWSER)) {
        fputs("pic: --no-browser only applies to signing in; leave it out with --api-key\n", stderr);
        return 2;
    }
    if (known_provider(provider, &m) != 0) {
        return 1;
    }
    if (as && !api_key && pic_cred_oauth_label(provider)) {
        fprintf(stderr, "pic: --as names an API key: pic auth login %s --api-key --as %s\n", provider, as);
        return 2;
    }
    if (flags & PIC_CRED_PIPE && (api_key || named || !pic_cred_oauth_label(provider))) {
        fprintf(stderr, "pic: %s has no subscription sign-in\n", provider);
        return 1;
    }
    if (api_key || named || !pic_cred_oauth_label(provider)) {
        return key_login(provider, as, &m);
    }
    if (auth_json) {
        fputs("pic: --json stores an API key (--api-key); a sign-in is RPC's login\n", stderr);
        return 2;
    }
    return sign_in(provider, &m, flags);
}

/* pic logout PROVIDER[:LABEL]: the provider's own key or sign-in, or its key LABEL. */
static int logout_command(const char *name) {
    char provider[128], *colon;
    pic_cred_source was;
    int rc;
    (void)snprintf(provider, sizeof provider, "%s", name);
    if ((colon = strchr(provider, ':'))) {
        *colon = '\0';
        if (strcmp(colon + 1, "default") == 0) {
            name = provider;
            colon = NULL;
        }
    }
    was = colon ? PIC_CRED_STORED_KEY : pic_cred_stored(provider) ? pic_cred_source_of(provider, NULL, NULL) : PIC_CRED_NONE;
    rc = pic_cred_logout(name);
    if (rc < 0) {
        fputs("pic: cannot write ~/.pic/pic.sqlite\n", stderr);
        return 1;
    }
    if (auth_json) {
        fputs("{\"provider\":", stdout);
        json_text(stdout, provider);
        fputs(",\"label\":", stdout);
        json_text(stdout, colon ? colon + 1 : "default");
        printf(",\"removed\":%s}\n", rc ? "true" : "false");
        return 0;
    }
    if (colon) {
        printf(rc ? "Removed the API key \"%s\" for %s.\n" : "No key named \"%s\" is stored for %s.\n", colon + 1, provider);
        return 0;
    }
    printf(!rc ? "No stored credentials for %s. Environment variables and models.json config are unchanged.\n"
           : was == PIC_CRED_STORED_OAUTH
               ? "Removed the sign-in for %s. Environment variables and models.json config are unchanged.\n"
               : "Removed the stored API key for %s. Environment variables and models.json config are unchanged.\n",
           provider);
    return 0;
}

/* pic auth reset [--yes]: the way out of a forgotten passphrase. Forgets the master key and
 * every row sealed under it (cred.h, pic_cred_reset), after asking on the terminal; with no
 * terminal, only with --yes. */
static int reset_command(int argc, char **argv) {
    char err[256];
    if (argc > 1 || (argc == 1 && strcmp(argv[0], "--yes") != 0)) {
        return usage();
    }
    if (argc == 0) {
        FILE *tty = fopen("/dev/tty", "r+");
        char answer[16] = "";
        int yes;
        if (!tty) {
            fputs("pic: auth reset forgets every stored key, sign-in and paired phone; with no terminal to ask on, pass"
                  " --yes\n",
                  stderr);
            return 1;
        }
        fputs("Forget the credential store's passphrase and every key, sign-in and paired phone sealed under it?\n"
              "Settings, sessions and trust stay. [y/N] ",
              tty);
        (void)fflush(tty);
        yes = fgets(answer, sizeof answer, tty) && (answer[0] == 'y' || answer[0] == 'Y');
        (void)fclose(tty);
        if (!yes) {
            puts("Nothing was changed.");
            return 0;
        }
    }
    if (pic_cred_reset(err, sizeof err) != 0) {
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    puts("Forgot the credential store. `pic login PROVIDER` sets a new passphrase; phones pair again with"
         " `pic remote pair`.");
    return 0;
}

/* pic auth use PROVIDER LABEL: requests to PROVIDER use its key LABEL from now on. */
static int use_command(const char *provider, const char *label) {
    pic_model m;
    char err[256];
    char before[PIC_CRED_LABEL_CAP];
    if (known_provider(provider, &m) != 0) {
        return 1;
    }
    active_label(&m, before, sizeof before);
    if (pic_cred_use(provider, label, m.key_env, m.key_literal, err, sizeof err) != 0) {
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    if (auth_json) {
        fputs("{\"provider\":", stdout);
        json_text(stdout, provider);
        fputs(",\"label\":", stdout);
        json_text(stdout, label);
        printf(",\"changed\":%s}\n", strcmp(before, label) != 0 ? "true" : "false");
        return 0;
    }
    printf("Requests to %s use the key \"%s\".\n", provider, label);
    return 0;
}

/* The provider whose variable VAR is, or whose variable VAR extends
 * (ANTHROPIC_API_KEY_2): the longest such. */
typedef struct {
    const char *var;
    char provider[64];
    size_t best;
} import_find;

static int import_match(void *ctx, const char *provider) {
    import_find *f = ctx;
    pic_model m;
    char err[256], name[128];
    size_t n;
    (void)snprintf(name, sizeof name, "%s/x", provider);
    if (pic_model_resolve(name, &m, err, sizeof err) != 0 || !m.key_env[0]) {
        return 0;
    }
    n = strlen(m.key_env);
    if (n > f->best && strncmp(f->var, m.key_env, n) == 0 && (f->var[n] == '\0' || f->var[n] == '_')) {
        (void)snprintf(f->provider, sizeof f->provider, "%s", provider);
        f->best = n;
    }
    return 0;
}

/* pic auth import VAR [PROVIDER] [--as LABEL]: seals the variable's value once. */
static int import_command(int argc, char **argv) {
    const char *var = NULL, *provider = NULL, *as = NULL, *value;
    char err[256], row[PIC_CRED_NAME_CAP];
    import_find f = {NULL, "", 0};
    pic_model m;
    int force = 0;
    size_t en;
    for (int k = 0; k < argc; k++) {
        if (strcmp(argv[k], "--force") == 0) {
            force = 1;
        } else if (strcmp(argv[k], "--as") == 0 && k + 1 < argc) {
            if ((as = as_label(argv[++k])) && !*as) {
                return 2;
            }
        } else if (argv[k][0] == '-' || (var && provider)) {
            var = NULL;
            break;
        } else if (!var) {
            var = argv[k];
        } else {
            provider = argv[k];
        }
    }
    if (!var) {
        fputs("usage: pic auth import VAR [PROVIDER] [--as LABEL] [--force]\n", stderr);
        return 2;
    }
    if (!provider) {
        f.var = var;
        (void)pic_providers_each(import_match, &f);
        if (!f.provider[0]) {
            fprintf(stderr, "pic: no provider reads %s: name it (pic auth import %s PROVIDER)\n", var, var);
            return 2;
        }
        provider = f.provider;
    }
    if (known_provider(provider, &m) != 0) {
        return 1;
    }
    /* A variable that is not the provider's own (or a variant: ANTHROPIC_API_KEY_2) is likely a mistake (PATH, a token for something else). */
    en = strlen(m.key_env);
    if (!force && (!en || strncmp(var, m.key_env, en) != 0 || (var[en] != '\0' && var[en] != '_'))) {
        fprintf(stderr, "pic: %s is not the variable %s reads (%s): add --force to seal it anyway\n", var, provider,
                en ? m.key_env : "none");
        return 2;
    }
    value = getenv(var);
    if (!value || !*value) {
        fprintf(stderr, "pic: %s is not set\n", var);
        return 1;
    }
    (void)snprintf(row, sizeof row, as ? "%s:%s" : "%s", provider, as ? as : "");
    if (pic_cred_stored(row)) {
        fprintf(stderr, as ? "pic: %s already has a key named \"%s\": pic auth logout %s:%s first\n"
                           : "pic: %s already has its own key%s: name this one with --as LABEL\n",
                provider, as ? as : "", provider, as ? as : "");
        return 1;
    }
    if (pic_cred_login_as(provider, as, value, err, sizeof err) != 0) {
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    printf("Sealed %s as the key \"%s\" for %s in ~/.pic/pic.sqlite; the variable can go.\n", var, as ? as : "default",
           provider);
    return 0;
}

/* ---- pic auth status: every key of every provider, with what pic knows of it */

typedef struct {
    int n;
    int stored_active; /* the provider's key in use is a stored one */
    long long now;
    int stored; /* stored credentials seen */
    const char *only; /* just this provider's keys; NULL: all */
} status_ctx;

static int status_entry(void *ctx, const pic_cred_entry *e) {
    status_ctx *c = ctx;
    char label[48], how[64], state[160];
    pic_key_health h;
    (void)snprintf(label, sizeof label, "%s%s", e->label, e->active ? "*" : "");
    if (strcmp(e->kind, "oauth") == 0) {
        const char *sign = pic_cred_oauth_label(e->provider);
        (void)snprintf(how, sizeof how, "%s", sign ? sign : "subscription sign-in");
    } else if (strcmp(e->kind, "env") == 0) {
        (void)snprintf(how, sizeof how, "%s", e->env);
    } else if (strcmp(e->kind, "file") == 0) {
        (void)snprintf(how, sizeof how, "models.json apiKey");
    } else {
        (void)snprintf(how, sizeof how, "API key");
    }
    (void)pic_cred_health_of(e->name, &h);
    if (!e->active && c->stored_active && (strcmp(e->kind, "env") == 0 || strcmp(e->kind, "file") == 0)) {
        (void)snprintf(state, sizeof state, "not used: a stored key wins");
    } else {
        pic_keyhealth_phrase(&h, c->now, state, sizeof state);
    }
    printf("%-12s %-10s %-22s %s\n", e->provider, label, how, state);
    c->n++;
    return 0;
}

static int status_provider(void *ctx, const char *provider) {
    status_ctx *c = ctx;
    pic_model m;
    char err[256], name[128];
    pic_cred_source src;
    if (c->only && strcmp(c->only, provider) != 0) {
        return 0;
    }
    (void)snprintf(name, sizeof name, "%s/x", provider);
    if (pic_model_resolve(name, &m, err, sizeof err) != 0) {
        return 0;
    }
    src = pic_cred_source_of(provider, m.key_env, m.key_literal);
    c->stored_active = src == PIC_CRED_STORED_KEY || src == PIC_CRED_STORED_OAUTH;
    (void)pic_cred_entries(provider, m.key_env, m.key_literal, status_entry, c);
    if (src == PIC_CRED_NONE && pic_cred_stored(provider) == 0) {
        char why[200];
        pic_cred_describe(provider, m.key_env, m.key_literal, why, sizeof why);
        if (strcmp(why, "none") != 0) { /* a chosen key it does not have */
            printf("%-12s %-10s %-22s %s\n", provider, "-", "", why);
        }
    }
    return 0;
}

/* Stored rows of providers pic does not know (a provider gone from the
 * catalog): listed too, so they can be removed. */
static int status_orphan(void *ctx, const char *name, const char *kind, long long created_ms, long long used_ms) {
    status_ctx *c = ctx;
    char provider[128], probe[160], err[256];
    pic_model m;
    (void)kind;
    (void)created_ms;
    (void)used_ms;
    c->stored++;
    (void)snprintf(provider, sizeof provider, "%.*s", (int)strcspn(name, ":"), name);
    if (c->only && strcmp(c->only, provider) != 0) {
        return 0;
    }
    (void)snprintf(probe, sizeof probe, "%s/x", provider);
    if (pic_model_resolve(probe, &m, err, sizeof err) != 0 || strcmp(m.provider, provider) != 0) {
        printf("%-12s %-10s %-22s %s\n", provider, strchr(name, ':') ? strchr(name, ':') + 1 : "default", "API key",
               "unknown provider");
        c->n++;
    }
    return 0;
}

/* pic auth status [--check | --refresh] [--active] [PROVIDER]: the table of keys; with --check
 * every key is first asked its provider's free check, with --refresh only those not checked in
 * ten minutes, and without ever asking for the passphrase (what the terminal interface runs). */
static int auth_status(int argc, char **argv) {
    status_ctx c = {0, 0, (long long)(pic_platform_get()->wall_ns() / 1000000), 0, NULL};
    pic_keyprobe_opts probe;
    int check = 0;
    memset(&probe, 0, sizeof probe);
    for (int i = 0; i < argc; i++) {
        if (strcmp(argv[i], "--check") == 0) {
            check = probe.force = 1;
        } else if (strcmp(argv[i], "--refresh") == 0) {
            check = probe.no_prompt = 1;
        } else if (strcmp(argv[i], "--active") == 0) {
            probe.active_only = 1;
        } else if (strcmp(argv[i], "--json") == 0) {
            auth_json = 1;
        } else if (argv[i][0] != '-' && !c.only) {
            c.only = probe.provider = argv[i];
        } else {
            fprintf(stderr, "pic: auth status [--check | --refresh] [--active] [PROVIDER]: unknown argument %s\n", argv[i]);
            return 2;
        }
    }
    if (probe.active_only && !check) {
        fputs("pic: --active needs --check or --refresh\n", stderr);
        return 2;
    }
    if (!pic_userdb(NULL, 0)) {
        fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr);
        return 1;
    }
    if (auth_json) { /* get_credentials's answer, or check_credentials's with --check */
        int n = check ? (probe.force ? run_checks(c.only, probe.active_only) : pic_keyprobe(&probe)) : -1;
        char *json;
        if (check && n < 0) {
            fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr);
            return 1;
        }
        if (!(json = credentials_json(c.only, n))) {
            fputs("pic: out of memory\n", stderr);
            return 1;
        }
        puts(json);
        free(json);
        return 0;
    }
    if (check && pic_keyprobe(&probe) < 0) {
        fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr);
        return 1;
    }
    c.now = (long long)(pic_platform_get()->wall_ns() / 1000000);
    (void)pic_providers_each(status_provider, &c);
    c.stored = 0;
    (void)pic_cred_each(status_orphan, &c);
    if (c.stored == 0) {
        puts("No stored credentials (pic auth login PROVIDER signs in or stores a key).");
    }
    return 0;
}

static int print_key(void *ctx, const char *name, const char *kind, 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)kind;
    (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;
}

/* pic auth rekey keychain|file|passphrase: moves the store's key, resealing every row. */
static int rekey_command(const char *target) {
    char err[512] = "", source[32] = "";
    int skipped = 0, rc;
    if (!*target || strspn(target, "abcdefghijklmnopqrstuvwxyz0123456789-") != strlen(target)) {
        fputs("usage: pic auth rekey keychain|file|passphrase\n", stderr); /* the platform names its sources */
        return 2;
    }
    pic_cred_offer_register(NULL); /* the passphrase typed here is the one being moved off */
    rc = pic_cred_rekey(target, source, sizeof source, &skipped, err, sizeof err);
    if (rc < 0) {
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    if (strcmp(source, "passphrase") == 0) {
        puts(rc == 2 ? "The credential store's key already comes from a passphrase."
                     : "The credential store's key now comes from a passphrase, asked when a stored key is needed.");
    } else {
        printf(rc == 2 ? "The credential store's key is already in %s.\n" : "The credential store's key is now in %s.\n",
               pic_host_where(source));
    }
    if (skipped) {
        printf("%d sealed row%s did not open under the old key either and %s left as %s.\n", skipped, skipped == 1 ? "" : "s",
               skipped == 1 ? "was" : "were", skipped == 1 ? "it was" : "they were");
    }
    return 0;
}

/* Right after a passphrase typed at the terminal opened the store: asked once, a no remembered. */
static void offer_keeper(void) {
    char prompt[200], yn[16] = "", err[512] = "", source[32] = "";
    int skipped = 0;
    long n;
    (void)snprintf(prompt, sizeof prompt, "Stop asking for this passphrase? pic can keep the key in %s. [y/N] ",
                   pic_host_where(NULL));
    n = pic_tty_answer(prompt, yn, sizeof yn);
    if (n < 0) {
        return; /* no terminal after all: asked another time */
    }
    pic_cred_offer_answer(yn[0] == 'y' || yn[0] == 'Y');
    if (yn[0] != 'y' && yn[0] != 'Y') {
        return;
    }
    if (pic_cred_rekey(NULL, source, sizeof source, &skipped, err, sizeof err) < 0) {
        fprintf(stderr, "pic: the key stays behind the passphrase: %s\n", err);
    } else {
        fprintf(stderr, "pic: the credential store's key is now in %s (pic auth rekey passphrase goes back).\n",
                pic_host_where(source));
    }
}

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(argc - 1, argv + 1);
    }
    if (strcmp(argv[0], "logout") == 0 && argc == 2) {
        return logout_command(argv[1]);
    }
    if (strcmp(argv[0], "auth") == 0 && argc >= 2 && strcmp(argv[1], "login") == 0) {
        return auth_login(argc - 2, argv + 2);
    }
    if (strcmp(argv[0], "auth") == 0 && (argc == 3 || (argc == 4 && strcmp(argv[3], "--json") == 0)) &&
        strcmp(argv[1], "logout") == 0) {
        auth_json = argc == 4;
        return logout_command(argv[2]);
    }
    if (strcmp(argv[0], "auth") == 0 && argc >= 2 && strcmp(argv[1], "reset") == 0) {
        return reset_command(argc - 2, argv + 2);
    }
    if (strcmp(argv[0], "auth") == 0 && (argc == 4 || (argc == 5 && strcmp(argv[4], "--json") == 0)) &&
        strcmp(argv[1], "use") == 0) {
        auth_json = argc == 5;
        return use_command(argv[2], argv[3]);
    }
    if (strcmp(argv[0], "auth") == 0 && argc >= 3 && strcmp(argv[1], "import") == 0) {
        return import_command(argc - 2, argv + 2);
    }
    if (strcmp(argv[0], "auth") == 0 && argc >= 2 && strcmp(argv[1], "status") == 0) {
        return auth_status(argc - 2, argv + 2);
    }
    if (strcmp(argv[0], "auth") == 0 && argc == 3 && strcmp(argv[1], "rekey") == 0) {
        return rekey_command(argv[2]);
    }
    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. */
/* pic send [--session ID] [--key K] [--expires SECS] [--wait] COMMAND-JSON
 * | prompt|steer|follow_up|abort [TEXT...]: one message into the conversation's
 * inbox, through the narrow open; delivered by the pic running it. */
static int send_message_command(const char *db, int argc, char **argv) {
    const char *session = "latest", *key = NULL, *type = NULL;
    long expires = 0;
    int wait = 0, k = 0, rc;
    char sid[64], got[64], state[16], text[8192] = "";
    char *line = NULL;
    pic_store s;
    pic_inbox_msg m;
    for (; k < argc && argv[k][0] == '-'; k++) {
        if (strcmp(argv[k], "--wait") == 0) {
            wait = 1;
        } else if (k + 1 >= argc) {
            return usage();
        } else if (strcmp(argv[k], "--session") == 0) {
            session = argv[++k];
        } else if (strcmp(argv[k], "--key") == 0) {
            key = argv[++k];
        } else if (strcmp(argv[k], "--expires") == 0) {
            char *end = NULL;
            expires = strtol(argv[++k], &end, 10);
            if (!end || *end || expires < 1 || expires > PIC_INBOX_MAX_SECONDS) {
                fputs("pic: --expires is 1 to 604800 seconds\n", stderr);
                return 2;
            }
        } else {
            return usage();
        }
    }
    if (k >= argc) {
        return usage();
    }
    if (argv[k][0] != '{') {
        type = argv[k];
        if (strcmp(type, "prompt") != 0 && strcmp(type, "steer") != 0 && strcmp(type, "follow_up") != 0 &&
            strcmp(type, "abort") != 0) {
            fprintf(stderr, "pic: send takes prompt, steer, follow_up or abort (or one RPC command as JSON), not %s\n", type);
            return 2;
        }
        for (int j = k + 1; j < argc; j++) {
            size_t n = strlen(text);
            if (n + strlen(argv[j]) + 2 > sizeof text) {
                fputs("pic: the message is too long for the command line; send it as JSON\n", stderr);
                return 2;
            }
            (void)snprintf(text + n, sizeof text - n, "%s%s", n ? " " : "", argv[j]);
        }
        if ((strcmp(type, "abort") == 0) != !text[0]) {
            fputs(strcmp(type, "abort") == 0 ? "pic: abort takes no text\n" : "pic: a prompt, steer or follow-up needs its text\n", stderr);
            return 2;
        }
    } else if (k + 1 != argc) {
        return usage();
    }
    if (pic_open_narrow(&s, db) != 0 || pic_session_resolve(&s, session, sid, sizeof sid) != 0) {
        fprintf(stderr, "pic: %s\n", s.err);
        pic_close(&s);
        return 1;
    }
    if (type) {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s.db, "SELECT json_patch('{}', json_object('type', ?1, 'message', nullif(?2, '')))", -1, &q, NULL) ==
            SQLITE_OK) {
            sqlite3_bind_text(q, 1, type, -1, SQLITE_STATIC);
            sqlite3_bind_text(q, 2, text, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                line = strdup((const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
    }
    memset(&m, 0, sizeof m);
    m.session = sid;
    m.key = key;
    m.line = type ? line : argv[k];
    m.sender = "cli";
    m.expires_s = expires;
    rc = m.line ? pic_inbox_accept(&s, &m, got, sizeof got, state, sizeof state) : -1;
    free(line);
    if (rc != 0) {
        fprintf(stderr, "pic: %s\n", m.line ? s.err : "out of memory");
        pic_close(&s);
        return 1;
    }
    if (!wait) {
        printf("%s %s\n", state, got);
        pic_close(&s);
        return 0;
    }
    for (;;) { /* --wait: until it is delivered, refused or expired; its response line */
        char *response = NULL;
        struct timespec ts = {0, 100000000L};
        rc = pic_inbox_status(&s, got, state, sizeof state, &response);
        if (rc == 0 && strcmp(state, "pending") == 0 && pic_inbox_expire(&s, got) == 0) {
            free(response); /* settled now if its time has passed */
            rc = pic_inbox_status(&s, got, state, sizeof state, &response);
        }
        if (rc != 0 || strcmp(state, "pending") != 0) {
            if (rc == 0) {
                puts(response ? response : state);
            }
            free(response);
            break;
        }
        (void)nanosleep(&ts, NULL);
    }
    pic_close(&s);
    return rc == 0 && strcmp(state, "delivered") == 0 ? 0 : 1;
}

/* pic attach [--session ID | -c] [--from SEQ] [--format json|text] [-i]
 * [--no-follow]. With -i, a line typed while nothing runs starts a request
 * as pic ask --session would, with the --model and --thinking given here. */
static int attach_command(const char *argv0, const char *db, const char *workspace, const char *thinking,
                          const char *key_model, int argc, char **argv) {
    char self[PATH_MAX];
    pic_attach_options o = {db, "latest", -1, 0, 0, 1, self, workspace, model_flag, thinking, key_model};
    self_path(argv0, self, sizeof self);
    for (int k = 0; k < argc; k++) {
        if (strcmp(argv[k], "-c") == 0 || strcmp(argv[k], "--continue") == 0) {
            o.session = "latest";
        } else if (strcmp(argv[k], "-i") == 0) {
            o.interactive = 1;
        } else if (strcmp(argv[k], "--no-follow") == 0) {
            o.follow = 0;
        } else if (k + 1 >= argc) {
            return usage();
        } else if (strcmp(argv[k], "--session") == 0) {
            o.session = argv[++k];
        } else if (strcmp(argv[k], "--from") == 0) {
            char *end = NULL;
            o.from = strcmp(argv[k + 1], "end") == 0 ? (end = argv[k + 1] + 3, -2) : strtoll(argv[k + 1], &end, 10);
            k++;
            if (!end || *end || o.from < -2 || o.from == -1) {
                fputs("pic: --from takes an entry number (0: the whole conversation) or end\n", stderr);
                return 2;
            }
        } else if (strcmp(argv[k], "--format") == 0) {
            k++;
            if (strcmp(argv[k], "text") != 0 && strcmp(argv[k], "json") != 0) {
                fputs("pic: --format is json or text\n", stderr);
                return 2;
            }
            o.text = strcmp(argv[k], "text") == 0;
        } else {
            return usage();
        }
    }
    return pic_attach_main(&o);
}

static void remote_show_qr(const char *text);

/* pic remote-control | rc [--session ID] [--ssh | --link]: what /remote-control shows, on stdout:
 * the phone page's address for the conversation and its QR code, or how to pair a phone; --link
 * the address alone; --ssh the ssh command and its checks. The conversation: --session's, else
 * the latest when there is a journal (none: the command continues the latest, -c). */
static int remote_command(const char *argv0, const char *db, const char *workspace, int argc, char **argv) {
    char self[PATH_MAX], real[PATH_MAX], sid[64] = "", link[2048];
    const char *session = NULL, *ws;
    int ssh = 0, only_link = 0, phones;
    for (int k = 0; k < argc; k++) {
        if (strcmp(argv[k], "--session") == 0 && k + 1 < argc) {
            session = argv[++k];
        } else if (strcmp(argv[k], "--ssh") == 0) {
            ssh = 1;
        } else if (strcmp(argv[k], "--link") == 0) {
            only_link = 1;
        } else {
            return usage();
        }
    }
    if (ssh && only_link) {
        return usage();
    }
    if (!session || *session) { /* --session "": no conversation yet (the terminal's new one) */
        pic_store s;
        struct stat st;
        if (stat(db, &st) == 0 && pic_open_narrow(&s, db) == 0) {
            if (pic_session_resolve(&s, session ? session : "latest", sid, sizeof sid) != 0) {
                sid[0] = '\0';
                if (session) {
                    fprintf(stderr, "pic: %s\n", s.err);
                    pic_close(&s);
                    return 1;
                }
            }
            pic_close(&s);
        } else if (session) {
            (void)snprintf(sid, sizeof sid, "%s", session);
        }
    }
    ws = realpath(workspace, real) ? real : workspace;
    if (ssh) {
        tui_remote r;
        char *page;
        self_path(argv0, self, sizeof self);
        tui_remote_info(&r, self, ws, sid);
        if (!(page = tui_remote_page(&r))) {
            fputs("pic: out of memory\n", stderr);
            return 1;
        }
        fputs(page, stdout);
        free(page);
        return 0;
    }
    phones = pic_remote_link(sid, link, sizeof link);
    if (phones < 0) {
        fputs("pic: the phone's address is too long\n", stderr);
        return 1;
    }
    if (only_link) {
        if (phones == 0) {
            fputs("pic: no phone is paired: pic remote pair\n", stderr);
            return 1;
        }
        puts(link);
        return 0;
    }
    if (phones == 0) {
        puts("No phone is paired yet. Pair one with pic remote pair (or /rc in pic), then run pic rc again.");
        puts("ssh instead: pic rc --ssh");
        return 0;
    }
    puts(sid[0] ? "Open this conversation on your phone: scan the code with its camera, or open the address."
                : "Open pic on your phone: scan the code with its camera, or open the address.");
    remote_show_qr(link);
    puts(link);
    puts(pic_remote_running() ? "pic remote is running." : "pic remote is not running: start it with pic remote (or /rc in pic).");
    return 0;
}

/* pic remote pair's QR code: white on black on a terminal, else dark modules on the page. */
static void remote_show_qr(const char *text) {
    int rows = 0, tty = isatty(STDOUT_FILENO);
    char *qr = tui_remote_qr(text, tty, &rows);
    if (!qr) {
        return;
    }
    if (!tty) {
        fputs(qr, stdout);
    } else {
        for (char *at = qr, *nl; (nl = strchr(at, '\n')) != NULL; at = nl + 1) {
            *nl = '\0';
            printf("\x1b[38;5;231;48;5;16m%s\x1b[0m\n", at);
        }
    }
    free(qr);
}

/* The command table is up in every run, so the inbox (pic send, pic
 * attach) can deliver through it; --mode rpc has started its own. */
static int run_with_commands(pic_store *s, const char *workspace, pic_provider *provider, int exec_seconds) {
    int rc, own = !pic_commands_active();
    if (own) {
        pic_commands_start(s, main_commands ? STDIN_FILENO : -1, expand_template, (void *)(uintptr_t)workspace);
    }
    rc = pic_run(s, workspace, provider, exec_seconds);
    if (own) {
        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, NULL, 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];
        int interrupted = pic_interrupted;
        (void)snprintf(saved, sizeof saved, "%s", s->err);
        pic_interrupted = 0; /* the signal that stopped the request must not stop the hook that tells of it */
        if (pic_hooks_session_end(s, sid, "other") != 0) {
            fprintf(stderr, "pic: warning: SessionEnd hooks: %s\n", s->err);
        }
        pic_interrupted = interrupted;
        (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;
    }
    { /* a sealed key is opened now: a request that cannot have it journals nothing */
        pic_model m;
        if (pic_model_resolve(built_model, &m, s->err, sizeof s->err) != 0 ||
            pic_cred_ready(m.provider, m.key_env, m.key_literal, s->err, sizeof s->err) != 0) {
            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) {
        catch_interrupt_and_term();
    }
    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;
    }
    skills_budget_warning(workspace, provider.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 (*on_admitted)(void *ctx), void *ctx) {
    const char *saved = thinking_opt;
    int rc;
    thinking_opt = thinking;
    ask_new_id = new_id;
    ask_admitted = on_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_key_ready(const char *model, char *provider, size_t pcap, char *err, size_t errcap) {
    pic_model m;
    int rc;
    if (pic_model_resolve(model, &m, err, errcap) != 0) {
        return 0; /* the prompt reports it */
    }
    rc = pic_cred_ready(m.provider, m.key_env, m.key_literal, err, errcap);
    (void)snprintf(provider, pcap, "%s", m.provider);
    return rc == PIC_CRED_NO_TTY ? 1 : 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. */
/* pic rewind [ID] --to ENTRY [--files | --conversation] [--force-partial] [--json],
 * pic rewind [ID] --undo [--force-partial] [--json], pic rewind [ID] --list.
 * 0; 3 when files were refused and nothing was done; 2 for a usage error; -1. */
static int rewind_command(pic_store *s, const char *workspace, int argc, char **argv) {
    const char *session = "latest";
    char real[PATH_MAX];
    long long to = 0;
    int mode = PIC_REWIND_BOTH, force = 0, json = 0, list = 0, undo = 0, rc;
    pic_rewind_report r;
    for (int j = 0; j < argc; j++) {
        if (strcmp(argv[j], "--to") == 0 && j + 1 < argc) {
            to = strtoll(argv[++j], NULL, 10);
        } else if (strcmp(argv[j], "--files") == 0 && mode == PIC_REWIND_BOTH) {
            mode = PIC_REWIND_FILES;
        } else if (strcmp(argv[j], "--conversation") == 0 && mode == PIC_REWIND_BOTH) {
            mode = PIC_REWIND_CONVERSATION;
        } else if (strcmp(argv[j], "--force-partial") == 0) {
            force = 1;
        } else if (strcmp(argv[j], "--json") == 0) {
            json = 1;
        } else if (strcmp(argv[j], "--list") == 0) {
            list = 1;
        } else if (strcmp(argv[j], "--undo") == 0) {
            undo = 1;
        } else if (j == 0 && argv[j][0] != '-') {
            session = argv[j];
        } else {
            return 2;
        }
    }
    if (list + undo + (to > 0) != 1 || (undo && mode != PIC_REWIND_BOTH)) {
        return 2;
    }
    if (list) {
        return pic_rewind_points(s, session, stdout);
    }
    rc = undo ? pic_rewind_undo(s, session, force, &r) : pic_rewind(s, session, to, mode, force, &r);
    if (rc == 0) {
        pic_rewind_print(&r, realpath(workspace, real) ? real : workspace, json, stdout);
        rc = r.applied ? 0 : 3;
    }
    pic_rewind_report_free(&r);
    return rc;
}

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], "--session-id") == 0 && !session && i + 2 < argc && valid_session_id(argv[i + 1])) {
            ask_new_id = argv[++i]; /* the terminal's first request under --session-id */
        } 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;
        }
    }
    if (resume_choice(s, session, &model) != 0) {
        rc = 125; /* said */
        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 submit KEY TEXT [--session ID | --new-session ID] [--images FILE] (ARGV[0] is "submit"). */
static int submit_args(int argc, char **argv) {
    int at = 3;
    if (argc >= at + 2 && (strcmp(argv[at], "--session") == 0 || strcmp(argv[at], "--new-session") == 0)) {
        at += 2;
    }
    if (argc >= at + 2 && strcmp(argv[at], "--images") == 0) {
        at += 2;
    }
    return argc == at;
}

/* 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 = main_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 && resume_choice(s, session, &model) != 0) {
        rc = 125; /* said */
    }
    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;
    pic_store_role("pic chat", 0);
    (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 main_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 ? main_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;
}

/* -r, --resume and --no-session take no value. */
static int session_switch(const char *a) {
    return strcmp(a, "-r") == 0 || strcmp(a, "--resume") == 0 || strcmp(a, "--no-session") == 0;
}

/* Pi's assertValidSessionId: alphanumeric ends, alphanumerics . _ - between. */
static int valid_session_id(const char *id) {
    size_t n = strlen(id);
    if (n == 0 || n > 63 || !isalnum((unsigned char)id[0]) || !isalnum((unsigned char)id[n - 1])) {
        return 0;
    }
    for (size_t k = 0; k < n; k++) {
        if (!isalnum((unsigned char)id[k]) && id[k] != '.' && id[k] != '_' && id[k] != '-') {
            return 0;
        }
    }
    return 1;
}

/* Whether a conversation has exactly this id (a prefix does not count). */
static int session_id_exists(pic_store *s, const char *id) {
    sqlite3_stmt *q = NULL;
    int found = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT 1 FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
        found = sqlite3_step(q) == SQLITE_ROW;
    }
    sqlite3_finalize(q);
    return found;
}

/* --no-session: the journal is a directory of its own under the temporary
 * directory, removed at exit. Its name marks it, so the workspace's record of
 * its journal (picu_workspace) is left alone. */
#define NOSESSION_MARK "/pic-nosession."
static char nosession_dir[PATH_MAX];

static void remove_tree(const char *path) {
    DIR *d = opendir(path);
    struct dirent *e;
    char child[PATH_MAX + 300];
    while (d && (e = readdir(d))) {
        if (strcmp(e->d_name, ".") != 0 && strcmp(e->d_name, "..") != 0) {
            (void)snprintf(child, sizeof child, "%s/%s", path, e->d_name);
            if (unlink(child) != 0) { /* a directory: the journal's lease files live in one */
                remove_tree(child);
            }
        }
    }
    if (d) {
        (void)closedir(d);
    }
    (void)rmdir(path);
}

static void nosession_cleanup(void) { remove_tree(nosession_dir); }

static int nosession_db(char *out, size_t cap) {
    const char *tmp = getenv("TMPDIR");
    if (snprintf(nosession_dir, sizeof nosession_dir, "%s" NOSESSION_MARK "XXXXXX", tmp && *tmp ? tmp : "/tmp") >=
            (int)sizeof nosession_dir ||
        !mkdtemp(nosession_dir) || snprintf(out, cap, "%s/journal.sqlite", nosession_dir) >= (int)cap) {
        return -1;
    }
    (void)atexit(nosession_cleanup);
    return 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;
}

/* ---- RPC: the keys (pic additions; Pi has one credential per provider) ---- */

static void rpc_keys_str(sqlite3_str *out, const char *v) {
    sqlite3_str_appendchar(out, 1, '"');
    for (; v && *v; v++) {
        unsigned char c = (unsigned char)*v;
        if (c == '"' || c == '\\') {
            sqlite3_str_appendf(out, "\\%c", c);
        } else if (c < 0x20) {
            sqlite3_str_appendf(out, "\\u%04x", c);
        } else {
            sqlite3_str_appendchar(out, 1, (char)c);
        }
    }
    sqlite3_str_appendchar(out, 1, '"');
}

typedef struct {
    sqlite3_str *out;
    const char *only;
    int n;
    long long now;
} rpc_keys;

static int rpc_key_entry(void *ctx, const pic_cred_entry *e) {
    rpc_keys *k = ctx;
    pic_key_health h;
    (void)pic_cred_health_of(e->name, &h);
    sqlite3_str_appendall(k->out, k->n++ ? ",{\"provider\":" : "{\"provider\":");
    rpc_keys_str(k->out, e->provider);
    sqlite3_str_appendall(k->out, ",\"label\":");
    rpc_keys_str(k->out, e->label);
    sqlite3_str_appendall(k->out, ",\"kind\":");
    rpc_keys_str(k->out, e->kind);
    sqlite3_str_appendf(k->out, ",\"active\":%s,\"state\":", e->active ? "true" : "false");
    rpc_keys_str(k->out, pic_key_state_name(h.state));
    if (h.status) {
        sqlite3_str_appendf(k->out, ",\"status\":%d", h.status);
    }
    if (h.until_ms) {
        sqlite3_str_appendf(k->out, ",\"until\":%lld", h.until_ms);
    }
    if (h.checked_ms) {
        sqlite3_str_appendf(k->out, ",\"checked\":%lld", h.checked_ms);
    }
    if (h.has_remaining) {
        sqlite3_str_appendf(k->out, ",\"remaining\":%.2f,\"currency\":", h.remaining);
        rpc_keys_str(k->out, h.currency[0] ? h.currency : "$");
    }
    if (h.probed_ms) {
        sqlite3_str_appendf(k->out, ",\"probed\":%lld", h.probed_ms);
    }
    if (e->env) {
        sqlite3_str_appendall(k->out, ",\"env\":");
        rpc_keys_str(k->out, e->env);
    }
    if (h.reason[0]) {
        sqlite3_str_appendall(k->out, ",\"reason\":");
        rpc_keys_str(k->out, h.reason);
    }
    sqlite3_str_appendchar(k->out, 1, '}');
    return 0;
}

static int rpc_key_provider(void *ctx, const char *provider) {
    rpc_keys *k = ctx;
    pic_model m;
    char err[256], name[128];
    (void)snprintf(name, sizeof name, "%s/x", provider);
    if ((k->only && strcmp(k->only, provider) != 0) || pic_model_resolve(name, &m, err, sizeof err) != 0) {
        return 0;
    }
    return pic_cred_entries(provider, m.key_env, m.key_literal, rpc_key_entry, k) != 0;
}

/* get_credentials's data for ONLY (NULL: every provider), led by "checked":CHECKED when it is not
 * negative; malloc'd, NULL out of memory. Never a value. */
static char *credentials_json(const char *only, int checked) {
    rpc_keys k = {sqlite3_str_new(NULL), only, 0, (long long)(pic_platform_get()->wall_ns() / 1000000)};
    char *json, *out;
    sqlite3_str_appendall(k.out, "{");
    if (checked >= 0) {
        sqlite3_str_appendf(k.out, "\"checked\":%d,", checked);
    }
    sqlite3_str_appendall(k.out, "\"credentials\":[");
    (void)pic_providers_each(rpc_key_provider, &k);
    sqlite3_str_appendall(k.out, "]}");
    json = sqlite3_str_finish(k.out);
    out = json ? pic_strdup(json) : NULL;
    sqlite3_free(json);
    return out;
}

/* The free checks of ONLY's keys (NULL: every provider's), opening the store as a request would
 * (RPC never asks on a terminal: a locked store is opened with unlock first): how many were
 * checked, or -1. */
static int run_checks(const char *only, int active_only) {
    pic_keyprobe_opts probe;
    memset(&probe, 0, sizeof probe);
    probe.force = 1;
    probe.active_only = active_only;
    probe.provider = only;
    return pic_keyprobe(&probe);
}

/* get_credentials [provider]: every key of every provider (or one), with what pic knows of it; never a value. */
static int rpc_get_credentials(pic_rpc_call *c) {
    sqlite3 *udb = pic_userdb(c->err, sizeof c->err);
    char *only = udb ? pic_json_body(udb, "SELECT json_extract(?1, '$.provider')", 1, c->line) : NULL;
    if (!udb) {
        return -1;
    }
    c->data = credentials_json(only, -1);
    free(only);
    return 0;
}

/* check_credentials [provider] [active]: the free checks now (nothing sent but each key to its own
 * provider's check), then get_credentials's answer with "checked". */
static int rpc_check_credentials(pic_rpc_call *c) {
    sqlite3 *udb = pic_userdb(c->err, sizeof c->err);
    char *only = udb ? pic_json_body(udb, "SELECT json_extract(?1, '$.provider')", 1, c->line) : NULL;
    char *act = udb ? pic_json_body(udb, "SELECT json_extract(?1, '$.active')", 1, c->line) : NULL;
    int n;
    if (!udb) {
        return -1;
    }
    n = run_checks(only, act && strcmp(act, "1") == 0);
    free(act);
    if (n < 0) {
        free(only);
        (void)snprintf(c->err, sizeof c->err, "cannot read ~/.pic/pic.sqlite");
        return -1;
    }
    c->data = credentials_json(only, n);
    free(only);
    return 0;
}

/* PROVIDER as a provider pic knows, into m: 0, or -1 with err. */
static int auth_provider(const char *provider, pic_model *m, char *err, size_t errcap) {
    char name[128];
    (void)snprintf(name, sizeof name, "%s/x", provider ? provider : "");
    if (!provider || !*provider || strchr(provider, ':') || pic_model_resolve(name, m, err, errcap) != 0 ||
        strcmp(m->provider, provider) != 0) {
        (void)snprintf(err, errcap, "unknown provider %.64s (pic models --all lists them)", provider ? provider : "");
        return -1;
    }
    return 0;
}

/* The label PROVIDER's requests use now, into out ("" when none). */
static void active_label(const pic_model *m, char *out, size_t cap) {
    pic_cred_used u;
    (void)snprintf(out, cap, "%s", pic_cred_active(m->provider, m->key_env, m->key_literal, &u) == 0 ? u.label : "");
}

/* Stores KEY as PROVIDER's key LABEL (NULL: its own), unless that key is already there (*changed 0);
 * USE also makes it the provider's saved choice. *active: whether requests use it now. 0, or -1
 * with err. The key is never written anywhere else. */
static int add_key(const char *provider, const char *label, const char *key, int use, int *changed, int *in_use, char *err,
                   size_t errcap) {
    pic_model m;
    char now[PIC_CRED_LABEL_CAP];
    const char *l = label && *label ? label : "default";
    int same;
    *changed = *in_use = 0;
    if (auth_provider(provider, &m, err, errcap) != 0) {
        return -1;
    }
    if (strcmp(l, "default") != 0 && pic_cred_label_check(l, err, errcap) != 0) {
        return -1;
    }
    if (!key || !*key) {
        (void)snprintf(err, errcap, "no key given");
        return -1;
    }
    if ((same = pic_cred_same(provider, l, key, err, errcap)) < 0) {
        return -1;
    }
    if (!same) {
        if (pic_cred_login_as(provider, l, key, err, errcap) != 0) {
            return -1;
        }
        *changed = 1;
    }
    if (use) {
        active_label(&m, now, sizeof now);
        if (strcmp(now, l) != 0) {
            if (pic_cred_use(provider, l, m.key_env, m.key_literal, err, errcap) != 0) {
                return -1;
            }
            *changed = 1;
        }
    }
    active_label(&m, now, sizeof now);
    *in_use = strcmp(now, l) == 0;
    return 0;
}

static char *added_json(const char *provider, const char *label, int changed, int in_use) {
    sqlite3_str *o = sqlite3_str_new(NULL);
    char *json, *out;
    sqlite3_str_appendall(o, "{\"provider\":");
    rpc_keys_str(o, provider);
    sqlite3_str_appendall(o, ",\"label\":");
    rpc_keys_str(o, label && *label ? label : "default");
    sqlite3_str_appendf(o, ",\"kind\":\"api_key\",\"changed\":%s,\"active\":%s}", changed ? "true" : "false",
                        in_use ? "true" : "false");
    json = sqlite3_str_finish(o);
    out = json ? pic_strdup(json) : NULL;
    sqlite3_free(json);
    return out;
}

static void json_text(FILE *out, const char *v) {
    sqlite3_str *o = sqlite3_str_new(NULL);
    char *json;
    rpc_keys_str(o, v);
    json = sqlite3_str_finish(o);
    fputs(json ? json : "\"\"", out);
    sqlite3_free(json);
}

/* pic models use MODEL [--key LABEL] [--json]: MODEL is the model new conversations start on, and
 * with --key its provider's saved key is LABEL; a key it does not have changes nothing (exit 1).
 * Again changes nothing and says so. */
static int models_use(int argc, char **argv) {
    const char *model = NULL, *label = NULL;
    int json = 0, changed = 0;
    pic_model m;
    char err[PIC_ERR_CAP], name[200], before[PIC_CRED_LABEL_CAP] = "", *def;
    for (int i = 0; i < argc; i++) {
        if (strcmp(argv[i], "--json") == 0) {
            json = 1;
        } else if (strcmp(argv[i], "--key") == 0 && i + 1 < argc) {
            label = argv[++i];
        } else if (argv[i][0] != '-' && !model) {
            model = argv[i];
        } else {
            return usage();
        }
    }
    if (!model) {
        return usage();
    }
    if (pic_model_resolve(model, &m, err, sizeof err) != 0) {
        fprintf(stderr, "pic: %s\n", err);
        return 1;
    }
    (void)snprintf(name, sizeof name, "%s/%s", m.provider, m.id);
    if (label && !pic_cred_has(m.provider, label, m.key_env, m.key_literal)) {
        fprintf(stderr, "pic: no key \"%s\" for %s (pic auth status lists its keys)\n", label, m.provider);
        return 1;
    }
    def = setting("defaultModel");
    changed = !def || strcmp(def, name) != 0;
    free(def);
    if (changed && (set_setting("defaultModel", name) != 0 || set_setting("lastModel", NULL) != 0)) {
        fputs("pic: cannot save the setting in ~/.pic/pic.sqlite\n", stderr);
        return 1;
    }
    if (label) {
        active_label(&m, before, sizeof before);
        if (pic_cred_use(m.provider, label, m.key_env, m.key_literal, err, sizeof err) != 0) {
            fprintf(stderr, "pic: %s\n", err);
            return 1;
        }
        changed |= strcmp(before, label) != 0;
    }
    if (json) {
        fputs("{\"model\":", stdout);
        json_text(stdout, name);
        if (label) {
            char cred[PIC_CRED_NAME_CAP];
            (void)snprintf(cred, sizeof cred, "%s:%s", m.provider, label);
            fputs(",\"credential\":", stdout);
            json_text(stdout, cred);
        }
        printf(",\"changed\":%s}\n", changed ? "true" : "false");
    } else {
        printf(label ? "default model: %s, key \"%s\"\n" : "default model: %s\n", name, label);
    }
    return 0;
}

/* add_credential provider [label] key [use]: stores an API key, sealed; the same key again changes
 * nothing. data: provider, label, kind, changed, active. Never echoes the key. */
static int rpc_add_credential(pic_rpc_call *c) {
    sqlite3 *udb = pic_userdb(c->err, sizeof c->err);
    char *provider = udb ? pic_json_body(udb, "SELECT json_extract(?1, '$.provider')", 1, c->line) : NULL;
    char *label = udb ? pic_json_body(udb, "SELECT json_extract(?1, '$.label')", 1, c->line) : NULL;
    char *key = udb ? pic_json_body(udb, "SELECT json_extract(?1, '$.key')", 1, c->line) : NULL;
    char *use = udb ? pic_json_body(udb, "SELECT json_extract(?1, '$.use')", 1, c->line) : NULL;
    int changed = 0, in_use = 0, rc = -1;
    if (udb && add_key(provider, label, key, use && strcmp(use, "1") == 0, &changed, &in_use, c->err, sizeof c->err) == 0) {
        c->data = added_json(provider, label, changed, in_use);
        rc = 0;
    }
    if (key) {
        pic_cred_wipe(key, strlen(key));
    }
    free(provider);
    free(label);
    free(key);
    free(use);
    return rc;
}

/* set_credential provider label [persist]: this RPC process's requests to provider use its key
 * label from the next one; with persist also the saved choice (pic auth use). data: provider,
 * label, persist, changed. */
static int rpc_set_credential(pic_rpc_call *c) {
    sqlite3 *udb = pic_userdb(c->err, sizeof c->err);
    char *provider = udb ? pic_json_body(udb, "SELECT json_extract(?1, '$.provider')", 1, c->line) : NULL;
    char *label = udb ? pic_json_body(udb, "SELECT json_extract(?1, '$.label')", 1, c->line) : NULL;
    char *persist = udb ? pic_json_body(udb, "SELECT json_extract(?1, '$.persist')", 1, c->line) : NULL;
    int save = persist && strcmp(persist, "1") == 0, changed = 0;
    pic_model m;
    char before[PIC_CRED_LABEL_CAP], *saved = NULL, key[PIC_CRED_PROVIDER_CAP + 16];
    int rc = -1;
    c->data = NULL;
    if (!provider || !label) {
        (void)snprintf(c->err, sizeof c->err, "set_credential needs provider and label");
    } else if (auth_provider(provider, &m, c->err, sizeof c->err) != 0) {
        /* said */
    } else if (!pic_cred_has(provider, label, m.key_env, m.key_literal)) {
        (void)snprintf(c->err, sizeof c->err, "%s has no key named \"%.40s\": pic auth status lists its keys", provider, label);
    } else {
        (void)snprintf(key, sizeof key, "activeKey:%s", provider);
        saved = pic_setting(key);
        active_label(&m, before, sizeof before);
        if (save && pic_cred_use(provider, label, m.key_env, m.key_literal, c->err, sizeof c->err) != 0) {
            /* said */
        } else if (pic_cred_override(provider, label) != 0) { /* this process's requests */
            (void)snprintf(c->err, sizeof c->err, "too many providers with a chosen key in this process");
        } else {
            sqlite3_str *o = sqlite3_str_new(NULL);
            char *json;
            changed = strcmp(before, label) != 0 || (save && !(saved && strcmp(saved, label) == 0));
            sqlite3_str_appendall(o, "{\"provider\":");
            rpc_keys_str(o, provider);
            sqlite3_str_appendall(o, ",\"label\":");
            rpc_keys_str(o, label);
            sqlite3_str_appendf(o, ",\"persist\":%s,\"changed\":%s}", save ? "true" : "false", changed ? "true" : "false");
            json = sqlite3_str_finish(o);
            c->data = json ? pic_strdup(json) : NULL;
            sqlite3_free(json);
            rc = 0;
        }
    }
    free(saved);
    free(provider);
    free(label);
    free(persist);
    return rc;
}

static const pic_rpc_command main_get_credentials = {"get_credentials", "every provider's keys with what pic knows of each",
                                                     PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_get_credentials};
static const pic_rpc_command main_set_credential = {"set_credential", "the key this process's requests to a provider use",
                                                    PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_set_credential};
static const pic_rpc_command main_add_credential = {"add_credential", "store an API key, sealed; the same key again changes nothing",
                                                    PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_add_credential};
static const pic_rpc_command main_check_credentials = {"check_credentials", "run the free checks, then every key with what is left",
                                                       PIC_RPC_JOURNAL_FREE, rpc_check_credentials};

/* The RPC command registry: the commands components answer. */
static const pic_rpc_command *const rpc_commands[] = {
    &pic_rewind_rpc,      &pic_models_rpc,      &pic_commands_rpc,    &main_get_credentials, &main_set_credential, &main_add_credential, &main_check_credentials,
    &pic_providers_rpc,   &pic_context_rpc,     &pic_files_rpc,       &pic_help_rpc,         &pic_changelog_rpc,
    &pic_compaction_settings_rpc, &pic_get_setting_rpc, &pic_set_setting_rpc, &pic_get_settings_rpc, &pic_get_trust_rpc, &pic_set_trust_rpc,
    &pic_get_scoped_rpc,  &pic_set_scoped_rpc,  &pic_report_bug_rpc,  &pic_get_phones_rpc,   &pic_get_hooks_rpc,
    &pic_proc_start_rpc,  &pic_proc_end_rpc,    &pic_get_endpoints_rpc, &pic_add_endpoint_rpc, &pic_remove_endpoint_rpc,
    &pic_refresh_endpoints_rpc};

/* The terminal interface's commands: answered here, in this process, by the registry. */
static pic_rpc_host tui_host;

static char *tui_ask(const char *session, const char *model, const char *line) {
    return pic_rpc_answer(&tui_host, session, model, line);
}

/* pic remote's: a component's journal-free command, for a phone (no journal is opened). */
static char *remote_ask(const char *workspace, const char *model, const char *line) {
    pic_rpc_host h;
    memset(&h, 0, sizeof h);
    h.workspace = workspace;
    h.commands = rpc_commands;
    h.ncommands = sizeof rpc_commands / sizeof rpc_commands[0];
    return pic_rpc_answer(&h, "", model, line);
}

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, *session_id = NULL, *mode = NULL;
    int resume_pick = 0, no_session = 0;
    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 test (test/run-logged.sh sets this) never reaches the account's own ~/.pic. */
    if (getenv("PIC_TEST_PRIVATE_HOME") && pic_host_own_home()) {
        fputs("pic: PIC_TEST_PRIVATE_HOME is set and HOME is your own home directory: a test must set a private HOME\n",
              stderr);
        return 70;
    }
    /* 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(main_hook_owner, sizeof main_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 */
    pic_cred_offer_register(offer_keeper); /* after a typed passphrase: offer to stop asking for it */
    pic_cred_oauth_register(pic_oauth_ops()); /* the subscription sign-ins (oauth_*.c) */
    pic_cred_health_register(&pic_keyhealth_ops); /* what a refusal means for the key (keyhealth.c) */
    pic_model_source_register(&pic_models_source); /* what a model name means, and its price (models.c) */
    /* the wire APIs (provider_*.c): request building, stream decoding, id rules, shapes, cache lifetimes */
    (void)pic_provider_register(&pic_anthropic_adapter);
    (void)pic_provider_register(&pic_chat_adapter);
    (void)pic_provider_register(&pic_responses_adapter);
    (void)pic_provider_register(&pic_gemini_adapter);
    if (argc > 1 && strcmp(argv[1], "help") == 0) { /* the manual, compiled in */
        return pic_help_command(argc - 2, argv + 2);
    }
    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 (strcmp(argv[h], "--version") == 0 || strcmp(argv[h], "-v") == 0) {
            char version[32];
            pic_version(version, sizeof version);
            printf("pic %s\n", version);
            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 || strcmp(argv[i], "--hold-key-failures") == 0 || tool_switch(argv[i]))) {
        if (strcmp(argv[i], "--hold-key-failures") == 0) {
            hold_key_failures_opt = 1;
        } else 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 : &main_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]) || session_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]) || session_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 (session_switch(argv[i])) {
            if (argv[i][1] == 'r' || argv[i][2] == 'r') { /* -r, --resume */
                resume_pick = 1;
            } else {
                no_session = 1;
            }
            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 : &main_commands) = 1;
            i++;
            continue;
        }
        if (strcmp(argv[i], "--hold-key-failures") == 0) {
            hold_key_failures_opt = 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];
            model_flag = model;
        } 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], "--passphrase-fd") == 0) {
            char *end = NULL;
            long fd = strtol(argv[i + 1], &end, 10);
            if (!end || *end || fd < 0 || fd > 65535 || fcntl((int)fd, F_GETFD) < 0) {
                fprintf(stderr, "pic: --passphrase-fd: %s is not an open descriptor\n", argv[i + 1]);
                return 2;
            }
            (void)fcntl((int)fd, F_SETFD, FD_CLOEXEC); /* nothing pic runs inherits it */
            pic_cred_passphrase_fd((int)fd);
        } else if (strcmp(argv[i], "--key") == 0) {
            char why[160];
            if (strcmp(argv[i + 1], "default") != 0 && strcmp(argv[i + 1], "env") != 0 && strcmp(argv[i + 1], "file") != 0 &&
                pic_cred_label_check(argv[i + 1], why, sizeof why) != 0) {
                fprintf(stderr, "pic: --key: %s\n", why);
                return 2;
            }
            key_opt = argv[i + 1];
        } 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 && strcmp(argv[i + 1], "json") != 0 && strcmp(argv[i + 1], "text") != 0) {
                fprintf(stderr, "pic: Invalid mode \"%s\". Valid values: text, json, rpc\n", argv[i + 1]);
                return 2;
            }
            mode = argv[i + 1]; /* the last one wins, as in Pi */
        } else if (strcmp(argv[i], "--session") == 0) {
            rpc_session = argv[i + 1];
        } else if (strcmp(argv[i], "--session-id") == 0) {
            session_id = 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;
    }
    if (mode && strcmp(mode, "rpc") == 0) {
        rpc_mode = 1;
    } else if (mode && strcmp(mode, "json") == 0) { /* Pi: print mode with JSON events, -p or not */
        print_mode = 1;
        json_events = 1;
    }
    if (session_id) { /* Pi's validateSessionIdFlags */
        const char *with = resume_pick ? "--resume" : rpc_session ? (strcmp(rpc_session, "latest") == 0 ? "--continue" : "--session") : NULL;
        if (with) {
            fprintf(stderr, "pic: --session-id cannot be combined with %s\n", with);
            return 2;
        }
        if (!valid_session_id(session_id)) {
            fputs("pic: Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and "
                  "end with an alphanumeric character\n", stderr);
            return 2;
        }
    }
    if (no_session) { /* Pi: --no-session wins; there is nothing to continue or pick from */
        rpc_session = NULL;
        resume_pick = 0;
    }
    if (resume_pick && (print_mode || rpc_mode)) {
        fputs("pic: --resume picks a conversation in the terminal interface; with -p use -c or --session ID\n", stderr);
        return 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 (main_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 || main_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 || resume_pick || session_id) && i < argc) {
        fputs("pic: --session, -c, -r and --session-id before a command are for the terminal, -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);
    pic_tool_read_observer(pic_skills_note_read); /* a read of a skill's file counts as a use */
    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 (main_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 a pick
     * in the terminal interface), 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_why, sizeof model_why);
        model = saved;
    } else {
        (void)snprintf(model_why, sizeof model_why, "from --model");
    }
    if (i < argc && strcmp(argv[i], "remote") == 0) { /* remote control through the relay */
        char self[PATH_MAX];
        pic_remote_options ro;
        self_path(argv[0], self, sizeof self);
        ro.self = self;
        ro.show_qr = remote_show_qr;
        ro.ask = remote_ask;
        ro.policy = &pic_compact_policy;
        pic_store_role("pic remote", 1); /* it closes a journal a newer pic waits to migrate */
        return pic_remote_main(&ro, argc - i - 1, argv + i + 1);
    }
    /* -p and ask with no --model may go on with a conversation's own model: --key waits for it */
    if (key_opt && (model_flag || !(print_mode || (i < argc && strcmp(argv[i], "ask") == 0))) && apply_key_opt(model) != 0) {
        return 2;
    }
    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], "endpoints") == 0) { /* picu_endpoint in ~/.pic/pic.sqlite */
        return endpoints_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] != '-') {
            const pic_setting_def *d = pic_settings_find(argv[i + 1]);
            char *v = d && d->field ? pic_settings_stored(d) : setting(argv[i + 1]);
            if (v) {
                puts(v);
            }
            free(v);
            return v ? 0 : 1;
        }
        if (argc - i == 3) { /* the settings list's keys take only what it allows; a field by its dotted name */
            int unset = strcmp(argv[i + 1], "--unset") == 0;
            const char *key = argv[i + (unset ? 2 : 1)], *value = unset ? NULL : argv[i + 2];
            const pic_setting_def *d = pic_settings_find(key);
            char err[PIC_ERR_CAP] = "";
            int saved = d ? pic_settings_write(d, value, err, sizeof err)
                          : pic_settings_check_object(key, value, err, sizeof err) == 0 ? set_setting(key, value) : -1;
            if (saved != 0) {
                fprintf(stderr, "pic: %s\n", err[0] ? err : "cannot save the setting");
            }
            return saved == 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 || strcmp(argv[i], "auth") == 0)) {
        return user_command(argc - i, argv + i, workspace);
    }
    if (no_session) {
        if (nosession_db(db_path, sizeof db_path) != 0) {
            fputs("pic: cannot make a temporary journal for --no-session\n", stderr);
            return 1;
        }
        db = db_path;
        (void)setenv("PIC_PI_EXPORT", "0", 1); /* nothing of it reaches ctx either */
    }
    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;
    }
    /* Opened as a journal, the user database would gain a journal's tables and be registered as
     * the workspace's journal. */
    if (pic_userdb_is(db)) {
        fprintf(stderr, "pic: %s is pic's user database, not a journal; --db names a workspace's journal "
                        "(WORKSPACE/.pic/journal.sqlite)\n", db);
        return 1;
    }
    /* Another process's conversation: the narrow open, no lease, no hooks. */
    if (i < argc && strcmp(argv[i], "send") == 0) {
        return send_message_command(db, argc - i - 1, argv + i + 1);
    }
    if (i < argc && (strcmp(argv[i], "remote-control") == 0 || strcmp(argv[i], "rc") == 0)) {
        return remote_command(argv[0], db, workspace, argc - i - 1, argv + i + 1);
    }
    if (i < argc && strcmp(argv[i], "doctor") == 0 && (argc - i == 1 || (argc - i == 2 && strcmp(argv[i + 1], "--json") == 0))) {
        return pic_doctor(db, json_events || argc - i == 2);
    }
    if (i < argc && strcmp(argv[i], "attach") == 0) {
        pic_store_role("pic attach", 1); /* a follower: it ends when a newer pic waits to migrate */
        return attach_command(argv[0], db, workspace, thinking_opt, model, argc - i - 1, argv + i + 1);
    }
    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, main_hook_owner[0] ? main_hook_owner : NULL, stderr);
    verify_command = pic_verify_load(workspace, 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.model_named = model_flag != NULL;
        h.open = open_store;
        h.prompt = rpc_prompt;
        h.provider = rpc_provider;
        h.key_ready = rpc_key_ready;
        h.level = rpc_level;
        h.expand = expand_template;
        h.end = end_conversations;
        h.commands = rpc_commands;
        h.ncommands = sizeof rpc_commands / sizeof rpc_commands[0];
        pic_store_role("pic --mode rpc", 0);
        rc = pic_rpc_main(&h, model, rpc_session);
        pic_hooks_free(hooks);
        free(verify_command);
        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, *new_id = 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();
        } else if (i >= argc && rpc_session) { /* pic -c, pic --session ID */
            resume = rpc_session;
        }
        if (session_id) { /* Pi: that conversation, else a new one that takes the id */
            pic_store probe;
            int exists = 0;
            if (open_store(&probe, db) == 0) {
                exists = session_id_exists(&probe, session_id);
            }
            pic_close(&probe);
            if (exists) {
                resume = session_id;
            } else {
                new_id = session_id;
            }
        }
        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.new_id = new_id;
        t.pick = resume_pick;
        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;
        t.key = key_opt;
        t.model_named = model_flag != NULL;
        tui_host.db = db;
        tui_host.workspace = workspace;
        tui_host.exec_seconds = exec_seconds;
        tui_host.open = open_store;
        tui_host.commands = rpc_commands;
        tui_host.ncommands = sizeof rpc_commands / sizeof rpc_commands[0];
        t.ask = tui_ask;
        { /* the line under the banner: no key yet, or why this model */
            static char note[512];
            char name[256];
            if (!model_with_key(model, name, sizeof name)) {
                (void)snprintf(note, sizeof note,
                               "No key yet: /login, or export a provider key such as OPENROUTER_API_KEY.");
            } else if (strcmp(model_why, "from --model") != 0) {
                (void)snprintf(note, sizeof note, "model %s (%s; Alt+P to change)", name, model_why);
            }
            t.model_note = note[0] ? note : NULL;
        }
        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]);
    }
    {
        char role[48];
        (void)snprintf(role, sizeof role, "pic %s", print_mode ? "-p" : argv[i]);
        pic_store_role(role, 0);
    }
    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;
        if (!strstr(db, NOSESSION_MARK)) {
            (void)pic_workspace_touch(ws, db);
        }
        pic_proc_scope(ws, NULL);
    }
    {
        char self[PATH_MAX];
        self_path(argv[0], self, sizeof self);
        pic_peer_self(self); /* a peer's wake runs this pic */
    }
    if (print_mode) {
        if (session_id && !rpc_session) { /* Pi: the conversation with this id, else a new one under it */
            if (session_id_exists(&s, session_id)) {
                rpc_session = session_id;
            } else {
                fprintf(stderr, "pic: no conversation with id '%s'; creating a new one with that id\n", session_id);
                ask_new_id = session_id;
            }
        }
        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();
        }
        if (rc == 125) { /* said already */
            pic_close(&s);
            return 1;
        }
    } else if (strcmp(argv[i], "submit") == 0 && submit_args(argc - i, argv + i)) {
        int duplicate = 0, fresh = 0, a = argc - i;
        int64_t first = 0;
        char joined[64], sid[64] = "", *images_json = NULL, *text = NULL;
        const char *images_from = a >= 5 && strcmp(argv[argc - 2], "--images") == 0 ? argv[argc - 1] : NULL;
        const char *session = a >= 5 && strcmp(argv[i + 3], "--session") == 0 ? argv[i + 4] : NULL;
        pic_image *images = NULL;
        unsigned char *bytes = NULL;
        size_t nimages = 0, ilen = 0;
        const char *error = NULL;
        if (a >= 5 && strcmp(argv[i + 3], "--new-session") == 0) { /* a new conversation with that id (pic remote's) */
            if (!valid_session_id(argv[i + 4])) {
                fprintf(stderr, "pic: --new-session: not a conversation id: %s\n", argv[i + 4]);
                pic_close(&s);
                return 2;
            }
            ask_new_id = argv[i + 4];
        }
        /* with --model, the request records its model and level, as ask's does (pic remote's prompts) */
        s.model = model_flag;
        s.thinking = model_flag ? thinking_opt : NULL;
        /* --images: Pi's image content as a JSON array, from FILE or stdin (pic remote's) */
        if (images_from && !(images_json = strcmp(images_from, "-") == 0 ? read_piped_stdin()
                                                                         : pic_input_read(images_from, 64u << 20, 0, &ilen, NULL))) {
            fprintf(stderr, "pic: --images: cannot read %s\n", images_from);
            pic_close(&s);
            return 1;
        }
        if (images_json && pic_images_from_json(s.db, images_json, "$", 1, &images, &nimages, &bytes, &error) != 0) {
            (void)snprintf(s.err, sizeof s.err, "--images: %s", error ? error : "not an array of image content");
            rc = -1;
        } else if (!(text = pic_image_prepare(argv[i + 2], images, &nimages, s.err, sizeof s.err))) {
            rc = -1; /* images that cannot go inline become notes after the text, as Pi's */
        } else {
            rc = s.hooks && hook_conversation(&s, session, sid, &fresh, text, &first) != 0
                     ? -1
                     : pic_submit_hooked(&s, argv[i + 1], text, images, nimages, fresh ? NULL : sid[0] ? sid : session,
                                         fresh ? sid : !session ? ask_new_id : NULL, first, &duplicate, joined, sizeof joined);
        }
        s.model = s.thinking = NULL;
        if (rc == 0) {
            puts(duplicate ? "duplicate: already admitted" : "admitted");
        }
        free(text);
        free(images);
        free(bytes);
        free(images_json);
        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, 0, 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 >= 3 && strcmp(argv[i + 1], "delete") == 0) {
        for (int j = i + 2; j < argc; j++) { /* each on its own: one that cannot be deleted leaves the rest */
            char id[64], title[160];
            if (pic_trash_delete(&s, argv[j], id, sizeof id, title, sizeof title) == 0) {
                printf("deleted %s  %s  (pic sessions restore %s brings it back)\n", id, *title ? title : "-", id);
            } else {
                fprintf(stderr, "pic: %s\n", s.err);
                rc = 1;
            }
        }
        s.err[0] = '\0';
        if (rc != 0) {
            pic_close(&s);
            return 1;
        }
    } else if (strcmp(argv[i], "sessions") == 0 && argc - i <= 3 && argc - i >= 2 && strcmp(argv[i + 1], "restore") == 0) {
        char id[64], title[160];
        rc = pic_trash_restore(&s, argc - i == 3 ? argv[i + 2] : NULL, id, sizeof id, title, sizeof title);
        if (rc == 0) {
            printf("restored %s  %s\n", id, *title ? title : "-");
        }
    } else if (strcmp(argv[i], "sessions") == 0 && argc - i >= 2 && argc - i <= 3 && strcmp(argv[i + 1], "trash") == 0 &&
               (argc - i == 2 || strcmp(argv[i + 2], "--json") == 0)) {
        rc = pic_trash_list(&s, argc - i == 3, stdout);
    } else if (strcmp(argv[i], "sessions") == 0 && argc - i == 2 && strcmp(argv[i + 1], "empty-trash") == 0) {
        long long count = 0, n = 0, bytes = 0;
        rc = pic_trash_purge(&s, LLONG_MAX, &count);
        if (rc == 0) { /* what they alone held goes now too */
            (void)pic_prune(&s, 0, &n, &bytes);
            s.err[0] = '\0';
            printf("purged %lld conversation%s for good\n", count, count == 1 ? "" : "s");
        }
    } 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], "sessions") == 0 && argc - i == 2 && strcmp(argv[i + 1], "--all") == 0) {
        rc = pic_peer_sessions_all(stdout, s.err, sizeof s.err); /* every workspace's: what send_message can reach */
    } 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], "rewind") == 0) {
        rc = rewind_command(&s, workspace, argc - i - 1, argv + i + 1);
        if (rc == 2 || rc == 3) {
            pic_close(&s);
            return rc == 2 ? usage() : 3;
        }
    } 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) { /* a prompt waiting in its inbox: a wake (docs/design/grapevine.md) */
                char *mw = pic_setting("grapevine.maxWakes");
                int woke = pic_inbox_wake(&s, sid, mw ? strtol(mw, NULL, 10) : 0);
                free(mw);
                if (woke < 0) {
                    rc = -1;
                } else if (woke == 0) {
                    (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], "usage") == 0 && argc - i >= 2 && strcmp(argv[i + 1], "--by-tool") == 0 &&
               (argc - i == 2 || (argc - i == 3 && strcmp(argv[i + 2], "--json") == 0))) {
        rc = pic_usage_by_tool(&s, argc - i == 3, stdout);
    } else if (strcmp(argv[i], "usage") == 0 && argc - i >= 2 && strcmp(argv[i + 1], "--lapse") == 0 &&
               (argc - i == 2 || (argc - i == 3 && strcmp(argv[i + 2], "--json") == 0))) {
        rc = pic_lapse_report(s.db, 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);
            rc = pic_prune_files(&s, dry, &count, &bytes);
        }
        if (rc == 0 && count > 0) {
            printf("%s %lld stored file%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);
    free(verify_command);
    return rc == 0 ? 0 : 1;
}