Skip to content
pi-c Artifact [1ea03bcc3b]
Login

Artifact [1ea03bcc3b]

Artifact 1ea03bcc3baff4f079267e28fca5534c7e942ce7d02bb4564838601def771c2a:


/* pic: durable coding-agent harness. Internal interfaces. */
#ifndef PIC_H
#define PIC_H

#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

#include "events.h"
#include "image.h"
#include "model.h"
#include "sqlite3.h"

#define PIC_SCHEMA_VERSION "21"
#define PIC_GENERATION_ATTEMPTS 3 /* provider requests per turn before the submission fails */
#define PIC_ERR_CAP 512
#define PIC_OUTPUT_CAP 65536 /* tool output kept in the journal, bytes */
/* What a person is told about a journal a newer pic wrote. */
#define PIC_JOURNAL_NEWER "this journal was written by a newer pic; update pic (in pic's source: make install-pic)"

struct pic_provider;
struct pic_context_policy;
struct pic_stop_policy;

typedef struct pic_store {
    sqlite3 *db;
    int lock_fd;                /* the journal lock, held shared */
    char *lock_path, *lease_dir;
    char *holder_path;          /* this process's entry in <journal>.pic-holders, or NULL */
    int holder_h;               /* its lock, held while the store is open */
    struct pic_lease *leases;   /* the conversations this store may advance */
    size_t nleases;
    struct pic_events *events; /* live events while running (events.h), or NULL */
    int64_t running;           /* the request pic_run drives, or last drove (0: none yet) */
    int64_t run_since;         /* the journal's last entry when pic_run took that request up */
    int steer_all, follow_up_all; /* deliver every queued message at once, not one at a time */
    /* Pi's auto retry off (set_auto_retry false): a failed provider request is
     * not tried again; abort_retry (Pi's abort_retry): the retry under way is
     * dropped and the request fails with its error. */
    int no_retry, abort_retry;
    void (*cancelled)(struct pic_store *s); /* after pic_run journals a cancel (Ctrl-C or abort) */
    struct pic_hooks *hooks; /* the configured command hooks (hooks.h), or NULL */
    /* The workspace's verify command (docs/design/verdict.md), run once for
     * each request about to end answered; NULL: none, and no verdict. */
    const char *verify;
    /* Kept on each request this process admits: its benchmark arm (NULL:
     * none) and its cap on provider requests (0: none). */
    const char *trial;
    long max_requests;
    /* Also kept on each request this process admits: the model
     * ("provider/id") and thinking level it is to run with (NULL: whatever
     * runs it). A request always finishes with its own: pic_run hands them to
     * provider_for, which makes *p the provider for them (0) or fails (-1,
     * s->err); NULL keeps the provider pic_run was given. */
    const char *model, *thinking;
    int (*provider_for)(struct pic_store *s, struct pic_provider *p, const char *model, const char *thinking);
    /* pic_run takes only requests of the conversation of the request in
     * running (pic run --session), not others left in the journal. */
    int session_only;
    int nest; /* pic_begin_outer's transaction: 1, plus a savepoint each */
    /* The context-policy component (policy.h) that answers before each
     * request whether to compact, and plans it; NULL: none, so pic never
     * compacts on its own. */
    const struct pic_context_policy *policy;
    /* The stop policy (policy.h) that says whether a goal is met when a request ends; NULL:
     * none, so goals never continue. */
    const struct pic_stop_policy *stop_policy;
    /* The credential the last provider request used (cred.h's name, and its
     * label; "" for none), and what a refusal said of it: cred.h's
     * pic_key_state (0: nothing) and, for a limit, when it lifts. */
    char credential[160], credential_label[40], credential_provider[64];
    int key_state, key_status;
    long long key_until_ms;
    /* A reply refused for its key (dead, out of credit, limited) leaves its
     * request unfinished for the user to choose another key, model or wait
     * (the terminal's swap prompt), instead of failing it. */
    int hold_key_failures;
    /* The reply streaming now, published for followers (pic_live_begin): its file, the journal's
     * last entry when it began, and its descriptor (-1 before the first text, -2 when it cannot
     * be written). NULL: no reply is streaming. */
    char *live_path;
    long long live_seq;
    int live_fd;
    char err[PIC_ERR_CAP];
} pic_store;

/* Store: owns the connection, the locks, schema, and invariants. Several pic
 * processes may have one journal open; pic_open settles what dead ones left
 * and leaves alone what live ones are doing. */
int pic_open(pic_store *s, const char *db_path);
/* For a process that only reads the journal or sends to its inbox
 * (inbox.h): the journal lock shared; never creates, migrates or recovers;
 * refuses a journal of another schema or another user. pic_close closes it. */
int pic_open_narrow(pic_store *s, const char *db_path);
void pic_close(pic_store *s);
/* What this process is ("pic remote"), for another pic's list of the processes that have a journal
 * open, and whether it closes a journal that a newer pic waits to migrate: set before opening. */
void pic_store_role(const char *role, int yields);
/* 1 when a pic with a newer schema waits for this store's journal to be let go of, to migrate it:
 * a process that keeps a journal open for long (pic remote, pic attach) closes it then. */
int pic_migration_wanted(pic_store *s);
/* What starts the conversations this process makes, as pic_session_origin records it: "person" (at a
 * terminal), "phone", "agent" (a pic a tool call or a hook of another started), "wake" (a loop or a
 * goal) or "headless"; PARENT, an agent's, the conversation whose tool call started it, as
 * JOURNAL/ID. main sets it from PIC_ORIGIN and PIC_PARENT, before anything opens a journal. */
void pic_store_origin(const char *origin, const char *parent);
const char *pic_store_origin_get(void);
const char *pic_store_parent_get(void);
/* Inside the caller's transaction: new conversation ID records what started it, ORIGIN, or this
 * process's when NULL, and its parent (pic_session_origin). 0, or -1 with s->err. */
int pic_session_stamp(pic_store *s, const char *id, const char *origin);
/* What the commands this process starts for conversation ID (its tool calls, its hooks) are: an
 * agent of it. Sets PIC_ORIGIN and PIC_PARENT in this process's environment. */
void pic_session_env(pic_store *s, const char *id);
/* A process that has a journal open, as it said when it opened it. */
typedef struct {
    long pid, ppid;     /* and the process that started it */
    long long since_ms; /* wall clock, when it opened the journal */
    int yields;         /* it closes the journal when a migration waits (pic_store_role) */
    long schema;        /* the schema its build reads (0: not known) */
    char role[48];
} pic_holder;
/* The live processes other than this one that have the journal at DB_PATH open and say so (a pic
 * from before holders said so does not): up to CAP of them in OUT; how many there are. */
int pic_holders(const char *db_path, pic_holder *out, int cap);
/* 1 when no process has the journal at DB_PATH open: its lock could be taken alone just now. */
int pic_journal_unheld(const char *db_path);
/* Every process that has the journal at DB_PATH open, whether it says so or not, as the platform
 * sees it (file_users): up to CAP pids and command names; how many, or -1 when it cannot tell. */
int pic_journal_users(const char *db_path, long *pids, char (*names)[32], int cap);
/* SESSION's bell, <journal>.pic-leases/ID.bell (inbox.c rings it). */
int pic_bell_path(pic_store *s, const char *session, char *out, size_t cap);
/* SESSION's streamed reply, <journal>.pic-leases/ID.live (docs/dev/remote.md): made at the reply's
 * first text, the line "pic-live 1 SEQ" (SEQ the journal's last entry when the reply began) and
 * then the reply's text, appended as it arrives; removed when the reply ends. Not durable: it
 * promises nothing. pic_live_begin removes one a dead process left. */
int pic_live_path(pic_store *s, const char *session, char *out, size_t cap);
/* An interface that follows SESSION says so while it does (pic attach on a lifeline): 0, or -1 when
 * it cannot. pic_watched: 1 when some process is following SESSION now. */
int pic_watch_hold(pic_store *s, const char *session);
int pic_watched(pic_store *s, const char *session);
void pic_live_begin(pic_store *s, const char *session, long long seq);
void pic_live_text(pic_store *s, const char *text, size_t len);
void pic_live_end(pic_store *s);
/* A conversation's lease: the right to advance it (run its request, journal
 * work under way for it, cancel or compact it), held by one process at a
 * time and let go when the store closes or the process dies in any way.
 * Whoever takes it first settles what its last owner left unfinished
 * (pic_recover_session). Waits up to WAIT_MS for a holder on its way out.
 * 0: held (again, if it was already); 1: another process has it, s->err
 * saying so; -1: an error. Everything that needs one takes it itself. */
int pic_lease(pic_store *s, const char *session, int wait_ms);
void pic_unlease(pic_store *s, const char *session);
int pic_leased(pic_store *s, const char *session); /* by this store; in SQL, pic_leased(session_id) */
/* The pid of the process holding SESSION's lease; -1 when one does and its
 * pid is not known; 0 when it is free. */
long pic_lease_holder(pic_store *s, const char *session);
/* s->err: "WHAT SESSION is in use by another pic process (pid N)". */
void pic_lease_err(pic_store *s, const char *what, const char *session);
#define PIC_LEASE_WAIT_MS 1000
int pic_exec(pic_store *s, const char *sql);
int pic_begin(pic_store *s);
/* A transaction inside which pic_begin and its commit or rollback are a
 * savepoint; pic_commit or pic_rollback ends it. */
int pic_begin_outer(pic_store *s);
int pic_commit(pic_store *s);
void pic_rollback(pic_store *s);
int pic_check(pic_store *s); /* hand-enforced integrity: foreign_keys is OFF */
/* pic_check, then what is too slow for every open: each stored image's
 * content hashes to its name (pic check). */
int pic_check_deep(pic_store *s);
/* Image retention (prune.c): drops the bytes of images no request sends any
 * more (every entry holding them compacted away on every conversation that
 * reaches it, and no queued message holds them) or not used for
 * imageRetentionDays (a setting; default 30, 0 never), keeping hash, type
 * and size; they show as "[image removed]". DRY_RUN only counts. The images
 * and bytes, in *count and *bytes. Its own transaction; never during a run. */
int pic_prune(pic_store *s, int dry_run, long long *count, long long *bytes);
/* Retention of stored file bytes (pic_blob): drops those no pic_file_change
 * names (a change's pre-image, a restore's target) once they were stored before this function's previous
 * mark an hour or more ago, so bytes a restore stored and has yet to journal
 * are safe; then moves the mark. DRY_RUN only counts. Called after pic_prune,
 * in its own transaction. */
int pic_prune_files(pic_store *s, int dry_run, long long *count, long long *bytes);

/* One assistant message from a provider, in two forms. native is what the
 * provider sent, journaled verbatim and replayed byte for byte to the same
 * provider, API and model (signatures and reasoning stay valid). neutral is
 * Pi's provider-neutral content array, which tool calls are taken from and
 * which other providers are sent:
 *   {"type":"text","text"}  {"type":"thinking","thinking","signature"?,"redacted"?}
 *   {"type":"toolCall","id","name","arguments":{...}}
 * stop_reason is normalised to Pi's: stop, length, toolUse, refusal, pause. */
typedef struct {
    char *native;      /* provider's content, JSON */
    char *neutral;     /* JSON array */
    char *stop_reason; /* stop, length, toolUse, refusal, pause */
    char *usage;       /* JSON object or NULL */
    char *request_id;  /* provider request id or NULL */
    char *provider, *api, *model; /* origin of the reply */
} pic_reply;
void pic_reply_free(pic_reply *r);

/* A provider produces the next assistant message for a submission from its
 * journal. On failure it sets err and *retryable: a retryable failure (network,
 * overload, cut stream) counts one attempt; any other fails the submission. */
typedef struct pic_provider {
    int (*reply)(struct pic_provider *p, pic_store *s, int64_t submission, int64_t turn, pic_reply *out,
                 int *retryable, char *err, size_t errcap);
    /* A plain request for compaction: SYSTEM and one USER message, no tools;
     * the reply's text in *text, usage in *usage (both malloc'd). */
    int (*summarize)(struct pic_provider *p, pic_store *s, const char *system, const char *user, char **text,
                     char **usage, int *retryable, char *err, size_t errcap);
    void (*free)(struct pic_provider *p);
    /* The input tokens of the submission's next request, by the provider's
     * own counter; NULL where the API has none. */
    int (*count)(struct pic_provider *p, pic_store *s, int64_t submission, long *tokens, char *err, size_t errcap);
    void *state;
    long context_window; /* tokens; 0 means never compact automatically */
    long cache_seconds;  /* how long the prompt cache outlives a request (cacheRetention); 0: none */
    char model[160]; /* "provider/model", for clients (events); "" when unknown */
    char thinking[16]; /* the thinking level in effect (model.h names); "" when none applies */
} pic_provider;

/* How long, in seconds, a prompt cache written for MODEL (NULL: any model,
 * the scripted provider) lives under cacheRetention: 300 for short; for long,
 * what the adapter registered for the model's API says its cache lives
 * (provider_http.h), else an hour, staying 300 for a model without long
 * retention; 0 for none. */
long pic_cache_seconds(const pic_model *model);
/* Scripted provider: turn N of a submission is line N+1 of the script. */
int pic_provider_script(pic_provider *p, const char *script);
/* A provider for a resolved model (model.h), made by the adapter registered
 * for its API (provider_http.h); url, when not NULL, replaces the model's
 * endpoint (tests). thinking is the
 * requested level (NULL or "": Pi's default, medium), clamped to what the
 * model supports. */
int pic_provider_for_model(pic_provider *p, const pic_model *model, const char *thinking, const char *url,
                           const char *workspace, char *err, size_t errcap);

/* Cross-provider conversion (transform.c), on a connection where
 * pic_transform_register has run. */
int pic_transform_register(sqlite3 *db);
/* The system prompt for a workspace, with its project instructions (malloc'd);
 * CONTEXT_WINDOW is the model's, in tokens (0: not known), which sizes the skill listing. */
char *pic_system_prompt(const char *workspace, long context_window);
/* Pi's --system-prompt and --append-system-prompt: each argument is a file
 * path or literal text. REPLACE (or NULL) replaces the default prompt; the
 * APPEND arguments (N, at most PIC_SYSTEM_APPEND_MAX) follow it. The arguments
 * must outlive the process's prompts. */
#define PIC_SYSTEM_APPEND_MAX 32
void pic_system_prompt_args(const char *replace, const char *const *append, size_t n);
/* Only the project instructions block (malloc'd; empty when there are none). */
char *pic_project_instructions(const char *workspace);

/* Tools run outside any transaction and return a malloc'd result string.
 * started() durably records that the effect has begun; tools call it exactly
 * once, before any external effect. If it fails the tool returns NULL and
 * nothing ran. NULL after a successful started() means the outcome is lost. */
typedef struct pic_tool_output {
    char *data;
    size_t len;
} pic_tool_output;
typedef struct {
    int exec_seconds; /* bash's default timeout */
    /* plan: bytes the tool will write, journaled with "started" so a replay
     * after a crash writes the same bytes (edit); NULL when there is none. */
    int (*started)(void *ctx, const char *plan, size_t plan_len);
    void *ctx;
    const char *plan; /* a plan an earlier attempt journaled, or NULL */
    size_t plan_len;
    /* bash: the name ("pic:output/N") its truncation notice gives the full
     * output, which it hands back in *output (malloc'd) for the caller to
     * journal. NULL name or output: the full output is not kept. */
    const char *output_name;
    struct pic_tool_output *output;
    /* read: the content of a journaled output by name (malloc'd, NUL after
     * len bytes), or NULL when there is none. NULL fetch: names are files. */
    char *(*fetch)(void *ctx, const char *name, size_t *len);
    /* read: an image file's bytes (data malloc'd) and inline type, which the
     * caller journals with the result. NULL: images are not kept. */
    struct pic_tool_image {
        const char *mime;
        unsigned char *data;
        size_t len;
        long width, height;
    } *image;
    /* bash: the output so far, at most every 100ms while the command runs
     * (first call: empty). NULL: no live updates. */
    void (*partial)(void *ctx, const char *text);
    void *partial_ctx;
    /* bash: what `pic ps` calls the command ("bash" when NULL). */
    const char *proc_kind;
    /* The call's journal (its file), effect and JSON input, for a tool that reads its own call
     * (send_message: its key and sender). NULL journal: not known. */
    const char *journal;
    long long effect;
    const char *input;
} pic_tool_hooks;
/* Where the host executor reports the processes it starts, for `pic ps`
 * (procs.c has the implementation; a build or test without it reports
 * nothing). start returns a handle for end (-1: not recorded); both are
 * best-effort and are called only in pic itself (a forked child reports to
 * it over its pipe and never touches the database). */
typedef struct {
    long long (*start)(const char *kind, const char *command, long pid, long pgid);
    void (*end)(long long id, int exit_code, int sig);
} pic_proc_sink;
void pic_proc_sink_set(const pic_proc_sink *sink);
const pic_proc_sink *pic_proc_sink_get(void); /* NULL when none is set */
/* Tool arguments from the call's JSON input. Strings are NULL when absent or
 * not strings; bad_input, when set, is reported instead of running. */
typedef struct {
    const char *path, *content, *command;
    long offset, limit, timeout;
    int has_offset, has_limit, has_timeout;
    size_t nedits;
    const char *const *old_text, *const *new_text;
    const char *bad_input;
    const char *pattern, *glob; /* grep, find */
    int ignore_case, literal, has_context;
    long context;
} pic_tool_args;
/* Where tools act: the files read, write and edit touch, and the commands
 * bash runs. The file half has the shape of libfossil's fsl_ckout_fs (an
 * operation set a cowoco checkout also implements): names are absolute,
 * already resolved against the workspace by Pi's path rules, and every
 * operation returns 0 or an errno value. The process half runs a command as
 * bash does, calling hooks->started() exactly once before it starts. */
typedef struct {
    int is_dir;
    uint64_t size;
    unsigned mode; /* permission bits, 07777 */
} pic_file_stat;
enum { PIC_FILE_WRITABLE = 1 }; /* read: also fail unless it may be written */
/* A hook command for an executor's spawn: /bin/sh -c COMMAND in CWD, the
 * INPUT_LEN bytes at INPUT on its stdin, ENV ("NAME=VALUE" strings,
 * NULL-terminated) added to pic's environment. It runs in a process group
 * of its own, which is killed at SECONDS, when pic dies, or once
 * CANCELLED(CTX) returns nonzero (Ctrl-C); once the command returns, what it
 * left running in the background is its author's. Its stdout and stderr are
 * kept apart, each up to OUT_CAP bytes. DETACHED: started and left to run,
 * timeout and all, holding none of pic's files; nothing is kept but that it
 * started. */
typedef struct {
    const char *command, *cwd, *input;
    size_t input_len;
    const char *const *env;
    int seconds, detached;
    size_t out_cap;
    int (*cancelled)(void *ctx);
    void *ctx;
} pic_spawn_req;
typedef struct {
    int started, exited, code, timed_out, cancelled;
    long ms;
    char *out, *err; /* malloc'd and NUL-terminated (NULL when nothing came) */
    size_t out_len, err_len;
    char why[160];   /* why it did not run to an exit, when it did not */
} pic_spawn_result;
typedef struct pic_executor {
    /* Describes name, following symlinks. */
    int (*stat)(void *state, const char *name, pic_file_stat *st);
    /* The whole regular file (malloc'd, NUL after *len bytes); EISDIR for a
     * directory, EFBIG over max. */
    int (*read)(void *state, const char *name, size_t max, int flags, char **buf, size_t *len);
    /* Replaces name with the n bytes at src, permission bits mode,
     * atomically and durably. Its directory exists. */
    int (*write)(void *state, const char *name, const char *src, size_t n, unsigned mode);
    int (*remove)(void *state, const char *name);
    /* Creates directory name, whose parent exists (EEXIST if it is there). */
    int (*mkdir)(void *state, const char *name);
    /* Removes directory name when it is empty (ENOTEMPTY otherwise, ENOTDIR
     * for anything but a directory). */
    int (*rmdir)(void *state, const char *name);
    /* Calls cb for each entry of directory name but "." and ".."; a nonzero
     * return from cb stops the listing and is returned. */
    int (*list)(void *state, const char *name, int (*cb)(void *cb_state, const char *entry), void *cb_state);
    /* Runs command with the shell in directory cwd for at most seconds; the
     * result is bash's (malloc'd), as pic_tool_run documents. */
    char *(*run)(void *state, const char *cwd, const char *command, int seconds, const pic_tool_hooks *h,
                 int *is_error);
    /* Runs a hook command (pic_spawn_req); 0, or -1 when it could not
     * start (res->why). NULL: this executor runs no hooks. */
    int (*spawn)(void *state, const pic_spawn_req *req, pic_spawn_result *res);
    void *state;
} pic_executor;
/* Host only (tools.c, beside the host's spawn): a pic command made ready
 * now and started later from a signal handler, with async-signal-safe calls
 * alone: detached, its output discarded, once process WAIT_FOR (when > 0)
 * has exited or 10 s have passed. The terminal interface ends its
 * conversations' hooks this way when it is killed. */
typedef struct {
    char *argv[12];
    char **envp; /* NULL: nothing prepared, start does nothing */
    char extra[160];
    long delay_ms; /* development builds: PIC_LAUNCH_DELAY_MS, a pause before it leaves the session (tests) */
} pic_host_exec;
/* ARGV (NULL-terminated, at most 11, kept by pointer) with pic's environment
 * plus EXTRA ("NAME=VALUE"). 0, or -1 (nothing prepared). */
int pic_host_exec_prepare(pic_host_exec *x, const char *const *argv, const char *extra);
void pic_host_exec_start(const pic_host_exec *x, int wait_for);

/* This machine's filesystem and fork/exec, and the one tools use (the host's
 * unless another was set). */
const pic_executor *pic_executor_host(void);
const pic_executor *pic_executor_get(void);
void pic_executor_set(const pic_executor *e);

/* The file PATH names in WORKSPACE, by the tools' path rules, as one key for
 * every spelling of it (malloc'd; NULL when out of memory). */
char *pic_tool_path_key(const char *workspace, const char *path);
/* FN (NULL: none) is told the resolved path of each file the read tool read:
 * a client of the tools watching what they open (main.c wires skill use to it). */
void pic_tool_read_observer(void (*fn)(const char *path));
char *pic_tool_run(const char *workspace, const char *tool, const pic_tool_args *args, const pic_tool_hooks *hooks,
                   int *is_error);
/* The tool definitions sent to providers, as a JSON array (Pi's default four),
 * and each of the four alone. */
extern const char pic_tool_schemas[];
extern const char pic_tool_schema_read[], pic_tool_schema_bash[], pic_tool_schema_edit[], pic_tool_schema_write[];
/* "ENOENT" and the like for an errno, as Node names them in its messages. */
const char *pic_errno_name(int e);

/* Loop. */
/* SESSION: NULL starts a new session, "latest" continues the most recent,
 * else an id or unique prefix. The session joined is copied to session_out. */
int pic_submit(pic_store *s, const char *request_key, const char *content, const char *session, int *duplicate,
               char *session_out, size_t session_cap);
/* pic_submit with images after the text (pic_image_prepare'd: inline types
 * within the limit), journaled in the same transaction as its entry. */
int pic_submit_images(pic_store *s, const char *request_key, const char *content, const pic_image *images,
                      size_t nimages, const char *session, int *duplicate, char *session_out, size_t session_cap);
/* pic_submit_images for a prompt hooks have seen: NEW_ID (with SESSION
 * NULL) is the new conversation's id they were given, and the prompt's
 * UserPromptSubmit runs from PROMPT_HOOKS on (0: none) become this request's
 * in the admitting transaction (hooks.h). */
int pic_submit_hooked(pic_store *s, const char *request_key, const char *content, const pic_image *images,
                      size_t nimages, const char *session, const char *new_id, int64_t prompt_hooks, int *duplicate,
                      char *session_out, size_t session_cap);
/* A new session continuing from entry AT (0: the head) of session FROM. */
int pic_fork(pic_store *s, const char *from, sqlite3_int64 at, char *out, size_t cap);
/* Pi's /tree with a summary: a new session continuing from entry AT (any
 * that ends a turn) with a summary of what conversation FROM leaves behind,
 * asked of PROVIDER with INSTRUCTIONS (may be NULL) as its additional focus
 * (compact.h's pic_branch_plan). */
int pic_branch_summarize(pic_store *s, pic_provider *provider, const char *from, sqlite3_int64 at,
                         const char *instructions, char *out, size_t cap);
/* The first line of TEXT that is not blank, its runs of white space made one space and its control
 * characters removed, cut to MAX characters with an ellipsis; malloc'd ("" when none). In SQL,
 * pic_line(TEXT, MAX). */
char *pic_one_line(const char *text, size_t max);
/* A conversation's title, in SQL, for pic_session row S: its name, else the first line of its first
 * prompt, else of the first prompt of the one it was forked from; at most 60 characters; NULL when
 * none. Every list of conversations shows this one. */
#define PIC_TITLE_SQL(S)                                                                                                    \
    "coalesce(nullif(pic_line(" S ".name, 60), ''), nullif(pic_line((SELECT t_u.content FROM pic_submission t_u"            \
    " WHERE t_u.session_id = " S ".id ORDER BY t_u.id LIMIT 1), 60), ''), nullif(pic_line((SELECT t_u.content"             \
    " FROM pic_submission t_u WHERE t_u.session_id = " S ".forked_from ORDER BY t_u.id LIMIT 1), 60), ''))"
/* The first line of SESSION's last message along its path (a reply's text, else a prompt), cut to
 * MAX characters; malloc'd, NULL when it has none. */
char *pic_session_last_line(pic_store *s, const char *session, size_t max);
int pic_sessions(pic_store *s, FILE *out);
int pic_sessions_json(pic_store *s, FILE *out);
int pic_session_log_json(pic_store *s, const char *session, FILE *out);
int pic_session_name(pic_store *s, const char *session, const char *name);
/* A conversation id from an id, a unique prefix or "latest". */
int pic_session_resolve(pic_store *s, const char *session, char *out, size_t cap);
/* Whether a conversation can go on with MODEL ("provider/id") and its key LABEL ("" or NULL: any
 * of its provider's) without asking anyone: PIC_MODEL_USABLE, else what stops it, with why its
 * first words ("this conversation ran on X, and P has no key now"), the way on left to the caller. */
enum { PIC_MODEL_USABLE, PIC_MODEL_UNKNOWN, PIC_MODEL_NO_KEY, PIC_MODEL_KEY_GONE };
int pic_model_usable(const char *model, const char *label, char *why, size_t cap);
/* What SESSION (an id, a prefix or "latest") last ran with, or the conversation it was forked
 * from when it has run nothing yet: its latest request's model ("provider/id") and thinking level
 * ("" when none was kept), and the label of the key its replies to that model's provider last went
 * with ("default", a stored key's label, "env" or "file"; "" when none is known). 1, 0 when it has
 * none (a new conversation, or no such one), -1 with s->err. */
int pic_session_choice(pic_store *s, const char *session, char *model, size_t mcap, char *thinking, size_t tcap,
                       char *label, size_t lcap);
int pic_session_log(pic_store *s, const char *session, FILE *out);
/* Deleted conversations (trash.c, docs/design/session-delete.md). A pic_trash row hides one from
 * every list and from "latest"; removing it restores it. A purge empties the text of what it
 * deleted (prompts, replies, tool input and output, its name) and keeps the rows the journal's
 * invariants and its costs need, so it stays deleted for good; never one another pic works or with
 * a request unfinished. */
#define PIC_TRASH_DAYS 30
/* In SQL: pic_session row S is not deleted. */
/* SQL: what started conversation S (an alias): its pic_session_origin row's, else "person" (one
 * made before the table, or by a pic that does not write it). The table is made by pic_open, so a
 * narrow open of a journal only older pics have opened has none: a query falls back without it. */
#define PIC_STARTED_BY_SQL(S) "coalesce((SELECT o_o.origin FROM pic_session_origin o_o WHERE o_o.session_id = " S ".id), 'person')"
#define PIC_LISTED_SQL(S) "NOT EXISTS (SELECT 1 FROM pic_trash t_t WHERE t_t.session_id = " S ".id)"
/* In SQL: pic_session row S was purged (it resolves no more). */
#define PIC_PURGED_SQL(S) "EXISTS (SELECT 1 FROM pic_trash t_t WHERE t_t.session_id = " S ".id AND t_t.purged_ms IS NOT NULL)"
/* Deletes SESSION (an id, a unique prefix or a name); its id and title (or "") into ID and TITLE.
 * 0; 1 when it is running here or in another pic (s->err says so, in one sentence); -1. */
int pic_trash_delete(pic_store *s, const char *session, char *id, size_t idcap, char *title, size_t tcap);
/* Restores SESSION (an id, a unique prefix or a name, among the deleted; NULL: the one deleted
 * last). 0 or -1. */
int pic_trash_restore(pic_store *s, const char *session, char *id, size_t idcap, char *title, size_t tcap);
/* The deleted conversations, deleted last first; JSON lines with JSON. */
int pic_trash_list(pic_store *s, int json, FILE *out);
/* Purges the conversations deleted at or before BEFORE_MS (wall ms; LLONG_MAX: all), but one
 * another process holds or with a request unfinished; how many in *count. Its own transaction,
 * under each one's lease. */
int pic_trash_purge(pic_store *s, long long before_ms, long long *count);
/* Asks for SESSION to be compacted before its next request (the id joined in out). */
int pic_compact_request(pic_store *s, const char *session, const char *instructions, char *out, size_t cap);
/* Pi's compact: SESSION compacted now, outside any request (loop.c); the
 * compaction entry in *entry. Errors as Pi's: "Already compacted", "Nothing
 * to compact (session too small)", "Compaction cancelled" (pic_interrupted). */
int pic_compact_now(pic_store *s, pic_provider *provider, const char *session, const char *instructions,
                    sqlite3_int64 *entry);
/* Finished entries after SINCE as JSON lines (the cursor is the entry number). */
int pic_export(pic_store *s, const char *workspace, sqlite3_int64 since, FILE *out);
/* Pi v3 session files (export_pi.c) for SESSION (NULL: every conversation),
 * appended in DIR (NULL: ~/.pic/sessions/--<workspace>--/). */
int pic_export_pi(pic_store *s, const char *workspace, const char *dir, const char *session);
/* pic_export_pi of SESSION to ~/.pic/pic.sqlite (and its file, with
 * piSessionFiles=1) through its latest entry, a running request's included,
 * and stopping before entry BEFORE when it is not 0: what a hook reads
 * (hooks.h). */
int pic_export_pi_head(pic_store *s, const char *workspace, const char *session, sqlite3_int64 before);
/* SESSION's path, every entry through its head (a running request's too),
 * as a JSON array of Pi session entries (malloc'd), or NULL (s->err). */
/* MOST: the newest that many entries of the path alone (0: all), so the work is bounded by MOST,
 * not by the conversation's length. */
char *pic_pi_entries(pic_store *s, const char *session, int most);
/* SESSION as one self-contained HTML page (export_html.c). */
int pic_export_html(pic_store *s, const char *session, FILE *out);
/* The requests of SESSION's conversation tree as JSON lines (tree.c). */
int pic_tree_json(pic_store *s, const char *session, FILE *out);
/* A Pi v3 session JSONL from IN as a new conversation (import_pi.c); its id
 * goes to session_out, the requests imported to *turns. */
int pic_import_pi(pic_store *s, FILE *in, char *session_out, size_t cap, long *turns);
/* What pic_import_claude made: requests, tool calls journaled as pic's tools
 * and rendered as text, Pi's estimate of the next request's context, and the
 * transcript's own usage at the cut (-1: none recorded). */
typedef struct {
    long requests, calls, text_calls, context_tokens;
    long long usage;
    int64_t last; /* the conversation's latest request */
} pic_claude_import;
/* A Claude Code transcript (JSONL) as a new conversation (import_claude.c):
 * its main thread before the record UNTIL (NULL: all of it), from its latest
 * compact summary; its id goes to session_out. */
int pic_import_claude(pic_store *s, FILE *in, const char *until, char *session_out, size_t cap, pic_claude_import *out);
/* The cwd of PATH's last record before UNTIL, into out; -1 with err set when
 * there is none. */
int pic_claude_cwd(const char *path, const char *until, char *out, size_t cap, char *err, size_t errcap);
/* The frozen system prompt or tools ("system_prompt" or "tools") of a
 * submission's session, as its first generation set them (malloc'd). */
char *pic_session_text(pic_store *s, int64_t submission, const char *column);
/* The context a submission's next request sends, for adapters: prefix a query
 * with PIC_CONTEXT_CTE, select FROM pic_entry e JOIN v ON v.seq = e.seq CROSS
 * JOIN kk, ORDER BY e.kind != 'compaction', e.seq; ?1 is the submission. v is
 * the latest compaction on the conversation's path (its summary goes first),
 * the entries it kept and everything after; v.fresh is 0 for kept entries from
 * before it, which go out rebuilt without thinking (thinking is bound to the
 * whole history before it). kk.cseq is that compaction (0: none). */
#define PIC_CONTEXT_CTE \
    "WITH RECURSIVE p(seq) AS (SELECT head_seq FROM pic_session WHERE id = (SELECT session_id FROM pic_submission" \
    " WHERE id = ?1) UNION ALL SELECT x.parent_seq FROM pic_entry x JOIN p ON x.seq = p.seq WHERE x.parent_seq IS NOT NULL)," \
    " k(cseq) AS (SELECT coalesce(max(x.seq), 0) FROM pic_entry x JOIN p ON p.seq = x.seq WHERE x.kind = 'compaction')," \
    " kk(cseq, kept) AS (SELECT cseq, coalesce((SELECT first_kept_seq FROM pic_entry WHERE seq = cseq), 0) FROM k)," \
    " v(seq, fresh) AS (SELECT x.seq, x.seq > kk.cseq FROM pic_entry x JOIN p ON p.seq = x.seq, kk" \
    "   WHERE x.seq = kk.cseq OR (x.kind != 'compaction' AND x.seq >= kk.kept AND NOT EXISTS" \
    "   (SELECT 1 FROM pic_bash b WHERE b.entry_seq = x.seq AND b.exclude))) "
/* Who sent a user entry, when it was not the person at this computer's terminal: the inbox row's
 * sender for a delivered steer or follow-up, remote:DEVICE for a phone's prompt (its request key
 * rc:DEVICE:KEY); NULL otherwise, which json_patch leaves out. E and U are the entry and its
 * submission (pic attach and pic log --json). */
#define PIC_ORIGIN_SQL                                                                                                     \
    "coalesce((SELECT i.sender FROM pic_inbox i JOIN pic_queued k ON k.id = i.queued_id WHERE k.entry_seq = e.seq),"   \
    " CASE WHEN u.request_key LIKE 'rc:%:%' AND e.seq = (SELECT min(x.seq) FROM pic_entry x WHERE x.submission_id = u.id)" \
    " THEN 'remote:' || substr(u.request_key, 4, instr(substr(u.request_key, 4), ':') - 1) END)"
/* A user entry's text as the model is sent it (SQL text; E a pic_entry alias): the journal's,
 * and when it is the last entry of a request that was cancelled (a prompt or steer stopped before
 * any reply), marked as Claude Code marks one, so the model does not answer it with the next
 * prompt. Pi sends it unmarked. */
#define PIC_USER_TEXT_SQL(e) \
    "(" e ".body || CASE WHEN (SELECT u.status = 'failed' AND u.error = 'cancelled' FROM pic_submission u" \
    " WHERE u.id = " e ".submission_id) AND NOT EXISTS (SELECT 1 FROM pic_entry n WHERE n.submission_id = " e ".submission_id" \
    " AND n.seq > " e ".seq) THEN char(10) || char(10) || '" PIC_INTERRUPTED "' ELSE '' END)"
#define PIC_INTERRUPTED "[Request interrupted by user]"
/* Pi's wording for a compaction summary sent as a user message (SQL text). */
#define PIC_SUMMARY_SQL(col) \
    "('The conversation history before this point was compacted into the following summary:' || char(10) ||" \
    " char(10) || '<summary>' || char(10) || " col " || char(10) || '</summary>')"
/* Pi's wording for a branch summary sent as a user message (SQL text). */
#define PIC_BRANCH_SUMMARY_SQL(col) \
    "('The following is a summary of a branch that this conversation came back from:' || char(10) ||" \
    " char(10) || '<summary>' || char(10) || " col " || '</summary>')"
/* pic_content(seq, body, shape, vision, first) (transform.c): a user or
 * tool_result entry's text and images as JSON in an adapter's or Pi's shape
 * (provider_http.h's pic_content_shape), NULL when it has none; images before
 * attachment FIRST go as text. */
/* A request's image budget: the newest images in its context, at most
 * PIC_REQUEST_IMAGES of them and PIC_REQUEST_IMAGE_BYTES of base64, go as
 * images, older ones as Pi's placeholder. Both sit under the strictest
 * bundled adapter's request limits (its file says which), leaving the rest
 * of the request room. */
#define PIC_REQUEST_IMAGES 20
#define PIC_REQUEST_IMAGE_BYTES (20u << 20)
/* Pi's ImageContent blocks ({"type":"image","data":BASE64,"mimeType"}) at
 * PATH in JSON, decoded into *list (*n of them, bytes and declared types in
 * one malloc'd *buf). ALL: every element must be one (RPC images), else
 * other elements are passed over (a message's content). -1 with *error set
 * when one is malformed or not base64. */
int pic_images_from_json(sqlite3 *db, const char *json, const char *path, int all, pic_image **list, size_t *n,
                         unsigned char **buf, const char **error);
/* Inside a transaction: IMAGES (checked) become the attachments of entry
 * SEQ, or of queued message QUEUED (SEQ 0). */
int pic_attach_images(pic_store *s, sqlite3_int64 seq, sqlite3_int64 queued, const pic_image *images, size_t n);
/* The first attachment id within SUBMISSION's budget, for pic_content. */
sqlite3_int64 pic_image_budget(pic_store *s, int64_t submission);
/* Inside nothing: settles what the last owner of SESSION left under way, for
 * the process that now holds its lease (pic_lease calls it). */
int pic_recover_session(pic_store *s, const char *session);
/* A command the user ran, journaled as Pi's bashExecution message: its own
 * answered request in SESSION (NULL: a new conversation, "latest", or an id;
 * the one used goes to session_out). output is the text as shown (ANSI
 * sequences and CRs already removed); exit_code is ignored unless has_exit.
 * exclude ("!!"): kept, but never sent to the model. full: the whole output
 * of a truncated one, read back as pic:bash/SEQ; seq_out gets the entry.
 * named (or NULL): the entry number the output was named for; when another
 * process's entry has taken it, nothing is journaled, *named becomes the
 * number the entry will have, and 1 is returned for the caller to rename. */
typedef struct {
    const char *command, *output;
    int has_exit, exit_code, cancelled, truncated, exclude;
    const char *full;
    size_t full_len;
} pic_bash_msg;
int pic_bash_record(pic_store *s, const char *session, const pic_bash_msg *m, char *session_out, size_t cap,
                    sqlite3_int64 *seq_out, sqlite3_int64 *named);
/* The entry number the next journaled entry will have (names pic:bash/SEQ before it exists). */
sqlite3_int64 pic_next_entry_seq(pic_store *s);
/* pic bash: runs COMMAND in the workspace through the bash tool's supervisor and
 * journals it with pic_bash_record; see bash.c. live: output so far, when set. */
int pic_bash_run(pic_store *s, const char *workspace, const char *session, const char *command, int exclude,
                 int exec_seconds, void (*live)(void *ctx, const char *text), void *ctx, pic_bash_msg *out,
                 char *session_out, size_t cap);
/* Wording of the message in the model's context (Pi's bashExecutionToText); malloc'd. */
char *pic_bash_text(const pic_bash_msg *m);
/* Steering and follow-ups (Pi's steer and follow_up) for the running
 * request, each journaled in its own transaction as it arrives (kind "steer"
 * or "follow_up"); the request owns them. pic_run delivers them: queued
 * steering at each turn boundary as user entries, after the turn's tool
 * results; with its answer, the next queued message (steering first, then
 * follow-ups) becomes the conversation's next request, holding the rest. A
 * request that fails or is cancelled returns what it held: never run, and
 * reported as a queue_returned event. */
int pic_queue_add(pic_store *s, const char *kind, const char *text);
/* pic_queue_add with images (pic_image_prepare'd), journaled with it. */
int pic_queue_add_images(pic_store *s, const char *kind, const char *text, const pic_image *images, size_t nimages);
/* pic_queue_add_images for a message hooks have seen: its UserPromptSubmit
 * runs from PROMPT_HOOKS on (0: none) go with it to the request that takes it. */
int pic_queue_add_hooked(pic_store *s, const char *kind, const char *text, const pic_image *images, size_t nimages,
                         int64_t prompt_hooks);
/* Clears the running conversation's queue; what it held as Pi's
 * {"steering":[...],"followUp":[...]} (malloc'd) in *cleared. */
int pic_queue_clear(pic_store *s, char **cleared);
/* A queue_update event for the running conversation's queue. */
void pic_queue_event(pic_store *s);
int pic_run(pic_store *s, const char *workspace, pic_provider *provider, int exec_seconds);
/* Inside a transaction: freezes the session's system prompt and tools for
 * WORKSPACE as its first request does (or notes changed instructions). */
int pic_sync_session(pic_store *s, const char *workspace, long window, int64_t submission);
int pic_cancel(pic_store *s, const char *request_key);
char *pic_answer_text(pic_store *s, const char *request_key); /* malloc'd, or NULL */
int pic_dump(pic_store *s);
/* pic usage --by-trial: cost and tokens summed by trial arm. */
int pic_usage_by_trial(pic_store *s, int json, FILE *out);
/* pic usage --by-tool: each tool's calls and failures, and the tokens and cost of the requests that called it. */
int pic_usage_by_tool(pic_store *s, int json, FILE *out);

/* File history (filelog.c): what write and edit found in a file before they
 * touched it and what they left (pic_file_change), and restores that put
 * files back, journaled before any file is touched (docs/design/rewind.md).
 * Bytes are kept once per content (pic_blob) up to rewindMaxBytes. */
#define PIC_REWIND_MAX_BYTES 1048576LL
/* The most of a file read into memory: what a restore keeps for an undo. */
#define PIC_FILE_KEEP_MAX (256LL << 20)
typedef struct {
    int exists;      /* 1 when something is there (it may be unreadable) */
    unsigned mode;   /* permission bits */
    long long size;
    char hash[65];   /* SHA3-256 of the bytes, hex; "" when absent or unreadable */
    char *data;      /* the bytes (malloc'd) when kept */
    int kept;        /* the bytes are in data, or there is no file */
} pic_file_state;
/* The setting rewindMaxBytes (PIC_REWIND_MAX_BYTES unless set), read once. */
long long pic_filelog_cap(void);
/* PATH as it is now, through the executor; its bytes kept when at most KEEP
 * (-1: never; at most PIC_FILE_KEEP_MAX). Bytes not kept are hashed as a
 * stream on the host. */
void pic_file_state_read(const char *path, long long keep, pic_file_state *st);
void pic_file_state_free(pic_file_state *st);
/* Whether ST is the state EXISTS with HASH (HASH ignored when absent). */
int pic_file_state_same(const pic_file_state *st, int exists, const char *hash);
/* Whether EFFECT has its pre-image (1, 0, or -1). */
int pic_filelog_recorded(pic_store *s, sqlite3_int64 effect);
/* Inside a transaction: EFFECT found PATH as PRE (a replay keeps the first);
 * then left it as POST. */
int pic_filelog_before(pic_store *s, sqlite3_int64 effect, const char *path, const pic_file_state *pre, const char *made);
/* The folders above PATH that are missing now, outermost first, one per line
 * (malloc'd), or NULL when there are none: what a write to PATH would create.
 * Read before the transaction that records it (pic_filelog_before's MADE). */
char *pic_filelog_new_dirs(const char *path);
int pic_filelog_after(pic_store *s, sqlite3_int64 effect, const pic_file_state *post);
/* One file a restore puts back: to exist with MODE and the stored bytes
 * HASH, or to be absent. */
typedef struct {
    const char *path;
    int exists;
    unsigned mode;
    const char *hash;
    /* What the caller found there when it decided: the file is left alone
     * (outcome changed) unless it is still that when the restore is journaled. */
    int expect_exists;
    const char *expect_hash;
    /* The first change (pic_file_change id) of a write or edit this restore
     * undoes, 0 if unknown: when the file is deleted, the folders those
     * writes created go with it if they are empty. */
    sqlite3_int64 since;
} pic_restore_target;
typedef struct {
    sqlite3_int64 id;
    int forked;              /* the restore switched conversations */
    char conversation[64];   /* the one it switched to; "" a new, empty one */
    struct pic_restore_file {
        char *path;
        const char *outcome; /* restored, unchanged, changed (since planned: left alone), failed */
        int deleted;         /* the target was no file */
    } *files;
    size_t nfiles;
} pic_restore_result;
/* Journals a restore of conversation SESSION (whose lease the caller holds)
 * to before entry TO_SEQ (0: none), undoing restore UNDOES (0: none), with
 * each target's current state as its pre-image (a target no longer as the
 * caller found it is journaled as changed and left); then puts each file
 * back that is still as it was found, and, when FORK_AT >= 0, forks SESSION at
 * FORK_AT (0: a new, empty conversation) in the transaction that ends it.
 * Fault points restore-bytes-stored, restore-planned, restore-wrote, restore-done. */
int pic_restore(pic_store *s, const char *session, sqlite3_int64 to_seq, sqlite3_int64 undoes, sqlite3_int64 fork_at,
                const pic_restore_target *t, size_t n, pic_restore_result *out);
/* Finishes the restores of SESSION a dead process left started (pic_lease
 * calls it, outside any transaction). */
int pic_restore_resume(pic_store *s, const char *session);
void pic_restore_result_free(pic_restore_result *r);

/* Crash-injection hooks exist only in development builds. */
#ifdef PIC_FAULTS
void pic_fault(const char *point);
#else
#define pic_fault(point) ((void)0)
#endif

#endif