Skip to content
pi-c Artifact [bf241533f6]
Login

Artifact [bf241533f6]

Artifact bf241533f61dbab78222e2ffe0a032d183a32f37c541c74a3beaf31622bc8d1f:


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

#include "commands.h"
#include "net.h"
#include "catalog.h"
#include "userdb.h"
#include "pic.h"
#include "prompts.h"
#include "platform.h"
#include "tui/tui.h"
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif

/* --context-window: replaces the model's window for automatic compaction (-1: keep). */
static long context_window = -1;
/* --thinking: the thinking level asked for on the command line (NULL: the settings). */
static const char *thinking_opt;
/* --json: Pi-style events on stdout; --stream: stream reply text even when
 * stdout is not a terminal. */
static int json_events, force_stream;
/* --commands: Pi's RPC command lines on stdin steer ask and run (with --json). */
static int commands;
/* The line mode: ask prints the conversation it joined only when it changes. */
static int quiet;
static char last_session[64]; /* the line mode's conversation, set by ask */
static pic_events events;

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

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

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

static int usage(void);

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

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

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

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

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

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

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

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

static void print_usage(FILE *out) {
    fputs("usage: pic [--workspace DIR] [--db PATH] [--model MODEL] ask [-c | --session ID] TEXT\n"
          "           run TEXT in the workspace (default: the current directory) and print the answer;\n"
          "           a new session, or -c to continue the latest, --session to continue that one;\n"
          "           the journal defaults to WORKSPACE/.pic/journal.sqlite\n"
          "       pic [options] [tui [-c | --session ID]]   the terminal interface (plain pic in a terminal);\n"
          "           -c continues the latest conversation (the first in pic sessions), --session that one\n"
          "       pic [options] chat [-c | --session ID]   a plain line prompt for one conversation\n"
          "       pic [options] settings [KEY [VALUE] | --unset KEY]   settings kept in ~/.pic/pic.sqlite\n"
          "       pic [options] models [--json] [--all] [--refresh] | models --default NAME | models --thinking-default LEVEL\n"
          "           models from Pi's catalog (and models.json) whose provider has a key; --all every one\n"
          "       pic [options] sessions [--json] | log [--json] [ID] | name ID NAME | fork ID [--at ENTRY]\n"
          "       pic [options] tree --json [ID]   the requests of ID's conversation tree, branches included\n"
          "       pic [options] export --html ID [PATH | -]   a conversation as one self-contained HTML page (default -)\n"
          "       pic [options] import PATH | -   a Pi v3 session JSONL as a new conversation (the text of its messages)\n"
          "       pic [options] trust [yes | no] | scoped-models [--clear | --set PATTERN...] | bug [--list | TEXT]\n"
          "           the workspace's trust, the models Ctrl+P cycles, a bug report kept in ~/.pic/pic.sqlite (sent nowhere)\n"
          "       pic [options] prompts [--json]   the prompt templates (~/.pic/prompts, and the trusted workspace's .pic/prompts):\n"
          "           /NAME ARGS in a message sends the template with $1, $@, ${@:2} and the like filled in\n"
          "       pic [options] compact [ID [INSTRUCTIONS]]   summarize the conversation before its next request\n"
          "       pic [options] export [--since ENTRY]   finished entries as JSON lines\n"
          "       pic [options] export --pi [DIR | -]   conversations as Pi session lines: rows in ~/.pic/pic.sqlite\n"
          "           (for ctx; ask, chat and the terminal write them after each request unless PIC_PI_EXPORT=0),\n"
          "           and ~/.pic/sessions files only with piSessionFiles=1; DIR writes files there, - to stdout\n"
          "       pic [options] submit KEY TEXT [--session ID] | cancel KEY\n"
          "       pic [options] run --script FILE\n"
          "       pic [options] run --provider anthropic [--api-url URL]\n"
          "       pic [options] dump | check | result CALL_ID\n"
          "options: --workspace DIR  --db PATH  --model MODEL  --exec-timeout SECONDS (bash default, 600)\n"
          "         --thinking LEVEL (off, minimal, low, medium, high, xhigh, max; the model's supported ones;\n"
          "           default: settings thinkingLevel:MODEL / defaultThinkingLevel, else medium)\n"
          "         --json (events on stdout, as Pi's JSON mode)  --stream (stream the reply even when piped)\n"
          "         --context-window TOKENS (compact past this minus 16384; default: the model's, 0 never)\n"
          "         --commands (with --json, for ask and run: Pi's RPC command lines on stdin steer the running\n"
          "           request: steer, follow_up, clear_queue, abort, set_steering_mode, set_follow_up_mode;\n"
          "           each is journaled as it arrives. While a request runs its process owns the journal, so\n"
          "           this is the only way to steer it: there is no separate steer command)\n",
          out);
}

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

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

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

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], "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], "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;
}

/* 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) {
        return -1;
    }
    return pic_provider_for_model(p, &m, level, url, workspace, err, errcap);
}

/* A prompt template's expansion of TEXT ("/name ARGS"), or NULL. */
static char *expand_template(void *workspace, const char *text) {
    pic_prompts templates;
    char *expanded = NULL;
    if (text[0] == '/' && load_prompts(&templates, workspace) == 0) {
        expanded = pic_prompts_expand(&templates, text);
        pic_prompts_free(&templates);
    }
    return expanded;
}

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

/* submit under a fresh key, run with the model's provider, print the answer. */
static int ask(pic_store *s, const char *workspace, const char *model, const char *url, int exec_seconds,
               const char *session, const char *text) {
    char key[64], joined[64] = "";
    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);
    expanded = expand_template((void *)(uintptr_t)workspace, text); /* a prompt template: submit what it expands to */
    rc = pic_submit(s, key, expanded ? expanded : text, session, &duplicate, joined, sizeof joined);
    free(expanded);
    if (rc != 0) {
        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 (!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);
    }
    if (model_provider(&provider, model, url, workspace, s->err, sizeof s->err) != 0) {
        if (provider.free) {
            provider.free(&provider);
        }
        return -1;
    }
    pic_events_init(&events, stdout, stderr, json_events, !json_events && (force_stream || isatty(STDOUT_FILENO)));
    s->events = &events;
    if (context_window >= 0) {
        provider.context_window = context_window;
    }
    catch_interrupt();
    rc = run_with_commands(s, workspace, &provider, exec_seconds);
    provider.free(&provider);
    /* 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);
    }
    /* 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;
}

/* Whether CMD ("/name") names a prompt template. */
static int is_template(const char *workspace, const char *cmd) {
    pic_prompts p;
    int found = 0;
    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 before the next message\n"
    "  /model [NAME]        show or change the model (provider/model)\n"
    "  /NAME [ARGS]         a prompt template (pic prompts 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;
    }
}

/* pic with no command, in a terminal: a prompt that continues one
 * conversation. The journal is open only while an input is handled, so
 * other pic commands can use it between messages. */
static int repl(const char *db, const char *workspace, const char *model, int exec_seconds, const char *resume) {
    char current[64] = "", modelbuf[128];
    char *in;
    (void)snprintf(modelbuf, sizeof modelbuf, "%s", model);
    quiet = 1;
    catch_interrupt();
    if (resume) { /* -c: the latest conversation; --session ID: that one */
        pic_store s;
        int rc = pic_open(&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) {
            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 (pic_open(&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);
            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) {
                (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) {
                (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);
                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);
    }
    return 0;
}

int main(int argc, char **argv) {
    const char *db = NULL, *workspace = NULL, *model = NULL;
    char cwd[PATH_MAX], db_path[PATH_MAX];
    int exec_seconds = 600;
    struct stat st;
    pic_store s;
    int i = 1, rc = 0;
    /* A reader that goes away (a closed pipe) does not stop a run. */
    (void)signal(SIGPIPE, SIG_IGN);
    for (int h = 1; h < argc; h++) { /* --help anywhere among the options */
        if (strcmp(argv[h], "--help") == 0 || strcmp(argv[h], "-h") == 0) {
            print_usage(stdout);
            return 0;
        }
        if (argv[h][0] != '-') {
            break;
        }
    }
    while (i < argc && (strcmp(argv[i], "--json") == 0 || strcmp(argv[i], "--stream") == 0 ||
                        strcmp(argv[i], "--commands") == 0)) {
        *(strcmp(argv[i], "--json") == 0 ? &json_events : strcmp(argv[i], "--stream") == 0 ? &force_stream : &commands) = 1;
        i++;
    }
    while (i + 1 < argc && strncmp(argv[i], "--", 2) == 0) {
        if (strcmp(argv[i], "--json") == 0 || strcmp(argv[i], "--stream") == 0 || strcmp(argv[i], "--commands") == 0) {
            *(strcmp(argv[i], "--json") == 0 ? &json_events : strcmp(argv[i], "--stream") == 0 ? &force_stream : &commands) = 1;
            i++;
            continue;
        }
        if (strcmp(argv[i], "--db") == 0) {
            db = argv[i + 1];
        } else if (strcmp(argv[i], "--workspace") == 0) {
            workspace = argv[i + 1];
        } else if (strcmp(argv[i], "--model") == 0) {
            model = argv[i + 1];
        } else if (strcmp(argv[i], "--thinking") == 0) {
            if (pic_thinking_index(argv[i + 1]) < 0) {
                char list[128];
                level_names(list, sizeof list, pic_thinking_names, PIC_THINKING_LEVELS);
                fprintf(stderr, "pic: unknown thinking level %s (%s)\n", argv[i + 1], list);
                return 2;
            }
            thinking_opt = argv[i + 1];
        } else if (strcmp(argv[i], "--context-window") == 0) {
            char *end = NULL;
            long v = strtol(argv[i + 1], &end, 10);
            if (!end || *end || v < 0) {
                return usage();
            }
            context_window = v;
        } else if (strcmp(argv[i], "--exec-timeout") == 0) {
            char *end = NULL;
            long v = strtol(argv[i + 1], &end, 10);
            if (!end || *end || v < 1 || v > 86400) {
                return usage();
            }
            exec_seconds = (int)v;
        } else {
            fprintf(stderr, "pic: unknown option %s\n", argv[i]);
            return usage();
        }
        i += 2;
    }
    /* A leftover option (an unknown one, or one missing its value) is an error
     * before anything is opened: a typo must not create a journal here. */
    if (i < argc && argv[i][0] == '-') {
        fprintf(stderr, "pic: unknown option %s\n", argv[i]);
        return usage();
    }
    if (commands && (!json_events || i >= argc || (strcmp(argv[i], "ask") != 0 && strcmp(argv[i], "run") != 0))) {
        fputs("pic: --commands takes Pi's command lines on stdin for ask or run, with --json\n", stderr);
        return usage();
    }
    /* The model: --model, else the default saved with pic models --default (or
     * Ctrl+S in the model picker), else pic's own. */
    static char default_saved[256];
    {
        char *def = setting("defaultModel");
        (void)snprintf(default_saved, sizeof default_saved, "%s", def && *def ? def : default_model);
        free(def);
    }
    if (!model) {
        static char saved[256];
        char *def = setting("defaultModel");
        (void)snprintf(saved, sizeof saved, "%s", def && *def ? def : default_model);
        free(def);
        model = saved;
    }
    if (i < argc && strcmp(argv[i], "models") == 0) {
        return models_command(argc - i - 1, argv + i + 1);
    }
    if (i < argc && strcmp(argv[i], "settings") == 0) { /* stored in ~/.pic/pic.sqlite */
        if (argc - i == 1) {
            return pic_settings_each(print_setting, NULL) == 0 ? 0 : 1;
        }
        if (argc - i == 2 && argv[i + 1][0] != '-') {
            char *v = setting(argv[i + 1]);
            if (v) {
                puts(v);
            }
            free(v);
            return v ? 0 : 1;
        }
        if (argc - i == 3 && strcmp(argv[i + 1], "--unset") == 0) {
            return set_setting(argv[i + 2], NULL) == 0 ? 0 : 1;
        }
        if (argc - i == 3) {
            return set_setting(argv[i + 1], argv[i + 2]) == 0 ? 0 : 1;
        }
        return usage();
    }
    /* No command: the line mode, when a person is at a terminal. */
    if (i >= argc && !(isatty(STDIN_FILENO) && isatty(STDOUT_FILENO))) {
        return usage();
    }
    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)) {
        return user_command(argc - i, argv + i, workspace);
    }
    if (!db) {
        if (default_db(workspace, db_path, sizeof db_path) != 0) {
            fprintf(stderr, "pic: cannot create %s/.pic\n", workspace);
            return 1;
        }
        db = db_path;
    }
    if (i >= argc || (strcmp(argv[i], "tui") == 0 && argc - i <= 3)) {
        char self[PATH_MAX];
        pic_tui_options t;
        const char *resume = NULL;
        if (i < argc && argc - i == 2 && strcmp(argv[i + 1], "-c") == 0) {
            resume = "latest";
        } else if (i < argc && argc - i == 3 && strcmp(argv[i + 1], "--session") == 0) {
            resume = argv[i + 2];
        } else if (i < argc && argc - i != 1) {
            return usage();
        }
        self_path(argv[0], self, sizeof self);
        t.self = self;
        t.db = db;
        t.workspace = workspace;
        t.model = model;
        t.default_model = default_saved;
        t.exec_seconds = exec_seconds;
        t.context_window = context_window;
        t.resume = resume;
        return pic_tui_main(&t);
    }
    if (strcmp(argv[i], "chat") == 0 && argc - i == 1) {
        return repl(db, workspace, model, exec_seconds, NULL);
    }
    if (strcmp(argv[i], "chat") == 0 && argc - i == 2 && strcmp(argv[i + 1], "-c") == 0) {
        return repl(db, workspace, model, exec_seconds, "latest");
    }
    if (strcmp(argv[i], "chat") == 0 && argc - i == 3 && strcmp(argv[i + 1], "--session") == 0) {
        return repl(db, workspace, model, exec_seconds, argv[i + 2]);
    }
    if (pic_open(&s, db) != 0) {
        fprintf(stderr, "pic: %s\n", s.err);
        pic_close(&s);
        return 1;
    }
    {
        char real[PATH_MAX];
        (void)pic_workspace_touch(realpath(workspace, real) ? real : workspace, db);
    }
    if (strcmp(argv[i], "ask") == 0 && argc - i == 2) {
        rc = ask(&s, workspace, model, NULL, exec_seconds, NULL, argv[i + 1]);
    } else if (strcmp(argv[i], "ask") == 0 && argc - i == 3 && strcmp(argv[i + 1], "-c") == 0) {
        rc = ask(&s, workspace, model, NULL, exec_seconds, "latest", argv[i + 2]);
    } else if (strcmp(argv[i], "ask") == 0 && argc - i == 4 && strcmp(argv[i + 1], "--session") == 0) {
        rc = ask(&s, workspace, model, NULL, exec_seconds, argv[i + 2], argv[i + 3]);
    } else if (strcmp(argv[i], "submit") == 0 && (argc - i == 3 || (argc - i == 5 && strcmp(argv[i + 3], "--session") == 0))) {
        int duplicate = 0;
        char joined[64];
        rc = pic_submit(&s, argv[i + 1], argv[i + 2], argc - i == 5 ? argv[i + 4] : NULL, &duplicate, joined,
                        sizeof joined);
        if (rc == 0) {
            puts(duplicate ? "duplicate: already admitted" : "admitted");
        }
    } 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 (strcmp(argv[i], "import") == 0 && argc - i == 2) {
        char made[64];
        long turns = 0;
        FILE *f = strcmp(argv[i + 1], "-") == 0 ? stdin : fopen(argv[i + 1], "r");
        if (!f) {
            (void)snprintf(s.err, sizeof s.err, "cannot read %s: %s", argv[i + 1], strerror(errno));
            rc = -1;
        } else {
            rc = pic_import_pi(&s, f, made, sizeof made, &turns);
            if (f != stdin) {
                fclose(f);
            }
            if (rc == 0) {
                printf("%s\n", made);
            }
        }
    } else if (strcmp(argv[i], "export") == 0 && argc - i <= 3 && argc - i >= 2 && strcmp(argv[i + 1], "--pi") == 0) {
        rc = pic_export_pi(&s, workspace, argc - i == 3 ? argv[i + 2] : NULL, NULL);
    } else if (strcmp(argv[i], "export") == 0 && (argc - i == 1 || (argc - i == 3 && strcmp(argv[i + 1], "--since") == 0))) {
        char real[PATH_MAX];
        rc = pic_export(&s, realpath(workspace, real) ? real : workspace, argc - i == 3 ? strtoll(argv[i + 2], NULL, 10) : 0,
                        stdout);
    } else if (strcmp(argv[i], "sessions") == 0 && argc - i == 2 && strcmp(argv[i + 1], "--json") == 0) {
        rc = pic_sessions_json(&s, stdout);
    } else if (strcmp(argv[i], "log") == 0 && argc - i >= 2 && argc - i <= 3 && strcmp(argv[i + 1], "--json") == 0) {
        rc = pic_session_log_json(&s, argc - i == 3 ? argv[i + 2] : "latest", stdout);
    } else if (strcmp(argv[i], "sessions") == 0 && argc - i == 1) {
        rc = pic_sessions(&s, stdout);
    } else if (strcmp(argv[i], "log") == 0 && argc - i <= 2) {
        rc = pic_session_log(&s, argc - i == 2 ? argv[i + 1] : "latest", stdout);
    } else if (strcmp(argv[i], "name") == 0 && argc - i == 3) {
        rc = pic_session_name(&s, argv[i + 1], argv[i + 2]);
    } else if (strcmp(argv[i], "fork") == 0 && (argc - i == 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], "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;
        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], "--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);
        } else {
            pic_close(&s);
            return usage();
        }
        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], "dump") == 0 && argc - i == 1) {
        rc = pic_dump(&s);
    } 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(&s);
        if (rc == 0) {
            puts("check: ok");
        }
    } 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);
    return rc == 0 ? 0 : 1;
}