/* 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. The
* calls of one reply run at the same time (toolpar.h) unless toolExecution
* is "sequential"; their results reach the transcript in call order. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "cred.h"
#include "hooks.h"
#include "inbox.h"
#include "libfossil.h"
#include "net.h"
#include "perm.h"
#include "pic.h"
#include "procs.h"
#include "platform.h"
#include "policy.h"
#include "toolpar.h"
#include "toolreg.h"
#include "userdb.h"
#include "wake.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: the tool_result entries of settled calls, in call
* order. A call's entry waits while an earlier call of its turn is unsettled,
* so calls that finish out of order still reach the model in the order it
* made them (Pi's message order). EFFECT: the turn of that call alone (its
* calls by the effect index, their results by pic_entry_effect), as each
* call settles; 0: every turn, for recovery and cancel. */
#define FLUSH_SQL(where) \
"INSERT INTO pic_entry(submission_id,kind,body,effect_id)" \
" SELECT a.submission_id,'tool_result',f.result,f.id FROM pic_effect f JOIN pic_entry a ON a.seq=f.entry_seq" \
" WHERE " where " f.state IN ('done','unknown','skipped')" \
" AND NOT EXISTS (SELECT 1 FROM pic_entry r WHERE r.effect_id=f.id AND r.kind='tool_result')" \
" AND NOT EXISTS (SELECT 1 FROM pic_effect g WHERE g.entry_seq=f.entry_seq AND g.ordinal<f.ordinal" \
" AND g.state IN ('intent','started'))" \
" ORDER BY f.entry_seq, f.ordinal"
static int flush_results(pic_store *s, sqlite3_int64 effect) {
return effect ? run_stmt(s, FLUSH_SQL("f.entry_seq = (SELECT entry_seq FROM pic_effect WHERE id = ?1) AND"), "i", effect)
: pic_exec(s, FLUSH_SQL(""));
}
/* 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, const char *new_id, 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(coalesce(?1, 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);
}
if (new_id) {
sqlite3_bind_text(q, 1, new_id, -1, SQLITE_STATIC);
}
} else if (strcmp(session, "latest") == 0) {
if (sqlite3_prepare_v2(s->db, "SELECT s.id FROM pic_session s WHERE " PIC_LISTED_SQL("s") " ORDER BY s.updated_ms DESC, s.rowid DESC LIMIT 1", -1, &q,
NULL) != SQLITE_OK) {
return sql_fail(s);
}
} else {
if (sqlite3_prepare_v2(s->db, "SELECT s.id FROM pic_session s WHERE (s.id = ?1 OR s.id LIKE ?1 || '%') AND NOT " PIC_PURGED_SQL("s") " 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 && pic_session_stamp(s, out, NULL) != 0) {
return -1;
}
if (session && strcmp(session, "latest") != 0) {
int deleted = 0;
if (sqlite3_prepare_v2(s->db, "SELECT NOT " PIC_LISTED_SQL("s") " FROM pic_session s WHERE s.id = ?", -1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_text(q, 1, out, -1, SQLITE_STATIC);
deleted = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
sqlite3_finalize(q);
if (deleted) {
(void)snprintf(s->err, sizeof s->err, "conversation %s is deleted (pic sessions restore %s brings it back)", out, out);
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;
}
/* Before the transaction that advances SESSION ("latest", an id or a
* prefix): its lease. A name that resolves to nothing is left for the
* transaction to refuse in its own words. 0, or -1 with s->err. */
static int resolve_session(pic_store *s, const char *session, char *out, size_t cap);
static int lease_named(pic_store *s, const char *session) {
char id[64], saved[PIC_ERR_CAP];
(void)snprintf(saved, sizeof saved, "%s", s->err);
if (!session || resolve_session(s, session, id, sizeof id) != 0) {
(void)snprintf(s->err, sizeof s->err, "%s", saved);
return 0;
}
return pic_lease(s, id, PIC_LEASE_WAIT_MS) == 0 ? 0 : -1;
}
/* 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) {
return pic_submit_hooked(s, request_key, content, images, nimages, session, NULL, 0, duplicate, session_out, session_cap);
}
/* A conversation id as the journal makes them (8 lower-case hex digits), or
* one a person chose with --session-id: Pi's rule, up to 63 bytes. */
static int good_id(const char *id) {
size_t n = strlen(id);
return n >= 1 && n <= 63 && isalnum((unsigned char)id[0]) && isalnum((unsigned char)id[n - 1]) &&
strspn(id, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-") == n;
}
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) {
sqlite3_stmt *q = NULL;
if (new_id && (session || !good_id(new_id))) {
(void)snprintf(s->err, sizeof s->err, "a conversation id is letters, digits, . _ - (at most 63), starting and ending with a letter or digit");
return -1;
}
char chosen[64] = "";
sqlite3_int64 known = 0;
*duplicate = 0;
/* A new request advances its conversation; a retry of an admitted one
* (found again below) changes nothing and needs no lease. */
if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_submission WHERE request_key=?", -1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_text(q, 1, request_key, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
known = sqlite3_column_int64(q, 0);
}
sqlite3_finalize(q);
q = NULL;
if (!known && lease_named(s, session) != 0) {
return -1;
}
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, new_id, chosen, sizeof chosen) != 0 ||
/* a conversation made here is nobody else's yet; one named was leased above */
pic_lease(s, chosen, 0) != 0 ||
/* a new message brings an archived conversation back to the lists */
pic_archive_wake(s, chosen) != 0 ||
/* the conversation's permission mode: the flag's, or a new one's default */
pic_perm_admit(s, chosen) != 0 ||
run_stmt(s,
"INSERT INTO pic_submission(request_key,content,status,session_id,trial,max_requests,model,thinking)"
" VALUES(?,?,'admitted',?,?,nullif(?,0),?,?)",
"ttttitt", request_key, content, chosen, s->trial, (sqlite3_int64)s->max_requests, s->model,
s->thinking) != 0 ||
/* an UPDATE leaves the submission's rowid the last inserted */
pic_hooks_claim(s, prompt_hooks, sqlite3_last_insert_rowid(s->db), 0) != 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;
}
sqlite3_int64 pic_next_entry_seq(pic_store *s) {
sqlite3_int64 n = 0;
return query_int(s, "SELECT coalesce(max(seq), 0) + 1 FROM pic_entry", 0, &n) == 0 ? n : 0;
}
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) {
sqlite3_stmt *q = NULL;
char chosen[64] = "", key[96], *text = pic_bash_text(m);
sqlite3_int64 sub, seq, want;
int64_t now = pic_platform_get()->wall_ns();
int rc;
if (!text) {
return -1;
}
(void)snprintf(key, sizeof key, "bash-%lld-%09ld-%ld", (long long)(now / 1000000000), (long)(now % 1000000000),
(long)getpid());
if (lease_named(s, session) != 0 || pic_begin(s) != 0) {
free(text);
return -1;
}
/* The number is certain only now, with the write lock held: another
* process may have journaled an entry since the output was named. */
want = pic_next_entry_seq(s);
if (named && *named && want && *named != want) {
*named = want;
free(text);
pic_rollback(s);
return 1;
}
if (choose_session(s, session, NULL, chosen, sizeof chosen) != 0 || pic_lease(s, chosen, 0) != 0 ||
run_stmt(s, "INSERT INTO pic_submission(request_key,content,status,session_id) VALUES(?,?,'answered',?)", "ttt", key,
m->command, chosen) != 0) {
free(text);
pic_rollback(s);
return -1;
}
sub = sqlite3_last_insert_rowid(s->db);
rc = append_entry(s, sub, "user", text);
free(text);
seq = sqlite3_last_insert_rowid(s->db);
if (rc == 0 && seq != want && want) { /* the output was named for another entry */
(void)snprintf(s->err, sizeof s->err, "internal: bash entry %lld, expected %lld", (long long)seq, (long long)want);
rc = -1;
}
if (rc == 0) {
if (sqlite3_prepare_v2(s->db,
"INSERT INTO pic_bash(entry_seq, command, output, exit_code, cancelled, truncated, exclude,"
" full_sz, full) VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, CASE WHEN ?8 IS NULL THEN NULL"
" ELSE sqlar_compress(?9) END)",
-1, &q, NULL) != SQLITE_OK) {
rc = sql_fail(s);
} else {
sqlite3_bind_int64(q, 1, seq);
sqlite3_bind_text(q, 2, m->command, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 3, m->output, -1, SQLITE_STATIC);
if (m->has_exit) {
sqlite3_bind_int(q, 4, m->exit_code);
} else {
sqlite3_bind_null(q, 4);
}
sqlite3_bind_int(q, 5, m->cancelled != 0);
sqlite3_bind_int(q, 6, m->truncated != 0);
sqlite3_bind_int(q, 7, m->exclude != 0);
if (m->full && m->full_len) {
sqlite3_bind_int64(q, 8, (sqlite3_int64)m->full_len);
sqlite3_bind_blob64(q, 9, m->full, (sqlite3_uint64)m->full_len, SQLITE_STATIC);
} else {
sqlite3_bind_null(q, 8);
sqlite3_bind_null(q, 9);
}
rc = sqlite3_step(q) == SQLITE_DONE ? 0 : sql_fail(s);
sqlite3_finalize(q);
}
}
if (rc != 0 || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
if (session_out && cap) {
(void)snprintf(session_out, cap, "%s", chosen);
}
if (seq_out) {
*seq_out = seq;
}
return 0;
}
/* SQL: entry E (a pic_entry alias) ends a turn, so a conversation can go on
* from it: no tool call of its request still waits for a result at it, and
* it is not a prompt its request's reply follows. A user entry that is the
* last of its finished request is one: a prompt cancelled before its reply,
* a "!" command (Pi's /fork and /tree offer those points). */
#define ENDS_TURN_SQL(e) \
"((" e ".kind != 'user' OR (NOT EXISTS (SELECT 1 FROM pic_entry n WHERE n.submission_id = " e ".submission_id" \
" AND n.seq > " e ".seq) AND (SELECT status FROM pic_submission WHERE id = " e ".submission_id) != 'admitted'))" \
" AND NOT EXISTS (SELECT 1 FROM pic_effect f JOIN pic_entry a ON a.seq = f.entry_seq" \
" WHERE a.submission_id = " e ".submission_id AND a.seq <= " e ".seq" \
" AND NOT EXISTS (SELECT 1 FROM pic_entry r WHERE r.effect_id = f.id AND r.seq <= " e ".seq)))"
/* Inside a transaction: a new session forked from session SOURCE, its head
* AT (0: SOURCE's head), its id in OUT. */
static int fork_session(pic_store *s, const char *source, sqlite3_int64 at, char *out, size_t cap) {
sqlite3_stmt *q = NULL;
int rc = 0;
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) {
return sql_fail(s);
}
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);
return rc == 0 && pic_session_stamp(s, out, NULL) == 0 ? pic_perm_copy(s, source, out) : rc ? rc : -1;
}
/* 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.
* Inside a caller's transaction, it is part of that transaction. */
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, own = sqlite3_get_autocommit(s->db);
if (own && pic_begin(s) != 0) {
return -1;
}
if (sqlite3_prepare_v2(s->db, "SELECT s.id FROM pic_session s WHERE (s.id = ?1 OR s.id LIKE ?1 || '%') AND NOT " PIC_PURGED_SQL("s") " LIMIT 2", -1, &q, NULL) !=
SQLITE_OK) {
rc = sql_fail(s);
if (own) {
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]) {
if (own) {
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. */
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 EXISTS (SELECT 1 FROM pic_entry x WHERE x.seq = ?2 AND " ENDS_TURN_SQL("x") ")",
-1, &v, NULL) != SQLITE_OK) {
rc = sql_fail(s);
if (own) {
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 " ENDS_TURN_SQL("x") " 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);
}
if (own) {
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 (fork_session(s, source, at, out, cap) != 0 || (own && pic_commit(s) != 0)) {
if (own) {
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.
* Results that were waiting for an earlier call of their turn follow it into
* the transcript once it is settled. All of it for one conversation, by the
* process that has just taken its lease: nobody else is at that work now.
* ("" stands for hook runs of no conversation.) */
#define OF_SESSION(submission) "(SELECT u.session_id FROM pic_submission u WHERE u.id = " submission ") = ?1"
#define EFFECT_SESSION OF_SESSION("(SELECT e.submission_id FROM pic_entry e WHERE e.seq = pic_effect.entry_seq)")
static int settle_session(pic_store *s, const char *session);
/* A request an inbox abort was delivered to (inbox.c): its owner died before
* the cancel, which the abort's row stands for. Only an abort has a target. */
#define ABORTED_SQL \
"SELECT u.id FROM pic_submission u JOIN pic_inbox i ON i.target = u.id AND i.state = 'delivered'" \
" WHERE u.session_id = ?1 AND u.status = 'admitted'"
int pic_recover_session(pic_store *s, const char *session) {
sqlite3_stmt *q = NULL;
int any = 0, nested = !sqlite3_get_autocommit(s->db);
/* Nothing under way, as for nearly every lease taken: no write at all. */
if (sqlite3_prepare_v2(s->db,
"SELECT EXISTS (SELECT 1 FROM pic_effect WHERE state='started' AND " EFFECT_SESSION ")"
" OR EXISTS (SELECT 1 FROM pic_generation WHERE state='started' AND " OF_SESSION("submission_id") ")"
" OR EXISTS (SELECT 1 FROM pic_hook_run WHERE state='started' AND coalesce(session_id, '') = ?1)"
" OR EXISTS (SELECT 1 FROM pic_verdict WHERE state='started' AND " OF_SESSION("submission_id") ")"
" OR EXISTS (" ABORTED_SQL ")",
-1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
if (sqlite3_step(q) != SQLITE_ROW) { /* an error is never "nothing to settle" */
sqlite3_finalize(q);
return sql_fail(s);
}
any = sqlite3_column_int(q, 0);
sqlite3_finalize(q);
if (!any) {
return 0;
}
/* Inside a caller's transaction (a lease taken as a request is
* admitted), it is settled with that transaction. */
if (nested) {
return settle_session(s, session);
}
if (pic_begin(s) != 0) {
return -1;
}
if (settle_session(s, session) != 0 || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
return 0;
}
static int cancel_submission(pic_store *s, sqlite3_int64 submission);
/* Inside a transaction. */
/* The inner calls of a calling effect left started: finished ones stand, a started one's outcome
* is unknown, one not started never runs; and the calling effect's own result lists them. */
#define NESTED_OF_STARTED "parent_id IN (SELECT id FROM pic_effect WHERE state='started' AND " EFFECT_SESSION ")"
#define NESTED_LISTING \
"coalesce((SELECT char(10) || char(10) || 'Its inner calls:' || group_concat(char(10) || n.position || '. '" \
" || n.tool || ': ' || CASE WHEN n.state = 'done' AND n.is_error THEN 'finished with an error'" \
" WHEN n.state = 'done' THEN 'finished' WHEN n.state = 'unknown' THEN 'outcome unknown, not re-run'" \
" ELSE 'not run' END, '' ORDER BY n.position) FROM pic_nested_effect n WHERE n.parent_id = pic_effect.id), '')"
static int settle_session(pic_store *s, const char *session) {
sqlite3_int64 aborted = 0;
if (run_stmt(s,
"UPDATE pic_nested_effect SET state='unknown', is_error=1, result="
"'error: outcome unknown (interrupted before its result was recorded); not re-run'"
" WHERE state='started' AND " NESTED_OF_STARTED,
"t", session) != 0 ||
run_stmt(s,
"UPDATE pic_nested_effect SET state='skipped', is_error=1, result='error: not run: its caller was interrupted'"
" WHERE state='intent' AND " NESTED_OF_STARTED,
"t", session) != 0 ||
run_stmt(s, "UPDATE pic_effect SET state='intent' WHERE state='started' AND replay_safe=1 AND " EFFECT_SESSION, "t",
session) != 0 ||
run_stmt(s,
"UPDATE pic_hook_run SET state='interrupted', error='interrupted before its outcome was recorded; not run again'"
" WHERE state='started' AND coalesce(session_id, '') = ?1",
"t", session) != 0 ||
run_stmt(s,
"UPDATE pic_verdict SET state='unknown', error='interrupted before its outcome was recorded; not run again'"
" WHERE state='started' AND " OF_SESSION("submission_id"),
"t", session) != 0 ||
run_stmt(s,
"UPDATE pic_generation SET state='failed', error='interrupted before the reply was recorded'"
" WHERE state='started' AND " OF_SESSION("submission_id"),
"t", session) != 0 ||
run_stmt(s,
"UPDATE pic_effect SET state='unknown', is_error=1, result="
"'error: outcome unknown (interrupted before its result was recorded); not re-run' || " NESTED_LISTING
" WHERE state='started' AND replay_safe=0 AND " EFFECT_SESSION,
"t", session) != 0 ||
run_stmt(s, FLUSH_SQL("a.submission_id IN (SELECT id FROM pic_submission WHERE session_id = ?1) AND"), "t", session) !=
0) {
return -1;
}
/* An abort delivered before its owner could cancel: cancelled now, as
* its owner would have (and as Ctrl-C's is, when it gets that far). */
{
sqlite3_stmt *q = NULL;
int step;
if (sqlite3_prepare_v2(s->db, ABORTED_SQL, -1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
step = sqlite3_step(q);
aborted = step == SQLITE_ROW ? sqlite3_column_int64(q, 0) : 0;
sqlite3_finalize(q);
if (step != SQLITE_ROW && step != SQLITE_DONE) {
return sql_fail(s);
}
}
return aborted ? cancel_submission(s, aborted) : 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;
/* write and edit: the file they change (pic_tool_path_key), whose
* pre-image commits with "started" and post-image with the result. */
const char *path;
} started_ctx;
/* The file a write or edit call changes, or NULL (malloc'd). */
static char *changed_file(const char *workspace, const char *tool, const char *path) {
return path && (strcmp(tool, "write") == 0 || strcmp(tool, "edit") == 0) ? pic_tool_path_key(workspace, path) : NULL;
}
static int commit_started(void *p, const char *plan, size_t plan_len) {
started_ctx *c = p;
sqlite3_stmt *q = NULL;
pic_file_state pre;
char *made = NULL;
int step, before = 0;
/* The file as found, read before the transaction; a replay keeps the
* pre-image its first attempt recorded. */
memset(&pre, 0, sizeof pre);
if (c->path) {
if ((before = pic_filelog_recorded(c->s, c->effect)) < 0) {
return -1;
}
before = !before;
if (before) {
pic_file_state_read(c->path, pic_filelog_cap(), &pre);
made = pic_filelog_new_dirs(c->path);
}
}
if (pic_begin(c->s) != 0) {
pic_file_state_free(&pre);
free(made);
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 ||
(before && pic_filelog_before(c->s, c->effect, c->path, &pre, made) != 0) || pic_commit(c->s) != 0) {
if (step != SQLITE_DONE) {
sql_fail(c->s);
}
pic_rollback(c->s);
pic_file_state_free(&pre);
free(made);
return -1;
}
pic_file_state_free(&pre);
free(made);
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;
int bash = strncmp(name, "pic:bash/", 9) == 0, nested = strncmp(name, "pic:nested/", 11) == 0,
skip = bash ? 9 : 11;
if ((!bash && !nested && strncmp(name, "pic:output/", 11) != 0) || name[skip] < '0' || name[skip] > '9') {
return NULL;
}
id = strtoll(name + skip, &end, 10);
if (nested) {
id = -id; /* an inner call's whole output, under minus its row's id */
}
if (*end || sqlite3_prepare_v2(c->s->db,
bash ? "SELECT sqlar_uncompress(full, full_sz) FROM pic_bash WHERE entry_seq=?"
: "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;
/* The tools that results on SUBMISSION's branch have revealed (pic_tool_reveal), by the name's
* first reveal: its entries are the branch's, from the conversation's head up. ?1 is the
* submission. */
#define REVEALED_SQL \
"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)" \
" SELECT r.name FROM pic_tool_reveal r JOIN pic_effect f ON f.id = r.effect_id JOIN p ON p.seq = f.entry_seq" \
" GROUP BY r.name ORDER BY min(r.effect_id), min(r.ordinal)"
typedef struct {
pic_store *s;
sqlite3_int64 submission;
} declared_ctx;
/* pic_tool_hooks.declared: the revealed names, one per line (malloc'd); NULL when there are none. */
static char *declared_names(void *p) {
const declared_ctx *c = p;
sqlite3_stmt *q = NULL;
char *out = NULL;
size_t len = 0;
if (sqlite3_prepare_v2(c->s->db, REVEALED_SQL, -1, &q, NULL) != SQLITE_OK) {
return NULL; /* a journal opened narrowly has no such table */
}
sqlite3_bind_int64(q, 1, c->submission);
while (sqlite3_step(q) == SQLITE_ROW) {
const char *name = (const char *)sqlite3_column_text(q, 0);
size_t n = name ? strlen(name) : 0;
char *grown = n ? realloc(out, len + n + 2) : out;
if (!grown) {
break;
}
out = grown;
memcpy(out + len, name, n);
out[len + n] = '\n';
out[len + n + 1] = '\0';
len += n + 1;
}
sqlite3_finalize(q);
return out;
}
/* Inside the result's transaction: journals the tools a call revealed, one per line of NAMES. */
static int store_reveals(pic_store *s, sqlite3_int64 effect, const char *names) {
int ordinal = 0;
while (*names) {
size_t n = strcspn(names, "\n");
char name[256];
if (n > 0 && n < sizeof name) {
(void)snprintf(name, sizeof name, "%.*s", (int)n, names);
if (run_stmt(s, "INSERT INTO pic_tool_reveal(effect_id, ordinal, name) VALUES(?,?,?)", "iit", effect,
(sqlite3_int64)ordinal++, name) != 0) {
return -1;
}
}
names += n + (names[n] ? 1 : 0);
}
return 0;
}
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 void stale_edit_note(pic_store *s, sqlite3_int64 submission, const char *workspace, const char *tool, const char *path,
char **result, int is_error);
/* What a calling tool's inner calls run under (nested_call, below). */
typedef struct {
pic_store *s;
const char *workspace;
int exec_seconds;
sqlite3_int64 submission, parent;
const char *parent_call, *parent_tool;
} nest_ctx;
static int nested_call(void *ctx, pic_nested_call *calls, size_t n);
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) {
char *changed = changed_file(workspace, tool, args->path);
started_ctx ctx = {s, effect, 0, changed};
pic_file_state post;
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};
declared_ctx dctx = {s, submission};
pic_tool_output revealed = {NULL, 0};
nest_ctx nctx = {s, workspace, exec_seconds, submission, effect, call_id ? call_id : "", tool};
pic_tool_hooks hooks = {.exec_seconds = exec_seconds,
.started = commit_started,
.ctx = &ctx,
.plan = plan,
.plan_len = plan_len,
.output_name = name,
.output = &output,
.fetch = fetch_output,
.image = &image,
.partial = emit_partial,
.partial_ctx = &pctx,
.journal = sqlite3_db_filename(s->db, "main"),
.effect = (long long)effect,
.input = input,
.declared = declared_names,
.declared_ctx = &dctx,
.reveal = &revealed,
.call = nested_call,
.call_ctx = &nctx};
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_toolset_run(workspace, tool, args, &hooks, &is_error);
memset(&post, 0, sizeof post);
if (result && changed) {
pic_file_state_read(changed, -1, &post); /* outside the result's transaction */
}
ctx.path = NULL;
if (!result) {
free(changed);
free(output.data);
free(image.data);
free(revealed.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");
stale_edit_note(s, submission, workspace, tool, args->path, &result, is_error);
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) ||
(revealed.data && !is_error && store_reveals(s, effect, revealed.data) != 0) || flush_results(s, effect) != 0 ||
(changed && pic_filelog_after(s, effect, &post) != 0) || pic_commit(s) != 0;
free(changed);
free(revealed.data);
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, entry;
char *tool, *path, *content, *command, *plan, *call_id, *pattern, *glob;
size_t plan_len, nedits;
char **old_text, **new_text;
pic_tool_args args;
} loop_pending;
static void pending_free(loop_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->pattern);
free(p->glob);
free(p->plan);
}
static int load_edits(pic_store *s, const char *input, loop_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);
}
/* The session a submission is in, into out (64 bytes; "" when none). */
static void session_id_of(pic_store *s, sqlite3_int64 submission, char out[64]) {
sqlite3_stmt *q = NULL;
out[0] = '\0';
if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, submission);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
(void)snprintf(out, 64, "%s", (const char *)sqlite3_column_text(q, 0));
}
}
sqlite3_finalize(q);
}
/* A PreToolUse hook that allows a call may also rewrite it: Claude Code's
* hookSpecificOutput.updatedInput. The rewrite is merged into the journaled
* call, so a resumed run uses the rewritten input and not the original; a
* file_path the hook sent (Claude Code's name for it) becomes pic's path.
* Returns 1 when the input changed, 0 when it did not, -1 on error. */
static int apply_updated_input(pic_store *s, const pic_hook_fire *f, sqlite3_int64 effect, int nested) {
const char *patch = NULL;
if (f->blocked) {
return 0; /* the call is not run; there is nothing to rewrite */
}
for (size_t i = 0; i < f->n; i++) {
if (f->runs[i].updated_input && f->runs[i].outcome && strcmp(f->runs[i].outcome, "allow") == 0) {
patch = f->runs[i].updated_input; /* the last allowing hook decides, as run order says */
}
}
if (!patch) {
return 0;
}
if (pic_begin(s) != 0) {
return -1;
}
#define UPDATED_INPUT(table) \
"UPDATE " table " SET input = json_patch(" \
" CASE WHEN json_type(input,'$.path') IS NULL AND json_type(?1,'$.file_path') = 'text'" \
" THEN json_set(input,'$.path',json_extract(?1,'$.file_path')) ELSE input END," \
" json_remove(?1,'$.file_path')) WHERE id = ?2 AND json_valid(input)"
if (run_stmt(s, nested ? UPDATED_INPUT("pic_nested_effect") : UPDATED_INPUT("pic_effect"), "ti", patch, effect) != 0 ||
sqlite3_changes(s->db) != 1 || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
pic_fault("after-hook-rewrite");
return 1;
}
/* PreToolUse for a call about to run. Each hook run is journaled before it
* starts, and the decision is read back from the journal, so a recovery
* never asks the hooks again: a run a crash interrupted leaves the call
* undecided, and an undecided call does not run. A deny commits with the
* call's skipped result. 0: run it; 1: not run (journaled, or Ctrl-C);
* 2: run it with the input a hook rewrote; -1 on error. */
/* EXTRA (malloc'd, taken) with the calling call's id as parent_tool_use_id (malloc'd). */
static char *with_parent(pic_store *s, char *extra, const char *parent_call) {
sqlite3_stmt *q = NULL;
char *out = NULL;
if (extra && sqlite3_prepare_v2(s->db, "SELECT json_set(?1, '$.parent_tool_use_id', ?2)", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, extra, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, parent_call, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
out = dup_col(q, 0);
}
}
sqlite3_finalize(q);
free(extra);
return out;
}
/* A call to gate: a call of the model's (its pic_effect row), or one a tool made (its
* pic_nested_effect row, journaled in pic_hook_run as minus its id, PARENT_CALL its caller's). */
typedef struct {
sqlite3_int64 row;
const char *tool, *call_id, *summary, *parent_call;
} gate_call;
static int tool_gate(pic_store *s, sqlite3_int64 submission, const gate_call *g, const char *input);
static int pre_tool_gate(pic_store *s, sqlite3_int64 submission, const loop_pending *p, const char *input) {
gate_call g = {p->effect, p->tool, p->call_id ? p->call_id : "", p->command ? p->command : p->path, NULL};
return tool_gate(s, submission, &g, input);
}
static int tool_gate(pic_store *s, sqlite3_int64 submission, const gate_call *g, const char *input) {
sqlite3_int64 rows = 0, interrupted = 0, asks = 0, allows = 0, ref = g->parent_call ? -g->row : g->row;
char *reason = NULL, *ask_reason = NULL;
int rc = 0, rewritten = 0;
if (query_int(s, "SELECT count(*) FROM pic_hook_run WHERE event = 'PreToolUse' AND ref = ?", ref, &rows) != 0) {
return -1;
}
if (!rows && pic_hooks_has(s->hooks, "PreToolUse")) {
pic_hook_fire f;
const char *names[4];
char *extra = pic_hooks_tool_extra(s, g->tool, input, g->call_id, NULL, 0);
if (g->parent_call) {
extra = with_parent(s, extra, g->parent_call);
}
memset(&f, 0, sizeof f);
f.event = "PreToolUse";
f.submission = submission;
f.ref = ref;
session_id_of(s, submission, f.session);
pic_hooks_tool_names(g->tool, names);
rc = extra ? pic_hook_fire_run(s, &f, names, extra) : -1;
free(extra);
if (rc == 0) {
int w = apply_updated_input(s, &f, g->row, g->parent_call != NULL);
if (w < 0) {
rc = -1;
} else {
rewritten = w;
}
}
pic_hook_fire_free(&f);
if (rc != 0) {
if (!s->err[0]) {
(void)snprintf(s->err, sizeof s->err, "out of memory");
}
return -1;
}
}
if (pic_interrupted) {
return 1; /* pic_run cancels the request, this call with it */
}
{
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db,
"SELECT count(*) FILTER (WHERE state != 'done') + (count(*) > 0 AND count(*) FILTER"
" (WHERE command IS NULL) = 0), group_concat(CASE WHEN outcome = 'deny' THEN reason END, char(10)),"
" count(*) FILTER (WHERE outcome = 'ask'), count(*) FILTER (WHERE outcome = 'allow'),"
" group_concat(CASE WHEN outcome = 'ask' THEN reason END, char(10))"
" FROM (SELECT * FROM pic_hook_run WHERE event = 'PreToolUse' AND ref = ? ORDER BY id)",
-1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_int64(q, 1, ref);
if (sqlite3_step(q) == SQLITE_ROW) {
interrupted = sqlite3_column_int64(q, 0);
reason = dup_col(q, 1);
asks = sqlite3_column_int64(q, 2);
allows = sqlite3_column_int64(q, 3);
ask_reason = dup_col(q, 4);
}
sqlite3_finalize(q);
}
if (interrupted) {
free(reason);
reason = strdup("error: the PreToolUse hooks were interrupted before they decided; the call was not run");
}
if (!reason) { /* the conversation's permission mode, and a hook's ask (perm.h) */
char session[64] = "", key[48], *now = NULL;
sqlite3_stmt *q = NULL;
int perm;
session_id_of(s, submission, session);
(void)snprintf(key, sizeof key, g->parent_call ? "perm:n:%lld" : "perm:%lld", (long long)g->row);
/* the input as the journal holds it, after any hook's rewrite: what is asked is what runs */
if (sqlite3_prepare_v2(s->db, g->parent_call ? "SELECT input FROM pic_nested_effect WHERE id = ?" : "SELECT input FROM pic_effect WHERE id = ?",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, g->row);
if (sqlite3_step(q) == SQLITE_ROW) {
now = dup_col(q, 0);
}
}
sqlite3_finalize(q);
pic_perm_call pc = {session, submission, key, g->tool, now ? now : input, asks > 0, ask_reason, allows > 0 && asks == 0};
perm = pic_perm_gate(s, &pc, &reason);
free(now);
if (perm < 0 || (perm == 2 && !g->parent_call)) {
free(ask_reason);
return perm < 0 ? -1 : 1; /* Ctrl-C: pic_run cancels the request, this call with it */
}
if (perm == 2) { /* a tool's call: its caller reads the result, so it is recorded */
reason = strdup("interrupted: the question whether to run this call was withdrawn; it was not run");
}
}
free(ask_reason);
if (reason) {
if (pic_begin(s) != 0 ||
run_stmt(s,
g->parent_call
? "UPDATE pic_nested_effect SET state='skipped', result=?, is_error=1 WHERE id=? AND state='intent'"
: "UPDATE pic_effect SET state='skipped', result=?, is_error=1 WHERE id=? AND state='intent'",
"ti", reason, g->row) != 0 ||
sqlite3_changes(s->db) != 1 || (!g->parent_call && flush_results(s, g->row) != 0) || pic_commit(s) != 0) {
pic_rollback(s);
free(reason);
return -1;
}
if (g->parent_call) { /* its start was told when it was made */
pic_ev_nested_end(s, g->call_id, g->tool, reason, 1, g->parent_call);
} else {
pic_ev_tool_start(s, g->call_id, g->tool, input, g->summary);
pic_ev_tool_end(s, g->call_id, g->tool, reason, NULL, 1);
}
rc = 1;
}
free(reason);
pic_fault("after-hook-decision");
return rc == 0 && rewritten ? 2 : rc;
}
/* The call's input as the journal now holds it, after a PreToolUse hook
* rewrote it: the parsed fields come from that JSON again. */
static int parse_pending_input(pic_store *s, loop_pending *p, char *fresh, char **input);
static int reload_pending_input(pic_store *s, loop_pending *p, char **input) {
sqlite3_stmt *q = NULL;
char *fresh = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT input FROM pic_effect WHERE id = ?", -1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_int64(q, 1, p->effect);
if (sqlite3_step(q) == SQLITE_ROW) {
fresh = dup_col(q, 0);
}
sqlite3_finalize(q);
return fresh ? parse_pending_input(s, p, fresh, input) : -1;
}
/* P's argument fields from FRESH (malloc'd, taken), which replaces *INPUT. */
static int parse_pending_input(pic_store *s, loop_pending *p, char *fresh, char **input) {
sqlite3_stmt *q = NULL;
int rc = 0;
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->path);
free(p->content);
free(p->command);
free(p->pattern);
free(p->glob);
p->old_text = p->new_text = NULL;
p->path = p->content = p->command = p->pattern = p->glob = NULL;
p->nedits = 0;
p->args.has_offset = p->args.has_limit = p->args.has_timeout = 0;
p->args.has_context = 0;
p->args.ignore_case = p->args.literal = 0;
if (sqlite3_prepare_v2(s->db,
"SELECT CASE json_type(?1,'$.path') WHEN 'text' THEN json_extract(?1,'$.path') END,"
" CASE json_type(?1,'$.content') WHEN 'text' THEN json_extract(?1,'$.content') END,"
" CASE json_type(?1,'$.command') WHEN 'text' THEN json_extract(?1,'$.command') END,"
" json_type(?1,'$.offset') IN ('integer','real'), CAST(json_extract(?1,'$.offset') AS INTEGER),"
" json_type(?1,'$.limit') IN ('integer','real'), CAST(json_extract(?1,'$.limit') AS INTEGER),"
" json_type(?1,'$.timeout') IN ('integer','real'), CAST(json_extract(?1,'$.timeout') AS INTEGER),"
" CASE json_type(?1,'$.pattern') WHEN 'text' THEN json_extract(?1,'$.pattern') END,"
" CASE json_type(?1,'$.glob') WHEN 'text' THEN json_extract(?1,'$.glob') END,"
" json_type(?1,'$.ignoreCase')='true', json_type(?1,'$.literal')='true',"
" json_type(?1,'$.context') IN ('integer','real'), CAST(json_extract(?1,'$.context') AS INTEGER),"
" json_type(?1)='object'",
-1, &q, NULL) != SQLITE_OK) {
free(fresh);
return sql_fail(s);
}
sqlite3_bind_text(q, 1, fresh, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
p->path = dup_col(q, 0);
p->content = dup_col(q, 1);
p->command = dup_col(q, 2);
p->args.has_offset = sqlite3_column_int(q, 3);
p->args.offset = (long)sqlite3_column_int64(q, 4);
p->args.has_limit = sqlite3_column_int(q, 5);
p->args.limit = (long)sqlite3_column_int64(q, 6);
p->args.has_timeout = sqlite3_column_int(q, 7);
p->args.timeout = (long)sqlite3_column_int64(q, 8);
p->pattern = dup_col(q, 9);
p->glob = dup_col(q, 10);
p->args.ignore_case = sqlite3_column_int(q, 11);
p->args.literal = sqlite3_column_int(q, 12);
p->args.has_context = sqlite3_column_int(q, 13);
p->args.context = (long)sqlite3_column_int64(q, 14);
p->args.bad_input = sqlite3_column_int(q, 15) ? NULL : "Tool input is not a JSON object.";
}
sqlite3_finalize(q);
if (p->tool && strcmp(p->tool, "edit") == 0) {
rc = load_edits(s, fresh, p);
}
if (rc == 0) {
free(*input);
*input = fresh;
} else {
free(fresh);
}
return rc;
}
/* ---- a file another conversation changed ---------------------------------
* Conversations share the workspace and nothing merges their work. The
* journal knows who changed what: every edit and write is an effect with
* its path. PATH is stale for SUBMISSION's conversation when another one,
* while this process has been running the request, made a successful edit
* or write of the file later than this one last saw it (its latest read,
* edit or write of the file). "This conversation" is the path to its head,
* so a fork has seen what its parent saw. */
#define STALE_MARK "was changed by another pic conversation"
#define PATH_SQL \
"WITH RECURSIVE p(seq) AS (SELECT s.head_seq FROM pic_session s JOIN pic_submission u ON u.session_id = s.id" \
" WHERE u.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) "
/* Whether effect row Q (its path in column 0) is of the file KEY. */
static int same_file(const char *workspace, sqlite3_stmt *q, const char *key) {
const char *path = (const char *)sqlite3_column_text(q, 0);
char *k = path ? pic_tool_path_key(workspace, path) : NULL;
int same = k && strcmp(k, key) == 0;
free(k);
return same;
}
/* 1 with the other conversation's id in OTHER, 0, or -1. */
static int stale_file(pic_store *s, sqlite3_int64 submission, const char *workspace, const char *path, char other[64]) {
sqlite3_stmt *q = NULL;
sqlite3_int64 seen = 0;
char *key = path ? pic_tool_path_key(workspace, path) : NULL;
int stale = 0;
if (!key) {
return 0;
}
/* When this conversation last saw the file: a refused write showed it too. */
if (sqlite3_prepare_v2(s->db,
PATH_SQL "SELECT json_extract(f.input, '$.path'),"
" (SELECT max(r.seq) FROM pic_entry r WHERE r.effect_id = f.id) FROM pic_effect f"
" WHERE f.entry_seq IN p AND f.tool IN ('read','edit','write')"
" AND json_type(f.input, '$.path') = 'text'"
" AND (f.state = 'done' OR (f.state = 'skipped' AND instr(f.result, '" STALE_MARK "')))"
" ORDER BY f.id DESC",
-1, &q, NULL) != SQLITE_OK) {
free(key);
return sql_fail(s);
}
sqlite3_bind_int64(q, 1, submission);
while (!seen && sqlite3_step(q) == SQLITE_ROW) {
if (same_file(workspace, q, key)) {
seen = sqlite3_column_int64(q, 1);
}
}
sqlite3_finalize(q);
/* Only what was journaled since this process took the request up can be
* another process's doing while it ran: one pic, however many
* conversations it works one after another, never meets this. */
if (seen < (sqlite3_int64)s->run_since) {
seen = (sqlite3_int64)s->run_since;
}
if (sqlite3_prepare_v2(s->db,
PATH_SQL "SELECT json_extract(f.input, '$.path'), u.session_id FROM pic_effect f"
" JOIN pic_entry r ON r.effect_id = f.id AND r.kind = 'tool_result'"
" JOIN pic_entry a ON a.seq = f.entry_seq JOIN pic_submission u ON u.id = a.submission_id"
" WHERE f.tool IN ('edit','write') AND f.state = 'done' AND f.is_error = 0"
" AND json_type(f.input, '$.path') = 'text' AND r.seq > ?2"
" AND f.entry_seq NOT IN p ORDER BY r.seq DESC",
-1, &q, NULL) != SQLITE_OK) {
free(key);
return sql_fail(s);
}
sqlite3_bind_int64(q, 1, submission);
sqlite3_bind_int64(q, 2, seen);
while (!stale && sqlite3_step(q) == SQLITE_ROW) {
if (same_file(workspace, q, key)) {
(void)snprintf(other, 64, "%s", (const char *)sqlite3_column_text(q, 1));
stale = 1;
}
}
sqlite3_finalize(q);
free(key);
return stale;
}
static int stale_started(void *ctx, const char *plan, size_t plan_len) {
(void)ctx;
(void)plan;
(void)plan_len;
return 0;
}
/* The file as read returns it (its caps, its notices), or NULL. */
static char *stale_text(const char *workspace, const char *path) {
pic_tool_hooks hooks;
pic_tool_args args;
int is_error = 0;
char *text;
memset(&hooks, 0, sizeof hooks);
memset(&args, 0, sizeof args);
hooks.started = stale_started;
args.path = path;
text = pic_tool_run(workspace, "read", &args, &hooks, &is_error);
if (text && is_error) {
free(text);
text = NULL;
}
return text;
}
/* An edit that could not find its text, in a stale file: its error goes on
* to say whose change it met, with the file as it now is, so the agent can
* redo the edit. Anything else is left as it was. */
static void stale_edit_note(pic_store *s, sqlite3_int64 submission, const char *workspace, const char *tool, const char *path,
char **result, int is_error) {
char other[64], saved[PIC_ERR_CAP], *text, *noted;
size_t n;
if (!is_error || !path || !*result || strcmp(tool, "edit") != 0 ||
(strncmp(*result, "Could not find ", 15) != 0 && strncmp(*result, "Found ", 6) != 0)) {
return;
}
(void)snprintf(saved, sizeof saved, "%s", s->err);
if (stale_file(s, submission, workspace, path, other) == 1 && (text = stale_text(workspace, path))) {
n = strlen(*result) + strlen(path) + strlen(text) + 256;
if ((noted = malloc(n))) {
(void)snprintf(noted, n,
"%s\n\n%s " STALE_MARK " (%s) after this one last read it. Its current text follows; redo the"
" edit against it.\n\n%s",
*result, path, other, text);
free(*result);
*result = noted;
}
free(text);
}
(void)snprintf(s->err, sizeof s->err, "%s", saved);
}
/* A write to a stale file would discard the other conversation's change
* unseen: it is not run. Its result shows the file as it now is, which
* counts as seeing it, so writing again goes through. 0: run it; 1: not run
* (journaled); -1 on error. */
static int stale_write_gate(pic_store *s, sqlite3_int64 submission, const char *workspace, const loop_pending *p,
const char *input) {
char other[64], *text, *result;
size_t n;
int rc;
if (strcmp(p->tool, "write") != 0 || !p->path || !p->content) {
return 0;
}
if ((rc = stale_file(s, submission, workspace, p->path, other)) != 1) {
return rc;
}
if (!(text = stale_text(workspace, p->path))) {
return 0; /* gone, or unreadable: nothing to show, nothing kept from being lost */
}
n = strlen(p->path) * 2 + strlen(text) + 320;
if (!(result = malloc(n))) {
free(text);
return -1;
}
(void)snprintf(result, n,
"Did not write %s: it " STALE_MARK " (%s) after this one last read it, and writing would discard that"
" change. Its current text follows; write again to replace it.\n\n%s",
p->path, other, text);
free(text);
if (pic_begin(s) != 0 ||
run_stmt(s, "UPDATE pic_effect SET state='skipped', result=?, is_error=1 WHERE id=? AND state='intent'", "ti", result,
p->effect) != 0 ||
sqlite3_changes(s->db) != 1 || flush_results(s, p->effect) != 0 || pic_commit(s) != 0) {
pic_rollback(s);
free(result);
return -1;
}
pic_ev_tool_start(s, p->call_id ? p->call_id : "", p->tool, input, p->path);
pic_ev_tool_end(s, p->call_id ? p->call_id : "", p->tool, result, NULL, 1);
free(result);
return 1;
}
static void pending_args(loop_pending *p);
/* ---- a tool calling tools ---------------------------------------------------
* A call of the model's whose tool calls tools (codemode's script) runs each round of its calls
* here, through pic_tool_hooks.call: every inner call is journaled as an intent in
* pic_nested_effect under the calling effect, gated by PreToolUse (with the caller's id as
* parent_tool_use_id), started and finished as the model's own calls are, at once where they may
* run together, and given its ordinary PostToolUse hooks; its result goes back to the caller and
* never into the transcript. A crash leaves the calling effect started; recovery makes it
* unknown with its inner calls listed, and never runs it or them again (settle_session). */
typedef struct {
started_ctx st; /* first: fetch_output reads it as its context */
nest_ctx *nc;
sqlite3_int64 id;
int position, runnable, ended, lost;
char call_id[200], name[48];
loop_pending p;
char *input, *key, *result;
int is_error;
struct pic_tool_image image;
pic_tool_output output;
pic_tool_hooks hooks;
} nest_item;
/* An inner call's journal key where the model's calls use their effect id (file history,
* whole outputs): minus its row's id. */
#define NESTED_KEY(it) (-(it)->id)
static int nested_started(void *ctx, const char *plan, size_t plan_len) {
nest_item *it = ctx;
pic_store *s = it->nc->s;
sqlite3_stmt *q = NULL;
pic_file_state pre;
char *made = NULL;
int step, before = 0;
/* An inner write or edit keeps the file as found, for rewind, as a call of the model's does. */
memset(&pre, 0, sizeof pre);
if (it->st.path) {
if ((before = pic_filelog_recorded(s, NESTED_KEY(it))) < 0) {
return -1;
}
before = !before;
if (before) {
pic_file_state_read(it->st.path, pic_filelog_cap(), &pre);
made = pic_filelog_new_dirs(it->st.path);
}
}
if (pic_begin(s) != 0) {
pic_file_state_free(&pre);
free(made);
return -1;
}
if (sqlite3_prepare_v2(s->db, "UPDATE pic_nested_effect SET state='started', plan=coalesce(?, plan) WHERE id=? AND state='intent'",
-1, &q, NULL) != SQLITE_OK) {
sql_fail(s);
pic_rollback(s);
return -1;
}
if (plan) {
sqlite3_bind_blob64(q, 1, plan, (sqlite3_uint64)plan_len, SQLITE_STATIC);
}
sqlite3_bind_int64(q, 2, it->id);
step = sqlite3_step(q);
sqlite3_finalize(q);
if (step != SQLITE_DONE || sqlite3_changes(s->db) != 1 ||
(before && pic_filelog_before(s, NESTED_KEY(it), it->st.path, &pre, made) != 0) || pic_commit(s) != 0) {
if (step != SQLITE_DONE) {
sql_fail(s);
}
pic_rollback(s);
pic_file_state_free(&pre);
free(made);
return -1;
}
pic_file_state_free(&pre);
free(made);
it->st.started = 1;
pic_fault("after-nested-started");
return 0;
}
static void nested_partial(void *ctx, const char *text) {
nest_item *it = ctx;
pic_ev_nested_update(it->nc->s, it->call_id, it->p.tool, it->input, text, it->nc->parent_call);
}
/* An inner call has ended (its result malloc'd, NULL when lost): journaled now. */
static void nested_done(void *ctx, char *result, int is_error) {
nest_item *it = ctx;
pic_store *s = it->nc->s;
pic_file_state post;
it->ended = 1;
if (!result) {
it->lost = 1;
return;
}
pic_fault("after-nested-exec");
memset(&post, 0, sizeof post);
if (it->st.path) {
pic_file_state_read(it->st.path, -1, &post); /* outside the result's transaction */
}
if (pic_begin(s) != 0 ||
run_stmt(s, "UPDATE pic_nested_effect SET state='done', result=?, is_error=? WHERE id=? AND state='started'", "tii",
result, (sqlite3_int64)is_error, it->id) != 0 ||
sqlite3_changes(s->db) != 1 || (it->output.data && store_output(s, NESTED_KEY(it), &it->output) != 0) ||
(it->st.path && pic_filelog_after(s, NESTED_KEY(it), &post) != 0) || pic_commit(s) != 0) {
pic_rollback(s);
free(result);
it->lost = 1;
return;
}
it->result = result;
it->is_error = is_error;
pic_fault("after-nested-result");
}
/* Whether TEXT is a JSON object. */
static int json_object_text(pic_store *s, const char *text) {
sqlite3_stmt *q = NULL;
int ok = 0;
if (text && sqlite3_prepare_v2(s->db, "SELECT json_valid(?1) AND json_type(?1) = 'object'", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC);
ok = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
}
sqlite3_finalize(q);
return ok;
}
/* Why a call cannot be made at all (malloc'd), or NULL. */
static char *nested_refusal(pic_store *s, const nest_ctx *nc, const pic_nested_call *c) {
char *why = NULL;
size_t n = (c->tool ? strlen(c->tool) : 0) + 64;
if (!c->tool || !pic_tool_named(c->tool) || !pic_toolset_on(c->tool)) {
if ((why = malloc(n))) {
(void)snprintf(why, n, "Tool %s not found", c->tool ? c->tool : "");
}
} else if (strcmp(c->tool, "codemode") == 0 || strcmp(c->tool, nc->parent_tool) == 0) {
if ((why = malloc(n))) {
(void)snprintf(why, n, "error: %s cannot be called from inside a tool call", c->tool);
}
} else if (!json_object_text(s, c->input)) {
why = strdup("Tool input is not a JSON object.");
}
return why;
}
static long long nested_now_ms(void) {
struct timespec t;
(void)clock_gettime(CLOCK_MONOTONIC, &t);
return (long long)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}
static int nested_call(void *ctx, pic_nested_call *calls, size_t n) {
nest_ctx *nc = ctx;
pic_store *s = nc->s;
nest_item *items;
pic_par_call *par = NULL;
sqlite3_int64 first = 0;
size_t nrun = 0;
int rc = 0, together, cut = 0;
char *mode;
if (n == 0) {
return 0;
}
if (!(items = calloc(n, sizeof *items))) {
return -1;
}
/* Every call of the round is journaled before any is gated or run. */
if (query_int(s, "SELECT coalesce(max(position), 0) FROM pic_nested_effect WHERE parent_id = ?", nc->parent, &first) != 0 ||
pic_begin(s) != 0) {
free(items);
return -1;
}
for (size_t i = 0; i < n && rc == 0; i++) {
nest_item *it = &items[i];
char *why = nested_refusal(s, nc, &calls[i]);
it->nc = nc;
it->position = (int)first + (int)i + 1;
(void)snprintf(it->call_id, sizeof it->call_id, "%s/%d", nc->parent_call, it->position);
it->input = strdup(calls[i].input && json_object_text(s, calls[i].input) ? calls[i].input : "{}");
it->p.tool = strdup(calls[i].tool ? calls[i].tool : "");
if (!it->input || !it->p.tool) {
free(why);
rc = -1;
break;
}
rc = run_stmt(s,
"INSERT INTO pic_nested_effect(parent_id, position, call_id, tool, input, replay_safe, state, result, is_error)"
" VALUES(?, ?, ?, ?, ?, ?, CASE WHEN ?7 IS NULL THEN 'intent' ELSE 'skipped' END, ?7, ?7 IS NOT NULL)",
"iitttit", nc->parent, (sqlite3_int64)it->position, it->call_id, it->p.tool, it->input,
(sqlite3_int64)pic_tool_replay_safe(it->p.tool), why);
it->id = sqlite3_last_insert_rowid(s->db);
it->runnable = !why;
if (why) {
it->result = why;
it->is_error = 1;
}
}
if (rc != 0 || pic_commit(s) != 0) {
pic_rollback(s);
rc = -1;
goto out;
}
pic_fault("after-nested-intent");
for (size_t i = 0; i < n; i++) {
pic_ev_nested_start(s, items[i].call_id, items[i].p.tool, items[i].input, nc->parent_call);
if (!items[i].runnable) {
pic_ev_nested_end(s, items[i].call_id, items[i].p.tool, items[i].result, 1, nc->parent_call);
}
}
/* PreToolUse, call by call in order, as the model's calls are gated. */
for (size_t i = 0; i < n && rc == 0; i++) {
nest_item *it = &items[i];
gate_call g = {it->id, it->p.tool, it->call_id, NULL, nc->parent_call};
int gate;
if (!it->runnable) {
continue;
}
if (pic_interrupted) {
it->runnable = 0;
continue;
}
gate = tool_gate(s, nc->submission, &g, it->input);
if (gate < 0) {
rc = -1;
} else if (gate == 1) {
sqlite3_stmt *q = NULL;
it->runnable = 0;
it->is_error = 1;
if (sqlite3_prepare_v2(s->db, "SELECT result FROM pic_nested_effect WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, it->id);
if (sqlite3_step(q) == SQLITE_ROW) {
it->result = dup_col(q, 0);
}
}
sqlite3_finalize(q);
} else {
sqlite3_stmt *q = NULL;
char *fresh = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT input FROM pic_nested_effect WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, it->id);
if (sqlite3_step(q) == SQLITE_ROW) {
fresh = dup_col(q, 0); /* as a hook may have rewritten it */
}
}
sqlite3_finalize(q);
if (!fresh || parse_pending_input(s, &it->p, fresh, &it->input) != 0) {
rc = -1;
}
}
}
if (rc != 0) {
goto out;
}
pic_fault("after-nested-gate");
mode = pic_setting("toolExecution");
together = pic_executor_get() == pic_executor_host() && !(mode && strcmp(mode, "sequential") == 0);
free(mode);
if (!(par = calloc(n, sizeof *par))) {
rc = -1;
goto out;
}
for (size_t i = 0; i < n; i++) {
nest_item *it = &items[i];
if (!it->runnable) {
continue;
}
together &= !pic_toolset_sequential(it->p.tool);
pending_args(&it->p);
it->st = (started_ctx){s, nc->parent, 0, NULL};
(void)snprintf(it->name, sizeof it->name, "pic:nested/%lld", (long long)it->id);
it->hooks = (pic_tool_hooks){.exec_seconds = nc->exec_seconds,
.started = nested_started,
.ctx = it,
.output_name = it->name,
.output = &it->output,
.fetch = fetch_output,
.image = &it->image,
.partial = nested_partial,
.partial_ctx = it,
.journal = sqlite3_db_filename(s->db, "main"),
.effect = (long long)nc->parent,
.input = it->input,
.nested = it->position};
if (it->p.path && (strcmp(it->p.tool, "read") == 0 || strcmp(it->p.tool, "edit") == 0 ||
strcmp(it->p.tool, "write") == 0)) {
it->key = pic_tool_path_key(nc->workspace, it->p.path);
it->st.path = strcmp(it->p.tool, "read") != 0 ? it->key : NULL;
}
par[nrun++] = (pic_par_call){it->p.tool, &it->p.args, &it->hooks, it->key, strcmp(it->p.tool, "read") != 0,
nested_done, it, calls[i].deadline_ms};
cut |= calls[i].deadline_ms != 0;
}
/* With a deadline even one call runs in a child, which the deadline can stop (toolpar.h). */
if ((nrun > 1 || cut) && together) {
pic_par_run(nc->workspace, par, nrun);
} else {
for (size_t k = 0; k < nrun && !pic_interrupted; k++) {
int is_error = 0;
char *result;
if (par[k].deadline_ms) { /* run here (a tool that runs alone): a command's timeout is the deadline */
long long left = (par[k].deadline_ms - nested_now_ms() + 999) / 1000;
nest_item *it = par[k].ctx;
it->hooks.exec_seconds = left < 1 ? 1 : left < nc->exec_seconds ? (int)left : nc->exec_seconds;
}
result = pic_toolset_run(nc->workspace, par[k].tool, par[k].args, par[k].hooks, &is_error);
nested_done(par[k].ctx, result, is_error);
}
}
/* Each finished call: its ordinary PostToolUse hooks, then its end, in call order. */
for (size_t i = 0; i < n; i++) {
nest_item *it = &items[i];
if (it->lost) {
if (!s->err[0]) {
(void)snprintf(s->err, sizeof s->err, "lost the result of %s inside a tool call; recovery will settle it",
it->p.tool);
}
rc = -1;
} else if (it->runnable && it->ended) {
char *before = strdup(it->result);
if (!before || pic_hooks_post_nested(s, nc->submission, it->id, it->p.tool, it->input, it->call_id,
nc->parent_call, &it->result, it->is_error) != 0) {
rc = -1;
} else if (strcmp(before, it->result) != 0 &&
(pic_begin(s) != 0 ||
run_stmt(s, "UPDATE pic_nested_effect SET result = ? WHERE id = ?", "ti", it->result, it->id) != 0 ||
pic_commit(s) != 0)) {
pic_rollback(s);
rc = -1;
}
free(before);
pic_ev_nested_end(s, it->call_id, it->p.tool, it->result, it->is_error, nc->parent_call);
}
}
/* What a Ctrl-C kept from running is skipped, so nothing is left under way. */
if (pic_begin(s) != 0 ||
run_stmt(s,
"UPDATE pic_nested_effect SET state='skipped', result='error: cancelled before it ran', is_error=1"
" WHERE parent_id = ? AND state = 'intent'",
"i", nc->parent) != 0 ||
pic_commit(s) != 0) {
pic_rollback(s);
rc = -1;
}
out:
for (size_t i = 0; i < n; i++) {
nest_item *it = &items[i];
if (rc == 0) {
calls[i].result = it->result ? it->result : strdup("error: cancelled before it ran");
calls[i].is_error = it->result ? it->is_error : 1;
calls[i].mime = it->image.mime;
calls[i].image = it->image.data;
calls[i].image_len = it->image.len;
if (!calls[i].result) {
rc = -1;
}
} else {
free(it->result);
free(it->image.data);
}
free(it->input);
free(it->key);
free(it->output.data);
pending_free(&it->p);
}
if (rc != 0) {
for (size_t i = 0; i < n; i++) {
if (calls[i].result) {
free(calls[i].result);
free(calls[i].image);
calls[i].result = NULL;
calls[i].image = NULL;
}
}
}
free(par);
free(items);
return rc;
}
/* The unfinished tool calls of a submission, in call order. */
#define PENDING_SQL \
"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," \
" CASE json_type(f.input,'$.pattern') WHEN 'text' THEN json_extract(f.input,'$.pattern') END," \
" CASE json_type(f.input,'$.glob') WHEN 'text' THEN json_extract(f.input,'$.glob') END," \
" json_type(f.input,'$.ignoreCase')='true', json_type(f.input,'$.literal')='true'," \
" json_type(f.input,'$.context') IN ('integer','real'), CAST(json_extract(f.input,'$.context') AS INTEGER)," \
" f.entry_seq" \
" 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"
/* A row of PENDING_SQL into p (its input into *input); 0, or -1. */
static int load_pending(pic_store *s, sqlite3_stmt *q, loop_pending *p, char **input) {
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);
p->pattern = dup_col(q, 15);
p->glob = dup_col(q, 16);
p->args.ignore_case = sqlite3_column_int(q, 17);
p->args.literal = sqlite3_column_int(q, 18);
p->args.has_context = sqlite3_column_int(q, 19);
p->args.context = (long)sqlite3_column_int64(q, 20);
p->entry = sqlite3_column_int64(q, 21);
if (!sqlite3_column_int(q, 13)) {
p->args.bad_input = "Tool input is not a JSON object.";
}
if (!p->tool || !*input) {
return -1;
}
return strcmp(p->tool, "edit") == 0 ? load_edits(s, *input, p) : 0;
}
/* The argument strings p holds, as the tool's arguments. */
static void pending_args(loop_pending *p) {
p->args.path = p->path;
p->args.content = p->content;
p->args.command = p->command;
p->args.pattern = p->pattern;
p->args.glob = p->glob;
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;
}
/* 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;
loop_pending p;
char *input = NULL;
int rc, step;
memset(&p, 0, sizeof p);
if (sqlite3_prepare_v2(s->db, PENDING_SQL " 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) {
rc = load_pending(s, q, &p, &input);
} else {
rc = step == SQLITE_DONE ? 1 : sql_fail(s); /* an error is never "nothing to do" */
}
sqlite3_finalize(q);
if (rc == 0) {
int gate = pre_tool_gate(s, submission, &p, input);
if (gate < 0) {
rc = -1;
} else if (gate == 2) {
rc = reload_pending_input(s, &p, &input); /* a hook rewrote the call */
gate = rc == 0 ? 0 : -1;
}
if (rc == 0 && gate == 0) {
gate = stale_write_gate(s, submission, workspace, &p, input);
rc = gate < 0 ? -1 : 0;
}
if (rc == 0 && gate == 0) {
pending_args(&p);
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;
}
/* Whether the calls left in SUBMISSION's turn run at once: Pi's
* toolExecution setting (parallel unless "sequential"), more than one call
* left, none to a tool that must run alone (Pi's per-tool executionMode),
* and processes to run them in (the host's executor; toolpar.h). */
static int parallel_batch(pic_store *s, sqlite3_int64 submission) {
sqlite3_stmt *q = NULL;
char *mode;
int calls = 0, alone = 0, sequential;
if (pic_executor_get() != pic_executor_host()) {
return 0;
}
mode = pic_setting("toolExecution");
sequential = mode && strcmp(mode, "sequential") == 0;
free(mode);
if (sequential || sqlite3_prepare_v2(s->db,
"SELECT f.tool FROM pic_effect f JOIN pic_entry e ON e.seq=f.entry_seq"
" WHERE e.submission_id=? AND f.state='intent'",
-1, &q, NULL) != SQLITE_OK) {
return 0;
}
sqlite3_bind_int64(q, 1, submission);
while (sqlite3_step(q) == SQLITE_ROW) {
calls++;
alone |= pic_toolset_sequential((const char *)sqlite3_column_text(q, 0));
}
sqlite3_finalize(q);
return calls > 1 && !alone;
}
/* One call of a parallel batch, from its gate to its result. */
typedef struct par_batch par_batch;
typedef struct {
par_batch *batch;
loop_pending p;
char *input, *key;
started_ctx started;
partial_ctx partial;
nest_ctx nest;
char name[48];
pic_tool_output output;
struct pic_tool_image image;
pic_tool_hooks hooks;
/* Finished and not yet reported. An image result is journaled only in its
* turn; report: journaled in the transaction under way, its end event due. */
char *result;
int is_error, report;
int ran; /* given to pic_par_run; ended: pic_par_run's done came */
int ended;
} par_item;
struct par_batch {
pic_store *s;
const char *workspace;
sqlite3_int64 submission;
par_item *items;
size_t n;
int failed;
};
/* Inside a transaction: journals a finished call (result, image, output)
* with its tool_result entry. */
static int par_commit(pic_store *s, sqlite3_int64 submission, par_item *it) {
pic_image attached = {it->image.mime, it->image.data, it->image.len, it->image.width, it->image.height};
int rc = run_stmt(s, "UPDATE pic_effect SET state='done', result=?, is_error=? WHERE id=? AND state='started'", "tii",
it->result, (sqlite3_int64)it->is_error, it->p.effect) != 0 ||
sqlite3_changes(s->db) != 1 || append_result(s, submission, it->result, it->p.effect) != 0 ||
pic_attach_images(s, sqlite3_last_insert_rowid(s->db), 0, &attached, it->image.data ? 1 : 0) != 0 ||
(it->output.data && store_output(s, it->p.effect, &it->output) != 0)
? -1
: 0;
return rc;
}
/* Inside a transaction: the transcript catches up, in call order: settled
* calls' entries, and a waiting image result once it is the next one. */
static int par_settle(par_batch *b) {
for (;;) {
sqlite3_int64 next = 0;
par_item *it = NULL;
if (flush_results(b->s, b->items[0].p.effect) != 0 ||
query_int(b->s,
"SELECT f.id FROM pic_effect f WHERE f.entry_seq = ? AND NOT EXISTS (SELECT 1 FROM pic_entry r"
" WHERE r.kind='tool_result' AND r.effect_id=f.id) ORDER BY f.ordinal LIMIT 1",
b->items[0].p.entry, &next) != 0) {
return -1;
}
for (size_t i = 0; i < b->n && next; i++) {
if (b->items[i].p.effect == next && b->items[i].result && !b->items[i].report) {
it = &b->items[i];
}
}
if (!it) {
return 0;
}
if (par_commit(b->s, b->submission, it) != 0) {
return -1;
}
it->report = 1;
}
}
static void par_free_result(par_item *it) {
free(it->result);
free(it->output.data);
free(it->image.data);
it->result = NULL;
it->output = (pic_tool_output){NULL, 0};
it->image.data = NULL;
}
/* A call has ended (pic_par_run's done): its result commits now, its
* tool_result entry once every earlier call's has; an image result waits in
* memory for its turn (a read: run again if pic dies meanwhile). */
static void par_done(void *ctx, char *result, int is_error) {
par_item *it = ctx;
par_batch *b = it->batch;
pic_store *s = b->s;
pic_file_state post;
int failed;
it->ended = 1;
if (!result) {
par_free_result(it);
if (it->started.started) {
(void)snprintf(s->err, sizeof s->err, "lost the result of %s; recovery will settle it", it->p.tool);
} else if (!s->err[0]) {
(void)snprintf(s->err, sizeof s->err, "could not record the start of %s", it->p.tool);
}
b->failed = 1;
return;
}
pic_fault("after-exec");
memset(&post, 0, sizeof post);
if (it->started.path) {
pic_file_state_read(it->started.path, -1, &post); /* outside the result's transaction */
}
stale_edit_note(s, b->submission, b->workspace, it->p.tool, it->p.path, &result, is_error);
it->is_error = is_error;
it->result = result;
failed = pic_begin(s) != 0;
if (!failed && !it->image.data) {
failed = run_stmt(s, "UPDATE pic_effect SET state='done', result=?, is_error=? WHERE id=? AND state='started'",
"tii", result, (sqlite3_int64)is_error, it->p.effect) != 0 ||
sqlite3_changes(s->db) != 1 || (it->output.data && store_output(s, it->p.effect, &it->output) != 0) ||
(it->started.path && pic_filelog_after(s, it->p.effect, &post) != 0);
it->report = !failed;
}
if (failed || par_settle(b) != 0 || pic_commit(s) != 0) {
pic_rollback(s);
b->failed = 1;
for (size_t i = 0; i < b->n; i++) {
b->items[i].report = 0;
}
return;
}
/* Pi's tool_execution_end as each call finishes; an image result's once
* it is journaled. */
for (size_t i = 0; i < b->n; i++) {
par_item *r = &b->items[i];
char *images = NULL;
if (!r->report) {
continue;
}
r->report = 0;
if (r->image.data && s->events && s->events->json) {
images = image_blocks(s, r->image.mime, r->image.data, r->image.len);
}
pic_ev_tool_end(s, r->p.call_id ? r->p.call_id : "", r->p.tool, r->result, images, r->is_error);
free(images);
par_free_result(r);
}
pic_fault("after-result");
}
/* Runs every unfinished call of SUBMISSION's turn at once (parallel_batch
* said so). Each call's PreToolUse hooks run first, one call after another
* in call order, as Pi prepares calls before running them; then the calls
* run together, each journaling started and its result in short
* transactions of its own. 0, or -1 on error (s->err). */
static int run_parallel(pic_store *s, const char *workspace, int exec_seconds, sqlite3_int64 submission) {
sqlite3_stmt *q = NULL;
par_batch b = {s, workspace, submission, NULL, 0, 0};
pic_par_call *calls = NULL;
size_t ncalls = 0, cap = 0;
int rc = 0, step = SQLITE_DONE;
if (sqlite3_prepare_v2(s->db, PENDING_SQL, -1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_int64(q, 1, submission);
while (rc == 0 && (step = sqlite3_step(q)) == SQLITE_ROW) {
if (b.n == cap) {
size_t ncap = cap ? cap * 2 : 8;
par_item *grown = realloc(b.items, ncap * sizeof *grown);
if (!grown) {
rc = -1;
break;
}
b.items = grown;
cap = ncap;
}
memset(&b.items[b.n], 0, sizeof b.items[b.n]);
rc = load_pending(s, q, &b.items[b.n].p, &b.items[b.n].input);
b.n++;
}
if (rc == 0 && step != SQLITE_DONE) {
rc = sql_fail(s);
}
sqlite3_finalize(q);
if (rc == 0 && b.n && !(calls = calloc(b.n, sizeof *calls))) {
rc = -1;
}
for (size_t i = 0; rc == 0 && i < b.n && !pic_interrupted; i++) {
par_item *it = &b.items[i];
loop_pending *p = &it->p;
int gate = pre_tool_gate(s, submission, p, it->input);
if (gate == 2) {
gate = reload_pending_input(s, p, &it->input) < 0 ? -1 : 0; /* a hook rewrote the call */
}
if (gate == 0) {
gate = stale_write_gate(s, submission, workspace, p, it->input);
}
if (gate != 0) {
rc = gate < 0 ? -1 : 0; /* denied (journaled), or Ctrl-C */
continue;
}
pending_args(p);
it->batch = &b;
it->started = (started_ctx){s, p->effect, 0, NULL};
it->partial = (partial_ctx){s, p->call_id ? p->call_id : "", p->tool, it->input};
(void)snprintf(it->name, sizeof it->name, "pic:output/%lld", (long long)p->effect);
it->nest = (nest_ctx){s, workspace, exec_seconds, submission, p->effect, p->call_id ? p->call_id : "", p->tool};
it->hooks = (pic_tool_hooks){.exec_seconds = exec_seconds,
.started = commit_started,
.ctx = &it->started,
.plan = p->plan,
.plan_len = p->plan_len,
.output_name = it->name,
.output = &it->output,
.fetch = fetch_output,
.image = &it->image,
.partial = emit_partial,
.partial_ctx = &it->partial,
.journal = sqlite3_db_filename(s->db, "main"),
.effect = (long long)p->effect,
.input = it->input,
.call = nested_call,
.call_ctx = &it->nest};
if (p->path && (strcmp(p->tool, "read") == 0 || strcmp(p->tool, "edit") == 0 || strcmp(p->tool, "write") == 0)) {
it->key = pic_tool_path_key(workspace, p->path);
it->started.path = strcmp(p->tool, "read") != 0 ? it->key : NULL;
}
calls[ncalls++] = (pic_par_call){p->tool, &p->args, &it->hooks, it->key,
strcmp(p->tool, "read") != 0, par_done, it, 0};
it->ran = 1;
pic_ev_tool_start(s, p->call_id ? p->call_id : "", p->tool, it->input, p->command ? p->command : p->path);
}
if (rc == 0 && ncalls) {
s->err[0] = '\0';
pic_par_run(workspace, calls, ncalls);
rc = b.failed ? -1 : 0;
}
/* Every start has its end, as in Pi: a call an abort kept from running
* ends as pic_run's cancel journals it. */
for (size_t i = 0; i < b.n; i++) {
if (b.items[i].ran && !b.items[i].ended) {
pic_ev_tool_end(s, b.items[i].p.call_id ? b.items[i].p.call_id : "", b.items[i].p.tool,
"error: cancelled before it ran", NULL, 1);
}
}
for (size_t i = 0; i < b.n; i++) {
par_free_result(&b.items[i]);
free(b.items[i].input);
free(b.items[i].key);
pending_free(&b.items[i].p);
}
free(b.items);
free(calls);
return rc;
}
/* The next unfinished calls of SUBMISSION's turn: all at once, or the next
* one alone. 1 when none is pending, 0 after running, -1 on error. */
static int run_pending(pic_store *s, const char *workspace, int exec_seconds, sqlite3_int64 submission) {
return parallel_batch(s, submission) ? run_parallel(s, workspace, exec_seconds, submission)
: run_pending_effect(s, workspace, exec_seconds, submission);
}
/* 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,
"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 ||
flush_results(s, 0) != 0 || fail_submission(s, submission, "cancelled") != 0 ||
pic_wake_cancelled(s, submission) != 0 /* Esc on work a loop started pauses the loop */
? -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;
char sid[64] = "";
int rc = 0;
/* A request a live process is running is its to cancel (Ctrl-C there). */
if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE request_key=? AND status='admitted'", -1, &q,
NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_text(q, 1, request_key, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
(void)snprintf(sid, sizeof sid, "%s", (const char *)sqlite3_column_text(q, 0));
}
sqlite3_finalize(q);
q = NULL;
if (sid[0] && (rc = pic_lease(s, sid, PIC_LEASE_WAIT_MS)) != 0) {
if (rc == 1) {
long pid = pic_lease_holder(s, sid);
char who[48] = "";
if (pid > 0) {
(void)snprintf(who, sizeof who, " (pid %ld)", pid);
}
(void)snprintf(s->err, sizeof s->err,
"request %s is being run by another pic process%s; interrupt it there (Ctrl-C, or SIGINT)",
request_key, who);
}
return -1;
}
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;
}
/* A request ended cleanly before its answer (REASON: request_cap): its
* conversation stays usable; queued messages are returned, never run. */
static int stop_submission(pic_store *s, sqlite3_int64 submission, const char *reason) {
return run_stmt(s, "UPDATE pic_submission SET status='stopped', stop_reason=? WHERE id=?", "ti", reason, submission) != 0 ||
run_stmt(s, "UPDATE pic_queued SET state='returned' WHERE submission_id=? AND state='queued'", "i",
submission) != 0
? -1
: 0;
}
/* Inside a transaction: replay_safe for each call of reply ENTRY whose tool's
* registration allows a replay (toolreg.h); the rest stay 0. */
static int mark_replay_safe(pic_store *s, sqlite3_int64 entry) {
sqlite3_stmt *q = NULL;
sqlite3_int64 *safe = NULL;
size_t n = 0, cap = 0;
int step, rc = 0;
if (sqlite3_prepare_v2(s->db, "SELECT id, tool FROM pic_effect WHERE entry_seq = ?", -1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_int64(q, 1, entry);
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
if (!pic_tool_replay_safe((const char *)sqlite3_column_text(q, 1))) {
continue;
}
if (n == cap) {
sqlite3_int64 *grown = realloc(safe, (cap = cap ? cap * 2 : 8) * sizeof *safe);
if (!grown) {
step = SQLITE_NOMEM;
break;
}
safe = grown;
}
safe[n++] = sqlite3_column_int64(q, 0);
}
if (step == SQLITE_NOMEM) {
(void)snprintf(s->err, sizeof s->err, "out of memory");
rc = -1;
} else if (step != SQLITE_DONE) {
rc = sql_fail(s);
}
sqlite3_finalize(q);
for (size_t i = 0; rc == 0 && i < n; i++) {
rc = run_stmt(s, "UPDATE pic_effect SET replay_safe = 1 WHERE id = ?", "i", safe[i]);
}
free(safe);
return rc;
}
/* 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);
}
/* With Stop hooks, a verify command or a goal being worked, a finished reply stays an
* assistant turn until they have had their say (stop_gate). */
kind = refusal || calls > 0 || strcmp(stop, "pause") == 0 || pic_hooks_has(s->hooks, "Stop") || s->verify ||
(s->stop_policy && pic_wake_goal_active(s, submission))
? "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. Each records whether its
* tool's registration lets it run again after a crash. */
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'), 0, 'intent'"
" FROM json_each(?2) WHERE json_extract(value,'$.type')='toolCall'",
"it", entry, r->neutral) != 0 ||
mark_replay_safe(s, entry) != 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, long window, sqlite3_int64 submission) {
sqlite3_stmt *q = NULL;
char *prompt = NULL, *tools_json = 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, window);
tools_json = pic_toolset_schemas();
rc = prompt && tools_json ? run_stmt(s,
"UPDATE pic_session SET system_prompt = ?, tools = ?, instructions_hash = ?"
" WHERE id = (SELECT session_id FROM pic_submission WHERE id = ?)",
"ttti", prompt, tools_json, 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(tools_json);
free(instructions);
return rc;
}
int pic_sync_session(pic_store *s, const char *workspace, long window, int64_t submission) {
return sync_session(s, workspace, window, submission);
}
/* 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;
}
/* The usage of a compaction's summary requests, priced at MODEL's catalog
* price as a reply's is; a split turn's two requests summed into one, so
* what a compaction cost is counted whole (pic usage). Takes both; NULL
* when there was none. */
#define SUM2(path) "'" path "', coalesce(json_extract(?1,'" path "'),0) + coalesce(json_extract(?2,'" path "'),0)"
static char *summary_usage(pic_store *s, const char *model, char *usage, char *usage2) {
pic_model m;
char err[PIC_ERR_CAP];
char *out = NULL;
if (pic_model_resolve(model, &m, err, sizeof err) == 0) {
char *priced = usage ? pic_usage_priced(&m, usage) : NULL, *priced2 = usage2 ? pic_usage_priced(&m, usage2) : NULL;
if (priced) {
free(usage);
usage = priced;
}
if (priced2) {
free(usage2);
usage2 = priced2;
}
}
if (usage && usage2) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db,
"SELECT CASE WHEN json_type(?1,'$.pic_tokens') IS NULL OR json_type(?2,'$.pic_tokens') IS NULL"
" THEN ?1 ELSE json_set(?1, " SUM2("$.pic_tokens.input") ", " SUM2("$.pic_tokens.output") ","
" " SUM2("$.pic_tokens.cacheRead") ", " SUM2("$.pic_tokens.cacheWrite") ","
" " SUM2("$.pic_tokens.totalTokens") ", " SUM2("$.pic_cost.input") ", " SUM2("$.pic_cost.output") ","
" " SUM2("$.pic_cost.cacheRead") ", " SUM2("$.pic_cost.cacheWrite") ", " SUM2("$.pic_cost.total") ")"
" END",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, usage, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, usage2, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
out = dup_col(q, 0);
}
}
sqlite3_finalize(q);
}
if (!out) { /* only one, or they could not be summed: the first */
if (usage) {
free(usage2);
return usage;
}
return usage2;
}
free(usage);
free(usage2);
return out;
}
#undef SUM2
/* What PreRequest is asked with (policy.h): the facts core owns, as JSON
* (malloc'd). Idle is the journal's clock now less the end of the
* conversation's last reply; TURN 0 is the submission's first request. */
static char *request_facts(pic_store *s, const pic_provider *provider, sqlite3_int64 submission, sqlite3_int64 turn) {
sqlite3_stmt *q = NULL;
char *out = NULL;
if (sqlite3_prepare_v2(s->db,
PIC_CONTEXT_CTE "SELECT json_object('model', ?2, 'contextWindow', ?3, 'cacheSeconds', ?4, 'idleSeconds',"
" (SELECT (CAST(unixepoch('subsec') * 1000 AS INTEGER) - max(e.created_ms)) / 1000"
" FROM pic_entry e JOIN p ON p.seq = e.seq WHERE e.kind IN ('assistant','answer')),"
" 'firstRequest', json(CASE WHEN ?5 = 0 THEN 'true' ELSE 'false' END))",
-1, &q, NULL) != SQLITE_OK) {
return NULL;
}
sqlite3_bind_int64(q, 1, submission);
sqlite3_bind_text(q, 2, provider->model, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 3, provider->context_window);
sqlite3_bind_int64(q, 4, provider->cache_seconds);
sqlite3_bind_int64(q, 5, turn);
if (sqlite3_step(q) == SQLITE_ROW) {
out = dup_col(q, 0);
}
sqlite3_finalize(q);
return out;
}
/* Inside a transaction: compaction GENERATION is done with its entry, made
* from SUMMARY and plan P for SUBMISSION (FROM: the head it summarized when
* made outside a turn, else 0), the request for it cleared, and the latest
* project instructions summarized away sent again after it, so they stay in
* the conversation verbatim. The entry's seq in *seq. */
static int compaction_commit(pic_store *s, sqlite3_int64 submission, sqlite3_int64 generation, const char *summary,
const pic_compact_plan *p, const char *usage, sqlite3_int64 from, sqlite3_int64 *seq) {
if (run_stmt(s,
"INSERT INTO pic_entry(submission_id,kind,body,native,first_kept_seq,tokens_before,from_seq)"
" VALUES(?,'compaction',?,?,?,?,nullif(?,0))",
"ittiii", submission, summary, p->details, p->first_kept_seq, p->tokens_before, from) != 0) {
return -1;
}
*seq = sqlite3_last_insert_rowid(s->db);
return run_stmt(s, "UPDATE pic_generation SET state='done', entry_seq=?, usage=? WHERE id=?", "iti", *seq, usage,
generation) != 0 ||
(!from &&
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,from_seq) SELECT ?1, 'instructions', body,"
" nullif(?3, 0) 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",
"iii", submission, p->first_kept_seq, from) != 0
? -1
: 0;
}
/* Plan P's summary requests, made in order and joined by the policy into
* the entry's text (*summary), their usage summed into *usage (both
* malloc'd). 0, or the failing request's status with err and *retryable
* set. */
static int compaction_summarize(pic_store *s, pic_provider *provider, const pic_context_policy *pol,
const pic_compact_plan *p, char **summary, char **usage, int *retryable, char *err,
size_t errcap) {
char *reply[2] = {NULL, NULL}, *use[2] = {NULL, NULL};
int rc = 0;
*summary = *usage = NULL;
for (int i = 0; i < 2 && rc == 0 && p->prompt[i]; i++) {
rc = provider->summarize(provider, s, p->system, p->prompt[i], &reply[i], &use[i], retryable, err, errcap);
}
if (rc == 0 && !(*summary = pol->join(p, reply))) {
(void)snprintf(err, errcap, "out of memory");
rc = -1;
}
free(reply[0]);
free(reply[1]);
if (rc == 0) {
*usage = summary_usage(s, provider->model, use[0], use[1]);
} else {
free(use[0]);
free(use[1]);
}
return rc;
}
/* Before a reply: compacts the conversation when asked to (pic compact, or a
* context overflow: a summary), or when the context policy answers
* PreRequest with a mode to compact in (policy.h). The answer is journaled
* before it takes effect and stands for the turn: a retry or the next pic
* after a crash reads it, never asking again, and one automatic compaction
* is done at most once a turn. A summary's requests are journaled as a
* generation of purpose compaction, with the reason, and retried like
* replies; the entry, the generation's end and the cleared request commit
* together. A plan with no requests (trim) commits its generation and entry
* in one transaction. 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) {
const pic_context_policy *pol = s->policy;
sqlite3_stmt *q = NULL;
char *instructions = NULL, *usage = NULL, *summary = NULL, *mode = NULL, *reason = NULL, *answer = NULL;
char err[PIC_ERR_CAP] = "";
int requested = 0, retryable = 0, rc;
sqlite3_int64 attempts = 0, generation, seq, idle = -1;
pic_compact_plan p;
if (!pol) {
return 0;
}
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 (requested) {
mode = strdup("summary");
reason = strdup("manual");
} else {
pic_hook_answer a;
sqlite3_int64 done = 0;
char *facts;
if (query_int2(s,
"SELECT count(*) FROM pic_generation WHERE submission_id=? AND turn=? AND purpose='compaction'"
" AND state='done'",
submission, turn, &done) != 0) {
return -1;
}
if (done) {
return 0;
}
if (!(facts = request_facts(s, provider, submission, turn))) {
return sql_fail(s);
}
rc = pic_hooks_ask(s, "PreRequest", submission, turn, pol->name, pol->answer, facts, &a);
free(facts);
if (rc != 0) {
return -1;
}
if (a.context &&
sqlite3_prepare_v2(s->db,
"SELECT json_extract(?1,'$.compact'), coalesce(json_extract(?1,'$.idle'), -1)"
" WHERE json_valid(?1) AND json_type(?1,'$.compact') = 'text'",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, a.context, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
mode = dup_col(q, 0);
idle = sqlite3_column_int64(q, 1);
}
sqlite3_finalize(q);
}
reason = strdup(a.reason ? a.reason : "auto");
answer = a.context;
a.context = NULL;
pic_hook_answer_free(&a);
}
if (!mode || !reason || (strcmp(mode, "summary") == 0 && !provider->summarize)) {
free(instructions);
free(mode);
free(reason);
free(answer);
return 0;
}
{
char *extra = NULL;
if (pic_hooks_pre_compact(s, submission, turn, requested ? "manual" : "auto", instructions, &extra) != 0) {
free(instructions);
free(mode);
free(reason);
free(answer);
return -1;
}
if (extra) { /* what PreCompact hooks add joins the summary instructions */
char *joined = sqlite3_mprintf("%s%s%s", instructions && *instructions ? instructions : "",
instructions && *instructions ? "\n\n" : "", extra);
free(instructions);
free(extra);
instructions = joined ? strdup(joined) : NULL;
sqlite3_free(joined);
}
}
rc = pol->plan(s->db, submission, provider->model, mode, answer, instructions, &p);
free(instructions);
free(mode);
free(answer);
if (rc < 0) {
free(reason);
return sql_fail(s);
}
if (rc == 1) { /* nothing old enough to compact: the request is done */
free(reason);
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) {
pol->plan_free(&p);
free(reason);
return -1;
}
if (attempts >= PIC_GENERATION_ATTEMPTS) {
pol->plan_free(&p);
free(reason);
(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 (!p.prompt[0]) { /* no request: the generation, the entry and the cleared request commit together */
pic_ev_compaction_start(s, reason, (long long)p.tokens_before);
rc = pic_begin(s) != 0 ||
run_stmt(s,
"INSERT INTO pic_generation(submission_id,turn,attempt,state,purpose,reason,idle_seconds,context_tokens)"
" VALUES(?,?,?,'started','compaction',?,nullif(?,-1),?)",
"iiitii", submission, turn, attempts + 1, reason, idle, p.tokens_before) != 0 ||
compaction_commit(s, submission, sqlite3_last_insert_rowid(s->db), p.body, &p, NULL, 0, &seq) != 0 ||
pic_commit(s) != 0;
if (rc) {
pic_rollback(s);
} else {
pic_ev_compaction_end(s, reason, p.body, (long long)p.first_kept_seq, (long long)p.tokens_before, NULL);
}
pol->plan_free(&p);
free(reason);
if (rc) {
return -1;
}
pic_fault("after-compaction");
return 0;
}
if (pic_begin(s) != 0 ||
run_stmt(s,
"INSERT INTO pic_generation(submission_id,turn,attempt,state,purpose,reason,idle_seconds,context_tokens)"
" VALUES(?,?,?,'started','compaction',?,nullif(?,-1),?)",
"iiitii", submission, turn, attempts + 1, reason, idle, p.tokens_before) != 0 ||
pic_commit(s) != 0) {
pic_rollback(s);
pol->plan_free(&p);
free(reason);
return -1;
}
generation = sqlite3_last_insert_rowid(s->db);
pic_fault("after-compaction-started");
pic_ev_compaction_start(s, reason, (long long)p.tokens_before);
rc = compaction_summarize(s, provider, pol, &p, &summary, &usage, &retryable, err, sizeof err);
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 */
pic_ev_compaction_end(s, reason, NULL, 0, 0, err);
pol->plan_free(&p);
free(reason);
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 || compaction_commit(s, submission, generation, summary, &p, usage, 0, &seq) != 0 ||
pic_commit(s) != 0;
if (!rc) {
pic_ev_compaction_end(s, reason, summary, (long long)p.first_kept_seq, (long long)p.tokens_before, NULL);
}
free(summary);
free(usage);
free(reason);
pol->plan_free(&p);
if (rc) {
pic_rollback(s);
return -1;
}
pic_fault("after-compaction");
return 0;
}
/* Pi's compact command: the conversation compacted now, outside any turn.
* The entry and its done generation belong to the conversation's latest
* request (answered, failed or stopped: never one still running) and mark
* themselves made outside a turn with from_seq, the head they summarized,
* as a branch summary does; they commit together, so a crash leaves either
* the compaction or a failed attempt. The latest project instructions go
* out again after the summary, as compact_step's do. An abort meanwhile
* (pic_interrupted) ends it with "Compaction cancelled". *ENTRY is the
* compaction's entry. */
int pic_compact_now(pic_store *s, pic_provider *provider, const char *session, const char *instructions,
sqlite3_int64 *entry) {
char sid[64], err[PIC_ERR_CAP] = "";
sqlite3_int64 owner = 0, head = 0, busy = 0, turn = 0, last_compaction = 0;
const pic_context_policy *pol = s->policy;
pic_compact_plan c;
char *extra = NULL, *joined = NULL;
int rc;
*entry = 0;
if (pic_session_resolve(s, session, sid, sizeof sid) != 0 || pic_lease(s, sid, PIC_LEASE_WAIT_MS) != 0) {
return -1;
}
{
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db,
"SELECT coalesce((SELECT head_seq FROM pic_session WHERE id = ?1), 0),"
" coalesce((SELECT max(id) FROM pic_submission WHERE session_id = ?1), 0),"
" (SELECT count(*) FROM pic_submission WHERE session_id = ?1 AND status = 'admitted'),"
" coalesce((SELECT e.kind = 'compaction' FROM pic_entry e WHERE e.seq ="
" (SELECT head_seq FROM pic_session WHERE id = ?1)), 0)",
-1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
head = sqlite3_column_int64(q, 0);
owner = sqlite3_column_int64(q, 1);
busy = sqlite3_column_int64(q, 2);
last_compaction = sqlite3_column_int64(q, 3);
}
sqlite3_finalize(q);
}
if (busy) {
(void)snprintf(s->err, sizeof s->err, "session %s is still working on a request (pic run finishes it)", sid);
return -1;
}
if (last_compaction) {
(void)snprintf(s->err, sizeof s->err, "Already compacted");
return -1;
}
if (!head || !owner) {
(void)snprintf(s->err, sizeof s->err, "Nothing to compact (session too small)");
return -1;
}
if (!provider->summarize) {
(void)snprintf(s->err, sizeof s->err, "%s cannot summarize a conversation", provider->model);
return -1;
}
if (!pol) {
(void)snprintf(s->err, sizeof s->err, "this pic has no compaction component");
return -1;
}
if (query_int(s, "SELECT coalesce(max(turn), 0) + 1 FROM pic_generation WHERE submission_id = ?", owner, &turn) != 0) {
return -1;
}
if (pic_hooks_pre_compact(s, owner, turn, "manual", instructions, &extra) != 0) {
return -1;
}
if (extra) { /* what PreCompact hooks add joins the summary instructions */
char *both = sqlite3_mprintf("%s%s%s", instructions && *instructions ? instructions : "",
instructions && *instructions ? "\n\n" : "", extra);
free(extra);
joined = both ? strdup(both) : NULL;
sqlite3_free(both);
instructions = joined;
}
rc = pol->plan(s->db, owner, provider->model, "summary", NULL, instructions, &c);
free(joined);
if (rc < 0) {
return sql_fail(s);
}
if (rc == 1) {
(void)snprintf(s->err, sizeof s->err, "Nothing to compact (session too small)");
return -1;
}
pic_ev_compaction_start(s, "manual", (long long)c.tokens_before);
for (sqlite3_int64 attempt = 1;; attempt++) {
char *usage = NULL, *summary = NULL;
int retryable = 0;
sqlite3_int64 generation, seq;
err[0] = '\0';
if (pic_begin(s) != 0 ||
run_stmt(s,
"INSERT INTO pic_generation(submission_id,turn,attempt,state,purpose,reason,context_tokens)"
" VALUES(?,?,?,'started','compaction','manual',?)",
"iiii", owner, turn, attempt, c.tokens_before) != 0 ||
pic_commit(s) != 0) {
pic_rollback(s);
pol->plan_free(&c);
return -1;
}
generation = sqlite3_last_insert_rowid(s->db);
pic_fault("after-compact-now-started");
rc = compaction_summarize(s, provider, pol, &c, &summary, &usage, &retryable, err, sizeof err);
if (rc != 0) {
if (pic_interrupted) {
(void)snprintf(err, sizeof err, "Compaction cancelled");
} else if (!err[0]) {
(void)snprintf(err, sizeof err, "the summary request failed");
}
if (pic_begin(s) != 0 ||
run_stmt(s, "UPDATE pic_generation SET state='failed', error=? WHERE id=?", "ti", err, generation) != 0 ||
pic_commit(s) != 0) {
pic_rollback(s);
pol->plan_free(&c);
return -1;
}
if (retryable && !pic_interrupted && attempt < PIC_GENERATION_ATTEMPTS) {
continue;
}
pic_ev_compaction_end(s, "manual", NULL, 0, 0, err);
pol->plan_free(&c);
(void)snprintf(s->err, sizeof s->err, "%s", err);
return -1;
}
pic_fault("after-compact-now-summary");
rc = pic_begin(s) != 0 || compaction_commit(s, owner, generation, summary, &c, usage, head, &seq) != 0 ||
pic_commit(s) != 0;
if (!rc) {
pic_ev_compaction_end(s, "manual", summary, (long long)c.first_kept_seq, (long long)c.tokens_before, NULL);
*entry = seq;
}
free(summary);
free(usage);
pol->plan_free(&c);
if (rc) {
pic_rollback(s);
return -1;
}
pic_fault("after-compact-now");
return 0;
}
}
/* ---- branch summaries ------------------------------------------------------- */
/* Inside a transaction: the new conversation that starts with SUMMARY,
* made at entry AT for the conversation ending at FROM, its id in OUT; the
* entry belongs to AT's request and the done generation GENERATION (0 for
* none) to it. */
static int branch_commit(pic_store *s, const char *source, sqlite3_int64 from, sqlite3_int64 at, sqlite3_int64 owner,
const char *summary, const char *details, sqlite3_int64 generation, const char *usage,
char *out, size_t cap) {
sqlite3_int64 seq;
if (fork_session(s, source, at, out, cap) != 0 ||
run_stmt(s,
"INSERT INTO pic_entry(submission_id,kind,body,native,parent_seq,from_seq,created_ms)"
" VALUES(?,'branch_summary',?,?,?,?,CAST(unixepoch('subsec') * 1000 AS INTEGER))",
"ittii", owner, summary, details, at, from) != 0) {
return -1;
}
seq = sqlite3_last_insert_rowid(s->db);
return run_stmt(s, "UPDATE pic_session SET head_seq = ?, updated_ms = CAST(unixepoch('subsec') * 1000 AS INTEGER) WHERE id = ?",
"it", seq, out) != 0 ||
(generation && run_stmt(s, "UPDATE pic_generation SET state='done', entry_seq=?, usage=? WHERE id=?", "iti", seq,
usage, generation) != 0)
? -1
: 0;
}
/* Pi's navigateTree with a summary: the request made, journaled as a
* generation of purpose branch_summary (by AT's request) and retried like a
* reply's; the new conversation, its summary entry and the generation's end
* commit together, so a crash leaves either nothing or all of it, and the
* interrupted attempt is failed at the next open. With nothing below the
* common ancestor (AT is FROM's head or past it) the new conversation simply
* starts at AT, as Pi navigates without a summary. */
int pic_branch_summarize(pic_store *s, pic_provider *provider, const char *from, sqlite3_int64 at,
const char *instructions, char *out, size_t cap) {
char source[64], err[PIC_ERR_CAP] = "";
sqlite3_int64 head = 0, owner = 0, ok = 0, turn = 0;
const pic_context_policy *pol = s->policy;
pic_compact_plan b;
int rc;
/* Its summary request is journaled under the conversation it leaves. */
if (pic_session_resolve(s, from, source, sizeof source) != 0 || pic_lease(s, source, PIC_LEASE_WAIT_MS) != 0) {
return -1;
}
{
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT coalesce(head_seq, 0) FROM pic_session WHERE id = ?", -1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_text(q, 1, source, -1, SQLITE_STATIC);
head = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int64(q, 0) : 0;
sqlite3_finalize(q);
}
/* AT ends a turn, as a fork point must, and is not a summary of a branch. */
if (query_int(s,
"SELECT coalesce((SELECT submission_id FROM pic_entry WHERE seq = ?1), 0)", at, &owner) != 0 ||
query_int(s,
"SELECT EXISTS (SELECT 1 FROM pic_entry e WHERE e.seq = ?1 AND e.kind != 'branch_summary'"
" AND " ENDS_TURN_SQL("e") ")",
at, &ok) != 0) {
return -1;
}
if (!ok || !owner) {
(void)snprintf(s->err, sizeof s->err, "entry %lld is not a point to continue from: it must end a turn (pic log shows them)",
(long long)at);
return -1;
}
{ /* The summary request is journaled under AT's request: after a fork, one of an ancestor conversation. */
char under[64];
session_id_of(s, owner, under);
if (under[0] && pic_lease(s, under, PIC_LEASE_WAIT_MS) != 0) {
return -1;
}
}
if (at == head) {
(void)snprintf(s->err, sizeof s->err, "%s is already at entry %lld", source, (long long)at);
return -1;
}
if (!pol) {
(void)snprintf(s->err, sizeof s->err, "this pic has no compaction component to summarize a branch");
return -1;
}
rc = pol->branch_plan(s->db, head, at, provider->context_window, instructions, &b);
if (rc < 0) {
return sql_fail(s);
}
if (rc == 1) { /* nothing left behind: no summary */
if (pic_begin(s) != 0 || fork_session(s, source, at, out, cap) != 0 || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
return 0;
}
if (!b.prompt[0]) { /* nothing fit the budget: the plan's text, no request */
rc = pic_begin(s) != 0 || branch_commit(s, source, head, at, owner, b.body, b.details, 0, NULL, out, cap) != 0 ||
pic_commit(s) != 0;
pol->plan_free(&b);
if (rc) {
pic_rollback(s);
return -1;
}
return 0;
}
if (query_int(s, "SELECT coalesce(max(turn), 0) + 1 FROM pic_generation WHERE submission_id = ? AND purpose = 'branch_summary'",
owner, &turn) != 0) {
pol->plan_free(&b);
return -1;
}
for (int attempt = 1;; attempt++) {
char *text = NULL, *usage = NULL, *summary;
int retryable = 0;
sqlite3_int64 generation;
if (pic_begin(s) != 0 ||
run_stmt(s,
"INSERT INTO pic_generation(submission_id,turn,attempt,state,purpose) VALUES(?,?,?,'started','branch_summary')",
"iii", owner, turn, (sqlite3_int64)attempt) != 0 ||
pic_commit(s) != 0) {
pic_rollback(s);
pol->plan_free(&b);
return -1;
}
generation = sqlite3_last_insert_rowid(s->db);
pic_fault("after-branch-summary-started");
err[0] = '\0';
rc = provider->summarize(provider, s, b.system, b.prompt[0], &text, &usage, &retryable, err, sizeof err);
if (rc != 0) {
if (!err[0]) {
(void)snprintf(err, sizeof err, "the summary request failed");
}
if (pic_interrupted) {
(void)snprintf(err, sizeof err, "Branch summarization cancelled");
}
free(text);
free(usage);
if (pic_begin(s) != 0 ||
run_stmt(s, "UPDATE pic_generation SET state='failed', error=? WHERE id=?", "ti", err, generation) != 0 ||
pic_commit(s) != 0) {
pic_rollback(s);
pol->plan_free(&b);
return -1;
}
if (retryable && !pic_interrupted && attempt < PIC_GENERATION_ATTEMPTS) {
continue;
}
pol->plan_free(&b);
(void)snprintf(s->err, sizeof s->err, "branch summary: %s", err);
return -1;
}
pic_fault("after-branch-summary");
{
char *reply[2] = {text, NULL};
summary = pol->join(&b, reply);
}
free(text);
usage = summary_usage(s, provider->model, usage, NULL);
rc = !summary || pic_begin(s) != 0 ||
branch_commit(s, source, head, at, owner, summary, b.details, generation, usage, out, cap) != 0 ||
pic_commit(s) != 0;
free(summary);
free(usage);
pol->plan_free(&b);
if (rc) {
pic_rollback(s);
return -1;
}
pic_fault("after-branch-summary-entry");
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) {
return pic_queue_add_hooked(s, kind, text, images, nimages, 0);
}
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) {
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_hooks_claim(s, prompt_hooks, 0, sqlite3_last_insert_rowid(s->db)) != 0 ||
(!prompt_hooks && pic_hooks_mark_pending(s, sqlite3_last_insert_rowid(s->db)) != 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 || pic_hooks_claim_queued(s, id, into) != 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, trial, max_requests, model, thinking)"
" SELECT 'queued-' || q.id, q.text, 'admitted', q.session_id, u.trial, u.max_requests, u.model, u.thinking"
" FROM pic_queued q JOIN pic_submission u ON u.id = ?2 WHERE q.id = ?1",
"ii", first, from) != 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),"
" (SELECT i.sender FROM pic_inbox i WHERE i.queued_id = q.id)"
" 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_from(s, (const char *)sqlite3_column_text(q, 0), (const char *)sqlite3_column_text(q, 1),
(const char *)sqlite3_column_text(q, 2));
}
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;
}
/* The request cap: a request that would send its (N+1)th reply request
* stops instead. Counted from the journal, a turn's retries as one, so
* recovery after a crash goes on counting. */
if (attempts == 0) {
sqlite3_int64 cap = 0, sent = 0;
if (query_int(s, "SELECT coalesce(max_requests, 0) FROM pic_submission WHERE id=?", submission, &cap) != 0 ||
(cap > 0 && query_int(s, "SELECT count(DISTINCT turn) FROM pic_generation WHERE submission_id=? AND purpose='reply'",
submission, &sent) != 0)) {
return -1;
}
if (cap > 0 && sent >= cap) {
if (pic_begin(s) != 0 || stop_submission(s, submission, "request_cap") != 0 || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
pic_fault("after-request-cap");
return 0;
}
}
/* Steering queued meanwhile goes before the reply; after a compaction,
* steering that arrived while it ran (Pi polls again there too). Each
* message's prompt hooks have run first. */
if (pic_hooks_run_pending(s) != 0 || deliver_steering(s, submission) != 0) {
return -1;
}
rc = compact_step(s, provider, submission, turn);
if (rc != 0) {
return rc == 2 ? 0 : rc;
}
if (pic_hooks_run_pending(s) != 0 || deliver_steering(s, submission) != 0 || pic_hooks_compact_start(s, submission) != 0) {
return -1;
}
/* Hook context journaled since the last request goes with this one. */
pic_toolset_model(provider->model); /* a tool may be on by default for some models only */
if (pic_begin(s) != 0 || sync_session(s, workspace, provider->context_window, submission) != 0 || pic_hooks_deliver(s, 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';
s->abort_retry = 0;
s->credential[0] = s->credential_label[0] = s->credential_provider[0] = '\0';
s->key_state = s->key_status = 0;
s->key_until_ms = 0;
{ /* the reply's text, for followers, as it streams */
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT session_id, (SELECT coalesce(max(seq), 0) FROM pic_entry) FROM pic_submission WHERE id = ?",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, submission);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) == SQLITE_TEXT) {
pic_live_begin(s, (const char *)sqlite3_column_text(q, 0), sqlite3_column_int64(q, 1));
}
}
sqlite3_finalize(q);
}
rc = provider->reply(provider, s, submission, turn, &reply, &retryable, err, sizeof err);
pic_live_end(s);
if (rc != 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_aborted(s);
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;
}
if (s->no_retry || s->abort_retry) { /* Pi's auto retry off, or its retry aborted */
retryable = 0;
s->abort_retry = 0;
}
/* Too long for the model: compact once, then try again (Pi's
* overflow recovery, off with its automatic compaction). */
if (!retryable && context_overflow(err) && s->policy && s->policy->overflow(provider->model)) {
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;
}
/* Refused for its key (dead, out of credit, limited): with someone
* there to choose (the terminal's swap prompt), the request is left
* unfinished, this attempt failed; the next request asks the turn
* again with whatever key is active then. Never another key here. */
if (!retryable && s->hold_key_failures &&
(s->key_state == PIC_KEY_INVALID || s->key_state == PIC_KEY_CREDIT || s->key_state == PIC_KEY_LIMITED)) {
char *key = NULL;
sqlite3_stmt *q = NULL;
pic_ev_message_error(s, err, (int)attempts + 1, PIC_GENERATION_ATTEMPTS, 0);
if (pic_begin(s) != 0 ||
run_stmt(s, "UPDATE pic_generation SET state='failed', error=?, credential=nullif(?, '') WHERE id=?", "tti",
err, s->credential, generation) != 0 ||
pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
if (sqlite3_prepare_v2(s->db, "SELECT request_key FROM pic_submission WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, submission);
key = sqlite3_step(q) == SQLITE_ROW ? dup_col(q, 0) : NULL;
}
sqlite3_finalize(q);
pic_ev_key_failure(s, key ? key : "", s->credential_provider, s->credential, s->credential_label,
pic_key_state_name((pic_key_state)s->key_state), s->key_status, s->key_until_ms, err);
free(key);
(void)snprintf(s->err, sizeof s->err, "%s", err);
return 3;
}
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=?, credential=nullif(?, '') WHERE id=?", "tti", err,
s->credential, 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");
if (pic_hooks_run_pending(s) != 0) { /* an answer may admit the queue */
pic_reply_free(&reply);
return -1;
}
price_reply(&reply);
if (pic_begin(s) != 0 || record_reply(s, submission, generation, &reply, &fault, &next) != 0 ||
(s->credential[0] && run_stmt(s, "UPDATE pic_generation SET credential=? WHERE id=?", "ti", s->credential, generation) != 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), stop_reason,"
" (SELECT coalesce(v.outcome, v.state) FROM pic_verdict v WHERE v.submission_id = u.id"
" AND u.status = 'answered')"
" 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);
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),
(const char *)sqlite3_column_text(q, 6), (const char *)sqlite3_column_text(q, 7));
}
}
sqlite3_finalize(q);
}
/* What a verdict keeps of each of the verify command's streams. */
#define VERIFY_OUT_MAX 8192
static int verify_cancelled(void *ctx) {
(void)ctx;
return pic_interrupted != 0;
}
/* The request's verdict on its reply SEQ (docs/design/verdict.md): the
* workspace's verify command, journaled as started in its own transaction
* before it runs and done with its outcome after, once per request. A
* verdict already journaled (done, or unknown after a crash) stands: the
* command is never run again. 0, or -1 on error. */
static int verdict(pic_store *s, sqlite3_int64 submission, sqlite3_int64 seq, const char *workspace, int exec_seconds) {
static const char *const env[] = {"PIC_VERIFY=1", NULL};
const pic_executor *ex = pic_executor_get();
pic_spawn_result p;
sqlite3_int64 had = 0;
char *output = NULL, why[200] = "";
const char *outcome;
int rc;
if (!s->verify || pic_interrupted) {
return 0;
}
if (query_int(s, "SELECT count(*) FROM pic_verdict WHERE submission_id = ?", submission, &had) != 0) {
return -1;
}
if (had) {
return 0;
}
if (pic_begin(s) != 0) {
return -1;
}
if (run_stmt(s,
"INSERT INTO pic_verdict(submission_id, entry_seq, command, state, created_ms)"
" VALUES(?, ?, ?, 'started', CAST(unixepoch('subsec') * 1000 AS INTEGER))",
"iit", submission, seq, s->verify) != 0 ||
pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
pic_fault("after-verdict-started");
memset(&p, 0, sizeof p);
if (!ex->spawn) {
(void)snprintf(p.why, sizeof p.why, "this build's executor runs no commands");
} else {
pic_spawn_req q = {s->verify, workspace, "", 0, env, exec_seconds, 0, VERIFY_OUT_MAX, verify_cancelled, NULL};
(void)ex->spawn(ex->state, &q, &p);
}
pic_fault("after-verdict-run");
if (p.timed_out) {
(void)snprintf(why, sizeof why, "timed out after %d s (its process group was killed)", exec_seconds);
} else if (!p.exited && !p.cancelled) {
(void)snprintf(why, sizeof why, "%s", p.why[0] ? p.why : "did not run to an exit");
}
outcome = p.exited && p.code == 0 ? "pass" : "fail";
if (p.out || p.err) {
size_t no = p.out ? strlen(p.out) : 0, ne = p.err ? strlen(p.err) : 0;
if ((output = malloc(no + ne + 2))) {
(void)snprintf(output, no + ne + 2, "%s%s%s", p.out ? p.out : "", no && ne ? "\n" : "", p.err ? p.err : "");
}
}
if (pic_begin(s) != 0) {
free(p.out);
free(p.err);
free(output);
return -1;
}
/* Cut off by Ctrl-C: whatever it did, it said nothing, and the request is cancelled. */
rc = p.cancelled ? run_stmt(s,
"UPDATE pic_verdict SET state = 'unknown', error = 'cancelled before it finished',"
" duration_ms = ?, output = ? WHERE submission_id = ? AND state = 'started'",
"iti", (sqlite3_int64)p.ms, output, submission)
: run_stmt(s,
"UPDATE pic_verdict SET state = 'done', outcome = ?, exit_code = nullif(?, -1), duration_ms = ?,"
" error = nullif(?, ''), output = ? WHERE submission_id = ? AND state = 'started'",
"tiitti", outcome, p.exited ? (sqlite3_int64)p.code : (sqlite3_int64)-1,
(sqlite3_int64)p.ms, why, output, submission);
free(p.out);
free(p.err);
free(output);
if (rc != 0 || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
pic_fault("after-verdict");
return 0;
}
/* Continuations a request's Stop hooks get before a block is ignored. */
#define PIC_STOP_BLOCKS 5
#define STR_GUARD "5"
/* A finished reply waiting for its Stop hooks (record_reply left it an
* assistant turn). The hooks run, each journaled before it starts; their
* decision is then read back from the journal and its effect commits: the
* reply becomes the answer, or a block's reason goes to the model as a hook
* entry and the request goes on. Driven by the journal, so a reply left
* waiting by a crash is settled without running its hooks again (a run cut
* off blocks nothing), hooks configured or not. 1: nothing waiting;
* 0: settled (or Ctrl-C); -1 on error. */
static int stop_gate(pic_store *s, sqlite3_int64 submission, const char *workspace, int exec_seconds) {
sqlite3_int64 seq = 0, before = 0, rows = 0, entry = 0, next = 0;
char *reason = NULL;
int rc = 0, guard = 0, goal_fired = 0;
if (query_int(s,
"SELECT e.seq FROM pic_entry e JOIN pic_generation g ON g.entry_seq = e.seq AND g.state = 'done'"
" WHERE e.submission_id = ?1 AND e.kind = 'assistant'"
" AND e.seq = (SELECT max(seq) FROM pic_entry WHERE submission_id = ?1)"
" AND coalesce(g.stop_reason, '') NOT IN ('pause', 'refusal')"
" AND NOT EXISTS (SELECT 1 FROM pic_effect x WHERE x.entry_seq = e.seq)",
submission, &seq) != 0) {
return -1;
}
if (!seq) {
return 1;
}
if (query_int2(s,
"SELECT count(DISTINCT ref) FROM pic_hook_run WHERE event = 'Stop' AND submission_id = ? AND outcome = 'block'"
" AND ref < ?",
submission, seq, &before) != 0 ||
query_int(s, "SELECT count(*) FROM pic_hook_run WHERE event = 'Stop' AND ref = ?", seq, &rows) != 0) {
return -1;
}
if (!rows && pic_hooks_has(s->hooks, "Stop")) {
pic_hook_fire f;
memset(&f, 0, sizeof f);
f.event = "Stop";
f.submission = submission;
f.ref = seq;
session_id_of(s, submission, f.session);
rc = pic_hook_fire_run(s, &f, NULL, before ? "{\"stop_hook_active\":true}" : "{\"stop_hook_active\":false}");
pic_hook_fire_free(&f);
if (rc != 0) {
return -1;
}
}
if (pic_interrupted) {
return 0; /* pic_run cancels the request */
}
{
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db,
"SELECT group_concat(reason, char(10)) FROM (SELECT reason FROM pic_hook_run WHERE event = 'Stop'"
" AND ref = ? AND state = 'done' AND outcome = 'block' ORDER BY id)",
-1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_int64(q, 1, seq);
if (sqlite3_step(q) == SQLITE_ROW) {
reason = dup_col(q, 0);
}
sqlite3_finalize(q);
}
guard = reason && before >= PIC_STOP_BLOCKS; /* a hook that never lets go: the reply stands */
/* The reply stands: the request is about to end answered, so its verdict comes first. */
if ((!reason || guard) && verdict(s, submission, seq, workspace, exec_seconds) != 0) {
free(reason);
return -1;
}
if (pic_interrupted) {
free(reason);
return 0; /* pic_run cancels the request */
}
/* The reply stands: a goal of the conversation is checked and judged (policy.h), and acted on
* in the transaction that makes it the answer. */
if ((!reason || guard) && pic_wake_goal_judge(s, submission, workspace, exec_seconds) != 0) {
free(reason);
return -1;
}
if (pic_interrupted) {
free(reason);
return 0;
}
if (pic_begin_outer(s) != 0) { /* the goal's next round goes to the inbox inside it */
free(reason);
return -1;
}
if (reason && !guard) {
char *feedback = pic_hooks_stop_feedback(reason);
rc = !feedback || append_entry(s, submission, "hook", feedback) != 0 ? -1 : 0;
entry = sqlite3_last_insert_rowid(s->db);
rc = rc ||
run_stmt(s, "UPDATE pic_hook_run SET entry_seq = ? WHERE event = 'Stop' AND ref = ? AND outcome = 'block'", "ii",
entry, seq) != 0;
free(feedback);
} else {
rc = (guard && run_stmt(s,
"UPDATE pic_hook_run SET error = 'loop guard: ignored after " STR_GUARD
" Stop hook continuations' WHERE event = 'Stop' AND ref = ? AND outcome = 'block'",
"i", seq) != 0) ||
run_stmt(s, "UPDATE pic_entry SET kind = 'answer' WHERE seq = ?", "i", seq) != 0 ||
run_stmt(s, "UPDATE pic_submission SET status = 'answered' WHERE id = ?", "i", submission) != 0 ||
admit_next(s, submission, &next) < 0 || pic_wake_goal_apply(s, submission, &goal_fired) != 0;
}
free(reason);
if (rc != 0 || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
pic_fault("after-stop-hook");
if (next) {
s->running = next;
pic_queue_event(s);
} else if (goal_fired) { /* the goal's next round: this process holds the lease, so it runs it */
char sid[64];
session_id_of(s, submission, sid);
pic_inbox_ring(s, sid);
if (sid[0] && pic_inbox_wake(s, sid, 0) < 0) {
return -1;
}
}
return 0;
}
/* What `pic ps` records with the processes started for SUBMISSION. */
static void scope_processes(pic_store *s, const char *workspace, sqlite3_int64 submission) {
sqlite3_stmt *q = NULL;
const char *session = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, submission);
if (sqlite3_step(q) == SQLITE_ROW) {
session = (const char *)sqlite3_column_text(q, 0);
}
}
pic_proc_scope(workspace, session);
sqlite3_finalize(q);
}
/* What pic_run has claimed. took: the conversation whose lease the last
* choice took (not one this process came with), given back once it has no
* request left. plain: pic run, asked for whatever is unfinished, which
* waits once for holders on their way out and says what it left to others. */
typedef struct {
char took[64];
int plain, waited;
} run_claim;
/* The oldest admitted request whose conversation this process holds or can
* take, the running conversation's first (only its own with session_only),
* passing over the NSKIP in SKIP, in *submission (0: none). A
* conversation another process is working is left to it. Taking a lease
* settles what a dead owner left (pic_lease); the request is read again
* once it is held, since only its holder changes it. */
static int next_request(pic_store *s, run_claim *c, const sqlite3_int64 *skip, size_t nskip, sqlite3_int64 *submission) {
*submission = 0;
if (c->took[0]) {
sqlite3_stmt *q = NULL;
int more = 1;
if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_submission WHERE session_id = ? AND status = 'admitted'", -1,
&q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, c->took, -1, SQLITE_STATIC);
more = sqlite3_step(q) != SQLITE_ROW || sqlite3_column_int(q, 0) != 0;
}
sqlite3_finalize(q);
if (!more) {
pic_unlease(s, c->took);
c->took[0] = '\0';
}
}
for (;;) {
struct {
sqlite3_int64 id;
char session[64], key[128];
} *found = NULL, *grown;
size_t n = 0, held = 0;
sqlite3_stmt *q = NULL;
int rc = 0;
if (sqlite3_prepare_v2(s->db,
"SELECT id, session_id, request_key FROM pic_submission WHERE status='admitted'"
" AND (?2 = 0 OR session_id IS (SELECT session_id FROM pic_submission WHERE id = ?1)) ORDER BY"
" session_id IS NOT (SELECT session_id FROM pic_submission WHERE id = ?1),"
" NOT pic_leased(session_id), id", /* one under way is finished before another is begun */
-1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_int64(q, 1, (sqlite3_int64)s->running);
sqlite3_bind_int64(q, 2, (sqlite3_int64)s->session_only);
while (sqlite3_step(q) == SQLITE_ROW) {
size_t k = 0;
while (k < nskip && skip[k] != sqlite3_column_int64(q, 0)) {
k++;
}
if (k < nskip) {
continue; /* its model cannot be had here */
}
if (!(grown = realloc(found, (n + 1) * sizeof *found))) {
break;
}
found = grown;
found[n].id = sqlite3_column_int64(q, 0);
(void)snprintf(found[n].session, sizeof found[n].session, "%s", (const char *)sqlite3_column_text(q, 1));
(void)snprintf(found[n].key, sizeof found[n].key, "%s", (const char *)sqlite3_column_text(q, 2));
n++;
}
sqlite3_finalize(q);
for (size_t i = 0; i < n && rc == 0 && !*submission; i++) {
int had = pic_leased(s, found[i].session);
sqlite3_int64 still = 0;
rc = pic_lease(s, found[i].session, 0);
if (rc == 1) { /* its owner is alive */
found[held++] = found[i];
s->err[0] = '\0';
rc = 0;
continue;
}
if (rc == 0 && (rc = query_int(s, "SELECT status = 'admitted' FROM pic_submission WHERE id = ?", found[i].id,
&still)) == 0) {
if (still) {
*submission = found[i].id;
if (!had) {
(void)snprintf(c->took, sizeof c->took, "%s", found[i].session);
}
} else if (!had) {
pic_unlease(s, found[i].session); /* finished by an owner since gone */
}
}
}
if (rc != 0 || *submission || !held || !c->plain) {
free(found);
return rc;
}
if (c->waited < PIC_LEASE_WAIT_MS) { /* a holder on its way out lets go in moments */
free(found);
c->waited += 20;
(void)usleep(20000);
continue;
}
for (size_t i = 0; i < held; i++) {
long pid = pic_lease_holder(s, found[i].session);
if (pid > 0) {
fprintf(stderr, "pic: request %s is being run by another pic process (pid %ld); left to it\n", found[i].key, pid);
} else if (pid) {
fprintf(stderr, "pic: request %s is being run by another pic process; left to it\n", found[i].key);
}
}
free(found);
return 0;
}
}
/* The provider for SUBMISSION's own model and thinking level, as it was
* admitted (s->provider_for makes it); one admitted without keeps PROVIDER. */
static int switch_provider(pic_store *s, pic_provider *provider, sqlite3_int64 submission) {
sqlite3_stmt *q = NULL;
int rc = 0;
if (!s->provider_for) {
return 0;
}
if (sqlite3_prepare_v2(s->db, "SELECT model, thinking FROM pic_submission WHERE id = ? AND model IS NOT NULL", -1, &q,
NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_int64(q, 1, submission);
if (sqlite3_step(q) == SQLITE_ROW) {
rc = s->provider_for(s, provider, (const char *)sqlite3_column_text(q, 0), (const char *)sqlite3_column_text(q, 1));
}
sqlite3_finalize(q);
return rc;
}
static int run_requests(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] = "";
run_claim claim = {.plain = s->running == 0};
/* Requests whose own model cannot be had here: left admitted for a run that has it. */
sqlite3_int64 skip[64];
size_t nskip = 0;
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);
/* Prompt hooks of messages queued meanwhile (or before a crash). */
if (pic_hooks_run_pending(s) != 0) {
return -1;
}
/* The oldest admitted request this process may run, the running
* conversation's first. */
if (next_request(s, &claim, skip, nskip, &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 (submission && open != submission) { /* a pic its tool calls or hooks start is its agent */
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, submission);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
pic_session_env(s, (const char *)sqlite3_column_text(q, 0));
}
}
sqlite3_finalize(q);
}
if (open && open != submission) {
request_event(s, provider, open, 0);
}
if (submission && open != submission && switch_provider(s, provider, submission) != 0) {
/* Its model cannot be had here (no key, gone from the registry):
* it is never run with another, nor failed for it; it stays
* admitted, untouched, for a run that has the model. */
char *sid = NULL, why[PIC_ERR_CAP];
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, submission);
sid = sqlite3_step(q) == SQLITE_ROW ? dup_col(q, 0) : NULL;
}
sqlite3_finalize(q);
(void)snprintf(why, sizeof why, "request %lld of conversation %s left unfinished: %s", (long long)submission,
sid ? sid : "-", s->err);
/* Not run here: its conversation is free for a pic that has the model. */
if (sid && strcmp(claim.took, sid) == 0) {
pic_unlease(s, sid);
claim.took[0] = '\0';
}
free(sid);
fprintf(stderr, "pic: %s\n", why);
if (nskip == sizeof skip / sizeof skip[0]) {
(void)snprintf(s->err, sizeof s->err, "%s", why);
return -1;
}
skip[nskip++] = submission;
open = 0; /* its predecessor's end event went out above */
continue;
}
if (submission && open != submission) {
sqlite3_int64 last = 0;
if (query_int(s, "SELECT coalesce(max(seq), 0) FROM pic_entry", 0, &last) != 0) {
return -1;
}
s->run_since = last;
request_event(s, provider, submission, 1);
}
open = submission;
if (submission) {
scope_processes(s, workspace, submission);
/* Messages from other processes (pic send, pic attach): this
* process holds the running request's lease, so it delivers. */
pic_inbox_poll(s);
}
if (pic_interrupted) { /* Ctrl-C: cancel this request, keep the rest for later */
pic_interrupted = 0;
pic_fault("before-cancel");
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) {
pic_fault("run-end"); /* the last look at the inbox was taken; the conversation is still held */
if (any_failed) {
(void)snprintf(s->err, sizeof s->err, "%s", failure);
} else if (nskip) {
(void)snprintf(s->err, sizeof s->err, "%zu unfinished request%s left for a run that has %s model", nskip,
nskip == 1 ? "" : "s", nskip == 1 ? "its" : "their");
}
return any_failed || nskip ? -1 : 0;
}
rc = run_pending(s, workspace, exec_seconds, submission);
/* PostToolUse after each call; again before the next reply, for a
* call whose hooks a crash cut off. */
if (rc == 0) {
rc = pic_hooks_post_tools(s, submission);
} else if (rc == 1 && (rc = pic_hooks_post_tools(s, submission)) == 0) {
rc = stop_gate(s, submission, workspace, exec_seconds);
}
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;
} else if (rc == 3) {
/* Refused for its key and left for the user's choice: not run
* again here, and its conversation let go for the run that
* follows the choice. */
char *sid = NULL;
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_int64(q, 1, submission);
sid = sqlite3_step(q) == SQLITE_ROW ? dup_col(q, 0) : NULL;
}
sqlite3_finalize(q);
request_event(s, provider, submission, 0);
if (sid && strcmp(claim.took, sid) == 0) {
pic_unlease(s, sid);
claim.took[0] = '\0';
}
free(sid);
any_failed = 1;
(void)snprintf(failure, sizeof failure, "%s", s->err);
if (nskip == sizeof skip / sizeof skip[0]) {
return -1;
}
skip[nskip++] = submission;
open = 0;
rc = 0;
}
}
if (rc != 0) {
return -1;
}
}
}
int pic_run(pic_store *s, const char *workspace, pic_provider *provider, int exec_seconds) {
int rc = run_requests(s, workspace, provider, exec_seconds);
pic_inbox_stop();
return rc;
}
/* Canonical journal listing for tests and inspection. */
int pic_dump(pic_store *s) {
static const char *const queries[] = {
("SELECT 'submission', id, request_key, status || coalesce(' stop=' || stop_reason, '') || coalesce(' trial=' || trial, '')"
" || coalesce(' max=' || max_requests, ''), 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 'nested', id, parent_id || '.' || position, tool || ' ' || state || ' safe=' || replay_safe,"
" coalesce(result,'') FROM pic_nested_effect ORDER BY id"),
("SELECT 'generation', id, submission_id || '.' || turn || '.' || attempt,"
" state || coalesce(' stop=' || stop_reason, '') || CASE WHEN purpose != 'reply' THEN ' ' || purpose ELSE '' END"
" || coalesce(' reason=' || reason, '') || coalesce(' idle=' || idle_seconds, '') || coalesce(' tokens=' || context_tokens, ''),"
" 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"),
("SELECT 'hook', id, event || coalesce(' ' || session_id, '') || ' ref=' || coalesce(ref, 0),"
" 'exit=' || coalesce(exit_code, '-') || ' ms=' || coalesce(duration_ms, 0) || coalesce(' ' || outcome, '')"
" || coalesce(' entry=' || entry_seq, ''),"
" coalesce(command, '(end of firing)') || coalesce(' error=' || error, '') || coalesce(' reason=' || reason, '')"
" || coalesce(' context=' || context, '') FROM pic_hook_run ORDER BY id"),
("SELECT 'verdict', submission_id, 'entry=' || entry_seq, state || coalesce(' ' || outcome, '')"
" || coalesce(' exit=' || exit_code, '') || ' ms=' || coalesce(duration_ms, 0),"
" command || coalesce(' error=' || error, '') FROM pic_verdict ORDER BY submission_id"),
};
/* One read transaction: one state of a journal others may be writing. */
if (pic_exec(s, "BEGIN") != 0) {
return -1;
}
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) {
int rc = sql_fail(s);
pic_rollback(s);
return rc;
}
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);
}
pic_rollback(s);
return 0;
}
/* pic usage --by-trial: each arm's requests and what their provider
* requests used and cost (summary requests included), from the usage each
* done generation journaled with its price (pic_tokens, pic_cost); and, once
* any answered request has a verdict, how many of each arm's passed and
* failed (unknown too, once any is). */
int pic_usage_by_trial(pic_store *s, int json, FILE *out) {
sqlite3_stmt *q = NULL;
sqlite3_int64 verdicts = 0, unknown = 0;
int step;
if (query_int(s,
"SELECT count(*) FROM pic_verdict v JOIN pic_submission u ON u.id = v.submission_id"
" WHERE u.status = 'answered' AND v.state != 'started'",
0, &verdicts) != 0 ||
query_int(s,
"SELECT count(*) FROM pic_verdict v JOIN pic_submission u ON u.id = v.submission_id"
" WHERE u.status = 'answered' AND v.state = 'unknown'",
0, &unknown) != 0) {
return -1;
}
if (sqlite3_prepare_v2(
s->db,
"SELECT trial, submissions, requests, input, output, cache_read, cache_write, cost, passed, failed, unknown,"
" CASE WHEN ?2 THEN json_set(base, '$.passed', passed, '$.failed', failed, '$.unknown', unknown)"
" WHEN ?1 THEN json_set(base, '$.passed', passed, '$.failed', failed) ELSE base END"
" FROM (SELECT *, json_object('trial', trial, 'submissions', submissions, 'requests', requests, 'input', input,"
" 'output', output, 'cacheRead', cache_read, 'cacheWrite', cache_write, 'cost', cost) AS base,"
" (SELECT count(*) FILTER (WHERE v.outcome = 'pass') FROM pic_verdict v JOIN pic_submission w"
" ON w.id = v.submission_id AND w.status = 'answered' WHERE w.trial IS t.trial) AS passed,"
" (SELECT count(*) FILTER (WHERE v.outcome = 'fail') FROM pic_verdict v JOIN pic_submission w"
" ON w.id = v.submission_id AND w.status = 'answered' WHERE w.trial IS t.trial) AS failed,"
" (SELECT count(*) FILTER (WHERE v.state = 'unknown') FROM pic_verdict v JOIN pic_submission w"
" ON w.id = v.submission_id AND w.status = 'answered' WHERE w.trial IS t.trial) AS unknown"
" FROM (SELECT u.trial AS trial, count(DISTINCT u.id) AS submissions, count(g.id) AS requests,"
" sum(coalesce(json_extract(g.usage,'$.pic_tokens.input'), json_extract(g.usage,'$.input_tokens'),"
" json_extract(g.usage,'$.prompt_tokens'), 0)) AS input,"
" sum(coalesce(json_extract(g.usage,'$.pic_tokens.output'), json_extract(g.usage,'$.output_tokens'),"
" json_extract(g.usage,'$.completion_tokens'), 0)) AS output,"
" sum(coalesce(json_extract(g.usage,'$.pic_tokens.cacheRead'), json_extract(g.usage,'$.cache_read_input_tokens'), 0))"
" AS cache_read,"
" sum(coalesce(json_extract(g.usage,'$.pic_tokens.cacheWrite'), json_extract(g.usage,'$.cache_creation_input_tokens'), 0))"
" AS cache_write,"
" coalesce(sum(json_extract(g.usage,'$.pic_cost.total')), 0) AS cost"
" FROM pic_submission u JOIN pic_generation g ON g.submission_id = u.id AND g.state = 'done' AND json_valid(g.usage)"
" AND json_extract(g.usage,'$.imported') IS NULL"
" GROUP BY u.trial) t) ORDER BY trial IS NULL, trial",
-1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_int(q, 1, verdicts > 0);
sqlite3_bind_int(q, 2, unknown > 0);
if (!json) {
fprintf(out, "%-24s %11s %8s %12s %12s %12s %12s %12s", "trial", "submissions", "requests", "input", "output",
"cacheRead", "cacheWrite", "cost");
fprintf(out, verdicts ? (unknown ? " %8s %8s %8s\n" : " %8s %8s\n") : "\n", "passed", "failed", "unknown");
}
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
if (json) {
fprintf(out, "%s\n", (const char *)sqlite3_column_text(q, 11));
} else {
fprintf(out, "%-24s %11lld %8lld %12lld %12lld %12lld %12lld %12.6f",
sqlite3_column_text(q, 0) ? (const char *)sqlite3_column_text(q, 0) : "(none)",
(long long)sqlite3_column_int64(q, 1), (long long)sqlite3_column_int64(q, 2),
(long long)sqlite3_column_int64(q, 3), (long long)sqlite3_column_int64(q, 4),
(long long)sqlite3_column_int64(q, 5), (long long)sqlite3_column_int64(q, 6), sqlite3_column_double(q, 7));
fprintf(out, verdicts ? (unknown ? " %8lld %8lld %8lld\n" : " %8lld %8lld\n") : "\n",
(long long)sqlite3_column_int64(q, 8), (long long)sqlite3_column_int64(q, 9),
(long long)sqlite3_column_int64(q, 10));
}
}
sqlite3_finalize(q);
return step == SQLITE_DONE ? 0 : sql_fail(s);
}
/* pic usage --by-tool: per tool name, its calls and failures, and the requests that called it
* with what they used and cost. A request that called several tools counts toward each of them. */
int pic_usage_by_tool(pic_store *s, int json, FILE *out) {
sqlite3_stmt *q = NULL;
int step;
if (sqlite3_prepare_v2(
s->db,
"SELECT tool, calls, failures, requests, input, output, cache_read, cache_write, cost,"
" json_object('tool', tool, 'calls', calls, 'failures', failures, 'requests', requests, 'input', input,"
" 'output', output, 'cacheRead', cache_read, 'cacheWrite', cache_write, 'cost', cost)"
" FROM (SELECT c.tool AS tool, sum(c.calls) AS calls, sum(c.failures) AS failures, count(g.id) AS requests,"
" sum(coalesce(json_extract(g.usage,'$.pic_tokens.input'), json_extract(g.usage,'$.input_tokens'),"
" json_extract(g.usage,'$.prompt_tokens'), 0)) AS input,"
" sum(coalesce(json_extract(g.usage,'$.pic_tokens.output'), json_extract(g.usage,'$.output_tokens'),"
" json_extract(g.usage,'$.completion_tokens'), 0)) AS output,"
" sum(coalesce(json_extract(g.usage,'$.pic_tokens.cacheRead'), json_extract(g.usage,'$.cache_read_input_tokens'), 0))"
" AS cache_read,"
" sum(coalesce(json_extract(g.usage,'$.pic_tokens.cacheWrite'), json_extract(g.usage,'$.cache_creation_input_tokens'), 0))"
" AS cache_write,"
" coalesce(sum(json_extract(g.usage,'$.pic_cost.total')), 0) AS cost"
" FROM (SELECT tool, entry_seq, count(*) AS calls, sum(is_error) AS failures FROM pic_effect"
" GROUP BY tool, entry_seq) c"
" LEFT JOIN pic_generation g ON g.entry_seq = c.entry_seq AND g.state = 'done' AND g.purpose = 'reply'"
" AND json_valid(g.usage) AND json_extract(g.usage,'$.imported') IS NULL"
" GROUP BY c.tool) ORDER BY tool",
-1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
if (!json) {
fprintf(out, "%-24s %8s %9s %8s %12s %12s %12s %12s %12s\n", "tool", "calls", "failures", "requests", "input", "output",
"cacheRead", "cacheWrite", "cost");
}
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
if (json) {
fprintf(out, "%s\n", (const char *)sqlite3_column_text(q, 9));
} else {
fprintf(out, "%-24s %8lld %9lld %8lld %12lld %12lld %12lld %12lld %12.6f\n",
(const char *)sqlite3_column_text(q, 0), (long long)sqlite3_column_int64(q, 1),
(long long)sqlite3_column_int64(q, 2), (long long)sqlite3_column_int64(q, 3),
(long long)sqlite3_column_int64(q, 4), (long long)sqlite3_column_int64(q, 5),
(long long)sqlite3_column_int64(q, 6), (long long)sqlite3_column_int64(q, 7), sqlite3_column_double(q, 8));
}
}
sqlite3_finalize(q);
return step == SQLITE_DONE ? 0 : sql_fail(s);
}
/* The frozen system prompt or tools of a submission's session (malloc'd).
* column is "system_prompt" or "tools"; set by the first generation. */
/* The frozen tools TOOLS (a JSON array, freed) and the deferred tools its branch's tool_search
* results revealed that the registry still has, in the order they were revealed (malloc'd). */
static char *with_revealed(pic_store *s, int64_t submission, char *tools) {
sqlite3_stmt *q = NULL;
if (!tools || sqlite3_prepare_v2(s->db, REVEALED_SQL, -1, &q, NULL) != SQLITE_OK) {
return tools; /* a journal opened narrowly has no such table */
}
sqlite3_bind_int64(q, 1, submission);
while (sqlite3_step(q) == SQLITE_ROW) {
const pic_tool_def *d = pic_tool_named((const char *)sqlite3_column_text(q, 0));
sqlite3_stmt *m = NULL;
if (d && !pic_tool_codemode_only(d) && sqlite3_prepare_v2(s->db,
"SELECT json_insert(?1, '$[#]', json(?2)) WHERE NOT EXISTS"
" (SELECT 1 FROM json_each(?1) WHERE json_extract(value, '$.name') = ?3)",
-1, &m, NULL) == SQLITE_OK) {
sqlite3_bind_text(m, 1, tools, -1, SQLITE_STATIC);
sqlite3_bind_text(m, 2, d->schema, -1, SQLITE_STATIC);
sqlite3_bind_text(m, 3, d->name, -1, SQLITE_STATIC);
if (sqlite3_step(m) == SQLITE_ROW && sqlite3_column_text(m, 0)) {
char *grown = dup_col(m, 0);
if (grown) {
free(tools);
tools = grown;
}
}
}
sqlite3_finalize(m);
}
sqlite3_finalize(q);
return tools;
}
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 strcmp(column, "tools") == 0 ? with_revealed(s, submission, out) : 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 s.id FROM pic_session s WHERE " PIC_LISTED_SQL("s") " ORDER BY s.updated_ms DESC, s.rowid DESC LIMIT 1"
: "SELECT s.id FROM pic_session s WHERE (s.id = ?1 OR s.id LIKE ?1 || '%') AND NOT " PIC_PURGED_SQL("s") " 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, int archived, FILE *out) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(
s->db,
"SELECT s.id, 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(" PIC_TITLE_SQL("s") ", '(forked from ' || s.forked_from || ')', '-'),"
" coalesce((SELECT u.model FROM pic_submission u WHERE u.session_id = s.id AND u.model IS NOT NULL"
" ORDER BY u.id DESC LIMIT 1), '-'),"
" coalesce((SELECT u.status = 'failed' AND coalesce(u.error, '') != 'cancelled' FROM pic_submission u"
" WHERE u.session_id = s.id ORDER BY u.id DESC LIMIT 1), 0)"
" FROM pic_session s WHERE " PIC_LISTED_SQL("s") " AND (" PIC_ARCHIVED_SQL("s") ") = ?1"
" ORDER BY s.updated_ms DESC, s.rowid DESC",
-1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_int(q, 1, archived != 0);
while (sqlite3_step(q) == SQLITE_ROW) {
/* One another pic process is working says so, and which. */
long pid = pic_lease_holder(s, (const char *)sqlite3_column_text(q, 0));
char who[48] = "";
if (pid > 0 && pid != (long)getpid()) {
(void)snprintf(who, sizeof who, " (in use by pid %ld)", pid);
} else if (pid < 0) {
(void)snprintf(who, sizeof who, " (in use)");
}
fprintf(out, "%s %s %3lld %s %s%s%s\n", (const char *)sqlite3_column_text(q, 0), (const char *)sqlite3_column_text(q, 1),
(long long)sqlite3_column_int64(q, 2), (const char *)sqlite3_column_text(q, 4),
(const char *)sqlite3_column_text(q, 3), sqlite3_column_int(q, 5) ? " (last request failed)" : "", who);
}
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 CASE WHEN b.entry_seq IS NOT NULL THEN '$ ' || b.command ||"
" CASE WHEN b.exclude THEN ' (not sent to the model)' ELSE '' END ||"
" CASE WHEN b.cancelled THEN ' (cancelled)' WHEN b.exit_code IS NOT NULL AND b.exit_code != 0"
" THEN ' (exit ' || b.exit_code || ')' ELSE '' END || char(10) || b.output ELSE e.body END"
" WHEN 'tool_result' THEN substr(replace(e.body, char(10), ' '), 1, 100)"
" WHEN 'instructions' THEN 'project instructions updated'"
" WHEN 'hook' THEN 'hook: ' || replace(replace(replace(e.body, '<system-reminder>' || char(10), ''),"
" char(10) || '</system-reminder>', ''), char(10), ' ')"
" WHEN 'compaction' THEN 'compacted ' || coalesce(e.tokens_before, 0) || ' tokens; the summary:' || char(10) || e.body"
" WHEN 'branch_summary' THEN 'branch summary (of the branch ending at ' || e.from_seq || '):' || 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, u.stop_reason, ''),"
" e.seq = (SELECT max(x.seq) FROM pic_entry x WHERE x.submission_id = e.submission_id AND x.kind != 'branch_summary'),"
" 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), ''),"
" b.entry_seq IS NOT NULL,"
" (SELECT CASE WHEN v.outcome = 'pass' THEN 'passed' WHEN v.outcome = 'fail' THEN 'failed'"
" || coalesce(', exit ' || v.exit_code, coalesce(', ' || v.error, ''))"
" ELSE 'unknown, interrupted; not run again' END"
" FROM pic_verdict v WHERE v.submission_id = u.id AND v.state != 'started' AND u.status = 'answered')"
" FROM pic_entry e JOIN p ON p.seq = e.seq JOIN pic_submission u ON u.id = e.submission_id"
" LEFT JOIN pic_bash b ON b.entry_seq = e.seq 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 && sqlite3_column_int(q, 8)) {
fprintf(out, "\n[%lld] bash %s\n", (long long)sqlite3_column_int64(q, 0), text);
} else 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 || strcmp(kind, "branch_summary") == 0) {
fprintf(out, "[%lld] (%s)\n", (long long)sqlite3_column_int64(q, 0), text);
} else if (strcmp(kind, "instructions") == 0 || strcmp(kind, "hook") == 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, or its verdict. */
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);
} else if (strcmp(status, "stopped") == 0) {
fprintf(out, " (request stopped: %s; it can be continued)\n", error);
} else if (sqlite3_column_text(q, 9)) {
fprintf(out, " (verify: %s)\n", (const char *)sqlite3_column_text(q, 9));
}
}
}
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,
/* A branch summary belongs to the request it was made at, but to
* the conversation it starts: the first made of those whose path
* holds it (later ones are forks of that one). */
"WITH RECURSIVE w(sid, r, seq, target) AS (SELECT s.id, s.rowid, s.head_seq, b.seq FROM pic_session s"
" JOIN pic_entry b ON b.kind = 'branch_summary' AND b.seq > ?1 AND s.head_seq >= b.seq"
" UNION ALL SELECT w.sid, w.r, x.parent_seq, w.target FROM w JOIN pic_entry x ON x.seq = w.seq"
" WHERE x.seq > w.target AND x.parent_seq IS NOT NULL),"
" owner(seq, sid, r) AS (SELECT target, sid, min(r) FROM w WHERE seq = target GROUP BY target)"
" SELECT json_patch('{}', json_object('conversation', coalesce(o.sid, 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"
" LEFT JOIN owner o ON o.seq = e.seq"
" 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);
}
int pic_model_usable(const char *model, const char *label, char *why, size_t cap) {
pic_model m;
char err[256];
why[0] = '\0';
if (pic_model_resolve(model, &m, err, sizeof err) != 0) {
(void)snprintf(why, cap, "this conversation ran on %s, which pic no longer knows", model);
return PIC_MODEL_UNKNOWN;
}
/* a server that needs no key (no variable, no literal) is always usable */
if ((m.key_env[0] || m.key_literal[0]) && pic_cred_source_of(m.provider, m.key_env, m.key_literal) == PIC_CRED_NONE) {
(void)snprintf(why, cap, "this conversation ran on %s, and %s has no key now", model, m.provider);
return PIC_MODEL_NO_KEY;
}
if (label && *label && !pic_cred_has(m.provider, label, m.key_env, m.key_literal)) {
(void)snprintf(why, cap, "this conversation ran on %s with the key \"%s\", which %s no longer has", model, label,
m.provider);
return PIC_MODEL_KEY_GONE;
}
return PIC_MODEL_USABLE;
}
/* The latest request with a model along the conversation and the ones it was forked from (the
* nearest first), and the credential of the last reply to that model's provider. */
static const char choice_sql[] =
"WITH RECURSIVE f(id, n) AS (SELECT ?1, 0 UNION ALL SELECT s.forked_from, f.n + 1 FROM f JOIN pic_session s"
" ON s.id = f.id WHERE s.forked_from IS NOT NULL AND f.n < 32),"
" c AS (SELECT u.model, u.thinking FROM f JOIN pic_submission u ON u.session_id = f.id"
" WHERE u.model IS NOT NULL ORDER BY f.n, u.id DESC LIMIT 1)"
" SELECT c.model, c.thinking, (SELECT g.credential FROM f JOIN pic_submission v ON v.session_id = f.id"
" JOIN pic_generation g ON g.submission_id = v.id WHERE g.credential IS NOT NULL"
" AND substr(v.model, 1, instr(v.model, '/')) = substr(c.model, 1, instr(c.model, '/'))"
" ORDER BY f.n, g.id DESC LIMIT 1) FROM c";
/* The label of the credential named NAME (cred.h's names) for PROVIDER, or "". */
static void choice_label(const char *provider, const char *name, char *out, size_t cap) {
size_t n = strlen(provider);
out[0] = '\0';
if (strcmp(name, provider) == 0) {
(void)snprintf(out, cap, "default");
} else if (strncmp(name, provider, n) == 0 && name[n] == ':') {
(void)snprintf(out, cap, "%s", name + n + 1);
} else if (strncmp(name, "env:", 4) == 0) {
(void)snprintf(out, cap, "env");
} else if (strncmp(name, "file:", 5) == 0) {
(void)snprintf(out, cap, "file");
}
}
static int session_choice(pic_store *s, const char *id, char *model, size_t mcap, char *thinking, size_t tcap,
char *label, size_t lcap) {
sqlite3_stmt *q = NULL;
int found = 0;
model[0] = thinking[0] = label[0] = '\0';
if (sqlite3_prepare_v2(s->db, choice_sql, -1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
const char *m = (const char *)sqlite3_column_text(q, 0), *slash = strchr(m, '/');
found = 1;
(void)snprintf(model, mcap, "%s", m);
(void)snprintf(thinking, tcap, "%s", sqlite3_column_text(q, 1) ? (const char *)sqlite3_column_text(q, 1) : "");
if (slash && sqlite3_column_text(q, 2)) {
char provider[64];
(void)snprintf(provider, sizeof provider, "%.*s", (int)(slash - m), m);
choice_label(provider, (const char *)sqlite3_column_text(q, 2), label, lcap);
}
}
sqlite3_finalize(q);
return found;
}
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) {
char id[64], saved[PIC_ERR_CAP];
model[0] = thinking[0] = label[0] = '\0';
(void)snprintf(saved, sizeof saved, "%s", s->err);
if (resolve_session(s, session, id, sizeof id) != 0) {
(void)snprintf(s->err, sizeof s->err, "%s", saved); /* no such conversation: the request says so */
return 0;
}
return session_choice(s, id, model, mcap, thinking, tcap, label, lcap);
}
char *pic_session_last_line(pic_store *s, const char *session, size_t max) {
sqlite3_stmt *q = NULL;
char *line = NULL;
/* Back from the head along the path: a branch left behind is not this conversation's. */
if (sqlite3_prepare_v2(s->db,
"WITH RECURSIVE p(seq, n) AS (SELECT head_seq, 0 FROM pic_session WHERE id = ?1"
" UNION ALL SELECT e.parent_seq, p.n + 1 FROM p JOIN pic_entry e ON e.seq = p.seq"
" WHERE e.parent_seq IS NOT NULL AND p.n < 400)"
" SELECT t FROM (SELECT p.n AS n, CASE WHEN e.kind = 'user' THEN e.body WHEN json_valid(e.body) THEN"
" (SELECT group_concat(json_extract(c.value, '$.text'), char(10)) FROM json_each(e.body) c"
" WHERE json_extract(c.value, '$.type') = 'text') END AS t"
" FROM p JOIN pic_entry e ON e.seq = p.seq WHERE e.kind IN ('user', 'assistant', 'answer'))"
" WHERE trim(coalesce(t, ''), ' ' || char(9, 10, 13)) != '' ORDER BY n LIMIT 1",
-1, &q, NULL) != SQLITE_OK) {
return NULL;
}
sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
line = pic_one_line((const char *)sqlite3_column_text(q, 0), max);
}
sqlite3_finalize(q);
return line;
}
/* pic sessions --json: one object per conversation, most recent first. */
int pic_sessions_json(pic_store *s, int archived, FILE *out) {
sqlite3_stmt *q = NULL, *j = NULL;
if (sqlite3_prepare_v2(
s->db,
"SELECT json_object('id', s.id, 'name', s.name, 'title', " PIC_TITLE_SQL("s") ", 'updatedMs', s.updated_ms,"
" 'createdMs', s.created_ms, 'archived', json(iif(?1, 'true', 'false')),"
" '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')),"
" 'pending', (SELECT u.request_key FROM pic_submission u WHERE u.session_id = s.id AND u.status = 'admitted'"
" ORDER BY u.id LIMIT 1),"
" 'pendingModel', (SELECT u.model FROM pic_submission u WHERE u.session_id = s.id AND u.status = 'admitted'"
" ORDER BY u.id LIMIT 1),"
" '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)))), s.id"
" FROM pic_session s WHERE " PIC_LISTED_SQL("s") " AND (" PIC_ARCHIVED_SQL("s") ") = ?1"
" ORDER BY s.updated_ms DESC, s.rowid DESC",
-1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_int(q, 1, archived != 0);
if (sqlite3_prepare_v2(s->db, "SELECT json_object('model', ?1, 'credential', ?2, 'thinking', ?3)", -1, &j, NULL) !=
SQLITE_OK) {
j = NULL;
}
while (sqlite3_step(q) == SQLITE_ROW) {
/* live: another pic process holds it now (running its request, as pic sessions says) */
const char *row = (const char *)sqlite3_column_text(q, 0);
long pid = pic_lease_holder(s, (const char *)sqlite3_column_text(q, 1));
char model[200], thinking[16], label[PIC_CRED_LABEL_CAP], credential[PIC_CRED_NAME_CAP] = "";
const char *own = NULL;
/* the conversation's own model, key and level: what it goes on with */
if (j && session_choice(s, (const char *)sqlite3_column_text(q, 1), model, sizeof model, thinking, sizeof thinking,
label, sizeof label) == 1) {
const char *slash = strchr(model, '/');
if (label[0] && slash) {
(void)snprintf(credential, sizeof credential, "%.*s:%s", (int)(slash - model), model, label);
}
sqlite3_reset(j);
sqlite3_bind_text(j, 1, model, -1, SQLITE_STATIC);
sqlite3_bind_text(j, 2, credential[0] ? credential : NULL, -1, SQLITE_STATIC);
sqlite3_bind_text(j, 3, thinking[0] ? thinking : NULL, -1, SQLITE_STATIC);
own = sqlite3_step(j) == SQLITE_ROW ? (const char *)sqlite3_column_text(j, 0) : NULL;
}
fprintf(out, "%.*s%s%.*s,\"live\":%s}\n", (int)strlen(row) - 1, row, own ? "," : "", own ? (int)strlen(own) - 2 : 0,
own ? own + 1 : "", pid != 0 && pid != (long)getpid() ? "true" : "false");
}
sqlite3_finalize(j);
sqlite3_finalize(q);
return 0;
}
/* pic log --json: the conversation's path, one object per entry, for a
* client to show a resumed conversation: a reply's content blocks in order
* (thinking, text, tool calls) and the usage of the request that made it. */
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"
" AND x.kind != 'branch_summary')"
" THEN u.status END, 'error', CASE WHEN u.status = 'failed' THEN u.error END,"
" 'stopReason', CASE WHEN e.seq = (SELECT max(x.seq) FROM pic_entry x WHERE x.submission_id = e.submission_id"
" AND x.kind != 'branch_summary')"
" THEN u.stop_reason 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),"
" 'origin', CASE WHEN e.kind = 'user' THEN " PIC_ORIGIN_SQL " 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,"
" 'content', CASE WHEN e.kind IN ('assistant','answer') AND json_valid(e.body) THEN json(e.body) END,"
" 'usage', json((SELECT g.usage FROM pic_generation g WHERE g.entry_seq = e.seq AND g.state = 'done'"
" AND json_valid(g.usage) ORDER BY g.id DESC LIMIT 1)),"
" 'bash', CASE WHEN b.entry_seq IS NOT NULL THEN json_object('command', b.command, 'output', b.output,"
" 'exitCode', b.exit_code, 'cancelled', json(iif(b.cancelled,'true','false')),"
" 'truncated', json(iif(b.truncated,'true','false')), 'excludeFromContext', json(iif(b.exclude,'true','false'))) END))"
" 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 LEFT JOIN pic_bash b ON b.entry_seq = e.seq 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;
}