/* pic command line: ask for work, run it durably, inspect the journal. */
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <signal.h>
#include <stdint.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "attach.h"
#include "commands.h"
#include "compact.h"
#include "cred.h"
#include "help.h"
#include "hooks.h"
#include "inbox.h"
#include "input.h"
#include "net.h"
#include "oauth.h"
#include "catalog.h"
#include "userdb.h"
#include "pic.h"
#include "procs.h"
#include "prompts.h"
#include "rewind.h"
#include "rpc.h"
#include "skills.h"
#include "platform.h"
#include "tui/tui.h"
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
/* --context-window: replaces the model's window for automatic compaction (-1: keep). */
static long context_window = -1;
/* --thinking: the thinking level asked for on the command line (NULL: the settings). */
static const char *thinking_opt;
/* --json: Pi-style events on stdout; --stream: stream reply text even when
* stdout is not a terminal. */
static int json_events, force_stream;
/* --commands: Pi's RPC command lines on stdin steer ask and run (with --json). */
static int main_commands;
/* The line mode: ask prints the conversation it joined only when it changes. */
static int quiet;
static char last_session[64]; /* the line mode's conversation, set by ask */
static pic_events events;
/* --mode rpc (rpc.c): a new conversation's id, chosen before its first
* prompt, and what runs once ask has admitted a prompt. */
static const char *ask_new_id;
static void (*ask_admitted)(void *ctx);
static void *ask_admitted_ctx;
/* The command hooks (hooks.h), loaded once the workspace and journal are known. */
static pic_hooks *hooks;
/* PIC_HOOK_OWNER, taken from the environment so tools and hooks never see it. */
static char 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->trial = bench.trial;
s->max_requests = bench.max_requests;
s->policy = &pic_compact_policy;
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);
}
/* ---- models and settings ------------------------------------------------ */
static int usage(void);
/* A setting (malloc'd), or NULL: picu_setting in ~/.pic/pic.sqlite. */
static char *setting(const char *key) { return pic_setting(key); }
/* Sets KEY to VALUE in picu_setting. */
static int set_setting(const char *key, const char *value) { return pic_setting_set(key, value); }
static int print_project(void *ctx, const pic_project *p) {
(void)ctx;
printf("%s\t%s\t%s\t%s\n", p->name, p->kind, p->state, p->remote);
return 0;
}
static int print_setting(void *ctx, const char *key, const char *value) {
(void)ctx;
printf("%s=%s\n", key, value);
return 0;
}
static void level_names(char *out, size_t cap, const char *const *names, int n) {
size_t used = 0;
out[0] = '\0';
for (int i = 0; i < n && used < cap; i++) {
used += (size_t)snprintf(out + used, cap - used, "%s%s", i ? ", " : "", names[i]);
}
}
typedef struct {
sqlite3_stmt *q;
int json, all, available;
char provider[64];
} listing;
static int list_model(void *ctx, const char *provider, const char *json) {
listing *l = ctx;
char levels[96];
if (strcmp(provider, l->provider) != 0) {
(void)snprintf(l->provider, sizeof l->provider, "%s", provider);
l->available = pic_model_available(provider);
}
if (!l->all && !l->available) {
return 0;
}
sqlite3_bind_text(l->q, 1, json, -1, SQLITE_STATIC);
sqlite3_bind_text(l->q, 2, provider, -1, SQLITE_STATIC);
sqlite3_bind_int(l->q, 3, l->available);
pic_model_thinking_json(json, levels, sizeof levels);
sqlite3_bind_text(l->q, 4, levels, -1, SQLITE_STATIC);
if (sqlite3_step(l->q) == SQLITE_ROW) {
printf("%s\n", (const char *)sqlite3_column_text(l->q, l->json ? 0 : 1));
}
sqlite3_reset(l->q);
return 0;
}
/* pic models: the catalog (Pi's) plus the models file, for providers with a
* key unless --all; --refresh fetches fresher lists first. */
static int models_command(int argc, char **argv) {
listing l;
sqlite3 *db = NULL;
int refresh = 0;
memset(&l, 0, sizeof l);
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "--json") == 0) {
l.json = 1;
} else if (strcmp(argv[i], "--all") == 0) {
l.all = 1;
} else if (strcmp(argv[i], "--refresh") == 0) {
refresh = 1;
} else if (strcmp(argv[i], "--default") == 0 && i + 1 < argc) {
pic_model m;
char err[PIC_ERR_CAP];
if (pic_model_resolve(argv[i + 1], &m, err, sizeof err) != 0) {
fprintf(stderr, "pic: %s\n", err);
return 1;
}
if (set_setting("defaultModel", argv[i + 1]) != 0) {
fprintf(stderr, "pic: cannot save the setting in ~/.pic/pic.sqlite\n");
return 1;
}
printf("default model: %s\n", argv[i + 1]);
return 0;
} else if (strcmp(argv[i], "--thinking-default") == 0 && i + 1 < argc) {
if (pic_thinking_index(argv[i + 1]) < 0) {
char list[128];
level_names(list, sizeof list, pic_thinking_names, PIC_THINKING_LEVELS);
fprintf(stderr, "pic: unknown thinking level %s (%s)\n", argv[i + 1], list);
return 1;
}
if (set_setting("defaultThinkingLevel", argv[i + 1]) != 0) {
fprintf(stderr, "pic: cannot save the setting in ~/.pic/pic.sqlite\n");
return 1;
}
printf("default thinking level: %s\n", argv[i + 1]);
return 0;
} else {
return usage();
}
}
if (refresh) {
char err[PIC_ERR_CAP];
if (pic_catalog_refresh(1, err, sizeof err) != 0) {
fprintf(stderr, "pic: model catalog: %s (showing what is stored)\n", err);
}
}
if (sqlite3_open(":memory:", &db) != SQLITE_OK ||
sqlite3_prepare_v2(db,
"SELECT json_object('model', ?2 || '/' || json_extract(?1, '$.id'), 'provider', ?2,"
" 'id', json_extract(?1, '$.id'), 'name', coalesce(json_extract(?1, '$.name'), json_extract(?1, '$.id')),"
" 'contextWindow', json_extract(?1, '$.contextWindow'),"
" 'reasoning', json(iif(json_extract(?1, '$.reasoning'), 'true', 'false')), 'thinkingLevels', json(?4),"
" 'cost', json(coalesce(json_extract(?1, '$.cost'),"
" '{\"input\":0,\"output\":0,\"cacheRead\":0,\"cacheWrite\":0}')),"
" 'available', json(iif(?3, 'true', 'false'))),"
" printf('%-48s %s', ?2 || '/' || json_extract(?1, '$.id'),"
" coalesce(json_extract(?1, '$.name'), '') || CASE WHEN ?3 THEN '' ELSE ' (no key)' END)",
-1, &l.q, NULL) != SQLITE_OK) {
sqlite3_close(db);
return 1;
}
(void)pic_catalog_each(list_model, &l);
l.provider[0] = '\0';
(void)pic_models_each_user(list_model, &l);
sqlite3_finalize(l.q);
sqlite3_close(db);
return 0;
}
/* This executable's path, for the TUI's child processes. */
static void self_path(const char *argv0, char *out, size_t cap) {
#ifdef __APPLE__
uint32_t size = (uint32_t)cap;
char raw[PATH_MAX];
if (_NSGetExecutablePath(raw, &size) == 0 && realpath(raw, out)) {
return;
}
#else
ssize_t n = readlink("/proc/self/exe", out, cap - 1);
if (n > 0) {
out[n] = '\0';
return;
}
#endif
if (!realpath(argv0, out)) {
(void)snprintf(out, cap, "%s", argv0);
}
}
/* 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"
"\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 auth login PROVIDER [--api-key] [--no-browser] | auth logout PROVIDER | auth status\n"
" pic login PROVIDER | logout PROVIDER | keys\n"
" pic settings [KEY [VALUE] | --unset KEY] | trust [yes | no]\n"
" pic prompts | skills | hooks | ps [--all] | usage --by-trial|--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-opus-5-5";
/* Pi's defaultModelPerProvider (model-resolver.ts), in its order: with no
* usable saved default, the first of these whose provider has a key. */
static const char *const default_per_provider[][2] = {
{"amazon-bedrock", "us.anthropic.claude-opus-5-5"},
{"ant-ling", "Ring-2.6-1T"},
{"anthropic", "claude-opus-5-5"},
{"openai", "gpt-6.2-sol"},
{"azure", "gpt-6.2-sol"},
{"openai-codex", "gpt-6.2-sol"},
{"radius", "balanced"},
{"nvidia", "nvidia/nemotron-3.5-super-vl-120b-a12b"},
{"deepseek", "deepseek-v4-pro"},
{"google", "gemini-4-argon"},
{"google-vertex", "gemini-4-argon"},
{"github-copilot", "gpt-6.1-sol"},
{"openrouter", "moonshotai/kimi-k2.7-code"},
{"vercel-ai-gateway", "zai/glm-5.3"},
{"xai", "grok-4.7"},
{"groq", "openai/gpt-oss-120b"},
{"cerebras", "gpt-oss-120b"},
{"zai", "glm-5.3"},
{"zai-coding-cn", "glm-5.3"},
{"mistral", "devstral-medium-latest"},
{"minimax", "MiniMax-M3"},
{"minimax-cn", "MiniMax-M3"},
{"moonshotai", "kimi-k2.7-code"},
{"moonshotai-cn", "kimi-k2.7-code"},
{"huggingface", "moonshotai/Kimi-K2.7-Code"},
{"fireworks", "accounts/fireworks/models/kimi-k3"},
{"together", "moonshotai/Kimi-K3"},
{"baseten", "zai-org/GLM-5.3"},
{"opencode", "kimi-k2.7-code"},
{"opencode-go", "kimi-k3.1-pro"},
{"kimi-coding", "kimi-for-coding"},
{"meta", "muse-spark-1.3"},
{"cloudflare-workers-ai", "@cf/moonshotai/kimi-k2.7-code"},
{"cloudflare-ai-gateway", "workers-ai/@cf/moonshotai/kimi-k2.7-code"},
{"qwen-token-plan", "qwen3.8-max"},
{"qwen-token-plan-cn", "qwen3.8-max"},
{"qwen-token-plan-individual", "qwen3.8-max"},
{"qwen-token-plan-individual-cn", "qwen3.8-max"},
{"xiaomi", "mimo-v2.6-pro"},
{"xiaomi-token-plan-cn", "mimo-v2.6-pro"},
{"xiaomi-token-plan-ams", "mimo-v2.6-pro"},
{"xiaomi-token-plan-sgp", "mimo-v2.6-pro"},
};
typedef struct {
sqlite3_stmt *id; /* json_extract(?1, '$.id') */
char provider[64];
int available;
char *out;
size_t cap;
} first_model;
static int first_available(void *ctx, const char *provider, const char *json) {
first_model *f = ctx;
if (strcmp(provider, f->provider) != 0) {
(void)snprintf(f->provider, sizeof f->provider, "%s", provider);
f->available = pic_model_available(provider);
}
if (!f->available) {
return 0;
}
sqlite3_bind_text(f->id, 1, json, -1, SQLITE_STATIC);
if (sqlite3_step(f->id) == SQLITE_ROW && sqlite3_column_text(f->id, 0)) {
(void)snprintf(f->out, f->cap, "%s/%s", provider, (const char *)sqlite3_column_text(f->id, 0));
}
sqlite3_reset(f->id);
return f->out[0] != '\0';
}
/* The model to start on, as Pi's findInitialModel picks it: the saved
* default when its provider has a key; else Pi's default for the first
* provider with one; else the first model with a key (catalog, then the
* models file); else pic's own default, whose error then names the key. */
static void initial_model(char *out, size_t cap) {
char *def = setting("defaultModel");
pic_model m;
char err[PIC_ERR_CAP];
if (def && *def && pic_model_resolve(def, &m, err, sizeof err) == 0 && pic_model_available(m.provider)) {
(void)snprintf(out, cap, "%s", def);
free(def);
return;
}
free(def);
for (size_t i = 0; i < sizeof default_per_provider / sizeof default_per_provider[0]; i++) {
char *found;
if (!pic_model_available(default_per_provider[i][0]) ||
!(found = pic_catalog_find(default_per_provider[i][0], default_per_provider[i][1]))) {
continue;
}
free(found);
(void)snprintf(out, cap, "%s/%s", default_per_provider[i][0], default_per_provider[i][1]);
return;
}
{
sqlite3 *db = NULL;
first_model f;
memset(&f, 0, sizeof f);
out[0] = '\0';
f.out = out;
f.cap = cap;
if (sqlite3_open(":memory:", &db) == SQLITE_OK &&
sqlite3_prepare_v2(db, "SELECT json_extract(?1, '$.id') WHERE json_valid(?1)", -1, &f.id, NULL) == SQLITE_OK) {
(void)pic_catalog_each(first_available, &f);
f.provider[0] = '\0';
if (!out[0]) {
(void)pic_models_each_user(first_available, &f);
}
}
sqlite3_finalize(f.id);
sqlite3_close(db);
}
if (!out[0]) {
(void)snprintf(out, cap, "%s", default_model);
}
}
/* WORKSPACE/.pic/journal.sqlite, creating .pic if needed. */
static int default_db(const char *workspace, char *out, size_t cap) {
char dir[PATH_MAX];
if (snprintf(dir, sizeof dir, "%s/.pic", workspace) >= (int)sizeof dir ||
snprintf(out, cap, "%s/journal.sqlite", dir) >= (int)cap) {
return -1;
}
if (mkdir(dir, 0700) != 0 && errno != EEXIST) {
return -1;
}
return 0;
}
/* pic trust [yes|no] | scoped-models [--clear | --set PATTERN...] | bug [--list | TEXT]:
* the user-level state the terminal's /trust, /scoped-models and /bug keep
* in ~/.pic/pic.sqlite. */
static int print_pattern(void *ctx, const char *pattern) {
(void)ctx;
puts(pattern);
return 0;
}
static int print_bug(void *ctx, long long id, long long ms, const char *workspace, const char *description) {
(void)ctx;
printf("%lld\t%lld\t%s\t%s\n", id, ms, workspace, description);
return 0;
}
/* The user's templates, and the workspace's when it is trusted. */
static int load_prompts(pic_prompts *p, const char *workspace) {
char real[PATH_MAX];
return pic_prompts_load(p, workspace, pic_trust_get(realpath(workspace, real) ? real : workspace) == 1);
}
/* The user's skills, and the workspace's when it is trusted. */
static int load_skills(pic_skills *s, const char *workspace, FILE *warn) {
char real[PATH_MAX];
return pic_skills_load(s, workspace, pic_trust_get(realpath(workspace, real) ? real : workspace) == 1, warn);
}
/* 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;
}
/* 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 key_login(const char *provider, const pic_model *mp) {
char key[2 * PIC_CRED_KEY_CAP], err[256];
pic_model m = *mp;
long n;
int rc;
if (isatty(STDIN_FILENO)) {
char prompt[160];
(void)snprintf(prompt, sizeof prompt, "API key for %s: ", provider);
n = pic_tty_secret(prompt, key, sizeof key, err, sizeof err);
} else {
/* read(2), not stdio: no copy of the key is left in a FILE buffer. */
size_t got = 0;
char c;
ssize_t r;
while (got < sizeof key && ((r = read(STDIN_FILENO, &c, 1)) > 0 || (r < 0 && errno == EINTR))) {
if (r < 0) {
continue;
}
if (c == '\n') {
break;
}
key[got++] = c;
}
c = 0;
n = got < sizeof key ? (long)got : -1;
if (n < 0) {
(void)snprintf(err, sizeof err, "the key is longer than %zu bytes", sizeof key - 1);
} else {
while (n > 0 && (key[n - 1] == '\r' || key[n - 1] == ' ' || key[n - 1] == '\t')) {
n--;
}
key[n] = '\0';
}
}
if (n < 0) {
pic_cred_wipe(key, sizeof key);
fprintf(stderr, "pic: %s\n", err);
return 1;
}
rc = pic_cred_login(provider, key, err, sizeof err);
pic_cred_wipe(key, sizeof key);
if (rc != 0) {
fprintf(stderr, "pic: %s\n", err);
return 1;
}
printf("Saved the API key for %s, sealed, in ~/.pic/pic.sqlite.\n", provider);
if (m.key_env[0] && getenv(m.key_env) && *getenv(m.key_env)) {
printf("%s is set in this environment and takes precedence over the stored key.\n", m.key_env);
}
return 0;
}
/* 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 set in this environment and takes precedence over the sign-in.\n", m->key_env);
}
return 0;
}
/* pic login PROVIDER: on a terminal, a provider with a subscription sign-in
* offers it beside an API key; otherwise the key. */
static int login_command(const char *provider) {
pic_model m;
const char *label;
if (known_provider(provider, &m) != 0) {
return 1;
}
label = pic_cred_oauth_label(provider);
if (label && 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, &m);
}
(void)snprintf(err, sizeof err, "Enter 1 or 2.");
puts(err);
}
}
return key_login(provider, &m);
}
/* pic auth login PROVIDER [--api-key] [--no-browser], as Pi's: account
* sign-in unless --api-key asks for a key; a provider without one takes a key. */
static int auth_login(int argc, char **argv) {
const char *provider = NULL;
int api_key = 0, flags = 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], "--no-browser") == 0) {
flags |= PIC_CRED_NO_BROWSER;
} else if (strcmp(argv[k], "--pipe") == 0) {
flags |= PIC_CRED_PIPE;
} else if (argv[k][0] == '-' || provider) {
provider = NULL;
break;
} else {
provider = argv[k];
}
}
if (!provider) {
fputs("usage: pic auth login PROVIDER [--api-key] [--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 (flags & PIC_CRED_PIPE && (api_key || !pic_cred_oauth_label(provider))) {
fprintf(stderr, "pic: %s has no subscription sign-in\n", provider);
return 1;
}
if (api_key || !pic_cred_oauth_label(provider)) {
return key_login(provider, &m);
}
return sign_in(provider, &m, flags);
}
static int logout_command(const char *provider) {
pic_cred_source was = pic_cred_source_of(provider, NULL, NULL);
int rc = pic_cred_logout(provider);
if (rc < 0) {
fputs("pic: cannot write ~/.pic/pic.sqlite\n", stderr);
return 1;
}
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;
}
static int print_status(void *ctx, const char *name, const char *kind, long long created_ms, long long used_ms) {
char added[32], used[32], how[96], src[200];
time_t t = (time_t)(created_ms / 1000);
struct tm tm;
const char *label = pic_cred_oauth_label(name);
int *n = ctx;
(void)strftime(added, sizeof added, "%Y-%m-%d %H:%M", localtime_r(&t, &tm));
t = (time_t)(used_ms / 1000);
if (used_ms) {
(void)strftime(used, sizeof used, "%Y-%m-%d %H:%M", localtime_r(&t, &tm));
}
(void)snprintf(how, sizeof how, "%s", strcmp(kind, "oauth") != 0 ? "API key" : label ? label : "subscription sign-in");
pic_provider_source(name, src, sizeof src);
printf("%-20s %-24s added %s %s%s [%s]\n", name, how, added, used_ms ? "last used " : "never used", used_ms ? used : "",
src);
(*n)++;
return 0;
}
/* pic auth status: each stored credential, how it signs in, and when it was
* stored and last used, then the source each provider's requests use (a stored credential
* first, then the models file's apiKey, then the variable; no value is read). */
static int print_unstored(void *ctx, const char *provider) {
char src[200];
int *n = ctx;
if (pic_cred_stored(provider)) {
return 0;
}
pic_provider_source(provider, src, sizeof src);
if (strcmp(src, "none") != 0 && strcmp(src, "unknown") != 0) {
printf("%-20s not stored [%s]\n", provider, src);
(*n)++;
}
return 0;
}
static int auth_status(void) {
int n = 0, others = 0;
if (pic_cred_each(print_status, &n) != 0) {
fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr);
return 1;
}
if (n == 0) {
puts("No stored credentials (pic auth login PROVIDER signs in or stores a key).");
}
(void)pic_providers_each(print_unstored, &others);
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;
}
static int user_command(int argc, char **argv, const char *workspace) {
char real[PATH_MAX];
const char *ws = realpath(workspace, real) ? real : workspace;
if (strcmp(argv[0], "login") == 0 && argc == 2) {
return login_command(argv[1]);
}
if (strcmp(argv[0], "logout") == 0 && argc == 2) {
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 && strcmp(argv[1], "logout") == 0) {
return logout_command(argv[2]);
}
if (strcmp(argv[0], "auth") == 0 && argc == 2 && strcmp(argv[1], "status") == 0) {
return auth_status();
}
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
* | 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, "steer") != 0 && strcmp(type, "follow_up") != 0 && strcmp(type, "abort") != 0) {
fprintf(stderr, "pic: send takes 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 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 const char *model_flag;
static int attach_command(const char *argv0, const char *db, const char *workspace, const char *thinking, int argc,
char **argv) {
char self[PATH_MAX];
pic_attach_options o = {db, "latest", -1, 0, 0, 1, self, workspace, model_flag, thinking};
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 = strtoll(argv[++k], &end, 10);
if (!end || *end || o.from < 0) {
fputs("pic: --from takes an entry number (0: the whole conversation)\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);
}
/* 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, first) == 0 ? 0 : -1;
}
/* A standalone process (not the line mode, not a terminal's child) ends the
* conversation it started on its way out. */
static void end_own(pic_store *s, const char *sid) {
if (s->hooks && sid[0] && !quiet && !pic_hooks_owned(s->hooks)) {
char saved[PIC_ERR_CAP];
(void)snprintf(saved, sizeof saved, "%s", s->err);
if (pic_hooks_session_end(s, sid, "other") != 0) {
fprintf(stderr, "pic: warning: SessionEnd hooks: %s\n", s->err);
}
(void)snprintf(s->err, sizeof s->err, "%s", saved);
}
}
static int ask(pic_store *s, const char *workspace, const char *model, const char *url, int exec_seconds,
const char *session, const char *text, pic_image *images, size_t nimages) {
char key[64], joined[64] = "", sid[64] = "";
int fresh = 0;
int64_t first = 0;
pic_provider provider;
char *expanded = NULL;
int duplicate = 0, rc;
int64_t now = pic_platform_get()->wall_ns();
(void)snprintf(key, sizeof key, "ask-%lld-%09ld-%ld", (long long)(now / 1000000000), (long)(now % 1000000000),
(long)getpid());
memset(&provider, 0, sizeof provider);
/* The provider first: a model that cannot be had leaves nothing admitted. */
if (model_provider(&provider, model, url, workspace, s->err, sizeof s->err) != 0) {
if (provider.free) {
provider.free(&provider);
}
return -1;
}
if (strncmp(text, "/skill:", 7) == 0) { /* a skill: submit its instructions and the arguments */
pic_skills skills;
int found = 0;
if (load_skills(&skills, workspace, NULL) == 0) {
found = pic_skills_expand(&skills, text, &expanded, s->err, sizeof s->err);
pic_skills_free(&skills);
}
if (found < 0) {
provider.free(&provider);
return -1;
}
} else {
expanded = expand_template((void *)(uintptr_t)workspace, text); /* a prompt template */
}
/* Hooks see the conversation before the prompt is admitted, so a new one
* gets its id now; UserPromptSubmit may reject the prompt. */
if (s->hooks && hook_conversation(s, session, sid, &fresh, text, &first) != 0) {
free(expanded);
end_own(s, sid);
provider.free(&provider);
return -1;
}
{ /* images that cannot go inline become notes after the text, as Pi's */
char *with_notes = pic_image_prepare(expanded ? expanded : text, images, &nimages, s->err, sizeof s->err);
s->model = built_model; /* the request keeps its model and level, to finish with them */
s->thinking = built_thinking;
rc = with_notes ? pic_submit_hooked(s, key, with_notes, images, nimages, fresh ? NULL : sid[0] ? sid : session,
fresh ? sid : !session ? ask_new_id : NULL, first, &duplicate, joined,
sizeof joined)
: -1;
s->model = s->thinking = NULL;
free(with_notes);
}
free(expanded);
if (rc != 0) {
end_own(s, sid);
provider.free(&provider);
return -1;
}
{ /* this request runs first, and commands steer it, whatever else the journal holds */
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_submission WHERE request_key = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
s->running = sqlite3_column_int64(q, 0);
}
}
sqlite3_finalize(q);
}
if (ask_admitted) {
ask_admitted(ask_admitted_ctx);
}
if (!quiet) {
fprintf(stderr, "pic: session %s, request %s (pic cancel %s to stop it)\n", joined, key, key);
}
if (session != joined && joined[0] && quiet) {
(void)snprintf(last_session, sizeof last_session, "%s", joined);
}
s->provider_for = provider_for;
s->session_only = 1; /* its own conversation's requests: another's unfinished one is left to it */
pic_events_init(&events, stdout, stderr, json_events, !json_events && (force_stream || isatty(STDOUT_FILENO)));
s->events = &events;
if (context_window >= 0) {
provider.context_window = context_window;
}
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 (*admitted)(void *ctx), void *ctx) {
const char *saved = thinking_opt;
int rc;
thinking_opt = thinking;
ask_new_id = new_id;
ask_admitted = admitted;
ask_admitted_ctx = ctx;
rc = ask(s, rpc_workspace, model, NULL, rpc_exec_seconds, session, text, images, n);
thinking_opt = saved;
ask_new_id = NULL;
ask_admitted = NULL;
ask_admitted_ctx = NULL;
return rc;
}
static int rpc_provider(pic_provider *p, const char *model, const char *thinking, char *err, size_t errcap) {
const char *saved = thinking_opt;
int rc;
thinking_opt = thinking;
rc = model_provider(p, model, NULL, rpc_workspace, err, errcap);
thinking_opt = saved;
if (rc == 0 && context_window >= 0) {
p->context_window = context_window;
}
return rc;
}
static int rpc_level(const char *model, char *out, size_t cap, char *err, size_t errcap) {
pic_model m;
if (pic_model_resolve(model, &m, err, errcap) != 0) { /* the first prompt reports it */
(void)snprintf(out, cap, "%s", thinking_opt ? thinking_opt : "medium");
return 0;
}
return thinking_level(&m, out, cap, err, errcap);
}
/* ask [-c | --session ID] [--image PATH]... TEXT: each image read through
* the input reader and sniffed as Pi's read does. 2 for a usage error. */
/* 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;
}
}
rc = ask(s, workspace, model, NULL, exec_seconds, session, argv[argc - 1], images, n);
done:
for (size_t k = 0; k < n; k++) {
free(bytes[k]);
}
free(bytes);
free(images);
return rc;
}
/* -p / --print, Pi's print mode: the messages and @files from the command
* line, then run them as ask does. */
static int print_mode;
static char *print_messages[256];
static size_t print_nmessages;
static char *print_files[256];
static size_t print_nfiles;
static int print_add(char **list, size_t *n, char *arg) {
if (*n >= 256) {
fputs("pic: too many arguments\n", stderr);
return -1;
}
list[(*n)++] = arg;
return 0;
}
/* Piped stdin, trimmed as Pi's readPipedStdin does; NULL when stdin is a
* terminal or holds only whitespace. */
static char *read_piped_stdin(void) {
size_t len = 0, cap = 4096, start = 0;
char *buf = malloc(cap);
if (!buf || isatty(STDIN_FILENO)) {
free(buf);
return NULL;
}
for (;;) {
ssize_t n;
if (len + 1 >= cap) {
char *bigger = realloc(buf, cap * 2);
if (!bigger) {
free(buf);
return NULL;
}
buf = bigger;
cap *= 2;
}
n = read(STDIN_FILENO, buf + len, cap - len - 1);
if (n < 0 && errno == EINTR) {
continue;
}
if (n <= 0) {
break;
}
len += (size_t)n;
}
while (len > 0 && isspace((unsigned char)buf[len - 1])) {
len--;
}
while (start < len && isspace((unsigned char)buf[start])) {
start++;
}
if (start == len) {
free(buf);
return NULL;
}
memmove(buf, buf + start, len - start);
buf[len - start] = '\0';
return buf;
}
static int grow_text(char **buf, size_t *len, size_t *cap, const char *s, size_t n) {
if (*len + n + 1 > *cap) {
size_t c = *cap ? *cap : 4096;
char *p;
while (c < *len + n + 1) {
c *= 2;
}
if (!(p = realloc(*buf, c))) {
return -1;
}
*buf = p;
*cap = c;
}
memcpy(*buf + *len, s, n);
*len += n;
(*buf)[*len] = '\0';
return 0;
}
/* Pi's processFileArguments: each file as <file name="PATH">, its text
* between newlines, or for an image the empty tag and the image attached.
* Empty files are skipped; a file that cannot be read ends the run. */
static int attach_files(const char *workspace, char **text, size_t *len, size_t *cap, pic_image *images, char **bytes,
size_t *nimages) {
char real[PATH_MAX];
const char *base = realpath(workspace, real) ? real : workspace;
for (size_t k = 0; k < print_nfiles; k++) {
const char *arg = print_files[k], *home = getenv("HOME");
char path[PATH_MAX], *data;
size_t n = 0;
int ok;
if (arg[0] == '/') {
ok = snprintf(path, sizeof path, "%s", arg) < (int)sizeof path;
} else if (arg[0] == '~' && (arg[1] == '/' || !arg[1]) && home) {
ok = snprintf(path, sizeof path, "%s%s", home, arg + 1) < (int)sizeof path;
} else {
ok = snprintf(path, sizeof path, "%s/%s", base, arg) < (int)sizeof path;
}
if (!ok) {
fprintf(stderr, "pic: Error: File not found: %s\n", arg);
return -1;
}
if (!(data = pic_input_read(path, 256u << 20, 0, &n, NULL))) {
if (errno == ENOENT) {
fprintf(stderr, "pic: Error: File not found: %s\n", path);
} else {
fprintf(stderr, "pic: Error: Could not read file %s: %s\n", path, strerror(errno));
}
return -1;
}
if (n == 0) {
free(data);
continue;
}
if (pic_image_sniff((const unsigned char *)data, n)) {
bytes[*nimages] = data;
images[*nimages].data = (const unsigned char *)data;
images[*nimages].len = n;
images[*nimages].mime = NULL;
(*nimages)++;
ok = grow_text(text, len, cap, "<file name=\"", 12) == 0 && grow_text(text, len, cap, path, strlen(path)) == 0 &&
grow_text(text, len, cap, "\"></file>\n", 10) == 0;
} else {
const char *body = n >= 3 && memcmp(data, "\xEF\xBB\xBF", 3) == 0 ? data + 3 : data;
ok = grow_text(text, len, cap, "<file name=\"", 12) == 0 && grow_text(text, len, cap, path, strlen(path)) == 0 &&
grow_text(text, len, cap, "\">\n", 3) == 0 && grow_text(text, len, cap, body, strlen(body)) == 0 &&
grow_text(text, len, cap, "\n</file>\n", 9) == 0;
free(data);
}
if (!ok) {
fputs("pic: out of memory\n", stderr);
return -1;
}
}
return 0;
}
/* pic -p: stdin, the @files and the first message make one prompt, joined as
* Pi's buildInitialMessage joins them (no separator); each further message
* continues the conversation. Nothing to send is not an error, as in Pi. */
static int print_command(pic_store *s, const char *workspace, const char *model, int exec_seconds, const char *session) {
pic_image images[256];
char *bytes[256], *text = NULL, *stdin_text = 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 && text) {
rc = ask(s, workspace, model, NULL, exec_seconds, session, text, images, nimages);
}
for (size_t k = first; rc == 0 && k < print_nmessages; k++) {
rc = ask(s, workspace, model, NULL, exec_seconds, "latest", print_messages[k], NULL, 0);
}
for (size_t k = 0; k < nimages; k++) {
free(bytes[k]);
}
free(text);
return rc;
}
/* Whether CMD ("/name") names a prompt template, or ("/skill:name") a skill. */
static int is_template(const char *workspace, const char *cmd) {
pic_prompts p;
int found = 0;
if (strncmp(cmd, "/skill:", 7) == 0) {
pic_skills k;
if (load_skills(&k, workspace, NULL) == 0) {
found = pic_skills_find(&k, cmd + 7) != NULL;
pic_skills_free(&k);
}
return found;
}
if (load_prompts(&p, workspace) == 0) {
found = pic_prompts_find(&p, cmd + 1) != NULL;
pic_prompts_free(&p);
}
return found;
}
static const char repl_help[] =
"Type a message to continue the conversation (a line ending in \\ continues on the next).\n"
" /new start a new conversation\n"
" /resume ID continue another conversation (/sessions lists them)\n"
" /sessions list conversations\n"
" /log this conversation so far\n"
" /name NAME name this conversation\n"
" /fork [ENTRY] branch this conversation (from ENTRY, see /log)\n"
" /compact [FOCUS] summarize the history now\n"
" /model [NAME] show or change the model (provider/model)\n"
" /NAME [ARGS] a prompt template (pic prompts lists them)\n"
" /skill:NAME [ARGS] a skill (pic skills lists them)\n"
" /help /quit Ctrl-C cancels a running reply; Ctrl-D quits\n";
/* Reads one message: lines ending in a backslash continue it. NULL at EOF;
* an empty string after a Ctrl-C at the prompt. */
static char *read_input(void) {
char line[8192], *all = NULL;
size_t len = 0;
for (;;) {
size_t n;
char *grown;
fputs(all ? ". " : "> ", stdout);
fflush(stdout);
if (!fgets(line, sizeof line, stdin)) {
if (ferror(stdin) && errno == EINTR) {
clearerr(stdin);
pic_interrupted = 0;
fputc('\n', stdout);
free(all);
all = malloc(1);
if (all) {
all[0] = '\0';
}
return all;
}
if (all) {
return all; /* EOF after a continued line: send what there is */
}
return NULL;
}
n = strcspn(line, "\n");
line[n] = '\0';
grown = realloc(all, len + n + 2);
if (!grown) {
free(all);
return NULL;
}
all = grown;
memcpy(all + len, line, n + 1);
len += n;
if (n > 0 && line[n - 1] == '\\') {
all[len - 1] = '\n';
all[len] = '\0';
continue;
}
return all;
}
}
/* SessionEnd for the conversations this process started (the line mode,
* which opens the journal only while it handles an input). */
static void end_conversations(const char *db, const char *reason) {
pic_store s;
if (!hooks) {
return;
}
if (open_store(&s, db) != 0 || pic_hooks_end_owned(&s, reason) != 0) {
fprintf(stderr, "pic: warning: SessionEnd hooks: %s\n", s.err);
}
pic_close(&s);
}
/* pic with no command, in a terminal: a prompt that continues one
* conversation. The journal is open only while an input is handled, so
* other pic commands can use it between messages. */
static int repl(const char *db, const char *workspace, const char *model, int exec_seconds, const char *resume) {
char current[64] = "", modelbuf[128];
char *in;
(void)snprintf(modelbuf, sizeof modelbuf, "%s", model);
quiet = 1;
catch_interrupt();
if (resume) { /* -c: the latest conversation; --session ID: that one */
pic_store s;
int rc = open_store(&s, db) != 0 ? -1 : pic_session_resolve(&s, resume, current, sizeof current);
if (rc != 0) {
fprintf(stderr, "pic: %s\n", s.err);
}
pic_close(&s);
if (rc != 0) {
return 1;
}
}
printf("pic: %s in %s, %s%s (/help for commands)\n", modelbuf, workspace, current[0] ? "continuing " : "a new conversation",
current);
while ((in = read_input()) != NULL) {
char *cmd = in, *arg;
pic_store s;
int rc = 0;
while (*cmd == ' ' || *cmd == '\t') {
cmd++;
}
if (!*cmd) {
free(in);
continue;
}
arg = cmd[0] == '/' ? cmd + strcspn(cmd, " \t") : NULL;
if (arg) {
if (*arg) {
*arg++ = '\0';
}
while (*arg == ' ' || *arg == '\t') {
arg++;
}
}
if (arg && (strcmp(cmd, "/quit") == 0 || strcmp(cmd, "/exit") == 0)) {
free(in);
break;
}
if (arg && strcmp(cmd, "/help") == 0) {
fputs(repl_help, stdout);
free(in);
continue;
}
if (arg && strcmp(cmd, "/new") == 0) {
end_conversations(db, "clear");
current[0] = '\0';
puts("pic: the next message starts a new conversation");
free(in);
continue;
}
if (arg && strcmp(cmd, "/model") == 0) {
pic_model m;
char err[PIC_ERR_CAP];
if (*arg && pic_model_resolve(arg, &m, err, sizeof err) != 0) {
fprintf(stderr, "pic: %s\n", err);
} else if (*arg) {
(void)snprintf(modelbuf, sizeof modelbuf, "%s", arg);
}
printf("pic: model %s\n", modelbuf);
free(in);
continue;
}
if (open_store(&s, db) != 0) {
fprintf(stderr, "pic: %s\n", s.err);
pic_close(&s);
free(in);
continue;
}
if (!arg) {
last_session[0] = '\0';
rc = ask(&s, workspace, modelbuf, NULL, exec_seconds, current[0] ? current : NULL, in, NULL, 0);
if (last_session[0] && strcmp(last_session, current) != 0) {
(void)snprintf(current, sizeof current, "%s", last_session);
}
} else if (strcmp(cmd, "/sessions") == 0) {
rc = pic_sessions(&s, stdout);
} else if (strcmp(cmd, "/log") == 0) {
rc = pic_session_log(&s, *arg ? arg : current[0] ? current : "latest", stdout);
} else if (strcmp(cmd, "/resume") == 0 && *arg) {
char id[64];
rc = pic_session_resolve(&s, arg, id, sizeof id);
if (rc == 0 && strcmp(id, current) != 0 && hooks) {
rc = pic_hooks_end_owned(&s, "other");
}
if (rc == 0) {
(void)snprintf(current, sizeof current, "%s", id);
printf("pic: now in %s\n", id);
}
} else if (strcmp(cmd, "/name") == 0 && *arg && current[0]) {
rc = pic_session_name(&s, current, arg);
} else if (strcmp(cmd, "/fork") == 0 && current[0]) {
char made[64];
rc = pic_fork(&s, current, *arg ? strtoll(arg, NULL, 10) : 0, made, sizeof made);
if (rc == 0 && hooks) {
rc = pic_hooks_end_owned(&s, "other");
}
if (rc == 0) {
(void)snprintf(current, sizeof current, "%s", made);
printf("pic: now in %s, a fork\n", made);
}
} else if (strcmp(cmd, "/compact") == 0 && current[0]) {
char id[64];
rc = pic_compact_request(&s, current, *arg ? arg : NULL, id, sizeof id);
if (rc == 0) {
puts("pic: the history is summarized before the next message");
}
} else if (strcmp(cmd, "/sessions") != 0 && strcmp(cmd, "/log") != 0 && strcmp(cmd, "/resume") != 0 &&
strcmp(cmd, "/name") != 0 && strcmp(cmd, "/fork") != 0 && strcmp(cmd, "/compact") != 0) {
size_t cap = strlen(cmd) + strlen(arg) + 2;
char *line = is_template(workspace, cmd) ? malloc(cap) : NULL;
if (line) { /* a prompt template: the model gets what it expands to */
(void)snprintf(line, cap, "%s %s", cmd, arg);
last_session[0] = '\0';
rc = ask(&s, workspace, modelbuf, NULL, exec_seconds, current[0] ? current : NULL, line, NULL, 0);
if (last_session[0] && strcmp(last_session, current) != 0) {
(void)snprintf(current, sizeof current, "%s", last_session);
}
free(line);
} else {
fprintf(stderr, "pic: unknown command %s (/help lists them)\n", cmd);
rc = 0;
}
} else {
fprintf(stderr, "pic: %s needs %s (/help)\n", cmd,
current[0] || strcmp(cmd, "/resume") == 0 || strcmp(cmd, "/name") == 0 ? "an argument"
: "a conversation first");
}
if (rc != 0) {
fprintf(stderr, "pic: %s\n", s.err);
}
pic_close(&s);
free(in);
}
if (!in) {
fputc('\n', stdout);
}
end_conversations(db, "prompt_input_exit");
return 0;
}
/* pic bash: see bash.c. */
static int bash_live_json(pic_store *s, const char *text) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT json_object('type', 'bash_execution_update', 'output', ?1)", -1, &q, NULL) ==
SQLITE_OK) {
sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
pic_ev_line(s, (const char *)sqlite3_column_text(q, 0));
}
}
sqlite3_finalize(q);
return 0;
}
static pic_store *bash_store;
static void 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;
}
/* The RPC commands components answer. */
static const pic_rpc_command *const rpc_commands[] = {&pic_rewind_rpc};
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 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_oauth_register(pic_oauth_ops()); /* the subscription sign-ins (oauth_*.c) */
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 (argv[h][0] != '-') {
break;
}
}
while (i < argc && (strcmp(argv[i], "--json") == 0 || strcmp(argv[i], "--stream") == 0 ||
strcmp(argv[i], "--commands") == 0 || tool_switch(argv[i]))) {
if (strcmp(argv[i], "--json") == 0 || strcmp(argv[i], "--stream") == 0 || strcmp(argv[i], "--commands") == 0) {
*(strcmp(argv[i], "--json") == 0 ? &json_events : strcmp(argv[i], "--stream") == 0 ? &force_stream : &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 (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], "--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
* Ctrl+S in the model picker), else pic's own. */
static char default_saved[256];
{
char *def = setting("defaultModel");
(void)snprintf(default_saved, sizeof default_saved, "%s", def && *def ? def : default_model);
free(def);
}
if (!model) {
static char saved[256];
initial_model(saved, sizeof saved);
model = saved;
}
if (i < argc && strcmp(argv[i], "ps") == 0) { /* picu_proc in ~/.pic/pic.sqlite */
return pic_ps_command(argc - i - 1, argv + i + 1);
}
pic_proc_sink_set(&pic_procs_sink);
pic_procs_init(!json_events);
if (i < argc && strcmp(argv[i], "models") == 0) {
return models_command(argc - i - 1, argv + i + 1);
}
if (i < argc && strcmp(argv[i], "projects") == 0) { /* picu_project in ~/.pic/pic.sqlite */
if (argc - i != 1) {
return usage();
}
if (pic_projects_each(print_project, NULL) != 0) {
fputs("pic: cannot read ~/.pic/pic.sqlite\n", stderr);
return 1;
}
return 0;
}
if (i < argc && strcmp(argv[i], "settings") == 0) { /* stored in ~/.pic/pic.sqlite */
if (argc - i == 1) {
return pic_settings_each(print_setting, NULL) == 0 ? 0 : 1;
}
if (argc - i == 2 && argv[i + 1][0] != '-') {
char *v = setting(argv[i + 1]);
if (v) {
puts(v);
}
free(v);
return v ? 0 : 1;
}
if (argc - i == 3 && strcmp(argv[i + 1], "--unset") == 0) {
return set_setting(argv[i + 2], NULL) == 0 ? 0 : 1;
}
if (argc - i == 3) {
return set_setting(argv[i + 1], argv[i + 2]) == 0 ? 0 : 1;
}
return usage();
}
/* No command: the line mode, when a person is at a terminal. */
if (i >= argc && !rpc_mode && !(isatty(STDIN_FILENO) && isatty(STDOUT_FILENO))) {
return usage();
}
/* import --claude: the transcript's cwd is the workspace unless one is named. */
if (i < argc && strcmp(argv[i], "import") == 0 && argc - i >= 3 && strcmp(argv[i + 1], "--claude") == 0) {
claude_path = argv[i + 2];
for (int k = i + 3; k < argc; k += 2) {
if (strcmp(argv[k], "--count") == 0) {
claude_count = 1;
k--;
} else if (k + 1 >= argc) {
return usage();
} else if (strcmp(argv[k], "--api-url") == 0) {
claude_url = argv[k + 1];
} else if (strcmp(argv[k], "--until") == 0) {
claude_until = argv[k + 1];
} else if (strcmp(argv[k], "--workspace") == 0) {
workspace = argv[k + 1];
} else {
return usage();
}
}
if (!workspace) {
char err[PATH_MAX + 64];
if (pic_claude_cwd(claude_path, claude_until, claude_cwd, sizeof claude_cwd, err, sizeof err) != 0) {
fprintf(stderr, "pic: %s\n", err);
return 1;
}
workspace = claude_cwd;
}
}
if (!workspace) {
if (!getcwd(cwd, sizeof cwd)) {
fprintf(stderr, "pic: cannot read the current directory\n");
return 1;
}
workspace = cwd;
}
/* A missing workspace would otherwise be recorded as a permanent tool error. */
if (stat(workspace, &st) != 0 || !S_ISDIR(st.st_mode)) {
fprintf(stderr, "pic: workspace is not a directory: %s\n", workspace);
return 1;
}
if (i < argc && (strcmp(argv[i], "trust") == 0 || strcmp(argv[i], "scoped-models") == 0 || strcmp(argv[i], "bug") == 0 ||
strcmp(argv[i], "prompts") == 0 || strcmp(argv[i], "skills") == 0 || strcmp(argv[i], "login") == 0 ||
strcmp(argv[i], "logout") == 0 || strcmp(argv[i], "keys") == 0 || 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;
}
/* 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], "attach") == 0) {
return attach_command(argv[0], db, workspace, thinking_opt, 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);
if (i < argc && strcmp(argv[i], "hooks") == 0 && argc - i == 3 && strcmp(argv[i + 1], "end") == 0 && !hooks) {
return 0; /* nothing configured: nothing to end */
}
if (rpc_mode) {
pic_rpc_host h;
memset(&h, 0, sizeof h);
quiet = 1; /* conversations end when the process does */
rpc_workspace = workspace;
rpc_exec_seconds = exec_seconds;
h.db = db;
h.workspace = workspace;
h.exec_seconds = exec_seconds;
h.open = open_store;
h.prompt = rpc_prompt;
h.provider = rpc_provider;
h.level = rpc_level;
h.expand = expand_template;
h.end = end_conversations;
h.commands = rpc_commands;
h.ncommands = sizeof rpc_commands / sizeof rpc_commands[0];
rc = pic_rpc_main(&h, model, rpc_session);
pic_hooks_free(hooks);
return rc;
}
if (i >= argc || (strcmp(argv[i], "tui") == 0 && argc - i <= 3)) {
char self[PATH_MAX];
pic_tui_options t;
const char *resume = NULL, *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;
return pic_tui_main(&t);
}
if (strcmp(argv[i], "chat") == 0 && argc - i == 1) {
return repl(db, workspace, model, exec_seconds, NULL);
}
if (strcmp(argv[i], "chat") == 0 && argc - i == 2 && strcmp(argv[i + 1], "-c") == 0) {
return repl(db, workspace, model, exec_seconds, "latest");
}
if (strcmp(argv[i], "chat") == 0 && argc - i == 3 && strcmp(argv[i + 1], "--session") == 0) {
return repl(db, workspace, model, exec_seconds, argv[i + 2]);
}
if (open_store(&s, db) != 0) {
fprintf(stderr, "pic: %s\n", s.err);
pic_close(&s);
return 1;
}
{
char real[PATH_MAX];
const char *ws = realpath(workspace, real) ? real : workspace;
if (!strstr(db, NOSESSION_MARK)) {
(void)pic_workspace_touch(ws, db);
}
pic_proc_scope(ws, NULL);
}
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();
}
} else if (strcmp(argv[i], "submit") == 0 && (argc - i == 3 || (argc - i == 5 && strcmp(argv[i + 3], "--session") == 0))) {
int duplicate = 0, fresh = 0;
int64_t first = 0;
char joined[64], sid[64] = "";
const char *session = argc - i == 5 ? argv[i + 4] : NULL;
rc = s.hooks && hook_conversation(&s, session, sid, &fresh, argv[i + 2], &first) != 0
? -1
: pic_submit_hooked(&s, argv[i + 1], argv[i + 2], NULL, 0, fresh ? NULL : sid[0] ? sid : session,
fresh ? sid : NULL, first, &duplicate, joined, sizeof joined);
if (rc == 0) {
puts(duplicate ? "duplicate: already admitted" : "admitted");
}
end_own(&s, sid);
} else if (strcmp(argv[i], "compact") == 0 && argc - i >= 2 && argc - i <= 4 && strcmp(argv[i + 1], "--now") == 0) {
/* Pi's /compact: at once, with this model (its events with --json). */
pic_provider provider;
sqlite3_int64 seq = 0;
memset(&provider, 0, sizeof provider);
rc = model_provider(&provider, model, NULL, workspace, s.err, sizeof s.err);
if (rc == 0) {
if (context_window >= 0) {
provider.context_window = context_window;
}
if (json_events) {
pic_events_init(&events, stdout, stderr, 1, 0);
s.events = &events;
}
catch_interrupt();
rc = pic_compact_now(&s, &provider, argc - i >= 3 ? argv[i + 2] : "latest", argc - i == 4 ? argv[i + 3] : NULL,
&seq);
s.events = NULL;
}
if (provider.free) {
provider.free(&provider);
}
if (rc == 0 && !json_events) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s.db, "SELECT coalesce(tokens_before, 0) FROM pic_entry WHERE seq = ?", -1, &q, NULL) ==
SQLITE_OK) {
sqlite3_bind_int64(q, 1, seq);
if (sqlite3_step(q) == SQLITE_ROW) {
printf("compacted %lld tokens of history into a summary\n", (long long)sqlite3_column_int64(q, 0));
}
}
sqlite3_finalize(q);
}
} else if (strcmp(argv[i], "compact") == 0 && argc - i <= 3) {
char id[64];
rc = pic_compact_request(&s, argc - i >= 2 ? argv[i + 1] : "latest", argc - i == 3 ? argv[i + 2] : NULL, id,
sizeof id);
if (rc == 0) {
printf("%s will be compacted before its next request\n", id);
}
} else if (strcmp(argv[i], "export") == 0 && argc - i >= 3 && argc - i <= 4 && strcmp(argv[i + 1], "--html") == 0) {
const char *path = argc - i == 4 ? argv[i + 3] : "-";
FILE *f = strcmp(path, "-") == 0 ? stdout : fopen(path, "w");
if (!f) {
(void)snprintf(s.err, sizeof s.err, "cannot write %s: %s", path, strerror(errno));
rc = -1;
} else {
rc = pic_export_html(&s, argv[i + 2], f);
if (f != stdout && fclose(f) != 0 && rc == 0) {
(void)snprintf(s.err, sizeof s.err, "cannot write %s: %s", path, strerror(errno));
rc = -1;
}
}
} else if (strcmp(argv[i], "tree") == 0 && argc - i >= 2 && argc - i <= 3 && strcmp(argv[i + 1], "--json") == 0) {
rc = pic_tree_json(&s, argc - i == 3 ? argv[i + 2] : "latest", stdout);
} else if (claude_path) {
pic_claude_import made_by;
char made[64];
FILE *f = fopen(claude_path, "r");
if (!f) {
(void)snprintf(s.err, sizeof s.err, "cannot read %s: %s", claude_path, strerror(errno));
rc = -1;
} else {
rc = pic_import_claude(&s, f, claude_until, made, sizeof made, &made_by);
fclose(f);
}
if (rc == 0) {
printf("%s\nrequests %ld, tool calls %ld structured, %ld as text\n"
"context %ld tokens (pic estimate: chars/4 of the messages)\n",
made, made_by.requests, made_by.calls, made_by.text_calls, made_by.context_tokens);
if (made_by.usage >= 0) {
printf("transcript usage %lld tokens (input + cache read + cache write of the last reply)\n", made_by.usage);
} else {
puts("transcript usage none recorded");
}
}
/* --count: the first request pic would send, its system prompt and
* tools frozen as that request freezes them, by the provider's counter. */
if (rc == 0 && claude_count) {
pic_provider provider;
long counted = 0;
if (pic_begin(&s) != 0) {
rc = -1;
} else if (pic_sync_session(&s, workspace, 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 == 2 && strcmp(argv[i + 1], "--json") == 0) {
rc = pic_sessions_json(&s, stdout);
} else if (strcmp(argv[i], "log") == 0 && argc - i >= 2 && argc - i <= 3 && strcmp(argv[i + 1], "--json") == 0) {
rc = pic_session_log_json(&s, argc - i == 3 ? argv[i + 2] : "latest", stdout);
} else if (strcmp(argv[i], "sessions") == 0 && argc - i == 1) {
rc = pic_sessions(&s, stdout);
} else if (strcmp(argv[i], "log") == 0 && argc - i <= 2) {
rc = pic_session_log(&s, argc - i == 2 ? argv[i + 1] : "latest", stdout);
} else if (strcmp(argv[i], "name") == 0 && argc - i == 3) {
rc = pic_session_name(&s, argv[i + 1], argv[i + 2]);
} else if (strcmp(argv[i], "fork") == 0 && argc - i >= 5 && strcmp(argv[i + 2], "--at") == 0 &&
strcmp(argv[i + 4], "--summarize") == 0) {
/* Pi's /tree with a summary of the branch left behind: its request
* goes to the model, or to --script / --api-url as pic run's would. */
const char *instructions = NULL, *script = NULL, *url = NULL;
pic_provider provider;
char made[64];
memset(&provider, 0, sizeof provider);
for (int j = i + 5; j < argc; j += 2) {
if (j + 1 >= argc) {
pic_close(&s);
return usage();
}
if (strcmp(argv[j], "--instructions") == 0) {
instructions = argv[j + 1];
} else if (strcmp(argv[j], "--script") == 0) {
script = argv[j + 1];
} else if (strcmp(argv[j], "--api-url") == 0) {
url = argv[j + 1];
} else {
pic_close(&s);
return usage();
}
}
rc = script ? pic_provider_script(&provider, script) : model_provider(&provider, model, url, workspace, s.err, sizeof s.err);
if (rc == 0) {
if (context_window >= 0) {
provider.context_window = context_window;
}
catch_interrupt();
rc = pic_branch_summarize(&s, &provider, argv[i + 1], strtoll(argv[i + 3], NULL, 10), instructions, made, sizeof made);
if (rc == 0) {
puts(made);
}
}
if (provider.free) {
provider.free(&provider);
}
} else if (strcmp(argv[i], "fork") == 0 && (argc - i == 2 || (argc - i == 4 && strcmp(argv[i + 2], "--at") == 0))) {
char made[64];
rc = pic_fork(&s, argv[i + 1], argc - i == 4 ? strtoll(argv[i + 3], NULL, 10) : 0, made, sizeof made);
if (rc == 0) {
puts(made);
}
} else if (strcmp(argv[i], "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) {
(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], "--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);
}
} else {
pic_close(&s);
fprintf(stderr, "pic: unknown %s %s\n", strncmp(argv[i], "-", 1) == 0 ? "option" : "command or arguments:", argv[i]);
return usage();
}
if (rc != 0) {
fprintf(stderr, "pic: %s\n", s.err);
}
pic_close(&s);
pic_hooks_free(hooks);
return rc == 0 ? 0 : 1;
}