Artifact bdd0c2ae774a1e2dc5c08ce21f65add915bf2024181eb9e290041317d0400fd7:
- File
src/hooks.c
— part of check-in
[eae917e9e9]
at
2026-11-21 12:03:36
on branch shared-store
— Shared journal store: several pic processes on one workspace, one conversation each
Each conversation has a lease (an exclusive flock beside the journal) that its process holds while it advances it and that the kernel drops when the process and its forked children are gone. Taking a lease claims the conversation's request and settles what a dead owner left; open recovers only conversations whose lease is free. The journal lock is held shared and taken exclusive only to create or migrate the schema. SQLite runs in normal locking mode with the fair busy handler; dev builds stop on a write begun under an open read.
pic run takes only requests nobody is running. A second pic asking into a conversation in use is refused with its owner's pid. An edit that misses in a file another conversation changed says so and shows the file; a write to such a file is refused once.
New test/pic/shared.sh: two-process crash matrix, kill -9 beside a live pic, claim and admission races, stale-file results. No schema change. (user: dmestas, size: 48748) [annotate] [blame] [check-ins using] [more...]
/* Command hooks (hooks.h): the configuration, the runner, and their journal. * A hook's command runs outside any transaction; what it decided is then * journaled, with its effect where it has one, so a resumed run acts on the * journal and never runs a hook a second time for the same thing. */ #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <poll.h> #include <regex.h> #include <signal.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <unistd.h> #include "hooks.h" #include "input.h" #include "net.h" #include "pic.h" #include "platform.h" #include "userdb.h" #define HOOK_FILE_MAX (1u << 20) #define HOOK_OUT_MAX (1u << 20) /* bytes kept from a run's stdout, and from its stderr */ #define HOOK_DEFAULT_SECONDS 10 #define HOOK_MAX_SECONDS 60 typedef struct { char *event, *matcher, *command, *file; int seconds, async; int any; /* no matcher, or "*" */ int exact; /* names separated by |, compared whole */ int bad; /* a pattern that does not compile: matches nothing */ regex_t re; } hook; struct pic_hooks { hook *list; size_t n, cap; char workspace[PATH_MAX]; /* real path: cwd */ char userdb[PATH_MAX]; /* transcript_path: ~/.pic/pic.sqlite, where the conversation's Pi lines are */ char owner[96]; int owned; }; static char *dup_str(const char *s) { size_t n; char *p; if (!s) { return NULL; } n = strlen(s) + 1; if ((p = malloc(n))) { memcpy(p, s, n); } return p; } static char *fmt(const char *f, ...) { va_list ap; char *out; va_start(ap, f); out = sqlite3_vmprintf(f, ap); va_end(ap); if (out) { /* callers free() it */ char *copy = dup_str(out); sqlite3_free(out); return copy; } return NULL; } /* ---- configuration -------------------------------------------------------- */ static void hook_clear(hook *k) { free(k->event); free(k->matcher); free(k->command); free(k->file); if (!k->any && !k->exact && !k->bad) { regfree(&k->re); } } void pic_hooks_free(pic_hooks *h) { if (!h) { return; } for (size_t i = 0; i < h->n; i++) { hook_clear(&h->list[i]); } free(h->list); free(h); } /* Claude Code compares a matcher of plain names (Write, Edit|Write) whole, * and searches with any other as a regular expression. */ static void classify(hook *k, FILE *warn) { const char *m = k->matcher; k->any = !*m || strcmp(m, "*") == 0; if (k->any) { return; } k->exact = strspn(m, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_|") == strlen(m); if (!k->exact && regcomp(&k->re, m, REG_EXTENDED | REG_NOSUB) != 0) { k->bad = 1; if (warn) { fprintf(warn, "pic: %s: matcher %s is not a regular expression pic reads; it matches nothing\n", k->file, m); } } } static int name_in(const char *list, const char *name) { size_t n = name ? strlen(name) : 0; for (const char *p = list; name && *p;) { size_t len = strcspn(p, "|"); if (len == n && strncmp(p, name, n) == 0) { return 1; } p += len + (p[len] == '|'); } return 0; } static int matches(const hook *k, const char *name, const char *alt) { if (k->any || (!name && !alt)) { return 1; } if (k->bad) { return 0; } if (k->exact) { return name_in(k->matcher, name) || name_in(k->matcher, alt); } return (name && regexec(&k->re, name, 0, NULL, 0) == 0) || (alt && regexec(&k->re, alt, 0, NULL, 0) == 0); } /* The command hooks of one file, in its order. A file that is missing adds * nothing; one that does not parse is skipped with a warning. */ static int load_file(pic_hooks *h, const char *path, FILE *warn) { sqlite3 *db = NULL; sqlite3_stmt *q = NULL; size_t len = 0; char *raw = pic_input_read(path, HOOK_FILE_MAX, 0, &len, NULL); int rc = 0; if (!raw) { if (errno != ENOENT && warn) { fprintf(warn, "pic: cannot read %s: %s\n", path, strerror(errno)); } return 0; } if (sqlite3_open(":memory:", &db) != SQLITE_OK || sqlite3_prepare_v2( db, /* Every element is checked before it is read as JSON: a string * where an object belongs is passed over, not an error. */ "SELECT ev.key, CASE WHEN json_type(m.value,'$.matcher') = 'text' THEN json_extract(m.value,'$.matcher') ELSE '' END," " json_extract(h.value,'$.command'), json_extract(h.value,'$.timeout')," " coalesce(json_extract(h.value,'$.async') IN (1, 'true'), 0)" " FROM json_each(?1,'$.hooks') ev," " json_each(CASE WHEN ev.type = 'array' THEN ev.value ELSE '[]' END) m," " json_each(coalesce(CASE WHEN m.type = 'object' THEN CASE WHEN json_type(m.value,'$.hooks') = 'array'" " THEN json_extract(m.value,'$.hooks') END END, '[]')) h" " WHERE CASE WHEN h.type = 'object' THEN json_extract(h.value,'$.type') = 'command'" " AND json_type(h.value,'$.command') = 'text' ELSE 0 END" " AND json_valid(?1) AND json_type(?1,'$.hooks') = 'object'" " ORDER BY ev.id, m.id, h.id", -1, &q, NULL) != SQLITE_OK) { free(raw); sqlite3_close(db); return -1; } sqlite3_bind_text(q, 1, raw, (int)len, SQLITE_STATIC); { sqlite3_stmt *v = NULL; int ok = 0; if (sqlite3_prepare_v2(db, "SELECT json_valid(?1) AND json_type(?1,'$.hooks') = 'object'", -1, &v, NULL) == SQLITE_OK) { sqlite3_bind_text(v, 1, raw, (int)len, SQLITE_STATIC); ok = sqlite3_step(v) == SQLITE_ROW && sqlite3_column_int(v, 0); } sqlite3_finalize(v); if (!ok && warn) { fprintf(warn, "pic: %s is not a hooks file (a JSON object with a \"hooks\" object); skipped\n", path); } } while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) { hook *k; double t = sqlite3_column_double(q, 3); if (h->n == h->cap) { size_t cap = h->cap ? h->cap * 2 : 8; hook *grown = realloc(h->list, cap * sizeof *grown); if (!grown) { rc = -1; break; } h->list = grown; h->cap = cap; } k = &h->list[h->n]; memset(k, 0, sizeof *k); k->event = dup_str((const char *)sqlite3_column_text(q, 0)); k->matcher = dup_str((const char *)sqlite3_column_text(q, 1)); k->command = dup_str((const char *)sqlite3_column_text(q, 2)); k->file = dup_str(path); k->seconds = sqlite3_column_type(q, 3) == SQLITE_NULL || t <= 0 ? HOOK_DEFAULT_SECONDS : t >= HOOK_MAX_SECONDS ? HOOK_MAX_SECONDS : (int)(t + 0.999); k->async = sqlite3_column_int(q, 4); if (!k->event || !k->matcher || !k->command || !k->file) { k->any = 1; hook_clear(k); rc = -1; break; } classify(k, warn); h->n++; } sqlite3_finalize(q); sqlite3_close(db); free(raw); return rc; } static int load_all(pic_hooks *h, const char *workspace, FILE *warn) { const char *home = getenv("HOME"); char path[PATH_MAX]; if (home && *home && snprintf(path, sizeof path, "%s/.pic/hooks.json", home) < (int)sizeof path && load_file(h, path, warn) != 0) { return -1; } if (pic_trust_get(h->workspace) == 1 && snprintf(path, sizeof path, "%s/.pic/hooks.json", workspace) < (int)sizeof path && load_file(h, path, warn) != 0) { return -1; } return 0; } static pic_hooks *hooks_new(const char *workspace) { pic_hooks *h = calloc(1, sizeof *h); if (h && !realpath(workspace, h->workspace)) { (void)snprintf(h->workspace, sizeof h->workspace, "%s", workspace); } return h; } pic_hooks *pic_hooks_load(const char *workspace, const char *owner, FILE *warn) { pic_hooks *h = hooks_new(workspace); if (!h || load_all(h, workspace, warn) != 0 || h->n == 0) { pic_hooks_free(h); return NULL; } if (pic_userdb_path(h->userdb, sizeof h->userdb) != 0) { h->userdb[0] = '\0'; } if (owner && *owner) { (void)snprintf(h->owner, sizeof h->owner, "%s", owner); h->owned = 1; } else { (void)snprintf(h->owner, sizeof h->owner, "pic-%ld-%lld", (long)getpid(), (long long)pic_platform_get()->wall_ns()); } return h; } int pic_hooks_list(const char *workspace, FILE *out) { pic_hooks *h = hooks_new(workspace); if (!h || load_all(h, workspace, stderr) != 0) { pic_hooks_free(h); return -1; } for (size_t i = 0; i < h->n; i++) { const hook *k = &h->list[i]; fprintf(out, "%s\t%s\t%d\t%s\t%s\t%s\n", k->event, k->matcher, k->seconds, k->async ? "async" : "sync", k->command, k->file); } pic_hooks_free(h); return 0; } int pic_hooks_has(const pic_hooks *h, const char *event) { for (size_t i = 0; h && i < h->n; i++) { if (strcmp(h->list[i].event, event) == 0) { return 1; } } return 0; } int pic_hooks_owned(const pic_hooks *h) { return h && h->owned; } /* ---- firing an event ---------------------------------------------------------- */ static int is(const char *a, const char *b) { return strcmp(a, b) == 0; } static char *trimmed(const char *text) { const char *p = text ? text : ""; size_t n; while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') { p++; } n = strlen(p); while (n > 0 && (p[n - 1] == ' ' || p[n - 1] == '\t' || p[n - 1] == '\n' || p[n - 1] == '\r')) { n--; } { char *out = malloc(n + 1); if (out) { memcpy(out, p, n); out[n] = '\0'; } return out; } } static void note(pic_store *s, const char *event, const char *text) { char line[600]; (void)snprintf(line, sizeof line, "%s hook: %s", event, text); pic_ev_note(s, line); } /* How one run ended, read as Claude Code reads it. */ static void judge(pic_store *s, const char *event, const pic_spawn_result *p, int seconds, pic_hook_run *r) { char *out = NULL, *err = trimmed(p->err); int blocks = is(event, "UserPromptSubmit") || is(event, "Stop") || is(event, "PostToolUse"); int context_events = is(event, "SessionStart") || is(event, "UserPromptSubmit") || is(event, "PostToolUse") || is(event, "PreCompact"); r->ms = p->ms; r->exited = p->exited; r->code = p->code; r->interrupted = p->cancelled; if (!p->started || (!p->exited && !p->timed_out)) { r->error = dup_str(p->why); } else if (p->timed_out) { r->error = fmt("timed out after %d s (its process group was killed)", seconds); } else if (p->code == 2) { if (is(event, "PreToolUse") || blocks) { r->outcome = is(event, "PreToolUse") ? "deny" : "block"; r->reason = err && *err ? dup_str(err) : fmt("blocked by a %s hook", event); } else { r->error = fmt("exit 2, which does not block %s: %.200s", event, err ? err : ""); } } else if (p->code != 0) { r->error = fmt("exit %d%s%.200s", p->code, err && *err ? ": " : "", err ? err : ""); } else if ((out = trimmed(p->out)) && out[0] == '{') { sqlite3_stmt *q = NULL; if (sqlite3_prepare_v2(s->db, "SELECT CASE WHEN json_type(?1,'$.hookSpecificOutput.additionalContext') = 'text'" " THEN json_extract(?1,'$.hookSpecificOutput.additionalContext') END," " json_extract(?1,'$.hookSpecificOutput.permissionDecision')," " json_extract(?1,'$.hookSpecificOutput.permissionDecisionReason')," " json_extract(?1,'$.decision'), json_extract(?1,'$.reason'), json_extract(?1,'$.systemMessage')" " WHERE json_valid(?1) AND json_type(?1) = 'object'", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, out, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { const char *context = (const char *)sqlite3_column_text(q, 0); const char *perm = (const char *)sqlite3_column_text(q, 1); const char *perm_reason = (const char *)sqlite3_column_text(q, 2); const char *decision = (const char *)sqlite3_column_text(q, 3); const char *reason = (const char *)sqlite3_column_text(q, 4); const char *message = (const char *)sqlite3_column_text(q, 5); if (context && *context && context_events) { r->context = dup_str(context); } if (is(event, "PreToolUse")) { /* "ask" runs the call: pic has no permission prompts. */ if ((perm && is(perm, "deny")) || (!perm && decision && is(decision, "block"))) { r->outcome = "deny"; r->reason = perm_reason && *perm_reason ? dup_str(perm_reason) : reason && *reason ? dup_str(reason) : dup_str("denied by a PreToolUse hook"); } else if (perm && (is(perm, "allow") || is(perm, "ask"))) { r->outcome = is(perm, "allow") ? "allow" : "ask"; } else if (!perm && decision && is(decision, "approve")) { r->outcome = "allow"; } } else if (blocks && decision && is(decision, "block")) { r->outcome = "block"; r->reason = reason && *reason ? dup_str(reason) : fmt("blocked by a %s hook", event); } if (message && *message) { note(s, event, message); } } else { r->error = dup_str("stdout is not valid JSON; ignored"); } } sqlite3_finalize(q); } else if (out && *out && (is(event, "SessionStart") || is(event, "UserPromptSubmit"))) { r->context = dup_str(out); /* plain stdout is context for these two */ } if (r->error) { note(s, event, r->error); } free(out); free(err); } /* The common fields, then EXTRA's members. */ static char *input_json(pic_store *s, const pic_hook_fire *f, const char *extra) { sqlite3_stmt *q = NULL; char *out = NULL; if (sqlite3_prepare_v2(s->db, "SELECT json_object('session_id', ?1, 'transcript_path', ?2, 'cwd', ?3, 'hook_event_name', ?4," " 'harness', 'pic', 'permission_mode', 'bypassPermissions')", -1, &q, NULL) != SQLITE_OK) { return NULL; } sqlite3_bind_text(q, 1, f->session, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, s->hooks->userdb, -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, s->hooks->workspace, -1, SQLITE_STATIC); sqlite3_bind_text(q, 4, f->event, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { const char *base = (const char *)sqlite3_column_text(q, 0); size_t n = strlen(base); if (extra && extra[0] == '{' && strcmp(extra, "{}") != 0) { out = fmt("%.*s,%s", (int)(n - 1), base, extra + 1); } else { out = dup_str(base); } } sqlite3_finalize(q); return out; } static void bind_opt_text(sqlite3_stmt *q, int i, const char *t) { if (t) { sqlite3_bind_text(q, i, t, -1, SQLITE_STATIC); } else { sqlite3_bind_null(q, i); } } /* Journals a run of COMMAND as started (a marker, done, when COMMAND is * NULL), in its own transaction; its row id, or -1. */ static int64_t row_start(pic_store *s, const pic_hook_fire *f, const char *command) { sqlite3_stmt *q = NULL; int64_t id = -1; if (pic_begin(s) != 0) { return -1; } if (sqlite3_prepare_v2(s->db, "INSERT INTO pic_hook_run(event, session_id, submission_id, ref, owner, command, duration_ms, state," " created_ms) VALUES(?1, nullif(?2, ''), nullif(?3, 0), ?4, ?5, ?6, 0," " CASE WHEN ?6 IS NULL THEN 'done' ELSE 'started' END, CAST(unixepoch('subsec') * 1000 AS INTEGER))", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, f->event, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, f->session, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 3, f->submission); sqlite3_bind_int64(q, 4, f->ref); bind_opt_text(q, 5, s->hooks ? s->hooks->owner : NULL); bind_opt_text(q, 6, command); if (sqlite3_step(q) == SQLITE_DONE) { id = sqlite3_last_insert_rowid(s->db); } } if (id < 0) { (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db)); } sqlite3_finalize(q); if (id < 0 || pic_commit(s) != 0) { pic_rollback(s); return -1; } return id; } /* Journals how run ID ended, in its own transaction. */ static int row_finish(pic_store *s, int64_t id, const pic_hook_run *r) { sqlite3_stmt *q = NULL; int ok = 0; if (pic_begin(s) != 0) { return -1; } if (sqlite3_prepare_v2(s->db, "UPDATE pic_hook_run SET exit_code = ?2, duration_ms = ?3, error = ?4, outcome = ?5, reason = ?6," " context = ?7, state = CASE WHEN ?8 THEN 'interrupted' ELSE 'done' END WHERE id = ?1 AND state = 'started'", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_int64(q, 1, id); if (r->exited) { sqlite3_bind_int(q, 2, r->code); } else { sqlite3_bind_null(q, 2); } sqlite3_bind_int64(q, 3, r->ms); bind_opt_text(q, 4, r->error); bind_opt_text(q, 5, r->outcome); bind_opt_text(q, 6, r->reason); bind_opt_text(q, 7, r->context); sqlite3_bind_int(q, 8, r->interrupted); ok = sqlite3_step(q) == SQLITE_DONE && sqlite3_changes(s->db) == 1; } if (!ok) { (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db)); } sqlite3_finalize(q); if (!ok || pic_commit(s) != 0) { pic_rollback(s); return -1; } return 0; } /* SESSION's Pi lines exported through its latest entry, when it exists yet * (a new conversation's first prompt has no entries to read). */ static int exported(pic_store *s, const char *session) { sqlite3_stmt *q = NULL; int exists = 0; if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_session WHERE id = ? AND head_seq IS NOT NULL", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC); exists = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0) > 0; } sqlite3_finalize(q); return exists ? pic_export_pi_head(s, s->hooks->workspace, session) : 0; } static int matches_any(const hook *k, const char *const *names) { if (!names || !names[0]) { return matches(k, NULL, NULL); } for (; *names; names++) { if (matches(k, *names, NULL)) { return 1; } } return 0; } static int interrupted(void *ctx) { (void)ctx; return pic_interrupted != 0; } /* How long a firing waits for its conversation's lease. Ending a terminal's * conversations (pic_hooks_end_owned) waits out the terminal's own dying * child, which may hold one a while yet. */ static int lease_wait_ms = PIC_LEASE_WAIT_MS; int pic_hook_fire_run(pic_store *s, pic_hook_fire *f, const char *const *names, const char *extra) { static const char *const env[] = {"PIC_HOOK=1", NULL}; const pic_executor *ex = pic_executor_get(); pic_hooks *h = s->hooks; char *input = NULL, unexported[PIC_ERR_CAP] = ""; int rc = 0, cut = 0; /* A run is journaled as under way for its conversation: that takes the * conversation's lease (held already inside a request). */ if (h && f->session[0] && pic_lease(s, f->session, lease_wait_ms) != 0) { return -1; } for (size_t i = 0; h && i < h->n && rc == 0 && !pic_interrupted; i++) { const hook *k = &h->list[i]; int seen = 0; int64_t id; pic_hook_run *r; pic_spawn_result p; if (!is(k->event, f->event) || !matches_any(k, names)) { continue; } for (size_t j = 0; j < f->n; j++) { /* the same command twice runs once, as in Claude Code */ seen |= is(f->runs[j].command, k->command); } if (seen || cut) { continue; } if (!input) { /* What the hook may read of the conversation is committed first: * its Pi lines in ~/.pic/pic.sqlite, through its latest entry. */ if (f->session[0] && exported(s, f->session) != 0) { (void)snprintf(unexported, sizeof unexported, "conversation lines not written for the hook: %s", s->err); note(s, f->event, unexported); s->err[0] = '\0'; } if (!(input = input_json(s, f, extra))) { (void)snprintf(s->err, sizeof s->err, "out of memory"); return -1; } } { pic_hook_run *grown = realloc(f->runs, (f->n + 1) * sizeof *grown); if (!grown) { free(input); (void)snprintf(s->err, sizeof s->err, "out of memory"); return -1; } f->runs = grown; } r = &f->runs[f->n++]; memset(r, 0, sizeof *r); r->command = dup_str(k->command); if ((id = row_start(s, f, k->command)) < 0) { rc = -1; break; } if (!f->first) { f->first = id; } if (!ex->spawn) { /* an executor that runs no processes: said once per firing */ r->error = dup_str("hooks are unavailable: this build's executor runs no commands"); cut = 1; } else { pic_spawn_req q = {k->command, h->workspace, input, strlen(input), env, k->seconds, k->async, HOOK_OUT_MAX, interrupted, NULL}; (void)ex->spawn(ex->state, &q, &p); if (k->async) { r->error = p.started ? dup_str("async: not waited for") : fmt("async: %s", p.why); } else { pic_fault("after-hook-run"); judge(s, f->event, &p, k->seconds, r); } free(p.out); free(p.err); } if (unexported[0]) { /* the hook ran without the conversation it may read */ char *joined = r->error ? fmt("%s; %s", r->error, unexported) : dup_str(unexported); free(r->error); r->error = joined; } rc = row_finish(s, id, r); pic_fault("after-hook-row"); if (r->outcome && (is(r->outcome, "deny") || is(r->outcome, "block"))) { char *joined = f->reason ? fmt("%s\n%s", f->reason, r->reason) : dup_str(r->reason); free(f->reason); f->reason = joined; f->blocked = 1; } } free(input); /* The firing's end: a row without a command. A firing with runs but no * end was cut off (a crash, Ctrl-C) between them; its event's safe * default applies (pic_hooks_complete). */ if (rc == 0 && !pic_interrupted && (f->n > 0 || f->marker)) { int64_t id = row_start(s, f, NULL); rc = id < 0 ? -1 : 0; f->first = f->first ? f->first : id; } return rc; } void pic_hook_fire_free(pic_hook_fire *f) { for (size_t i = 0; i < f->n; i++) { free(f->runs[i].command); free(f->runs[i].error); free(f->runs[i].reason); free(f->runs[i].context); } free(f->runs); free(f->reason); f->runs = NULL; f->reason = NULL; f->n = 0; } /* ---- journal helpers -------------------------------------------------------------- */ static int sql_fail(pic_store *s) { (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db)); return -1; } /* One text value from SQL with up to three text parameters and one integer * (?4), malloc'd; NULL when it is NULL or there is no row. */ static char *sql_text(pic_store *s, const char *sql, const char *a, const char *b, const char *c, int64_t i) { sqlite3_stmt *q = NULL; char *out = NULL; if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) { return NULL; } for (int k = 1; k <= sqlite3_bind_parameter_count(q); k++) { if (k == 4) { sqlite3_bind_int64(q, k, i); } else { bind_opt_text(q, k, k == 1 ? a : k == 2 ? b : c); } } if (sqlite3_step(q) == SQLITE_ROW) { out = dup_str((const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); return out; } static int64_t sql_int(pic_store *s, const char *sql, const char *a, const char *b, int64_t i, int64_t j) { sqlite3_stmt *q = NULL; int64_t out = 0; if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) { return -1; } for (int k = 1; k <= sqlite3_bind_parameter_count(q); k++) { if (k == 3 || k == 4) { sqlite3_bind_int64(q, k, k == 3 ? i : j); } else { bind_opt_text(q, k, k == 1 ? a : b); } } if (sqlite3_step(q) == SQLITE_ROW) { out = sqlite3_column_int64(q, 0); } sqlite3_finalize(q); return out; } static void fire_init(pic_hook_fire *f, const char *event, const char *session, int64_t submission, int64_t ref) { memset(f, 0, sizeof *f); f->event = event; (void)snprintf(f->session, sizeof f->session, "%s", session ? session : ""); f->submission = submission; f->ref = ref; } /* One-name list for a matcher. */ #define NAMES(name) ((const char *const[]){(name), NULL}) static void session_of(pic_store *s, int64_t submission, char out[64]) { char *id = sql_text(s, "SELECT session_id FROM pic_submission WHERE id = ?4", NULL, NULL, NULL, submission); (void)snprintf(out, 64, "%s", id ? id : ""); free(id); } /* ---- the firings ----------------------------------------------------------------- */ /* Whether owner ?1 has conversation ?2 open: a SessionStart since its last * SessionEnd. */ #define OPEN_SQL \ "EXISTS (SELECT 1 FROM pic_hook_run o WHERE o.event = 'SessionStart' AND o.owner = ?1 AND o.session_id = ?2" \ " AND o.id > coalesce((SELECT max(x.id) FROM pic_hook_run x WHERE x.event = 'SessionEnd' AND x.owner = ?1" \ " AND x.session_id = ?2), 0))" int pic_hooks_session_start(pic_store *s, const char *session, const char *source) { pic_hook_fire f; char *extra; int rc; if (!s->hooks || sql_int(s, "SELECT " OPEN_SQL, s->hooks->owner, session, 0, 0) != 0) { return 0; } fire_init(&f, "SessionStart", session, 0, 0); f.marker = 1; extra = sql_text(s, "SELECT json_object('source', ?1)", source, NULL, NULL, 0); rc = extra ? pic_hook_fire_run(s, &f, NAMES(source), extra) : -1; free(extra); pic_hook_fire_free(&f); return rc; } int pic_hooks_prompt(pic_store *s, const char *session, const char *prompt, int64_t *first) { pic_hook_fire f; char *extra; int rc; *first = 0; if (!s->hooks || !pic_hooks_has(s->hooks, "UserPromptSubmit")) { return 0; } fire_init(&f, "UserPromptSubmit", session, 0, 0); extra = sql_text(s, "SELECT json_object('prompt', ?1)", prompt, NULL, NULL, 0); rc = extra ? pic_hook_fire_run(s, &f, NULL, extra) : -1; free(extra); *first = f.first; if (rc == 0 && pic_interrupted) { (void)snprintf(s->err, sizeof s->err, "interrupted"); rc = 1; } else if (rc == 0 && f.blocked) { /* the prompt is never admitted, so its context is never claimed */ (void)snprintf(s->err, sizeof s->err, "prompt blocked by a UserPromptSubmit hook: %s", f.reason); rc = 1; } pic_hook_fire_free(&f); return rc; } int pic_hooks_session_end(pic_store *s, const char *session, const char *reason) { pic_hook_fire f; char *extra; int rc; if (!s->hooks || sql_int(s, "SELECT " OPEN_SQL, s->hooks->owner, session, 0, 0) != 1) { return 0; } fire_init(&f, "SessionEnd", session, 0, 0); f.marker = 1; extra = sql_text(s, "SELECT json_object('reason', ?1)", reason, NULL, NULL, 0); rc = extra ? pic_hook_fire_run(s, &f, NAMES(reason), extra) : -1; free(extra); pic_hook_fire_free(&f); return rc; } int pic_hooks_end_owned(pic_store *s, const char *reason) { sqlite3_stmt *q = NULL; char **ids = NULL; size_t n = 0; int rc = 0; if (!s->hooks) { return 0; } if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_hook_run r WHERE event = 'SessionStart' AND owner = ?1" " AND EXISTS (SELECT 1 FROM pic_session WHERE id = r.session_id)" " GROUP BY session_id ORDER BY min(id)", -1, &q, NULL) != SQLITE_OK) { return sql_fail(s); } sqlite3_bind_text(q, 1, s->hooks->owner, -1, SQLITE_STATIC); while (sqlite3_step(q) == SQLITE_ROW) { char **grown = realloc(ids, (n + 1) * sizeof *grown); if (!grown) { break; } ids = grown; if ((ids[n] = dup_str((const char *)sqlite3_column_text(q, 0)))) { n++; } } sqlite3_finalize(q); lease_wait_ms = 60000; for (size_t i = 0; i < n; i++) { if (rc == 0) { rc = pic_hooks_session_end(s, ids[i], reason); } free(ids[i]); } lease_wait_ms = PIC_LEASE_WAIT_MS; free(ids); return rc; } static const char *const cc_names[][2] = {{"bash", "Bash"}, {"read", "Read"}, {"edit", "Edit"}, {"write", "Write"}, {"grep", "Grep"}, {"find", "Glob"}, {"ls", "LS"}}; void pic_hooks_tool_names(const char *tool, const char *names[4]) { size_t n = 0; names[n++] = tool; if ((names[n] = pic_hooks_cc_name(tool)) != NULL) { n++; } if (is(tool, "edit")) { /* pic's edit takes several edits: Claude Code's MultiEdit too */ names[n++] = "MultiEdit"; } names[n] = NULL; } const char *pic_hooks_cc_name(const char *tool) { for (size_t i = 0; i < sizeof cc_names / sizeof cc_names[0]; i++) { if (is(cc_names[i][0], tool)) { return cc_names[i][1]; } } return NULL; } char *pic_hooks_tool_extra(pic_store *s, const char *tool, const char *input, const char *call_id, const char *result, int is_error) { sqlite3_stmt *q = NULL; const char *cc = pic_hooks_cc_name(tool); char *out = NULL; if (sqlite3_prepare_v2( s->db, "SELECT json_object('tool_name', ?1, 'tool_input', json(CASE WHEN ?5 AND json_type(?2) = 'object'" " AND json_type(?2,'$.path') = 'text' THEN json_set(?2,'$.file_path',json_extract(?2,'$.path')) ELSE ?2 END)," " 'tool_use_id', ?3)," " CASE WHEN ?4 IS NOT NULL THEN json_object('content', ?4, 'is_error', json(CASE WHEN ?6 THEN 'true' ELSE 'false' END)) END", -1, &q, NULL) != SQLITE_OK) { return NULL; } sqlite3_bind_text(q, 1, cc ? cc : tool, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, input && *input ? input : "null", -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, call_id, -1, SQLITE_STATIC); bind_opt_text(q, 4, result); sqlite3_bind_int(q, 5, is(tool, "read") || is(tool, "edit") || is(tool, "write")); sqlite3_bind_int(q, 6, is_error); if (sqlite3_step(q) == SQLITE_ROW) { const char *base = (const char *)sqlite3_column_text(q, 0), *response = (const char *)sqlite3_column_text(q, 1); out = response ? fmt("%.*s,\"tool_response\":%s}", (int)(strlen(base) - 1), base, response) : dup_str(base); } sqlite3_finalize(q); return out; } int pic_hooks_post_tools(pic_store *s, int64_t submission) { sqlite3_stmt *q = NULL; struct call { int64_t effect; char *tool, *input, *call_id, *result; int is_error; } *calls = NULL; size_t n = 0; int rc = 0; char session[64]; if (!s->hooks || !pic_hooks_has(s->hooks, "PostToolUse")) { return 0; } if (sqlite3_prepare_v2(s->db, "SELECT f.id, f.tool, f.input, f.call_id, f.result, f.is_error FROM pic_effect f" " WHERE f.entry_seq = (SELECT max(seq) FROM pic_entry WHERE submission_id = ?1 AND kind = 'assistant')" " AND f.state = 'done'" " AND NOT EXISTS (SELECT 1 FROM pic_hook_run r WHERE r.event = 'PostToolUse' AND r.ref = f.id)" " ORDER BY f.ordinal", -1, &q, NULL) != SQLITE_OK) { return sql_fail(s); } sqlite3_bind_int64(q, 1, submission); while (sqlite3_step(q) == SQLITE_ROW) { struct call *grown = realloc(calls, (n + 1) * sizeof *grown); if (!grown) { break; } calls = grown; calls[n].effect = sqlite3_column_int64(q, 0); calls[n].tool = dup_str((const char *)sqlite3_column_text(q, 1)); calls[n].input = dup_str((const char *)sqlite3_column_text(q, 2)); calls[n].call_id = dup_str((const char *)sqlite3_column_text(q, 3)); calls[n].result = dup_str(sqlite3_column_text(q, 4) ? (const char *)sqlite3_column_text(q, 4) : ""); calls[n].is_error = sqlite3_column_int(q, 5); n++; } sqlite3_finalize(q); session_of(s, submission, session); for (size_t i = 0; i < n; i++) { struct call *c = &calls[i]; if (rc == 0 && c->tool && c->input && c->call_id && c->result) { pic_hook_fire f; char *extra = pic_hooks_tool_extra(s, c->tool, c->input, c->call_id, c->result, c->is_error); const char *names[4]; pic_hooks_tool_names(c->tool, names); fire_init(&f, "PostToolUse", session, submission, c->effect); rc = extra ? pic_hook_fire_run(s, &f, names, extra) : -1; free(extra); pic_hook_fire_free(&f); } free(c->tool); free(c->input); free(c->call_id); free(c->result); } free(calls); return rc; } int pic_hooks_compact_start(pic_store *s, int64_t submission) { pic_hook_fire f; int64_t seq; char session[64]; int rc; if (!s->hooks || !pic_hooks_has(s->hooks, "SessionStart")) { return 0; } seq = sql_int(s, "SELECT coalesce(max(seq), 0) FROM pic_entry WHERE submission_id = ?3 AND kind = 'compaction' AND seq >" " coalesce((SELECT max(seq) FROM pic_entry WHERE submission_id = ?3 AND kind IN ('assistant','answer')), 0)" " AND NOT EXISTS (SELECT 1 FROM pic_hook_run r WHERE r.event = 'SessionStart' AND r.ref = pic_entry.seq" " AND r.submission_id = ?3)", NULL, NULL, submission, 0); if (seq <= 0) { return seq < 0 ? sql_fail(s) : 0; } session_of(s, submission, session); fire_init(&f, "SessionStart", session, submission, seq); f.marker = 1; rc = pic_hook_fire_run(s, &f, NAMES("compact"), "{\"source\":\"compact\"}"); pic_hook_fire_free(&f); return rc; } int pic_hooks_pre_compact(pic_store *s, int64_t submission, int64_t turn, const char *trigger, const char *instructions, char **extra) { pic_hook_fire f; char session[64], *fields; int rc; *extra = NULL; if (sql_int(s, "SELECT count(*) FROM pic_hook_run WHERE event = 'PreCompact' AND submission_id = ?3 AND ref = ?4", NULL, NULL, submission, turn) > 0) { { sqlite3_stmt *q = NULL; if (sqlite3_prepare_v2(s->db, "SELECT group_concat(context, char(10) || char(10)) FROM (SELECT context FROM pic_hook_run" " WHERE event = 'PreCompact' AND submission_id = ?1 AND ref = ?2 AND context IS NOT NULL ORDER BY id)", -1, &q, NULL) != SQLITE_OK) { return sql_fail(s); } sqlite3_bind_int64(q, 1, submission); sqlite3_bind_int64(q, 2, turn); if (sqlite3_step(q) == SQLITE_ROW) { *extra = dup_str((const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); } return 0; } if (!s->hooks || !pic_hooks_has(s->hooks, "PreCompact")) { return 0; } session_of(s, submission, session); fire_init(&f, "PreCompact", session, submission, turn); f.marker = 1; fields = sql_text(s, "SELECT json_object('trigger', ?1, 'custom_instructions', coalesce(?2, ''))", trigger, instructions, NULL, 0); rc = fields ? pic_hook_fire_run(s, &f, NAMES(trigger), fields) : -1; free(fields); if (rc == 0) { for (size_t i = 0; i < f.n; i++) { if (f.runs[i].context) { char *joined = *extra ? fmt("%s\n\n%s", *extra, f.runs[i].context) : dup_str(f.runs[i].context); free(*extra); *extra = joined; } } } pic_hook_fire_free(&f); return rc; } char *pic_hooks_stop_feedback(const char *reason) { return fmt("Stop hook feedback:\n%s", reason); } int pic_hooks_deliver(pic_store *s, int64_t submission) { sqlite3_stmt *q = NULL; struct pending { int64_t id; char *body; } *rows = NULL; size_t n = 0; int rc = 0, step; if (sqlite3_prepare_v2(s->db, "SELECT id, event, context, CASE WHEN outcome = 'block' THEN reason END FROM pic_hook_run" " WHERE entry_seq IS NULL AND state = 'done'" " AND (context IS NOT NULL OR (event = 'PostToolUse' AND outcome = 'block'))" " AND (submission_id = ?1 AND event IN ('UserPromptSubmit','PostToolUse')" " OR event = 'SessionStart' AND session_id = (SELECT session_id FROM pic_submission WHERE id = ?1))" " ORDER BY id", -1, &q, NULL) != SQLITE_OK) { return sql_fail(s); } sqlite3_bind_int64(q, 1, submission); while ((step = sqlite3_step(q)) == SQLITE_ROW) { const char *event = (const char *)sqlite3_column_text(q, 1), *context = (const char *)sqlite3_column_text(q, 2); const char *feedback = (const char *)sqlite3_column_text(q, 3); struct pending *grown = realloc(rows, (n + 1) * sizeof *grown); if (!grown) { rc = -1; break; } rows = grown; rows[n].id = sqlite3_column_int64(q, 0); rows[n].body = fmt("<system-reminder>\n%s%s%s%s%s%s\n</system-reminder>", context ? event : "", context ? " hook additional context: " : "", context ? context : "", context && feedback ? "\n" : "", feedback ? "PostToolUse hook feedback:\n" : "", feedback ? feedback : ""); if (!rows[n].body) { rc = -1; break; } n++; } sqlite3_finalize(q); if (rc == 0 && step != SQLITE_DONE) { rc = sql_fail(s); } else if (rc != 0) { (void)snprintf(s->err, sizeof s->err, "out of memory"); } for (size_t i = 0; i < n; i++) { if (rc == 0) { sqlite3_stmt *ins = NULL, *up = NULL; if (sqlite3_prepare_v2(s->db, "INSERT INTO pic_entry(submission_id, kind, body) VALUES(?1, 'hook', ?2)", -1, &ins, NULL) != SQLITE_OK || sqlite3_prepare_v2(s->db, "UPDATE pic_hook_run SET entry_seq = ?1 WHERE id = ?2", -1, &up, NULL) != SQLITE_OK) { rc = sql_fail(s); } else { sqlite3_bind_int64(ins, 1, submission); sqlite3_bind_text(ins, 2, rows[i].body, -1, SQLITE_STATIC); if (sqlite3_step(ins) != SQLITE_DONE) { rc = sql_fail(s); } else { sqlite3_bind_int64(up, 1, sqlite3_last_insert_rowid(s->db)); sqlite3_bind_int64(up, 2, rows[i].id); if (sqlite3_step(up) != SQLITE_DONE) { rc = sql_fail(s); } } } sqlite3_finalize(ins); sqlite3_finalize(up); } free(rows[i].body); } free(rows); return rc; } int pic_hooks_claim(pic_store *s, int64_t first, int64_t submission, int64_t queued) { sqlite3_stmt *q = NULL; int ok; if (first <= 0) { return 0; } if (sqlite3_prepare_v2(s->db, "UPDATE pic_hook_run SET submission_id = nullif(?2, 0), ref = ?3 WHERE event = 'UserPromptSubmit'" " AND id >= ?1 AND submission_id IS NULL AND ref = 0", -1, &q, NULL) != SQLITE_OK) { return sql_fail(s); } sqlite3_bind_int64(q, 1, first); sqlite3_bind_int64(q, 2, submission); sqlite3_bind_int64(q, 3, queued); ok = sqlite3_step(q) == SQLITE_DONE; sqlite3_finalize(q); return ok ? 0 : sql_fail(s); } int pic_hooks_claim_queued(pic_store *s, int64_t queued, int64_t submission) { sqlite3_stmt *q = NULL; int ok; if (sqlite3_prepare_v2(s->db, "UPDATE pic_hook_run SET submission_id = ?2 WHERE event = 'UserPromptSubmit' AND ref = ?1" " AND submission_id IS NULL", -1, &q, NULL) != SQLITE_OK) { return sql_fail(s); } sqlite3_bind_int64(q, 1, queued); sqlite3_bind_int64(q, 2, submission); ok = sqlite3_step(q) == SQLITE_DONE; sqlite3_finalize(q); return ok ? 0 : sql_fail(s); } int pic_hooks_mark_pending(pic_store *s, int64_t queued) { sqlite3_stmt *q = NULL; int ok; if (!pic_hooks_has(s->hooks, "UserPromptSubmit") && !pic_hooks_has(s->hooks, "SessionStart")) { return 0; } if (sqlite3_prepare_v2(s->db, "INSERT INTO pic_hook_run(event, session_id, ref, owner, duration_ms, state, created_ms)" " SELECT 'UserPromptSubmit', session_id, id, ?2, 0, 'pending'," " CAST(unixepoch('subsec') * 1000 AS INTEGER) FROM pic_queued WHERE id = ?1", -1, &q, NULL) != SQLITE_OK) { return sql_fail(s); } sqlite3_bind_int64(q, 1, queued); sqlite3_bind_text(q, 2, s->hooks->owner, -1, SQLITE_STATIC); ok = sqlite3_step(q) == SQLITE_DONE; sqlite3_finalize(q); return ok ? 0 : sql_fail(s); } /* The prompt hooks of pending row ROW, for queued message QUEUED. */ static int run_one_pending(pic_store *s, int64_t row, int64_t queued) { sqlite3_stmt *q = NULL; char session[64] = "", kind[16] = "", saved[PIC_ERR_CAP], *message = NULL, *reason = NULL; int64_t first = 0, delivered = 0; int state = 0, rc = 0, blocked = 0; (void)snprintf(saved, sizeof saved, "%s", s->err); /* 1: queued; 2: delivered (an answer admits a follow-up at once: its * context still goes to the request it became); 0: gone, nothing to run. */ if (sqlite3_prepare_v2(s->db, "SELECT session_id, kind, text, CASE state WHEN 'queued' THEN 1 WHEN 'delivered' THEN 2 ELSE 0 END," " CASE WHEN state = 'delivered' THEN submission_id ELSE 0 END FROM pic_queued WHERE id = ?", -1, &q, NULL) != SQLITE_OK) { return sql_fail(s); } sqlite3_bind_int64(q, 1, queued); if (sqlite3_step(q) == SQLITE_ROW) { (void)snprintf(session, sizeof session, "%s", (const char *)sqlite3_column_text(q, 0)); (void)snprintf(kind, sizeof kind, "%s", (const char *)sqlite3_column_text(q, 1)); message = dup_str((const char *)sqlite3_column_text(q, 2)); state = sqlite3_column_int(q, 3); delivered = sqlite3_column_int64(q, 4); } sqlite3_finalize(q); if (state && message && s->hooks) { rc = pic_hooks_session_start(s, session, "resume"); if (rc == 0) { rc = pic_hooks_prompt(s, session, message, &first); } if (rc == 1) { if (pic_interrupted) { free(message); (void)snprintf(s->err, sizeof s->err, "%s", saved); return 0; /* Ctrl-C: still pending; the request is cancelled, the queue returned */ } blocked = state == 1; reason = dup_str(s->err); rc = 0; } } if (rc != 0) { free(message); return -1; } /* The outcome and its effect commit with the pending row's end. */ if (pic_begin(s) != 0 || (!blocked && pic_hooks_claim(s, first, delivered, delivered ? 0 : queued) != 0)) { pic_rollback(s); free(message); free(reason); return -1; } if (sqlite3_prepare_v2(s->db, "UPDATE pic_queued SET state = CASE WHEN ?2 THEN 'cleared' ELSE state END WHERE id = ?1", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_int64(q, 1, queued); sqlite3_bind_int(q, 2, blocked); rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1; sqlite3_finalize(q); } else { rc = -1; } if (rc == 0 && sqlite3_prepare_v2(s->db, "UPDATE pic_hook_run SET state = 'done', error = ?2 WHERE id = ?1", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_int64(q, 1, row); bind_opt_text(q, 2, blocked ? "its message was blocked and taken out of the queue" : NULL); rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1; sqlite3_finalize(q); } if (rc != 0 || pic_commit(s) != 0) { (void)sql_fail(s); pic_rollback(s); free(message); free(reason); return -1; } if (blocked && sqlite3_prepare_v2(s->db, "SELECT json_object('type', 'queue_returned'," " 'steering', json(CASE WHEN ?1 = 'steer' THEN json_array(?2) ELSE '[]' END)," " 'followUp', json(CASE WHEN ?1 = 'follow_up' THEN json_array(?2) ELSE '[]' END)," " 'reason', ?3)", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, kind, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, message, -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, reason ? reason : "", -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { pic_ev_line(s, (const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); pic_queue_event(s); } free(message); free(reason); (void)snprintf(s->err, sizeof s->err, "%s", saved); pic_fault("after-pending-hooks"); return 0; } int pic_hooks_run_pending(pic_store *s) { for (;;) { sqlite3_stmt *q = NULL; int64_t row = 0, queued = 0; if (sqlite3_prepare_v2(s->db, "SELECT id, ref FROM pic_hook_run WHERE state = 'pending' AND pic_leased(session_id) ORDER BY id LIMIT 1", -1, &q, NULL) != SQLITE_OK) { return sql_fail(s); } if (sqlite3_step(q) == SQLITE_ROW) { row = sqlite3_column_int64(q, 0); queued = sqlite3_column_int64(q, 1); } sqlite3_finalize(q); if (!row || pic_interrupted) { return 0; } if (run_one_pending(s, row, queued) != 0) { return -1; } } }