Skip to content
pi-c Artifact [a212e675d7]
Login

Artifact [a212e675d7]

Artifact a212e675d7add0af3eb077194d604711d369d2fe19be8d235e1325d8b353aedf:


/* The durable agent loop. Every state change is one short transaction; no
 * transaction is ever open while the provider or a tool is running.
 *
 * A turn: commit a generation as started, ask the provider, then commit its
 * reply, the assistant entry and every tool call in it together. Each tool
 * call then runs as an effect: commit started, act, commit the result. */
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "compact.h"
#include "libfossil.h"
#include "models.h"
#include "net.h"
#include "pic.h"

static int sql_fail(pic_store *s) {
    (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
    return -1;
}

/* Runs one parameterized statement: 'i' binds an int64, 't' text (NULL binds
 * SQL NULL). */
static int run_stmt(pic_store *s, const char *sql, const char *types, ...) {
    sqlite3_stmt *q = NULL;
    va_list ap;
    int rc;
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    /* One type per parameter, or the varargs below read past what was passed. */
    if ((int)strlen(types) != sqlite3_bind_parameter_count(q)) {
        int want = sqlite3_bind_parameter_count(q);
        sqlite3_finalize(q);
        (void)snprintf(s->err, sizeof s->err, "internal: %zu bind types for %d parameters", strlen(types), want);
        return -1;
    }
    va_start(ap, types);
    for (int i = 0; types[i]; i++) {
        if (types[i] == 'i') {
            sqlite3_bind_int64(q, i + 1, va_arg(ap, sqlite3_int64));
        } else {
            const char *t = va_arg(ap, const char *);
            if (t) {
                sqlite3_bind_text(q, i + 1, t, -1, SQLITE_TRANSIENT);
            } else {
                sqlite3_bind_null(q, i + 1);
            }
        }
    }
    va_end(ap);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    return rc == SQLITE_DONE || rc == SQLITE_ROW ? 0 : sql_fail(s);
}

/* Reads the first column of the first row into *out (0 when NULL or no row).
 * Binds a then b to the statement's parameters, as many as it has. */
static int query_int2(pic_store *s, const char *sql, sqlite3_int64 a, sqlite3_int64 b, sqlite3_int64 *out) {
    sqlite3_stmt *q = NULL;
    int step;
    *out = 0;
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    if (sqlite3_bind_parameter_count(q) > 0) {
        sqlite3_bind_int64(q, 1, a);
    }
    if (sqlite3_bind_parameter_count(q) > 1) {
        sqlite3_bind_int64(q, 2, b);
    }
    step = sqlite3_step(q);
    if (step == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
        *out = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    return step == SQLITE_ROW || step == SQLITE_DONE ? 0 : sql_fail(s);
}

static int query_int(pic_store *s, const char *sql, sqlite3_int64 arg, sqlite3_int64 *out) {
    return query_int2(s, sql, arg, 0, out);
}

static int append_entry(pic_store *s, sqlite3_int64 submission, const char *kind, const char *body) {
    return run_stmt(s, "INSERT INTO pic_entry(submission_id,kind,body) VALUES(?,?,?)", "itt", submission,
                    kind, body);
}

static int append_result(pic_store *s, sqlite3_int64 submission, const char *body, sqlite3_int64 effect) {
    return run_stmt(s, "INSERT INTO pic_entry(submission_id,kind,body,effect_id) VALUES(?,'tool_result',?,?)",
                    "iti", submission, body, effect);
}

/* Inside a transaction: IMAGES become the attachments of entry SEQ, or of
 * queued message QUEUED; each content is stored once, by its SHA3-256. */
int pic_attach_images(pic_store *s, sqlite3_int64 seq, sqlite3_int64 queued, const pic_image *images, size_t n) {
    sqlite3_stmt *put = NULL, *link = NULL;
    int rc = 0;
    if (n == 0) {
        return 0;
    }
    if (sqlite3_prepare_v2(s->db,
                           /* The same content again: nothing to do, unless its bytes were
                            * pruned, in which case they are stored again. */
                           "INSERT INTO pic_image(hash, mime, width, height, sz, data)"
                           " VALUES(?1, ?2, ?4, ?5, length(?3), sqlar_compress(?3))"
                           " ON CONFLICT(hash) DO UPDATE SET data = excluded.data, sz = excluded.sz,"
                           " width = excluded.width, height = excluded.height WHERE pic_image.data IS NULL",
                           -1, &put, NULL) != SQLITE_OK ||
        sqlite3_prepare_v2(s->db, "INSERT INTO pic_attachment(entry_seq, queued_id, ordinal, image) VALUES(?1, ?2, ?3, ?4)",
                           -1, &link, NULL) != SQLITE_OK) {
        sqlite3_finalize(put);
        return sql_fail(s);
    }
    for (size_t i = 0; i < n && rc == 0; i++) {
        fsl_sha3_cx cx;
        fsl_sha3_init2(&cx, FSL_SHA3_256);
        /* fsl_sha3_update takes an unsigned count: feed large images in pieces. */
        for (size_t at = 0; at < images[i].len; at += 1u << 30) {
            size_t part = images[i].len - at < (1u << 30) ? images[i].len - at : 1u << 30;
            fsl_sha3_update(&cx, images[i].data + at, (unsigned)part);
        }
        fsl_sha3_end(&cx);
        sqlite3_bind_text(put, 1, (const char *)cx.hex, -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(put, 2, images[i].mime, -1, SQLITE_STATIC);
        sqlite3_bind_blob64(put, 3, images[i].data, (sqlite3_uint64)images[i].len, SQLITE_STATIC);
        sqlite3_bind_int64(put, 4, images[i].width);
        sqlite3_bind_int64(put, 5, images[i].height);
        if (seq) {
            sqlite3_bind_int64(link, 1, seq);
            sqlite3_bind_null(link, 2);
        } else {
            sqlite3_bind_null(link, 1);
            sqlite3_bind_int64(link, 2, queued);
        }
        sqlite3_bind_int64(link, 3, (sqlite3_int64)i);
        sqlite3_bind_text(link, 4, (const char *)cx.hex, -1, SQLITE_TRANSIENT);
        if (sqlite3_step(put) != SQLITE_DONE || sqlite3_step(link) != SQLITE_DONE) {
            rc = sql_fail(s);
        }
        sqlite3_reset(put);
        sqlite3_reset(link);
    }
    sqlite3_finalize(put);
    sqlite3_finalize(link);
    if (rc == 0) {
        pic_fault("after-image");
    }
    return rc;
}

void pic_reply_free(pic_reply *r) {
    free(r->native);
    free(r->neutral);
    free(r->stop_reason);
    free(r->usage);
    free(r->request_id);
    free(r->provider);
    free(r->api);
    free(r->model);
    memset(r, 0, sizeof *r);
}

/* The session a submission joins: SESSION is NULL for a new one, "latest"
 * for the most recently used, or an id (a unique prefix will do). Inside the
 * caller's transaction; the id goes to out. */
static int choose_session(pic_store *s, const char *session, char *out, size_t cap) {
    sqlite3_stmt *q = NULL;
    sqlite3_int64 busy = 0;
    int found = 0, step;
    if (!session) {
        if (sqlite3_prepare_v2(s->db,
                               "INSERT INTO pic_session(id, created_ms, updated_ms) VALUES(lower(hex(randomblob(4))),"
                               " CAST(unixepoch('subsec') * 1000 AS INTEGER), CAST(unixepoch('subsec') * 1000 AS INTEGER))"
                               " RETURNING id",
                               -1, &q, NULL) != SQLITE_OK) {
            return sql_fail(s);
        }
    } else if (strcmp(session, "latest") == 0) {
        if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_session ORDER BY updated_ms DESC, rowid DESC LIMIT 1", -1, &q,
                               NULL) != SQLITE_OK) {
            return sql_fail(s);
        }
    } else {
        if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_session WHERE id = ?1 OR id LIKE ?1 || '%' LIMIT 2", -1, &q,
                               NULL) != SQLITE_OK) {
            return sql_fail(s);
        }
        sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
    }
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        if (found++ == 0) {
            (void)snprintf(out, cap, "%s", (const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    if (step != SQLITE_DONE) {
        return sql_fail(s);
    }
    if (found == 0) {
        (void)snprintf(s->err, sizeof s->err,
                       session && strcmp(session, "latest") == 0 ? "no session to continue in this journal"
                                                                 : "no session %s (pic sessions lists them)",
                       session ? session : "");
        return -1;
    }
    if (found > 1) {
        (void)snprintf(s->err, sizeof s->err, "session prefix %s is not unique", session);
        return -1;
    }
    if (session) {
        if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_submission WHERE session_id = ? AND status = 'admitted'",
                               -1, &q, NULL) != SQLITE_OK) {
            return sql_fail(s);
        }
        sqlite3_bind_text(q, 1, out, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            busy = sqlite3_column_int64(q, 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)", out);
            return -1;
        }
    }
    return 0;
}

/* Admission is idempotent per request key: a retry finds the original. The
 * user entry becomes a child of the session's head (the trigger links it). */
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) {
    return pic_submit_images(s, request_key, content, NULL, 0, session, duplicate, session_out, session_cap);
}

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) {
    sqlite3_stmt *q = NULL;
    char chosen[64] = "";
    *duplicate = 0;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT content, session_id FROM pic_submission WHERE request_key=?", -1, &q, NULL) !=
        SQLITE_OK) {
        int rc = sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, request_key, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        const char *existing = (const char *)sqlite3_column_text(q, 0);
        int same = existing && strcmp(existing, content) == 0;
        if (session_cap) {
            (void)snprintf(session_out, session_cap, "%s",
                           sqlite3_column_text(q, 1) ? (const char *)sqlite3_column_text(q, 1) : "");
        }
        sqlite3_finalize(q);
        pic_rollback(s);
        if (!same) {
            (void)snprintf(s->err, sizeof s->err, "request key already used with different content");
            return -1;
        }
        *duplicate = 1;
        return 0;
    }
    sqlite3_finalize(q);
    if (choose_session(s, session, chosen, sizeof chosen) != 0 ||
        run_stmt(s, "INSERT INTO pic_submission(request_key,content,status,session_id) VALUES(?,?,'admitted',?)", "ttt",
                 request_key, content, chosen) != 0 ||
        append_entry(s, sqlite3_last_insert_rowid(s->db), "user", content) != 0 ||
        pic_attach_images(s, sqlite3_last_insert_rowid(s->db), 0, images, nimages) != 0 || pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    if (session_cap) {
        (void)snprintf(session_out, session_cap, "%s", chosen);
    }
    pic_fault("after-admit");
    return 0;
}

/* A new session that continues from entry AT of session FROM (default: its
 * head). Entries are shared, not copied: the new session's head is AT. */
int pic_fork(pic_store *s, const char *from, sqlite3_int64 at, char *out, size_t cap) {
    char source[64] = "";
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_session WHERE id = ?1 OR id LIKE ?1 || '%' LIMIT 2", -1, &q, NULL) !=
        SQLITE_OK) {
        rc = sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, from, -1, SQLITE_STATIC);
    for (int n = 0; sqlite3_step(q) == SQLITE_ROW; n++) {
        if (n == 0) {
            (void)snprintf(source, sizeof source, "%s", (const char *)sqlite3_column_text(q, 0));
        } else {
            source[0] = '\0';
            rc = -1;
        }
    }
    sqlite3_finalize(q);
    if (!source[0]) {
        pic_rollback(s);
        (void)snprintf(s->err, sizeof s->err, rc ? "session prefix %s is not unique" : "no session %s (pic sessions lists them)", from);
        return -1;
    }
    if (at > 0) {
        /* AT must be on the source session's path and end a turn: not a user
         * entry, and no tool call at or before it still waiting for its result. */
        sqlite3_stmt *v = NULL;
        int ok = 0;
        if (sqlite3_prepare_v2(
                s->db,
                "WITH RECURSIVE p(seq) AS (SELECT head_seq FROM pic_session WHERE id = ?1"
                " UNION ALL SELECT e.parent_seq FROM pic_entry e JOIN p ON e.seq = p.seq WHERE e.parent_seq IS NOT NULL)"
                " SELECT EXISTS (SELECT 1 FROM p WHERE seq = ?2)"
                " AND (SELECT kind FROM pic_entry WHERE seq = ?2) != 'user'"
                " AND NOT EXISTS (SELECT 1 FROM pic_effect f JOIN pic_entry a ON a.seq = f.entry_seq"
                "   WHERE a.submission_id = (SELECT submission_id FROM pic_entry WHERE seq = ?2) AND a.seq <= ?2"
                "   AND NOT EXISTS (SELECT 1 FROM pic_entry r WHERE r.effect_id = f.id AND r.seq <= ?2))",
                -1, &v, NULL) != SQLITE_OK) {
            rc = sql_fail(s);
            pic_rollback(s);
            return rc;
        }
        sqlite3_bind_text(v, 1, source, -1, SQLITE_STATIC);
        sqlite3_bind_int64(v, 2, at);
        ok = sqlite3_step(v) == SQLITE_ROW && sqlite3_column_int(v, 0) == 1;
        sqlite3_finalize(v);
        if (!ok) {
            /* Name the points that would work: the latest entries that end a turn. */
            char points[160] = "";
            if (sqlite3_prepare_v2(
                    s->db,
                    "WITH RECURSIVE p(seq) AS (SELECT head_seq FROM pic_session WHERE id = ?1"
                    " UNION ALL SELECT e.parent_seq FROM pic_entry e JOIN p ON e.seq = p.seq WHERE e.parent_seq IS NOT NULL)"
                    " SELECT group_concat(seq, ', ') FROM (SELECT x.seq FROM pic_entry x JOIN p ON p.seq = x.seq"
                    " WHERE x.kind != 'user' AND NOT EXISTS (SELECT 1 FROM pic_effect f JOIN pic_entry a ON a.seq = f.entry_seq"
                    "   WHERE a.submission_id = x.submission_id AND a.seq <= x.seq"
                    "   AND NOT EXISTS (SELECT 1 FROM pic_entry r WHERE r.effect_id = f.id AND r.seq <= x.seq))"
                    " ORDER BY x.seq DESC LIMIT 8)",
                    -1, &v, NULL) == SQLITE_OK) {
                sqlite3_bind_text(v, 1, source, -1, SQLITE_STATIC);
                if (sqlite3_step(v) == SQLITE_ROW && sqlite3_column_text(v, 0)) {
                    (void)snprintf(points, sizeof points, "%s", (const char *)sqlite3_column_text(v, 0));
                }
                sqlite3_finalize(v);
            }
            pic_rollback(s);
            (void)snprintf(s->err, sizeof s->err,
                           "entry %lld is not a point to fork %s from: it must be on the conversation and end a turn"
                           "%s%s (pic log shows them)",
                           (long long)at, source, points[0] ? "; the latest are " : "", points);
            return -1;
        }
    }
    if (sqlite3_prepare_v2(
            s->db,
            "INSERT INTO pic_session(id, created_ms, updated_ms, head_seq, forked_from, system_prompt, tools, instructions_hash)"
            " SELECT lower(hex(randomblob(4))), CAST(unixepoch('subsec') * 1000 AS INTEGER),"
            " CAST(unixepoch('subsec') * 1000 AS INTEGER), CASE WHEN ?2 > 0 THEN ?2 ELSE head_seq END, id,"
            " system_prompt, tools, instructions_hash FROM pic_session WHERE id = ?1 RETURNING id",
            -1, &q, NULL) != SQLITE_OK) {
        rc = sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, source, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 2, at);
    if (sqlite3_step(q) == SQLITE_ROW) {
        (void)snprintf(out, cap, "%s", (const char *)sqlite3_column_text(q, 0));
    } else {
        rc = sql_fail(s);
    }
    sqlite3_finalize(q);
    if (rc != 0 || pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    return 0;
}


/* A started replay-unsafe effect may or may not have happened: record that and
 * never run it again. A started replay-safe effect is simply run again. A
 * started generation lost its reply: it failed, and the turn is asked again. */
int pic_recover(pic_store *s) {
    static const char note[] = "error: outcome unknown (interrupted before its result was recorded); not re-run";
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (pic_exec(s, "UPDATE pic_effect SET state='intent' WHERE state='started' AND replay_safe=1") != 0 ||
        pic_exec(s, "UPDATE pic_generation SET state='failed', error='interrupted before the reply was recorded'"
                    " WHERE state='started'") != 0) {
        pic_rollback(s);
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT f.id, e.submission_id FROM pic_effect f JOIN pic_entry e ON e.seq=f.entry_seq"
                           " WHERE f.state='started' AND f.replay_safe=0 ORDER BY f.id",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) {
        sqlite3_int64 effect = sqlite3_column_int64(q, 0);
        sqlite3_int64 submission = sqlite3_column_int64(q, 1);
        if (run_stmt(s, "UPDATE pic_effect SET state='unknown', result=?, is_error=1 WHERE id=?", "ti", note, effect) !=
                0 ||
            append_result(s, submission, note, effect) != 0) {
            rc = -1;
        }
    }
    sqlite3_finalize(q);
    if (rc != 0 || pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    return 0;
}

/* Commit "started" (from inside the tool, just before its first external
 * effect), act outside any transaction, then commit the result and its
 * transcript entry together. */
typedef struct {
    pic_store *s;
    sqlite3_int64 effect;
    int started;
} started_ctx;

static int commit_started(void *p, const char *plan, size_t plan_len) {
    started_ctx *c = p;
    sqlite3_stmt *q = NULL;
    int step;
    if (pic_begin(c->s) != 0) {
        return -1;
    }
    /* A plan is kept once journaled: a replay passes the same bytes back. */
    if (sqlite3_prepare_v2(c->s->db,
                           "UPDATE pic_effect SET state='started', plan=coalesce(?, plan) WHERE id=? AND state='intent'",
                           -1, &q, NULL) != SQLITE_OK) {
        sql_fail(c->s);
        pic_rollback(c->s);
        return -1;
    }
    if (plan) {
        sqlite3_bind_blob64(q, 1, plan, (sqlite3_uint64)plan_len, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 2, c->effect);
    step = sqlite3_step(q);
    sqlite3_finalize(q);
    if (step != SQLITE_DONE || sqlite3_changes(c->s->db) != 1 || pic_commit(c->s) != 0) {
        if (step != SQLITE_DONE) {
            sql_fail(c->s);
        }
        pic_rollback(c->s);
        return -1;
    }
    c->started = 1;
    pic_fault("after-started");
    return 0;
}

/* A journaled bash output by name, for read; only this journal's effects. */
static char *fetch_output(void *p, const char *name, size_t *len) {
    started_ctx *c = p;
    sqlite3_stmt *q = NULL;
    char *end, *out = NULL;
    long long id;
    if (strncmp(name, "pic:output/", 11) != 0 || name[11] < '0' || name[11] > '9') {
        return NULL;
    }
    id = strtoll(name + 11, &end, 10);
    if (*end || sqlite3_prepare_v2(c->s->db, "SELECT sqlar_uncompress(data, sz) FROM pic_output WHERE effect_id=?", -1,
                                   &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_int64(q, 1, id);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) == SQLITE_BLOB) {
        size_t n = (size_t)sqlite3_column_bytes(q, 0);
        if ((out = malloc(n + 1))) {
            memcpy(out, sqlite3_column_blob(q, 0), n);
            out[n] = '\0';
            *len = n;
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* Stores a command's full output in the effect's result transaction. */
static int store_output(pic_store *s, sqlite3_int64 effect, const pic_tool_output *o) {
    sqlite3_stmt *q = NULL;
    int step;
    if (sqlite3_prepare_v2(s->db,
                           "INSERT INTO pic_output(effect_id, sz, data) VALUES(?1, length(?2), sqlar_compress(?2))", -1,
                           &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, effect);
    sqlite3_bind_blob64(q, 2, o->data, (sqlite3_uint64)o->len, SQLITE_STATIC);
    step = sqlite3_step(q);
    sqlite3_finalize(q);
    return step == SQLITE_DONE ? 0 : sql_fail(s);
}

/* One image as a JSON array of a Pi image block, for events (malloc'd). */
static char *image_blocks(pic_store *s, const char *mime, const unsigned char *data, size_t len) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(s->db, "SELECT json_array(json_object('type','image','data',pic_base64(?1),'mimeType',?2))", -1,
                           &q, NULL) == SQLITE_OK) {
        sqlite3_bind_blob64(q, 1, data, (sqlite3_uint64)len, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, mime, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

typedef struct {
    pic_store *s;
    const char *call_id, *tool, *input;
} partial_ctx;

static void emit_partial(void *p, const char *text) {
    partial_ctx *c = p;
    pic_ev_tool_update(c->s, c->call_id, c->tool, c->input, text);
}

static int run_effect(pic_store *s, const char *workspace, int exec_seconds, sqlite3_int64 effect,
                      sqlite3_int64 submission, const char *tool, const pic_tool_args *args, const char *plan,
                      size_t plan_len, const char *call_id, const char *input) {
    started_ctx ctx = {s, effect, 0};
    pic_tool_output output = {NULL, 0};
    struct pic_tool_image image = {NULL, NULL, 0, 0, 0};
    char name[48], *images = NULL;
    partial_ctx pctx = {s, call_id, tool, input};
    pic_tool_hooks hooks = {exec_seconds, commit_started, &ctx, plan, plan_len, name, &output, fetch_output, &image,
                            emit_partial, &pctx};
    pic_image attached;
    int is_error = 0, failed;
    char *result;
    (void)snprintf(name, sizeof name, "pic:output/%lld", (long long)effect);
    pic_ev_tool_start(s, call_id, tool, input, args->command ? args->command : args->path);
    result = pic_tool_run(workspace, tool, args, &hooks, &is_error);
    if (!result) {
        free(output.data);
        free(image.data);
        if (ctx.started) {
            (void)snprintf(s->err, sizeof s->err, "lost the result of %s; recovery will settle it", tool);
        } else if (!s->err[0]) {
            (void)snprintf(s->err, sizeof s->err, "could not record the start of %s", tool);
        }
        return -1;
    }
    pic_fault("after-exec");
    attached = (pic_image){image.mime, image.data, image.len, image.width, image.height};
    failed = pic_begin(s) != 0 ||
             run_stmt(s, "UPDATE pic_effect SET state='done', result=?, is_error=? WHERE id=? AND state='started'",
                      "tii", result, (sqlite3_int64)is_error, effect) != 0 ||
             sqlite3_changes(s->db) != 1 || append_result(s, submission, result, effect) != 0 ||
             pic_attach_images(s, sqlite3_last_insert_rowid(s->db), 0, &attached, image.data ? 1 : 0) != 0 ||
             (output.data && store_output(s, effect, &output) != 0) || pic_commit(s) != 0;
    free(output.data);
    if (!failed && image.data && s->events && s->events->json) {
        images = image_blocks(s, image.mime, image.data, image.len);
    }
    free(image.data);
    if (!failed) {
        pic_ev_tool_end(s, call_id, tool, result, images, is_error);
    }
    free(images);
    free(result);
    if (failed) {
        pic_rollback(s);
        return -1;
    }
    pic_fault("after-result");
    return 0;
}

static char *dup_col(sqlite3_stmt *q, int col) {
    const char *t = (const char *)sqlite3_column_text(q, col);
    return t ? strdup(t) : NULL;
}

/* A call's edits, accepted the ways Pi accepts them: an array, a JSON string
 * holding one, a single object, or legacy top-level oldText/newText. */
static const char edits_sql[] =
    "WITH e(v) AS (SELECT CASE json_type(?1,'$.edits')"
    "  WHEN 'array' THEN json_extract(?1,'$.edits')"
    "  WHEN 'object' THEN json_array(json_extract(?1,'$.edits'))"
    "  WHEN 'text' THEN CASE WHEN json_valid(json_extract(?1,'$.edits'))"
    "    AND json_type(json_extract(?1,'$.edits'))='array' THEN json_extract(?1,'$.edits') END END)"
    " SELECT json_type(value,'$.oldText')='text' AND json_type(value,'$.newText')='text',"
    "  json_extract(value,'$.oldText'), json_extract(value,'$.newText') FROM e, json_each(e.v)"
    " UNION ALL SELECT json_type(?1,'$.newText')='text', json_extract(?1,'$.oldText'), json_extract(?1,'$.newText')"
    "  WHERE json_type(?1,'$.oldText')='text'";

static int fail_submission(pic_store *s, sqlite3_int64 submission, const char *error);
static int admit_next(pic_store *s, sqlite3_int64 from, sqlite3_int64 *next);

typedef struct {
    sqlite3_int64 effect;
    char *tool, *path, *content, *command, *plan, *call_id;
    size_t plan_len, nedits;
    char **old_text, **new_text;
    pic_tool_args args;
} pending;

static void pending_free(pending *p) {
    for (size_t i = 0; i < p->nedits; i++) {
        free(p->old_text[i]);
        free(p->new_text[i]);
    }
    free(p->old_text);
    free(p->new_text);
    free(p->tool);
    free(p->path);
    free(p->content);
    free(p->command);
    free(p->call_id);
    free(p->plan);
}

static int load_edits(pic_store *s, const char *input, pending *p) {
    sqlite3_stmt *q = NULL;
    size_t cap = 0;
    int step;
    if (sqlite3_prepare_v2(s->db, edits_sql, -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_text(q, 1, input, -1, SQLITE_STATIC);
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        if (!sqlite3_column_int(q, 0)) {
            p->args.bad_input = "Edit tool input is invalid. Each edit needs string oldText and newText.";
            continue;
        }
        if (p->nedits == cap) {
            size_t ncap = cap ? cap * 2 : 4;
            char **o = realloc(p->old_text, ncap * sizeof *o), **n;
            if (!o) {
                break;
            }
            p->old_text = o;
            if (!(n = realloc(p->new_text, ncap * sizeof *n))) {
                break;
            }
            p->new_text = n;
            cap = ncap;
        }
        p->old_text[p->nedits] = dup_col(q, 1);
        p->new_text[p->nedits] = dup_col(q, 2);
        p->nedits++;
    }
    sqlite3_finalize(q);
    return step == SQLITE_DONE ? 0 : sql_fail(s);
}

/* Runs the next unfinished tool call, in call order. Returns 1 when none is
 * pending, 0 after running one, -1 on error. */
static int run_pending_effect(pic_store *s, const char *workspace, int exec_seconds, sqlite3_int64 submission) {
    sqlite3_stmt *q = NULL;
    pending p;
    char *input = NULL;
    int rc, step;
    memset(&p, 0, sizeof p);
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT f.id, f.tool, f.input, f.plan,"
            " CASE json_type(f.input,'$.path') WHEN 'text' THEN json_extract(f.input,'$.path') END,"
            " CASE json_type(f.input,'$.content') WHEN 'text' THEN json_extract(f.input,'$.content') END,"
            " CASE json_type(f.input,'$.command') WHEN 'text' THEN json_extract(f.input,'$.command') END,"
            " json_type(f.input,'$.offset') IN ('integer','real'), CAST(json_extract(f.input,'$.offset') AS INTEGER),"
            " json_type(f.input,'$.limit') IN ('integer','real'), CAST(json_extract(f.input,'$.limit') AS INTEGER),"
            " json_type(f.input,'$.timeout') IN ('integer','real'), CAST(json_extract(f.input,'$.timeout') AS INTEGER),"
            " json_type(f.input)='object', f.call_id"
            " FROM pic_effect f JOIN pic_entry e ON e.seq=f.entry_seq"
            " WHERE e.submission_id=? AND f.state='intent' ORDER BY f.entry_seq, f.ordinal LIMIT 1",
            -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, submission);
    step = sqlite3_step(q);
    if (step == SQLITE_ROW) {
        p.effect = sqlite3_column_int64(q, 0);
        p.tool = dup_col(q, 1);
        input = dup_col(q, 2);
        if (sqlite3_column_type(q, 3) != SQLITE_NULL) {
            p.plan_len = (size_t)sqlite3_column_bytes(q, 3);
            p.plan = malloc(p.plan_len + 1);
            if (p.plan) {
                memcpy(p.plan, sqlite3_column_blob(q, 3), p.plan_len);
            }
        }
        p.path = dup_col(q, 4);
        p.content = dup_col(q, 5);
        p.command = dup_col(q, 6);
        p.args.has_offset = sqlite3_column_int(q, 7);
        p.args.offset = (long)sqlite3_column_int64(q, 8);
        p.args.has_limit = sqlite3_column_int(q, 9);
        p.args.limit = (long)sqlite3_column_int64(q, 10);
        p.args.has_timeout = sqlite3_column_int(q, 11);
        p.args.timeout = (long)sqlite3_column_int64(q, 12);
        p.call_id = dup_col(q, 14);
        if (!sqlite3_column_int(q, 13)) {
            p.args.bad_input = "Tool input is not a JSON object.";
        }
        rc = p.tool && input ? 0 : -1;
    } else {
        rc = step == SQLITE_DONE ? 1 : sql_fail(s); /* an error is never "nothing to do" */
    }
    sqlite3_finalize(q);
    if (rc == 0 && strcmp(p.tool, "edit") == 0) {
        rc = load_edits(s, input, &p);
    }
    if (rc == 0) {
        p.args.path = p.path;
        p.args.content = p.content;
        p.args.command = p.command;
        p.args.nedits = p.nedits;
        p.args.old_text = (const char *const *)p.old_text;
        p.args.new_text = (const char *const *)p.new_text;
        rc = run_effect(s, workspace, exec_seconds, p.effect, submission, p.tool, &p.args, p.plan, p.plan_len, p.call_id,
                        input);
    }
    free(input);
    pending_free(&p);
    return rc;
}

/* Inside a transaction: fails the submission, skipping calls that have not
 * run, each with a result saying so, so the journal stays complete. */
static int cancel_submission(pic_store *s, sqlite3_int64 submission) {
    return run_stmt(s,
                    "INSERT INTO pic_entry(submission_id,kind,body,effect_id) SELECT ?1,'tool_result',"
                    "'error: cancelled before it ran',f.id FROM pic_effect f JOIN pic_entry e ON e.seq=f.entry_seq"
                    " WHERE e.submission_id=?1 AND f.state='intent' ORDER BY f.entry_seq, f.ordinal",
                    "i", submission) != 0 ||
                   run_stmt(s,
                            "UPDATE pic_effect SET state='skipped', result='error: cancelled before it ran', is_error=1"
                            " WHERE state='intent' AND entry_seq IN (SELECT seq FROM pic_entry WHERE submission_id=?)",
                            "i", submission) != 0 ||
                   fail_submission(s, submission, "cancelled") != 0
               ? -1
               : 0;
}

/* Fails an admitted submission on request. Calls that have not run are
 * skipped, each with a result saying so, so the journal stays complete. */
int pic_cancel(pic_store *s, const char *request_key) {
    sqlite3_int64 submission = 0;
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_submission WHERE request_key=? AND status='admitted'", -1, &q,
                           NULL) != SQLITE_OK) {
        rc = sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, request_key, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        submission = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    if (submission == 0) {
        pic_rollback(s);
        (void)snprintf(s->err, sizeof s->err, "no admitted submission with key %s", request_key);
        return -1;
    }
    if (cancel_submission(s, submission) != 0 || pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    return 0;
}

/* The answer's text blocks, joined, or NULL. */
char *pic_answer_text(pic_store *s, const char *request_key) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT (SELECT group_concat(json_extract(j.value,'$.text'), char(10)) FROM json_each(e.body) j"
                           "  WHERE json_extract(j.value,'$.type')='text')"
                           " FROM pic_entry e JOIN pic_submission u ON u.id=e.submission_id"
                           " WHERE u.request_key=? AND e.kind='answer'",
                           -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_text(q, 1, request_key, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        out = dup_col(q, 0);
    }
    sqlite3_finalize(q);
    return out;
}

/* A failed or cancelled request's queued messages are returned, never run. */
static int fail_submission(pic_store *s, sqlite3_int64 submission, const char *error) {
    return run_stmt(s, "UPDATE pic_submission SET status='failed', error=? WHERE id=?", "ti", error, submission) != 0 ||
                   run_stmt(s, "UPDATE pic_queued SET state='returned' WHERE submission_id=? AND state='queued'", "i",
                            submission) != 0
               ? -1
               : 0;
}

/* Records the provider's reply: the assistant entry, its tool calls, and the
 * generation, in one transaction. A reply without tool calls is the answer,
 * except pause_turn (the model continues) and refusal (the submission fails). */
static int record_reply(pic_store *s, sqlite3_int64 submission, sqlite3_int64 generation, const pic_reply *r,
                        const char **fault, sqlite3_int64 *next) {
    sqlite3_int64 calls = 0, entry;
    const char *stop = r->stop_reason ? r->stop_reason : "";
    int refusal = strcmp(stop, "refusal") == 0;
    const char *kind;
    if (!r->native || !r->neutral || !r->provider || !r->api || !r->model) {
        (void)snprintf(s->err, sizeof s->err, "provider reply is missing its content or origin");
        return -1;
    }
    {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db,
                               "SELECT json_valid(?1) AND json_type(?1)='array' AND json_valid(?2),"
                               " (SELECT count(*) FROM json_each(?1) WHERE json_extract(value,'$.type')='toolCall')",
                               -1, &q, NULL) != SQLITE_OK) {
            return sql_fail(s);
        }
        sqlite3_bind_text(q, 1, r->neutral, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, r->native, -1, SQLITE_STATIC);
        if (sqlite3_step(q) != SQLITE_ROW || sqlite3_column_int(q, 0) != 1) {
            sqlite3_finalize(q);
            (void)snprintf(s->err, sizeof s->err, "provider content is not valid JSON");
            return -1;
        }
        calls = sqlite3_column_int64(q, 1);
        sqlite3_finalize(q);
    }
    kind = refusal || calls > 0 || strcmp(stop, "pause") == 0 ? "assistant" : "answer";
    if (run_stmt(s, "INSERT INTO pic_entry(submission_id,kind,body,native,provider,api,model) VALUES(?,?,?,?,?,?,?)",
                 "itttttt", submission, kind, r->neutral, r->native, r->provider, r->api, r->model) != 0) {
        return -1;
    }
    entry = sqlite3_last_insert_rowid(s->db);
    if (!refusal && calls > 0) {
        /* Tool calls in content order, from the neutral form, the same for
         * every provider. Arguments that are not an object still make an
         * effect; the tool reports the bad input. */
        if (run_stmt(s,
                     "INSERT INTO pic_effect(entry_seq,ordinal,call_id,tool,input,replay_safe,state)"
                     " SELECT ?1, row_number() OVER (ORDER BY key) - 1,"
                     " coalesce(json_extract(value,'$.id'),''), coalesce(json_extract(value,'$.name'),''),"
                     " coalesce(json(json_extract(value,'$.arguments')),'null'),"
                     " coalesce(json_extract(value,'$.name') IN ('read','write','edit'), 0), 'intent'"
                     " FROM json_each(?2) WHERE json_extract(value,'$.type')='toolCall'",
                     "it", entry, r->neutral) != 0) {
            return -1;
        }
    }
    if (run_stmt(s,
                 "UPDATE pic_generation SET state='done', entry_seq=?, stop_reason=?, usage=?, request_id=?"
                 " WHERE id=? AND state='started'",
                 "ittti", entry, r->stop_reason, r->usage, r->request_id, generation) != 0) {
        return -1;
    }
    if (strcmp(kind, "answer") == 0) {
        *fault = "after-answer";
        return run_stmt(s, "UPDATE pic_submission SET status='answered' WHERE id=?", "i", submission) != 0 ||
                       admit_next(s, submission, next) < 0
                   ? -1
                   : 0;
    }
    *fault = "after-assistant";
    return refusal ? fail_submission(s, submission, "the model refused to continue") : 0;
}

/* Adds the reply's cost at the model's catalog price to its usage ("pic_cost"),
 * as Pi's calculateCost does when the message is made; a model pic cannot
 * resolve, or a reply without usage, costs nothing recorded. */
static void price_reply(pic_reply *r) {
    pic_model m;
    char name[300], err[PIC_ERR_CAP];
    char *priced;
    if (!r->usage || !r->provider || !r->model) {
        return;
    }
    (void)snprintf(name, sizeof name, "%s/%s", r->provider, r->model);
    if (pic_model_resolve(name, &m, err, sizeof err) != 0 || !(priced = pic_usage_priced(&m, r->usage))) {
        return;
    }
    free(r->usage);
    r->usage = priced;
}

/* Asks the provider for the next turn and records its reply durably. Returns
 * 0 when the turn advanced or failed one attempt, 1 when the submission
 * failed for good (s->err says why), -1 on a store error. */
/* 16 hex digits of FNV-1a 64: a fingerprint of the project instructions. */
static void fingerprint(const char *s, char out[17]) {
    unsigned long long h = 1469598103934665603ull;
    for (; *s; s++) {
        h ^= (unsigned char)*s;
        h *= 1099511628211ull;
    }
    (void)snprintf(out, 17, "%016llx", h);
}

/* Inside the generation's transaction: freezes the session's system prompt
 * and tools at its first request; later, appends an instructions entry when
 * the project instructions changed since the session last saw them. */
static int sync_session(pic_store *s, const char *workspace, sqlite3_int64 submission) {
    sqlite3_stmt *q = NULL;
    char *prompt = NULL, *instructions = pic_project_instructions(workspace), hash[17], seen[17] = "";
    int frozen = 0, rc = 0;
    if (!instructions) {
        (void)snprintf(s->err, sizeof s->err, "cannot read the project instructions");
        return -1;
    }
    fingerprint(instructions, hash);
    if (sqlite3_prepare_v2(s->db,
                           "SELECT s.system_prompt IS NOT NULL, coalesce(s.instructions_hash, '') FROM pic_session s"
                           " JOIN pic_submission u ON u.session_id = s.id WHERE u.id = ?",
                           -1, &q, NULL) != SQLITE_OK) {
        free(instructions);
        return sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, submission);
    if (sqlite3_step(q) == SQLITE_ROW) {
        frozen = sqlite3_column_int(q, 0);
        (void)snprintf(seen, sizeof seen, "%s", (const char *)sqlite3_column_text(q, 1));
    }
    sqlite3_finalize(q);
    if (!frozen) {
        prompt = pic_system_prompt(workspace);
        rc = prompt ? run_stmt(s,
                               "UPDATE pic_session SET system_prompt = ?, tools = ?, instructions_hash = ?"
                               " WHERE id = (SELECT session_id FROM pic_submission WHERE id = ?)",
                               "ttti", prompt, pic_tool_schemas, hash, submission)
                    : -1;
    } else if (strcmp(seen, hash) != 0) {
        rc = append_entry(s, submission, "instructions", *instructions ? instructions : "(no project instructions now)") ||
             run_stmt(s, "UPDATE pic_session SET instructions_hash = ? WHERE id = (SELECT session_id FROM pic_submission WHERE id = ?)",
                      "ti", hash, submission);
    }
    free(prompt);
    free(instructions);
    return rc;
}

/* A provider's refusal because the request is longer than the model's
 * context, in the words the APIs use. */
static int context_overflow(const char *err) {
    static const char *const words[] = {"prompt is too long", "context_length_exceeded", "maximum context length",
                                        "context window", "context length", "too many tokens", "input is too long",
                                        "exceeds the context", "request too large", "reduce the length"};
    char lower[PIC_ERR_CAP];
    size_t i;
    for (i = 0; err[i] && i + 1 < sizeof lower; i++) {
        lower[i] = (char)tolower((unsigned char)err[i]);
    }
    lower[i] = '\0';
    for (i = 0; i < sizeof words / sizeof words[0]; i++) {
        if (strstr(lower, words[i])) {
            return 1;
        }
    }
    return 0;
}

/* Before a reply: compacts the conversation when asked to (pic compact, or a
 * context overflow) or when Pi's estimate passes the window minus the
 * reserve. The summary requests are journaled as a generation of purpose
 * compaction and retried like replies; the entry, the generation's end and
 * the cleared request commit together. Returns 0 to go on to the reply, 1
 * when the submission failed, 2 to come back (a retryable attempt failed). */
static int compact_step(pic_store *s, pic_provider *provider, sqlite3_int64 submission, sqlite3_int64 turn) {
    sqlite3_stmt *q = NULL;
    char *instructions = NULL, *history = NULL, *prefix = NULL, *usage = NULL, *usage2 = NULL, *summary = NULL;
    char err[PIC_ERR_CAP] = "";
    int requested = 0, retryable = 0, rc;
    long tokens = 0;
    sqlite3_int64 attempts = 0, generation, seq;
    pic_compaction c;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT s.compact_requested FROM pic_session s JOIN pic_submission u ON u.session_id = s.id"
                           " WHERE u.id = ?",
                           -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, submission);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
        requested = 1;
        instructions = dup_col(q, 0);
    }
    sqlite3_finalize(q);
    if (!provider->summarize) {
        free(instructions);
        return 0;
    }
    if (!requested) {
        if (provider->context_window <= 0) {
            return 0;
        }
        if (pic_context_tokens(s->db, submission, &tokens) != 0) {
            return sql_fail(s);
        }
        if (tokens <= provider->context_window - PIC_RESERVE_TOKENS) {
            return 0;
        }
    }
    rc = pic_compaction_plan(s->db, submission, instructions, &c);
    free(instructions);
    if (rc < 0) {
        return sql_fail(s);
    }
    if (rc == 1) { /* nothing old enough to summarize: the request is done */
        if (requested) {
            pic_ev_note(s, "nothing old enough to compact");
        }
        if (requested &&
            (pic_begin(s) != 0 ||
             run_stmt(s, "UPDATE pic_session SET compact_requested = NULL WHERE id = (SELECT session_id FROM pic_submission WHERE id = ?)",
                      "i", submission) != 0 ||
             pic_commit(s) != 0)) {
            pic_rollback(s);
            return -1;
        }
        return 0;
    }
    if (query_int2(s, "SELECT count(*) FROM pic_generation WHERE submission_id=? AND turn=? AND purpose='compaction'",
                   submission, turn, &attempts) != 0) {
        pic_compaction_free(&c);
        return -1;
    }
    if (attempts >= PIC_GENERATION_ATTEMPTS) {
        pic_compaction_free(&c);
        (void)snprintf(err, sizeof err, "compaction gave up after %d attempts", PIC_GENERATION_ATTEMPTS);
        if (pic_begin(s) != 0 || fail_submission(s, submission, err) != 0 || pic_commit(s) != 0) {
            pic_rollback(s);
            return -1;
        }
        (void)snprintf(s->err, sizeof s->err, "submission %lld failed: %s", (long long)submission, err);
        return 1;
    }
    if (pic_begin(s) != 0 ||
        run_stmt(s, "INSERT INTO pic_generation(submission_id,turn,attempt,state,purpose) VALUES(?,?,?,'started','compaction')",
                 "iii", submission, turn, attempts + 1) != 0 ||
        pic_commit(s) != 0) {
        pic_rollback(s);
        pic_compaction_free(&c);
        return -1;
    }
    generation = sqlite3_last_insert_rowid(s->db);
    pic_fault("after-compaction-started");
    pic_ev_compaction_start(s, requested ? "manual" : "threshold", (long long)c.tokens_before);
    rc = 0;
    if (c.history_prompt) {
        rc = provider->summarize(provider, s, pic_summary_system_prompt, c.history_prompt, &history, &usage, &retryable,
                                 err, sizeof err);
    }
    if (rc == 0 && c.split) {
        rc = provider->summarize(provider, s, pic_summary_system_prompt, c.prefix_prompt, &prefix, &usage2, &retryable,
                                 err, sizeof err);
    }
    if (rc == 0) {
        sqlite3_str *t = sqlite3_str_new(s->db);
        if (c.split) {
            sqlite3_str_appendf(t, "%s\n\n---\n\n**Turn Context (split turn):**\n\n%s",
                                history ? history : c.previous_summary ? c.previous_summary : "No prior history.", prefix);
        } else {
            sqlite3_str_appendall(t, history);
        }
        sqlite3_str_appendall(t, c.files);
        summary = sqlite3_str_finish(t);
        if (!summary) {
            (void)snprintf(err, sizeof err, "out of memory");
            rc = -1;
        }
    }
    free(history);
    free(prefix);
    if (rc != 0) {
        if (!err[0]) {
            (void)snprintf(err, sizeof err, "the summary request failed");
        }
        retryable = retryable || pic_interrupted; /* Ctrl-C: pic_run cancels the request */
        free(usage);
        pic_ev_compaction_end(s, requested ? "manual" : "threshold", NULL, 0, 0, err);
        free(usage2);
        pic_compaction_free(&c);
        if (pic_begin(s) != 0 ||
            run_stmt(s, "UPDATE pic_generation SET state='failed', error=? WHERE id=?", "ti", err, generation) != 0 ||
            (!retryable && fail_submission(s, submission, err) != 0) || pic_commit(s) != 0) {
            pic_rollback(s);
            return -1;
        }
        if (!retryable) {
            (void)snprintf(s->err, sizeof s->err, "submission %lld failed: compaction: %s", (long long)submission, err);
            return 1;
        }
        return 2;
    }
    pic_fault("after-summary");
    rc = pic_begin(s) != 0 ||
         run_stmt(s,
                  "INSERT INTO pic_entry(submission_id,kind,body,native,first_kept_seq,tokens_before)"
                  " VALUES(?,'compaction',?,?,?,?)",
                  "ittii", submission, summary, c.details, c.first_kept_seq, c.tokens_before) != 0;
    seq = sqlite3_last_insert_rowid(s->db);
    /* Instructions updates summarized away go out again after the summary:
     * the latest project instructions stay in the conversation verbatim. */
    rc = rc ||
         run_stmt(s, "UPDATE pic_generation SET state='done', entry_seq=?, usage=? WHERE id=?", "iti", seq,
                  usage ? usage : usage2, generation) != 0 ||
         run_stmt(s, "UPDATE pic_session SET compact_requested = NULL WHERE id = (SELECT session_id FROM pic_submission WHERE id = ?)",
                  "i", submission) != 0 ||
         run_stmt(s,
                  PIC_CONTEXT_CTE "INSERT INTO pic_entry(submission_id,kind,body) SELECT ?1, 'instructions', body FROM"
                                  " (SELECT x.body, x.seq FROM pic_entry x JOIN p ON p.seq = x.seq WHERE x.kind = 'instructions'"
                                  " ORDER BY x.seq DESC LIMIT 1) WHERE seq < ?2",
                  "ii", submission, c.first_kept_seq) != 0 ||
         pic_commit(s) != 0;
    if (!rc) {
        pic_ev_compaction_end(s, requested ? "manual" : "threshold", summary, (long long)c.first_kept_seq,
                              (long long)c.tokens_before, NULL);
    }
    sqlite3_free(summary);
    free(usage);
    free(usage2);
    pic_compaction_free(&c);
    if (rc) {
        pic_rollback(s);
        return -1;
    }
    pic_fault("after-compaction");
    return 0;
}

/* ---- steering and follow-ups ------------------------------------------------ */

/* A queued message belongs to one request, which is always admitted: it is
 * delivered into it as steering, moves with the rest of its queue to the
 * next request the conversation's answer admits, or is returned (never run)
 * when the request fails or is cancelled. */

int pic_queue_add(pic_store *s, const char *kind, const char *text) {
    return pic_queue_add_images(s, kind, text, NULL, 0);
}

int pic_queue_add_images(pic_store *s, const char *kind, const char *text, const pic_image *images, size_t nimages) {
    sqlite3_int64 owner = 0, answered = 0, next = 0;
    if (pic_begin(s) != 0) {
        return -1;
    }
    /* The running conversation's admitted request; or, after its answer, the
     * answered one, whose queue becomes the next request at once. */
    if (query_int(s,
                  "SELECT id FROM pic_submission WHERE status = 'admitted' AND session_id ="
                  " (SELECT session_id FROM pic_submission WHERE id = ?)",
                  (sqlite3_int64)s->running, &owner) != 0 ||
        (!owner && query_int(s, "SELECT id FROM pic_submission WHERE id = ? AND status = 'answered'",
                             (sqlite3_int64)s->running, &answered) != 0)) {
        pic_rollback(s);
        return -1;
    }
    if (!owner && !answered) {
        pic_rollback(s);
        (void)snprintf(s->err, sizeof s->err, "no request is running");
        return -1;
    }
    if (run_stmt(s,
                 "INSERT INTO pic_queued(session_id, submission_id, kind, text, state, created_ms)"
                 " SELECT session_id, id, ?, ?, 'queued', CAST(unixepoch('subsec') * 1000 AS INTEGER)"
                 " FROM pic_submission WHERE id = ?",
                 "tti", kind, text, owner ? owner : answered) != 0 ||
        pic_attach_images(s, 0, sqlite3_last_insert_rowid(s->db), images, nimages) != 0 ||
        (answered && admit_next(s, answered, &next) < 0) || pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    if (next) {
        s->running = next;
    }
    pic_fault("after-enqueue");
    return 0;
}

/* A request's queue in Pi's queue_update fields (SQL; ?1 is the request,
 * state the rows shown). */
#define QUEUES_SQL(state)                                                                                              \
    "'steering', json((SELECT json_group_array(text) FROM (SELECT text FROM pic_queued WHERE submission_id = ?1"      \
    " AND state = " state " AND kind = 'steer' ORDER BY id))),"                                                        \
    " 'followUp', json((SELECT json_group_array(text) FROM (SELECT text FROM pic_queued WHERE submission_id = ?1"     \
    " AND state = " state " AND kind = 'follow_up' ORDER BY id)))"

/* The request whose queue commands see: the running conversation's admitted one. */
#define OWNER_SQL                                                                                                      \
    "(SELECT coalesce((SELECT id FROM pic_submission WHERE status = 'admitted' AND session_id ="                      \
    " (SELECT session_id FROM pic_submission WHERE id = ?1)), ?1))"

int pic_queue_clear(pic_store *s, char **cleared) {
    sqlite3_stmt *q = NULL;
    sqlite3_int64 owner = 0;
    *cleared = NULL;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (query_int(s, "SELECT " OWNER_SQL, (sqlite3_int64)s->running, &owner) != 0) {
        pic_rollback(s);
        return -1;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT json_object(" QUEUES_SQL("'queued'") ")", -1, &q, NULL) != SQLITE_OK) {
        sql_fail(s);
        pic_rollback(s);
        return -1;
    }
    sqlite3_bind_int64(q, 1, owner);
    if (sqlite3_step(q) == SQLITE_ROW) {
        *cleared = dup_col(q, 0);
    }
    sqlite3_finalize(q);
    if (!*cleared ||
        run_stmt(s, "UPDATE pic_queued SET state = 'cleared' WHERE state = 'queued' AND submission_id = ?", "i", owner) != 0 ||
        pic_commit(s) != 0) {
        if (!s->err[0]) {
            (void)snprintf(s->err, sizeof s->err, "out of memory");
        }
        free(*cleared);
        *cleared = NULL;
        pic_rollback(s);
        return -1;
    }
    return 0;
}

/* One event line: TYPE with REQUEST's queue rows in STATE. */
static void queue_line(pic_store *s, sqlite3_int64 request, const char *sql) {
    sqlite3_stmt *q = NULL;
    if (!s->events || !s->events->json || sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return;
    }
    sqlite3_bind_int64(q, 1, request);
    if (sqlite3_step(q) == SQLITE_ROW) {
        pic_ev_line(s, (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
}

void pic_queue_event(pic_store *s) {
    sqlite3_int64 owner = 0;
    if (s->events && s->events->json && query_int(s, "SELECT " OWNER_SQL, (sqlite3_int64)s->running, &owner) == 0) {
        queue_line(s, owner, "SELECT json_object('type', 'queue_update', " QUEUES_SQL("'queued'") ")");
    }
}

/* Inside a transaction: the oldest queued message of KIND that request OWNER
 * holds becomes the next user entry of request INTO. 1 when one did, 0 when
 * none is queued. */
static int take_queued(pic_store *s, sqlite3_int64 owner, sqlite3_int64 into, const char *kind) {
    sqlite3_stmt *q = NULL;
    sqlite3_int64 id = 0;
    char *text = NULL;
    int rc;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT id, text FROM pic_queued WHERE submission_id = ?1 AND state = 'queued' AND kind = ?2"
                           " ORDER BY id LIMIT 1",
                           -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, owner);
    sqlite3_bind_text(q, 2, kind, -1, SQLITE_STATIC);
    rc = sqlite3_step(q);
    if (rc == SQLITE_ROW) {
        id = sqlite3_column_int64(q, 0);
        text = dup_col(q, 1);
    }
    sqlite3_finalize(q);
    if (rc == SQLITE_DONE) {
        return 0;
    }
    if (rc != SQLITE_ROW || !text) {
        return rc != SQLITE_ROW ? sql_fail(s) : -1;
    }
    rc = append_entry(s, into, "user", text) != 0 ||
                 run_stmt(s,
                          "INSERT INTO pic_attachment(entry_seq, ordinal, image) SELECT ?, ordinal, image"
                          " FROM pic_attachment WHERE queued_id = ? ORDER BY ordinal",
                          "ii", sqlite3_last_insert_rowid(s->db), id) != 0 ||
                 run_stmt(s,
                          "UPDATE pic_queued SET state = 'delivered', submission_id = ?,"
                          " entry_seq = (SELECT max(seq) FROM pic_entry) WHERE id = ?",
                          "ii", into, id) != 0
             ? -1
             : 1;
    free(text);
    return rc;
}

/* Inside the transaction that answers request FROM: when it holds queued
 * messages the conversation goes on, as Pi's loop does where it would stop.
 * Its oldest steering, else its oldest follow-up (all of that kind with the
 * mode set), becomes the next request, which takes over the rest of the
 * queue. 1 with *next set when one was admitted, 0 when the queue is empty. */
static int admit_next(pic_store *s, sqlite3_int64 from, sqlite3_int64 *next) {
    sqlite3_int64 first = 0, steer = 0;
    const char *kind;
    int rc;
    *next = 0;
    if (query_int(s,
                  "SELECT id FROM pic_queued WHERE submission_id = ? AND state = 'queued' ORDER BY kind != 'steer', id LIMIT 1",
                  from, &first) != 0 ||
        query_int(s, "SELECT kind = 'steer' FROM pic_queued WHERE id = ?", first, &steer) != 0) {
        return -1;
    }
    if (!first) {
        return 0;
    }
    kind = steer ? "steer" : "follow_up";
    if (run_stmt(s,
                 "INSERT INTO pic_submission(request_key, content, status, session_id)"
                 " SELECT 'queued-' || id, text, 'admitted', session_id FROM pic_queued WHERE id = ?",
                 "i", first) != 0) {
        return -1;
    }
    *next = sqlite3_last_insert_rowid(s->db);
    while ((rc = take_queued(s, from, *next, kind)) == 1 && (steer ? s->steer_all : s->follow_up_all)) {
    }
    if (rc < 0 ||
        run_stmt(s, "UPDATE pic_queued SET submission_id = ? WHERE submission_id = ? AND state = 'queued'", "ii", *next,
                 from) != 0) {
        return -1;
    }
    return 1;
}

/* User message events for the messages delivered into SUBMISSION after entry
 * AFTER; FIRST_TURN: those after its own text, before its first reply. */
static void delivered_events(pic_store *s, sqlite3_int64 submission, sqlite3_int64 after, int first_turn) {
    sqlite3_stmt *q = NULL;
    if (!s->events ||
        sqlite3_prepare_v2(s->db,
                           "SELECT q.text, pic_content(e.seq, q.text, 'pi-images', 1, 0) FROM pic_queued q JOIN pic_entry e ON e.seq = q.entry_seq"
                           " WHERE e.submission_id = ?1"
                           " AND e.seq > max(?2, CASE WHEN ?3 THEN (SELECT min(x.seq) FROM pic_entry x WHERE x.submission_id = ?1)"
                           "   ELSE 0 END)"
                           " AND (NOT ?3 OR e.seq < coalesce((SELECT min(x.seq) FROM pic_entry x"
                           "   WHERE x.submission_id = ?1 AND x.kind != 'user'), 9223372036854775807))"
                           " ORDER BY e.seq",
                           -1, &q, NULL) != SQLITE_OK) {
        return;
    }
    sqlite3_bind_int64(q, 1, submission);
    sqlite3_bind_int64(q, 2, after);
    sqlite3_bind_int(q, 3, first_turn);
    while (sqlite3_step(q) == SQLITE_ROW) {
        pic_ev_user_message(s, (const char *)sqlite3_column_text(q, 0), (const char *)sqlite3_column_text(q, 1));
    }
    sqlite3_finalize(q);
}

/* Before a reply, after the turn's tool results: the request's queued
 * steering becomes user entries (one, or all with steer_all), marked
 * delivered in the same transaction. Once per turn: nothing when a message
 * was delivered since the last reply. */
static int deliver_steering(pic_store *s, sqlite3_int64 submission) {
    sqlite3_int64 done = 0, before = 0;
    int rc = 0, n = 0;
    if (query_int(s,
                  "SELECT count(*) FROM pic_queued q JOIN pic_entry e ON e.seq = q.entry_seq WHERE e.submission_id = ?1"
                  " AND e.seq > coalesce((SELECT max(seq) FROM pic_entry WHERE submission_id = ?1"
                  "   AND kind IN ('assistant','answer')), 0)",
                  submission, &done) != 0 ||
        query_int(s, "SELECT coalesce(max(seq), 0) FROM pic_entry", 0, &before) != 0) {
        return -1;
    }
    if (done) {
        return 0;
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    for (;;) {
        rc = take_queued(s, submission, submission, "steer");
        if (rc != 1) {
            break;
        }
        n++;
        if (!s->steer_all) {
            break;
        }
    }
    if (rc < 0 || pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    if (n > 0) {
        pic_fault("after-steer");
        delivered_events(s, submission, before, 0);
        pic_queue_event(s);
    }
    return 0;
}

static int generate(pic_store *s, const char *workspace, pic_provider *provider, sqlite3_int64 submission) {
    sqlite3_int64 turn = 0, attempts = 0, generation, next = 0;
    pic_reply reply;
    char err[PIC_ERR_CAP];
    int retryable = 0, rc;
    const char *fault = NULL;
    if (query_int(s, "SELECT count(*) FROM pic_entry WHERE submission_id=? AND kind IN ('assistant','answer')",
                  submission, &turn) != 0 ||
        query_int2(s, "SELECT count(*) FROM pic_generation WHERE submission_id=? AND turn=? AND purpose='reply'", submission, turn,
                   &attempts) != 0) {
        return -1;
    }
    if (attempts >= PIC_GENERATION_ATTEMPTS) {
        char last[PIC_ERR_CAP] = "";
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db,
                               "SELECT error FROM pic_generation WHERE submission_id=? AND turn=? AND purpose='reply' ORDER BY attempt DESC LIMIT 1",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_int64(q, 1, submission);
            sqlite3_bind_int64(q, 2, turn);
            if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
                (void)snprintf(last, sizeof last, "%s", (const char *)sqlite3_column_text(q, 0));
            }
            sqlite3_finalize(q);
        }
        (void)snprintf(err, sizeof err, "gave up after %d provider attempts: %s", PIC_GENERATION_ATTEMPTS, last);
        if (pic_begin(s) != 0 || fail_submission(s, submission, err) != 0 || pic_commit(s) != 0) {
            pic_rollback(s);
            return -1;
        }
        (void)snprintf(s->err, sizeof s->err, "submission %lld failed: %s", (long long)submission, err);
        return 1;
    }
    /* Steering queued meanwhile goes before the reply; after a compaction,
     * steering that arrived while it ran (Pi polls again there too). */
    if (deliver_steering(s, submission) != 0) {
        return -1;
    }
    rc = compact_step(s, provider, submission, turn);
    if (rc != 0) {
        return rc == 2 ? 0 : rc;
    }
    if (deliver_steering(s, submission) != 0) {
        return -1;
    }
    if (pic_begin(s) != 0 || sync_session(s, workspace, submission) != 0 ||
        run_stmt(s, "INSERT INTO pic_generation(submission_id,turn,attempt,state) VALUES(?,?,?,'started')", "iii",
                 submission, turn, attempts + 1) != 0 ||
        pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    generation = sqlite3_last_insert_rowid(s->db);
    pic_fault("after-generation-started");
    pic_ev_turn_start(s);
    memset(&reply, 0, sizeof reply);
    err[0] = '\0';
    if (provider->reply(provider, s, submission, turn, &reply, &retryable, err, sizeof err) != 0) {
        if (!err[0]) {
            (void)snprintf(err, sizeof err, "provider failed");
        }
        pic_reply_free(&reply);
        if (pic_interrupted) { /* Ctrl-C: no retry; pic_run cancels the request */
            pic_ev_message_error(s, "interrupted", (int)attempts + 1, PIC_GENERATION_ATTEMPTS, 0);
            if (pic_begin(s) != 0 ||
                run_stmt(s, "UPDATE pic_generation SET state='failed', error='interrupted' WHERE id=?", "i", generation) != 0 ||
                pic_commit(s) != 0) {
                pic_rollback(s);
                return -1;
            }
            return 0;
        }
        /* Too long for the model: compact once, then try again. */
        if (!retryable && context_overflow(err)) {
            sqlite3_int64 compacted = 0;
            if (query_int2(s,
                           "SELECT count(*) FROM pic_generation WHERE submission_id=? AND turn=? AND purpose='compaction'"
                           " AND state='done'",
                           submission, turn, &compacted) != 0) {
                return -1;
            }
            if (!compacted &&
                (pic_begin(s) != 0 ||
                 run_stmt(s, "UPDATE pic_session SET compact_requested = coalesce(compact_requested, '') WHERE id ="
                             " (SELECT session_id FROM pic_submission WHERE id = ?)", "i", submission) != 0 ||
                 pic_commit(s) != 0)) {
                pic_rollback(s);
                return -1;
            }
            retryable = !compacted;
        }
        pic_ev_message_error(s, err, (int)attempts + 1, PIC_GENERATION_ATTEMPTS,
                             retryable && attempts + 1 < PIC_GENERATION_ATTEMPTS);
        if (pic_begin(s) != 0 ||
            run_stmt(s, "UPDATE pic_generation SET state='failed', error=? WHERE id=?", "ti", err, generation) != 0 ||
            (!retryable && fail_submission(s, submission, err) != 0) || pic_commit(s) != 0) {
            pic_rollback(s);
            return -1;
        }
        if (!retryable) {
            (void)snprintf(s->err, sizeof s->err, "submission %lld failed: %s", (long long)submission, err);
            return 1;
        }
        return 0;
    }
    pic_fault("after-reply");
    price_reply(&reply);
    if (pic_begin(s) != 0 || record_reply(s, submission, generation, &reply, &fault, &next) != 0 || pic_commit(s) != 0) {
        pic_rollback(s);
        pic_reply_free(&reply);
        return -1;
    }
    if (s->events) {
        /* The reply's usage in Pi's shape, for clients' token and context counts. */
        sqlite3_stmt *u = NULL;
        const char *usage = NULL;
        if (reply.usage &&
            sqlite3_prepare_v2(
                s->db,
                "SELECT json_object('input', coalesce(json_extract(?1,'$.pic_tokens.input'), json_extract(?1,'$.input_tokens'), json_extract(?1,'$.prompt_tokens'), 0),"
                " 'output', coalesce(json_extract(?1,'$.pic_tokens.output'), json_extract(?1,'$.output_tokens'), json_extract(?1,'$.completion_tokens'), 0),"
                " 'cacheRead', coalesce(json_extract(?1,'$.pic_tokens.cacheRead'), json_extract(?1,'$.cache_read_input_tokens'),"
                "   json_extract(?1,'$.prompt_tokens_details.cached_tokens'), json_extract(?1,'$.input_tokens_details.cached_tokens'), 0),"
                " 'cacheWrite', coalesce(json_extract(?1,'$.pic_tokens.cacheWrite'), json_extract(?1,'$.cache_creation_input_tokens'), 0),"
                " 'totalTokens', coalesce(json_extract(?1,'$.pic_tokens.totalTokens'), json_extract(?1,'$.total_tokens'),"
                "   coalesce(json_extract(?1,'$.input_tokens'), 0) + coalesce(json_extract(?1,'$.output_tokens'), 0)"
                "   + coalesce(json_extract(?1,'$.cache_read_input_tokens'), 0) + coalesce(json_extract(?1,'$.cache_creation_input_tokens'), 0)),"
" 'cost', json(coalesce(json_extract(?1,'$.pic_cost'),"
                "   '{\"input\":0,\"output\":0,\"cacheRead\":0,\"cacheWrite\":0,\"total\":0}')))"
                " WHERE json_valid(?1)",
                -1, &u, NULL) == SQLITE_OK) {
            sqlite3_bind_text(u, 1, reply.usage, -1, SQLITE_STATIC);
            if (sqlite3_step(u) == SQLITE_ROW) {
                usage = (const char *)sqlite3_column_text(u, 0);
            }
        }
            pic_ev_message_end(s, reply.neutral, reply.stop_reason, reply.provider, reply.api, reply.model, usage);
        sqlite3_finalize(u);
    }
    pic_reply_free(&reply);
    if (next) { /* the queue moved to the next request */
        s->running = next;
        pic_queue_event(s);
    }
    pic_fault(fault);
    {
        sqlite3_int64 failed = 0;
        rc = query_int(s, "SELECT status='failed' FROM pic_submission WHERE id=?", submission, &failed);
        if (rc == 0 && failed) {
            (void)snprintf(s->err, sizeof s->err, "submission %lld failed: the model refused to continue",
                           (long long)submission);
            return 1;
        }
    }
    return rc;
}

/* Drives every admitted submission, oldest first, until each is answered or
 * failed. Returns -1 if any failed (s->err names the last) or on error. */
/* agent_start or agent_end for a request, with what clients show of it. */
static void request_event(pic_store *s, const pic_provider *provider, sqlite3_int64 submission, int start) {
    sqlite3_stmt *q = NULL;
    if (!s->events ||
        sqlite3_prepare_v2(s->db,
                           "SELECT request_key, content, status, error, session_id, pic_content((SELECT min(seq)"
                           " FROM pic_entry WHERE submission_id = u.id), content, 'pi-images', 1, 0) FROM pic_submission u WHERE id = ?",
                           -1, &q, NULL) != SQLITE_OK) {
        return;
    }
    sqlite3_bind_int64(q, 1, submission);
    if (sqlite3_step(q) == SQLITE_ROW) {
        const char *key = (const char *)sqlite3_column_text(q, 0);
        if (start) {
            pic_ev_agent_start(s, key, (const char *)sqlite3_column_text(q, 1), (const char *)sqlite3_column_text(q, 5),
                               (const char *)sqlite3_column_text(q, 4), provider->model, provider->context_window,
                               provider->thinking);
            delivered_events(s, submission, 0, 1);
        } else {
            sqlite3_int64 returned = 0;
            /* What it still held comes back, for the client to restore (Pi puts
             * queued messages back in the editor). */
            if (query_int(s, "SELECT count(*) FROM pic_queued WHERE submission_id = ? AND state = 'returned'", submission,
                          &returned) == 0 &&
                returned) {
                queue_line(s, submission, "SELECT json_object('type', 'queue_returned', " QUEUES_SQL("'returned'") ")");
                queue_line(s, submission, "SELECT json_object('type', 'queue_update', " QUEUES_SQL("'queued'") ")");
            }
            pic_ev_agent_end(s, key, (const char *)sqlite3_column_text(q, 2), (const char *)sqlite3_column_text(q, 3));
        }
    }
    sqlite3_finalize(q);
}

int pic_run(pic_store *s, const char *workspace, pic_provider *provider, int exec_seconds) {
    int any_failed = 0;
    sqlite3_int64 open = 0; /* the request events are being sent for */
    char failure[PIC_ERR_CAP] = "";
    for (;;) {
        sqlite3_int64 submission = 0;
        int rc;
        /* Commands that arrived since the last wait, before looking for work:
         * a follow-up taken here after the last answer is admitted at once and
         * must be found below, not left for another process. */
        pic_side_poll(0);
        /* The oldest admitted request, the running conversation's first. */
        if (query_int(s,
                      "SELECT id FROM pic_submission WHERE status='admitted' ORDER BY session_id IS NOT"
                      " (SELECT session_id FROM pic_submission WHERE id = ?), id LIMIT 1",
                      (sqlite3_int64)s->running, &submission) != 0) {
            return -1;
        }
        /* Commands steer the conversation pic was asked to run; other
         * requests left in the journal run after it without taking them. */
        if (submission) {
            sqlite3_int64 same = 0;
            if (query_int2(s,
                           "SELECT ?1 = 0 OR (SELECT session_id FROM pic_submission WHERE id = ?1) ="
                           " (SELECT session_id FROM pic_submission WHERE id = ?2)",
                           (sqlite3_int64)s->running, submission, &same) != 0) {
                return -1;
            }
            if (same) {
                s->running = submission;
            }
        }
        if (open && open != submission) {
            request_event(s, provider, open, 0);
        }
        if (submission && open != submission) {
            request_event(s, provider, submission, 1);
        }
        open = submission;
        if (pic_interrupted) { /* Ctrl-C: cancel this request, keep the rest for later */
            pic_interrupted = 0;
            if (submission) {
                if (pic_begin(s) != 0 || cancel_submission(s, submission) != 0 || pic_commit(s) != 0) {
                    pic_rollback(s);
                    return -1;
                }
                request_event(s, provider, submission, 0);
                if (s->cancelled) {
                    s->cancelled(s);
                }
                (void)snprintf(s->err, sizeof s->err, "cancelled");
                return -1;
            }
        }
        if (submission == 0) {
            if (any_failed) {
                (void)snprintf(s->err, sizeof s->err, "%s", failure);
            }
            return any_failed ? -1 : 0;
        }
        rc = run_pending_effect(s, workspace, exec_seconds, submission);
        if (rc == 1) {
            rc = generate(s, workspace, provider, submission);
            if (rc == 1) {
                any_failed = 1;
                (void)snprintf(failure, sizeof failure, "%s", s->err);
                rc = 0;
            }
        }
        if (rc != 0) {
            return -1;
        }
    }
}

/* Canonical journal listing for tests and inspection. */
int pic_dump(pic_store *s) {
    static const char *const queries[] = {
        "SELECT 'submission', id, request_key, status, content || coalesce(' error=' || error, '') FROM pic_submission ORDER BY id",
        "SELECT 'entry', seq, submission_id, kind || coalesce(' effect=' || effect_id, ''), body FROM pic_entry ORDER BY seq",
        "SELECT 'effect', id, entry_seq || '.' || ordinal, tool || ' ' || state || ' safe=' || replay_safe, coalesce(result,'') FROM pic_effect ORDER BY id",
        ("SELECT 'generation', id, submission_id || '.' || turn || '.' || attempt,"
         " state || coalesce(' stop=' || stop_reason, '') || CASE purpose WHEN 'compaction' THEN ' compaction' ELSE '' END,"
         " coalesce(error, '') FROM pic_generation ORDER BY id"),
        ("SELECT 'queued', id, submission_id || '.' || kind, state || coalesce(' entry=' || entry_seq, ''), text"
         " FROM pic_queued ORDER BY id"),
        ("SELECT 'image', a.id, coalesce('entry=' || a.entry_seq, 'queued=' || a.queued_id) || '.' || a.ordinal,"
         " i.mime || ' ' || i.sz || CASE WHEN length(i.data) < i.sz THEN ' deflated' ELSE ' raw' END, i.hash"
         " FROM pic_attachment a JOIN pic_image i ON i.hash = a.image ORDER BY a.id"),
    };
    for (size_t i = 0; i < sizeof queries / sizeof queries[0]; i++) {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db, queries[i], -1, &q, NULL) != SQLITE_OK) {
            return sql_fail(s);
        }
        while (sqlite3_step(q) == SQLITE_ROW) {
            printf("%s %lld %s %s | %s\n", (const char *)sqlite3_column_text(q, 0),
                   (long long)sqlite3_column_int64(q, 1), (const char *)sqlite3_column_text(q, 2),
                   (const char *)sqlite3_column_text(q, 3), (const char *)sqlite3_column_text(q, 4));
        }
        sqlite3_finalize(q);
    }
    return 0;
}

/* The frozen system prompt or tools of a submission's session (malloc'd).
 * column is "system_prompt" or "tools"; set by the first generation. */
char *pic_session_text(pic_store *s, int64_t submission, const char *column) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    char sql[200];
    if (strcmp(column, "system_prompt") != 0 && strcmp(column, "tools") != 0) {
        return NULL;
    }
    (void)snprintf(sql, sizeof sql,
                   "SELECT s.%s FROM pic_session s JOIN pic_submission u ON u.session_id = s.id WHERE u.id = ?", column);
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_int64(q, 1, submission);
    if (sqlite3_step(q) == SQLITE_ROW) {
        out = dup_col(q, 0);
    }
    sqlite3_finalize(q);
    return out;
}

/* Resolves a session id or unique prefix ("latest": the most recent). */
static int resolve_session(pic_store *s, const char *session, char *out, size_t cap) {
    sqlite3_stmt *q = NULL;
    int n = 0;
    if (sqlite3_prepare_v2(s->db,
                           strcmp(session, "latest") == 0
                               ? "SELECT id FROM pic_session ORDER BY updated_ms DESC, rowid DESC LIMIT 1"
                               : "SELECT id FROM pic_session WHERE id = ?1 OR id LIKE ?1 || '%' LIMIT 2",
                           -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    if (strcmp(session, "latest") != 0) {
        sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
    }
    while (sqlite3_step(q) == SQLITE_ROW) {
        if (n++ == 0) {
            (void)snprintf(out, cap, "%s", (const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    if (n != 1) {
        (void)snprintf(s->err, sizeof s->err, n ? "session prefix %s is not unique" : "no session %s (pic sessions lists them)", session);
        return -1;
    }
    return 0;
}

int pic_sessions(pic_store *s, FILE *out) {
    sqlite3_stmt *q = NULL;
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT s.id, coalesce(s.name, '-'), strftime('%Y-%m-%d %H:%M', s.updated_ms / 1000, 'unixepoch', 'localtime'),"
            " (SELECT count(*) FROM pic_submission u WHERE u.session_id = s.id),"
            " coalesce(replace(substr((SELECT u.content FROM pic_submission u WHERE u.session_id = s.id ORDER BY u.id LIMIT 1),"
            "   1, 60), char(10), ' '), '(forked from ' || s.forked_from || ')', '')"
            " FROM pic_session s ORDER BY s.updated_ms DESC, s.rowid DESC",
            -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    while (sqlite3_step(q) == SQLITE_ROW) {
        fprintf(out, "%s  %-16s %s  %3lld  %s\n", (const char *)sqlite3_column_text(q, 0),
                (const char *)sqlite3_column_text(q, 1), (const char *)sqlite3_column_text(q, 2),
                (long long)sqlite3_column_int64(q, 3), (const char *)sqlite3_column_text(q, 4));
    }
    sqlite3_finalize(q);
    return 0;
}

int pic_session_name(pic_store *s, const char *session, const char *name) {
    char id[64];
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (resolve_session(s, session, id, sizeof id) != 0 ||
        run_stmt(s, "UPDATE pic_session SET name = ? WHERE id = ?", "tt", name, id) != 0 || pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    return 0;
}

/* The conversation along a session's path: your messages, the replies'
 * text, tool calls with their first result line, instruction updates. */
int pic_session_log(pic_store *s, const char *session, FILE *out) {
    sqlite3_stmt *q = NULL;
    char id[64];
    if (resolve_session(s, session, id, sizeof id) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(
            s->db,
            "WITH RECURSIVE p(seq) AS (SELECT head_seq FROM pic_session 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)"
            " SELECT e.seq, e.kind, CASE e.kind"
            "  WHEN 'user' THEN e.body"
            "  WHEN 'tool_result' THEN substr(replace(e.body, char(10), ' '), 1, 100)"
            "  WHEN 'instructions' THEN 'project instructions updated'"
            "  WHEN 'compaction' THEN 'compacted ' || coalesce(e.tokens_before, 0) || ' tokens; the summary:' || char(10) || e.body"
            "  ELSE coalesce((SELECT group_concat(CASE json_extract(value,'$.type')"
            "    WHEN 'text' THEN json_extract(value,'$.text')"
            "    WHEN 'toolCall' THEN '-> ' || json_extract(value,'$.name') || ' ' ||"
            "      substr(coalesce(json_extract(value,'$.arguments.command'), json_extract(value,'$.arguments.path'), ''), 1, 80)"
            "    END, char(10)) FROM json_each(e.body) WHERE json_extract(value,'$.type') IN ('text','toolCall')), '')"
            "  END, coalesce(e.model, ''), u.status, coalesce(u.error, ''),"
            "  e.seq = (SELECT max(x.seq) FROM pic_entry x WHERE x.submission_id = e.submission_id),"
            "  coalesce((SELECT group_concat(CASE WHEN i.data IS NULL THEN '" PIC_IMAGE_REMOVED "'"
            "    ELSE '[image ' || i.width || 'x' || i.height || ']' END, ' ') FROM (SELECT i.data, i.width, i.height"
            "    FROM pic_attachment r JOIN pic_image i ON i.hash = r.image WHERE r.entry_seq = e.seq ORDER BY r.ordinal) i), '')"
            " FROM pic_entry e JOIN p ON p.seq = e.seq JOIN pic_submission u ON u.id = e.submission_id ORDER BY e.seq",
            -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
    while (sqlite3_step(q) == SQLITE_ROW) {
        const char *kind = (const char *)sqlite3_column_text(q, 1), *text = (const char *)sqlite3_column_text(q, 2);
        const char *images = (const char *)sqlite3_column_text(q, 7);
        if (strcmp(kind, "user") == 0) {
            fprintf(out, "\n[%lld] you: %s%s%s\n", (long long)sqlite3_column_int64(q, 0), text, *images ? " " : "", images);
        } else if (strcmp(kind, "tool_result") == 0) {
            fprintf(out, "[%lld]    = %s%s%s\n", (long long)sqlite3_column_int64(q, 0), text, *images ? " " : "", images);
        } else if (strcmp(kind, "compaction") == 0) {
            fprintf(out, "[%lld] (%s)\n", (long long)sqlite3_column_int64(q, 0), text);
        } else if (strcmp(kind, "instructions") == 0) {
            fprintf(out, "[%lld] (%s)\n", (long long)sqlite3_column_int64(q, 0), text);
        } else if (*text) {
            fprintf(out, "[%lld] pic (%s): %s\n", (long long)sqlite3_column_int64(q, 0),
                    (const char *)sqlite3_column_text(q, 3), text);
        }
        /* How the request ended, after its last entry, unless it was answered. */
        if (sqlite3_column_int(q, 6)) {
            const char *status = (const char *)sqlite3_column_text(q, 4), *error = (const char *)sqlite3_column_text(q, 5);
            if (strcmp(status, "admitted") == 0) {
                fputs("       (request still running, or waiting for pic run)\n", out);
            } else if (strcmp(status, "failed") == 0) {
                fprintf(out, strcmp(error, "cancelled") == 0 ? "       (request cancelled)\n" : "       (request failed: %s)\n",
                        error);
            }
        }
    }
    sqlite3_finalize(q);
    return 0;
}

/* pic compact: the conversation is compacted before its next request,
 * with INSTRUCTIONS (may be NULL) as the summary's additional focus. */
int pic_compact_request(pic_store *s, const char *session, const char *instructions, char *out, size_t cap) {
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (resolve_session(s, session, out, cap) != 0 ||
        run_stmt(s, "UPDATE pic_session SET compact_requested = ? WHERE id = ?", "tt", instructions ? instructions : "",
                 out) != 0 ||
        pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    return 0;
}

/* pic export: finished conversation entries after SINCE as JSON lines, for
 * ctx and other readers. The entry number is the cursor: export stops before
 * the first entry of any unfinished request, so a reader that keeps the last
 * number it saw never skips or repeats one. Thinking is left out. */
int pic_export(pic_store *s, const char *workspace, sqlite3_int64 since, FILE *out) {
    sqlite3_stmt *q = NULL;
    int step;
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT json_patch('{}', json_object('conversation', u.session_id, 'seq', e.seq, 'parent', e.parent_seq, 'request', u.request_key,"
            "  'role', CASE e.kind WHEN 'answer' THEN 'assistant' WHEN 'tool_result' THEN 'tool' ELSE e.kind END,"
            "  'time', strftime('%Y-%m-%dT%H:%M:%fZ', e.created_ms / 1000.0, 'unixepoch'),"
            "  'workspace', ?2, 'model', CASE WHEN e.model IS NOT NULL THEN e.provider || '/' || e.model END,"
            "  'text', CASE WHEN e.kind IN ('assistant','answer') THEN (SELECT group_concat(json_extract(value,'$.text'), char(10))"
            "    FROM json_each(e.body) WHERE json_extract(value,'$.type') = 'text') ELSE e.body END,"
            "  'tool_calls', json(CASE WHEN e.kind IN ('assistant','answer') THEN (SELECT json(json_group_array(json_object('id',"
            "    json_extract(value,'$.id'), 'name', json_extract(value,'$.name'), 'arguments', json(json_extract(value,'$.arguments')))))"
            "    FROM json_each(e.body) WHERE json_extract(value,'$.type') = 'toolCall' HAVING count(*) > 0) END),"
            "  'tool', f.tool, 'call_id', f.call_id, 'is_error', CASE WHEN f.id IS NOT NULL THEN json(iif(f.is_error,'true','false')) END,"
            "  'final', CASE WHEN e.kind = 'answer' THEN json('true') END))"
            " FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id LEFT JOIN pic_effect f ON f.id = e.effect_id"
            " WHERE e.seq > ?1 AND e.seq < coalesce((SELECT min(x.seq) FROM pic_entry x JOIN pic_submission y"
            "   ON y.id = x.submission_id WHERE y.status = 'admitted'), 9223372036854775807)"
            " ORDER BY e.seq",
            -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, since);
    sqlite3_bind_text(q, 2, workspace, -1, SQLITE_STATIC);
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        fprintf(out, "%s\n", (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return step == SQLITE_DONE ? 0 : sql_fail(s);
}

int pic_session_resolve(pic_store *s, const char *session, char *out, size_t cap) {
    return resolve_session(s, session, out, cap);
}

/* pic sessions --json: one object per conversation, most recent first. */
int pic_sessions_json(pic_store *s, FILE *out) {
    sqlite3_stmt *q = NULL;
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT json_object('id', s.id, 'name', s.name, 'updatedMs', s.updated_ms, 'createdMs', s.created_ms,"
            " 'requests', (SELECT count(*) FROM pic_submission u WHERE u.session_id = s.id),"
            " 'running', json(iif(EXISTS (SELECT 1 FROM pic_submission u WHERE u.session_id = s.id AND u.status = 'admitted'),"
            "   'true', 'false')),"
            " 'first', (SELECT u.content FROM pic_submission u WHERE u.session_id = s.id ORDER BY u.id LIMIT 1),"
            " 'forkedFrom', s.forked_from,"
            " 'cost', json((SELECT json_object('input', coalesce(sum(json_extract(g.usage,'$.pic_cost.input')), 0),"
            "   'output', coalesce(sum(json_extract(g.usage,'$.pic_cost.output')), 0),"
            "   'cacheRead', coalesce(sum(json_extract(g.usage,'$.pic_cost.cacheRead')), 0),"
            "   'cacheWrite', coalesce(sum(json_extract(g.usage,'$.pic_cost.cacheWrite')), 0),"
            "   'total', coalesce(sum(json_extract(g.usage,'$.pic_cost.total')), 0))"
            "   FROM pic_generation g JOIN pic_submission u ON u.id = g.submission_id"
            "   WHERE u.session_id = s.id AND g.state = 'done' AND json_valid(g.usage))))"
            " FROM pic_session s ORDER BY s.updated_ms DESC, s.rowid DESC",
            -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    while (sqlite3_step(q) == SQLITE_ROW) {
        fprintf(out, "%s\n", (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return 0;
}

/* pic log --json: the conversation's path, one object per entry, for a
 * client to show a resumed conversation. Thinking is left out. */
int pic_session_log_json(pic_store *s, const char *session, FILE *out) {
    sqlite3_stmt *q = NULL;
    char id[64];
    if (resolve_session(s, session, id, sizeof id) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(
            s->db,
            "WITH RECURSIVE p(seq) AS (SELECT head_seq FROM pic_session 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)"
            " SELECT json_patch('{}', json_object('seq', e.seq, 'kind', e.kind, 'request', u.request_key,"
            "  'status', CASE WHEN e.seq = (SELECT max(x.seq) FROM pic_entry x WHERE x.submission_id = e.submission_id)"
            "    THEN u.status END, 'error', CASE WHEN u.status = 'failed' THEN u.error END,"
            "  'model', CASE WHEN e.model IS NOT NULL THEN e.provider || '/' || e.model END,"
            "  'text', CASE WHEN e.kind IN ('assistant','answer') THEN (SELECT group_concat(json_extract(value,'$.text'), char(10))"
            "    FROM json_each(e.body) WHERE json_extract(value,'$.type') = 'text') ELSE e.body END,"
            "  'toolCalls', json(CASE WHEN e.kind IN ('assistant','answer') THEN (SELECT json(json_group_array(json_object("
            "    'id', json_extract(value,'$.id'), 'name', json_extract(value,'$.name'),"
            "    'arguments', json(json_extract(value,'$.arguments'))))) FROM json_each(e.body)"
            "    WHERE json_extract(value,'$.type') = 'toolCall' HAVING count(*) > 0) END),"
            "  'tool', f.tool, 'callId', f.call_id,"
            "  'isError', CASE WHEN f.id IS NOT NULL THEN json(iif(f.is_error,'true','false')) END,"
            "  'tokensBefore', e.tokens_before))"
            " FROM pic_entry e JOIN p ON p.seq = e.seq JOIN pic_submission u ON u.id = e.submission_id"
            " LEFT JOIN pic_effect f ON f.id = e.effect_id ORDER BY e.seq",
            -1, &q, NULL) != SQLITE_OK) {
        return sql_fail(s);
    }
    sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
    while (sqlite3_step(q) == SQLITE_ROW) {
        fprintf(out, "%s\n", (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return 0;
}