/* The durable agent loop. Every state change is one short transaction; no
* transaction is ever open while the provider or a tool is running.
*
* A turn: commit a generation as started, ask the provider, then commit its
* reply, the assistant entry and every tool call in it together. Each tool
* call then runs as an effect: commit started, act, commit the result. */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pic.h"
static int sql_fail(pic_store *s) {
(void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
return -1;
}
/* Runs one parameterized statement: 'i' binds an int64, 't' text (NULL binds
* SQL NULL). */
static int run_stmt(pic_store *s, const char *sql, const char *types, ...) {
sqlite3_stmt *q = NULL;
va_list ap;
int rc;
if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
/* One type per parameter, or the varargs below read past what was passed. */
if ((int)strlen(types) != sqlite3_bind_parameter_count(q)) {
int want = sqlite3_bind_parameter_count(q);
sqlite3_finalize(q);
(void)snprintf(s->err, sizeof s->err, "internal: %zu bind types for %d parameters", strlen(types), want);
return -1;
}
va_start(ap, types);
for (int i = 0; types[i]; i++) {
if (types[i] == 'i') {
sqlite3_bind_int64(q, i + 1, va_arg(ap, sqlite3_int64));
} else {
const char *t = va_arg(ap, const char *);
if (t) {
sqlite3_bind_text(q, i + 1, t, -1, SQLITE_TRANSIENT);
} else {
sqlite3_bind_null(q, i + 1);
}
}
}
va_end(ap);
rc = sqlite3_step(q);
sqlite3_finalize(q);
return rc == SQLITE_DONE || rc == SQLITE_ROW ? 0 : sql_fail(s);
}
/* Reads the first column of the first row into *out (0 when NULL or no row).
* Binds a then b to the statement's parameters, as many as it has. */
static int query_int2(pic_store *s, const char *sql, sqlite3_int64 a, sqlite3_int64 b, sqlite3_int64 *out) {
sqlite3_stmt *q = NULL;
int step;
*out = 0;
if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
if (sqlite3_bind_parameter_count(q) > 0) {
sqlite3_bind_int64(q, 1, a);
}
if (sqlite3_bind_parameter_count(q) > 1) {
sqlite3_bind_int64(q, 2, b);
}
step = sqlite3_step(q);
if (step == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
*out = sqlite3_column_int64(q, 0);
}
sqlite3_finalize(q);
return step == SQLITE_ROW || step == SQLITE_DONE ? 0 : sql_fail(s);
}
static int query_int(pic_store *s, const char *sql, sqlite3_int64 arg, sqlite3_int64 *out) {
return query_int2(s, sql, arg, 0, out);
}
static int append_entry(pic_store *s, sqlite3_int64 submission, const char *kind, const char *body) {
return run_stmt(s, "INSERT INTO pic_entry(submission_id,kind,body) VALUES(?,?,?)", "itt", submission,
kind, body);
}
static int append_result(pic_store *s, sqlite3_int64 submission, const char *body, sqlite3_int64 effect) {
return run_stmt(s, "INSERT INTO pic_entry(submission_id,kind,body,effect_id) VALUES(?,'tool_result',?,?)",
"iti", submission, body, effect);
}
void pic_reply_free(pic_reply *r) {
free(r->content);
free(r->stop_reason);
free(r->usage);
free(r->request_id);
memset(r, 0, sizeof *r);
}
/* Admission is idempotent per request key: a retry finds the original. */
int pic_submit(pic_store *s, const char *request_key, const char *content, int *duplicate) {
sqlite3_stmt *q = NULL;
*duplicate = 0;
if (pic_begin(s) != 0) {
return -1;
}
if (sqlite3_prepare_v2(s->db, "SELECT content 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;
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 (run_stmt(s, "INSERT INTO pic_submission(request_key,content,status) VALUES(?,?,'admitted')", "tt",
request_key, content) != 0 ||
append_entry(s, sqlite3_last_insert_rowid(s->db), "user", content) != 0 || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
pic_fault("after-admit");
return 0;
}
/* A started replay-unsafe effect may or may not have happened: record that and
* never run it again. A started replay-safe effect is simply run again. A
* started generation lost its reply: it failed, and the turn is asked again. */
int pic_recover(pic_store *s) {
static const char note[] = "error: outcome unknown (interrupted before its result was recorded); not re-run";
sqlite3_stmt *q = NULL;
int rc = 0;
if (pic_begin(s) != 0) {
return -1;
}
if (pic_exec(s, "UPDATE pic_effect SET state='intent' WHERE state='started' AND replay_safe=1") != 0 ||
pic_exec(s, "UPDATE pic_generation SET state='failed', error='interrupted before the reply was recorded'"
" WHERE state='started'") != 0) {
pic_rollback(s);
return -1;
}
if (sqlite3_prepare_v2(s->db,
"SELECT f.id, e.submission_id FROM pic_effect f JOIN pic_entry e ON e.seq=f.entry_seq"
" WHERE f.state='started' AND f.replay_safe=0 ORDER BY f.id",
-1, &q, NULL) != SQLITE_OK) {
rc = sql_fail(s);
pic_rollback(s);
return rc;
}
while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) {
sqlite3_int64 effect = sqlite3_column_int64(q, 0);
sqlite3_int64 submission = sqlite3_column_int64(q, 1);
if (run_stmt(s, "UPDATE pic_effect SET state='unknown', result=? WHERE id=?", "ti", note, effect) != 0 ||
append_result(s, submission, note, effect) != 0) {
rc = -1;
}
}
sqlite3_finalize(q);
if (rc != 0 || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
return 0;
}
/* Commit "started" (from inside the tool, just before its first external
* effect), act outside any transaction, then commit the result and its
* transcript entry together. */
typedef struct {
pic_store *s;
sqlite3_int64 effect;
int started;
} started_ctx;
static int commit_started(void *p) {
started_ctx *c = p;
if (pic_begin(c->s) != 0 ||
run_stmt(c->s, "UPDATE pic_effect SET state='started' WHERE id=? AND state='intent'", "i", c->effect) != 0 ||
sqlite3_changes(c->s->db) != 1 || pic_commit(c->s) != 0) {
pic_rollback(c->s);
return -1;
}
c->started = 1;
pic_fault("after-started");
return 0;
}
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) {
started_ctx ctx = {s, effect, 0};
pic_tool_hooks hooks = {exec_seconds, commit_started, &ctx};
char *result = pic_tool_run(workspace, tool, args, &hooks);
int failed;
if (!result) {
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");
failed = pic_begin(s) != 0 ||
run_stmt(s, "UPDATE pic_effect SET state='done', result=? WHERE id=? AND state='started'", "ti",
result, effect) != 0 ||
sqlite3_changes(s->db) != 1 || append_result(s, submission, result, effect) != 0 ||
pic_commit(s) != 0;
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;
}
/* 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;
sqlite3_int64 effect = 0;
char *tool = NULL, *path = NULL, *text = NULL, *command = NULL;
int rc, step;
if (sqlite3_prepare_v2(s->db,
"SELECT f.id, f.tool,"
" CASE json_type(f.input,'$.path') WHEN 'text' THEN json_extract(f.input,'$.path') END,"
" CASE json_type(f.input,'$.text') WHEN 'text' THEN json_extract(f.input,'$.text') END,"
" CASE json_type(f.input,'$.command') WHEN 'text' THEN json_extract(f.input,'$.command') END"
" FROM pic_effect f JOIN pic_entry e ON e.seq=f.entry_seq"
" WHERE e.submission_id=? AND f.state='intent' ORDER BY f.entry_seq, f.ordinal LIMIT 1",
-1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_int64(q, 1, submission);
step = sqlite3_step(q);
if (step == SQLITE_ROW) {
effect = sqlite3_column_int64(q, 0);
tool = dup_col(q, 1);
path = dup_col(q, 2);
text = dup_col(q, 3);
command = dup_col(q, 4);
rc = tool ? 0 : -1;
} else {
rc = step == SQLITE_DONE ? 1 : sql_fail(s); /* an error is never "nothing to do" */
}
sqlite3_finalize(q);
if (rc == 0) {
pic_tool_args args = {path, text, command};
rc = run_effect(s, workspace, exec_seconds, effect, submission, tool, &args);
}
free(tool);
free(path);
free(text);
free(command);
return rc;
}
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);
}
/* 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 calls = 0, entry;
const char *stop = r->stop_reason ? r->stop_reason : "";
int refusal = strcmp(stop, "refusal") == 0;
const char *kind;
{
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db,
"SELECT json_valid(?1) AND json_type(?1)='array',"
" (SELECT count(*) FROM json_each(?1) WHERE json_extract(value,'$.type')='tool_use')",
-1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
sqlite3_bind_text(q, 1, r->content, -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 a JSON array");
return -1;
}
calls = sqlite3_column_int64(q, 1);
sqlite3_finalize(q);
}
kind = refusal || calls > 0 || strcmp(stop, "pause_turn") == 0 ? "assistant" : "answer";
if (append_entry(s, submission, kind, r->content) != 0) {
return -1;
}
entry = sqlite3_last_insert_rowid(s->db);
if (!refusal && calls > 0) {
/* Tool calls in content order. A call with input that is not an
* object still becomes an effect; the tool reports the bad input. */
if (run_stmt(s,
"INSERT INTO pic_effect(entry_seq,ordinal,call_id,tool,input,replay_safe,state)"
" SELECT ?1, row_number() OVER (ORDER BY key) - 1,"
" coalesce(json_extract(value,'$.id'),''), coalesce(json_extract(value,'$.name'),''),"
" coalesce(json(json_extract(value,'$.input')),'null'),"
" json_extract(value,'$.name') IS 'write', 'intent'"
" FROM json_each(?2) WHERE json_extract(value,'$.type')='tool_use'",
"it", entry, r->content) != 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);
}
*fault = "after-assistant";
return refusal ? fail_submission(s, submission, "the model refused to continue") : 0;
}
/* 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. */
static int generate(pic_store *s, pic_provider *provider, sqlite3_int64 submission) {
sqlite3_int64 turn = 0, attempts = 0, generation;
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=?", 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=? 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;
}
if (pic_begin(s) != 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");
memset(&reply, 0, sizeof reply);
err[0] = '\0';
if (provider->reply(provider, s, submission, turn, &reply, &retryable, err, sizeof err) != 0) {
if (!err[0]) {
(void)snprintf(err, sizeof err, "provider failed");
}
pic_reply_free(&reply);
if (pic_begin(s) != 0 ||
run_stmt(s, "UPDATE pic_generation SET state='failed', error=? WHERE id=?", "ti", err, generation) != 0 ||
(!retryable && fail_submission(s, submission, err) != 0) || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
if (!retryable) {
(void)snprintf(s->err, sizeof s->err, "submission %lld failed: %s", (long long)submission, err);
return 1;
}
return 0;
}
pic_fault("after-reply");
if (pic_begin(s) != 0 || record_reply(s, submission, generation, &reply, &fault) != 0 || pic_commit(s) != 0) {
pic_rollback(s);
pic_reply_free(&reply);
return -1;
}
pic_reply_free(&reply);
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. */
int pic_run(pic_store *s, const char *workspace, pic_provider *provider, int exec_seconds) {
int any_failed = 0;
char failure[PIC_ERR_CAP] = "";
for (;;) {
sqlite3_int64 submission = 0;
int rc;
if (query_int(s, "SELECT min(id) FROM pic_submission WHERE status='admitted'", 0, &submission) != 0) {
return -1;
}
if (submission == 0) {
if (any_failed) {
(void)snprintf(s->err, sizeof s->err, "%s", failure);
}
return any_failed ? -1 : 0;
}
rc = run_pending_effect(s, workspace, exec_seconds, submission);
if (rc == 1) {
rc = generate(s, provider, submission);
if (rc == 1) {
any_failed = 1;
(void)snprintf(failure, sizeof failure, "%s", s->err);
rc = 0;
}
}
if (rc != 0) {
return -1;
}
}
}
/* Canonical journal listing for tests and inspection. */
int pic_dump(pic_store *s) {
static const char *const queries[] = {
"SELECT 'submission', id, request_key, status, content || coalesce(' error=' || error, '') FROM pic_submission ORDER BY id",
"SELECT 'entry', seq, submission_id, kind || coalesce(' effect=' || effect_id, ''), body FROM pic_entry ORDER BY seq",
"SELECT 'effect', id, entry_seq || '.' || ordinal, tool || ' ' || state || ' safe=' || replay_safe, coalesce(result,'') FROM pic_effect ORDER BY id",
("SELECT 'generation', id, submission_id || '.' || turn || '.' || attempt,"
" state || coalesce(' stop=' || stop_reason, ''), coalesce(error, '') FROM pic_generation ORDER BY id"),
};
for (size_t i = 0; i < sizeof queries / sizeof queries[0]; i++) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(s->db, queries[i], -1, &q, NULL) != SQLITE_OK) {
return sql_fail(s);
}
while (sqlite3_step(q) == SQLITE_ROW) {
printf("%s %lld %s %s | %s\n", (const char *)sqlite3_column_text(q, 0),
(long long)sqlite3_column_int64(q, 1), (const char *)sqlite3_column_text(q, 2),
(const char *)sqlite3_column_text(q, 3), (const char *)sqlite3_column_text(q, 4));
}
sqlite3_finalize(q);
}
return 0;
}