/* 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. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#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 "perm.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 required; /* fails closed: waited for, and its failure denies or withholds */
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 hk_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),"
" coalesce(json_extract(h.value,'$.required') 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->required = sqlite3_column_int(q, 5);
k->async = !k->required && sqlite3_column_int(q, 4); /* a required hook is always waited for */
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 &&
hk_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 &&
hk_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->required ? "required" : 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, int required, 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'),"
" CASE WHEN json_type(?1,'$.hookSpecificOutput.updatedInput') = 'object'"
" THEN json_extract(?1,'$.hookSpecificOutput.updatedInput') END,"
" CASE WHEN json_type(?1,'$.hookSpecificOutput.updatedToolOutput') = 'object'"
" THEN json_extract(?1,'$.hookSpecificOutput.updatedToolOutput') END"
" 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);
const char *new_input = (const char *)sqlite3_column_text(q, 6);
const char *new_output = (const char *)sqlite3_column_text(q, 7);
if (context && *context && context_events) {
r->context = dup_str(context);
}
/* What the call should be given, and what it should show: the two
* fields a policy needs to rewrite a call or a result. They are
* honoured only on an allow, below. */
if (new_input && is(event, "PreToolUse")) {
r->updated_input = dup_str(new_input);
}
if (new_output && is(event, "PostToolUse")) {
r->updated_output = dup_str(new_output);
}
if (is(event, "PreToolUse")) {
/* "ask" puts the call to the person in every permission mode (perm.h). */
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";
if (is(perm, "ask") && perm_reason && *perm_reason) {
r->reason = dup_str(perm_reason);
}
} 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 */
} else if (out && *out && required && (is(event, "PreToolUse") || is(event, "PostToolUse"))) {
r->error = dup_str("stdout is not JSON"); /* a required hook's answer must be read, or it did not finish */
}
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, mode[16];
if (pic_perm_get(s, f->session, mode, sizeof mode) != 0 ||
sqlite3_prepare_v2(s->db,
"SELECT json_object('session_id', ?1, 'transcript_path', ?2, 'cwd', ?3, 'hook_event_name', ?4,"
" 'harness', 'pic', 'permission_mode', ?5)",
-1, &q, NULL) != SQLITE_OK) {
return NULL;
}
sqlite3_bind_text(q, 5, pic_perm_claude_name(mode), -1, SQLITE_STATIC);
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;
}
static int hk_sql_fail(pic_store *s);
static int64_t sql_int(pic_store *s, const char *sql, const char *a, const char *b, int64_t i, int64_t j);
/* SESSION's Pi lines exported through its latest entry, when it exists yet
* (a new conversation's first prompt has no entries to read). A line is
* never rewritten, so it stops before the first result of the latest turn
* whose PostToolUse firing has not ended: a hook may still replace it. */
static int exported(pic_store *s, const char *session) {
sqlite3_stmt *q = NULL;
int exists = 0;
int64_t before = 0;
if (pic_hooks_has(s->hooks, "PostToolUse")) {
before = sql_int(s,
"SELECT coalesce(min(r.seq), 0) FROM pic_entry r JOIN pic_effect f ON f.id = r.effect_id"
" WHERE r.kind = 'tool_result' AND f.entry_seq = (SELECT max(e.seq) FROM pic_entry e"
" JOIN pic_submission u ON u.id = e.submission_id WHERE u.session_id = ?1 AND e.kind = 'assistant')"
" AND NOT EXISTS (SELECT 1 FROM pic_hook_run h WHERE h.event = 'PostToolUse' AND h.ref = f.id"
" AND h.command IS NULL)",
session, NULL, 0, 0);
if (before < 0) {
return hk_sql_fail(s);
}
}
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, before) : 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) || (f->ordinary && k->required)) {
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, k->required, r);
r->clean = !r->error && !r->interrupted;
}
free(p.out);
free(p.err);
}
if (k->required && !r->clean && is(f->event, "PreToolUse")) { /* fails closed: journaled as a deny */
r->outcome = "deny";
free(r->reason);
r->reason = fmt("the required hook %.200s did not finish: %.200s", k->command, r->error ? r->error : "interrupted");
}
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);
/* A required hook that matched and has no clean run: cut off above, or
* failed. */
for (size_t i = 0; h && i < h->n && !f->unfinished && !f->ordinary; i++) {
const hook *k = &h->list[i];
int ok = 0;
if (!k->required || !is(k->event, f->event) || !matches_any(k, names)) {
continue;
}
for (size_t j = 0; j < f->n; j++) {
ok |= f->runs[j].clean && is(f->runs[j].command, k->command);
}
if (!ok && !(f->unfinished = dup_str(k->command))) {
(void)snprintf(s->err, sizeof s->err, "out of memory");
rc = -1;
}
}
/* 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[i].updated_input);
free(f->runs[i].updated_output);
}
free(f->runs);
free(f->reason);
free(f->unfinished);
f->runs = NULL;
f->reason = NULL;
f->unfinished = NULL;
f->n = 0;
}
/* ---- journal helpers -------------------------------------------------------------- */
static int hk_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 *hk_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 = hk_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 = hk_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, const char *origin, 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 = hk_sql_text(s, "SELECT json_object('prompt', ?1, 'origin', ?2)", prompt, origin ? origin : "user", 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 = hk_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 WHERE event = 'SessionStart' AND owner = ?1"
" GROUP BY session_id ORDER BY min(id)",
-1, &q, NULL) != SQLITE_OK) {
return hk_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"}, {"web_fetch", "WebFetch"}, {"web_search", "WebSearch"}};
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;
}
/* The first required hook of EVENT that takes one of NAMES, or NULL. */
static const hook *required_for(const pic_hooks *h, const char *event, const char *const *names) {
for (size_t i = 0; h && i < h->n; i++) {
if (h->list[i].required && is(h->list[i].event, event) && matches_any(&h->list[i], names)) {
return &h->list[i];
}
}
return NULL;
}
/* What the model sees in place of an output a required hook did not pass. */
static char *withheld(const char *command) { return fmt("[output withheld: the required hook %.200s did not finish]", command); }
/* A PostToolUse hook may replace what the model sees of a finished call:
* Claude Code's hookSpecificOutput.updatedToolOutput. The text parts of the
* last replacing hook's content (malloc'd), or NULL when none replaced it; a
* result with no text part shows nothing rather than the text the hook
* removed. *FAILED on a store error. */
static char *updated_text(pic_store *s, const pic_hook_fire *f, int *failed) {
const char *json = NULL;
char *text = NULL;
*failed = 0;
for (size_t i = 0; i < f->n; i++) {
if (f->runs[i].updated_output) {
json = f->runs[i].updated_output; /* the last replacing hook wins */
}
}
if (json && !(text = hk_sql_text(s,
"SELECT COALESCE((SELECT group_concat(json_extract(j.value,'$.text'), char(10))"
" FROM json_each(?1,'$.content') j WHERE json_extract(j.value,'$.type') = 'text'), '')",
json, NULL, NULL, 0))) {
*failed = hk_sql_fail(s);
}
return text;
}
/* A call's whole output (read's pic:output/N), as its compressed row holds it. */
typedef struct {
void *data;
int len;
int64_t sz;
char **images; /* the hashes of its images, in order: a withheld result holds them back too */
size_t nimages;
} kept_output;
static void kept_free(kept_output *k) {
free(k->data);
for (size_t i = 0; i < k->nimages; i++) {
free(k->images[i]);
}
free(k->images);
memset(k, 0, sizeof *k);
}
static int keep_output(pic_store *s, int64_t effect, kept_output *k) {
sqlite3_stmt *q = NULL;
memset(k, 0, sizeof *k);
if (sqlite3_prepare_v2(s->db, "SELECT sz, data FROM pic_output WHERE effect_id = ?1", -1, &q, NULL) != SQLITE_OK) {
return hk_sql_fail(s);
}
sqlite3_bind_int64(q, 1, effect);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_bytes(q, 1) > 0) {
k->sz = sqlite3_column_int64(q, 0);
k->len = sqlite3_column_bytes(q, 1);
if ((k->data = malloc((size_t)k->len))) {
memcpy(k->data, sqlite3_column_blob(q, 1), (size_t)k->len);
}
}
sqlite3_finalize(q);
if (k->len && !k->data) {
(void)snprintf(s->err, sizeof s->err, "out of memory");
return -1;
}
if (sqlite3_prepare_v2(s->db,
"SELECT image FROM pic_attachment WHERE entry_seq ="
" (SELECT seq FROM pic_entry WHERE kind = 'tool_result' AND effect_id = ?1) ORDER BY ordinal",
-1, &q, NULL) != SQLITE_OK) {
return hk_sql_fail(s);
}
sqlite3_bind_int64(q, 1, effect);
while (sqlite3_step(q) == SQLITE_ROW) {
char **grown = realloc(k->images, (k->nimages + 1) * sizeof *grown);
if (!grown) {
break;
}
k->images = grown;
if (!(k->images[k->nimages] = dup_str((const char *)sqlite3_column_text(q, 0)))) {
break;
}
k->nimages++;
}
sqlite3_finalize(q);
return 0;
}
/* In a transaction of its own: what the model sees of call EFFECT, in the
* call and its tool_result entry, becomes TEXT, so a resumed run and the next
* request agree. Its whole output and its images go too, unless KEEP gives
* them back. */
static int set_result(pic_store *s, int64_t effect, const char *text, const kept_output *keep) {
static const char *const steps[] = {
"UPDATE pic_effect SET result = ?1 WHERE id = ?2",
"UPDATE pic_entry SET body = ?1 WHERE kind = 'tool_result' AND effect_id = ?2",
"DELETE FROM pic_attachment WHERE entry_seq = (SELECT seq FROM pic_entry WHERE kind = 'tool_result' AND effect_id = ?2)",
"DELETE FROM pic_output WHERE effect_id = ?2",
"INSERT INTO pic_output(effect_id, sz, data) VALUES(?2, ?3, ?4)",
};
int ok = 1;
if (pic_begin(s) != 0) {
return -1;
}
for (size_t k = 0; ok && k < sizeof steps / sizeof steps[0]; k++) {
sqlite3_stmt *u = NULL;
if (k == 4 && !(keep && keep->data)) {
break;
}
if (sqlite3_prepare_v2(s->db, steps[k], -1, &u, NULL) != SQLITE_OK) {
ok = 0;
break;
}
if (k < 2) {
sqlite3_bind_text(u, 1, text, -1, SQLITE_STATIC);
}
sqlite3_bind_int64(u, 2, effect);
if (k == 4) {
sqlite3_bind_int64(u, 3, keep->sz);
sqlite3_bind_blob(u, 4, keep->data, keep->len, SQLITE_STATIC);
}
ok = sqlite3_step(u) == SQLITE_DONE && (k >= 2 || sqlite3_changes(s->db) == 1);
sqlite3_finalize(u);
}
for (size_t i = 0; ok && keep && i < keep->nimages; i++) { /* given back, in their order */
sqlite3_stmt *u = NULL;
ok = sqlite3_prepare_v2(s->db,
"INSERT INTO pic_attachment(entry_seq, queued_id, ordinal, image)"
" SELECT seq, NULL, ?3, ?1 FROM pic_entry WHERE kind = 'tool_result' AND effect_id = ?2",
-1, &u, NULL) == SQLITE_OK;
if (ok) {
sqlite3_bind_text(u, 1, keep->images[i], -1, SQLITE_STATIC);
sqlite3_bind_int64(u, 2, effect);
sqlite3_bind_int64(u, 3, (sqlite3_int64)i);
ok = sqlite3_step(u) == SQLITE_DONE;
}
sqlite3_finalize(u);
}
if (!ok) {
(void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
}
if (!ok || pic_commit(s) != 0) {
pic_rollback(s);
return -1;
}
return 0;
}
/* After call EFFECT's PostToolUse firing F: a required hook that did not
* finish leaves (or names) the notice; else a hook's replacement is written,
* or, where a required hook held the result back (REQUIRED), ORIGINAL and
* its whole output (KEEP) are given back. */
static int post_settle(pic_store *s, const pic_hook_fire *f, int64_t effect, const hook *required, const char *original,
const kept_output *keep) {
int failed, rc = 0;
char *text = updated_text(s, f, &failed);
if (failed) {
return -1;
}
if (f->unfinished) {
if (!required || !is(f->unfinished, required->command)) {
char *notice = withheld(f->unfinished);
rc = notice ? set_result(s, effect, notice, NULL) : -1;
free(notice);
}
} else if (text) {
rc = set_result(s, effect, text, NULL);
} else if (required) {
rc = set_result(s, effect, original, keep);
}
free(text);
return rc;
}
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 hk_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;
kept_output keep = {NULL, 0, 0, NULL, 0};
char *extra = pic_hooks_tool_extra(s, c->tool, c->input, c->call_id, c->result, c->is_error);
const char *names[4];
const hook *required;
pic_hooks_tool_names(c->tool, names);
/* Held back before any hook runs: a crash from here on leaves the
* notice in the journal, never the output. */
if ((required = required_for(s->hooks, "PostToolUse", names))) {
char *notice = withheld(required->command);
rc = !notice || keep_output(s, c->effect, &keep) != 0 || set_result(s, c->effect, notice, NULL) != 0 ? -1 : 0;
free(notice);
pic_fault("after-withhold");
}
fire_init(&f, "PostToolUse", session, submission, c->effect);
if (rc == 0) {
rc = extra ? pic_hook_fire_run(s, &f, names, extra) : -1;
}
free(extra);
if (rc == 0 && post_settle(s, &f, c->effect, required, c->result, &keep) != 0) {
rc = -1;
}
kept_free(&keep);
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_post_nested(pic_store *s, int64_t submission, int64_t ref, const char *tool, const char *input,
const char *call_id, const char *parent_call, char **result, int is_error) {
pic_hook_fire f;
const char *names[4];
char session[64], *extra, *with, *text = NULL;
int rc, failed = 0;
if (!s->hooks || !pic_hooks_has(s->hooks, "PostToolUse")) {
return 0;
}
pic_hooks_tool_names(tool, names);
extra = pic_hooks_tool_extra(s, tool, input, call_id, *result, is_error);
with = extra ? hk_sql_text(s, "SELECT json_set(?1, '$.parent_tool_use_id', ?2)", extra, parent_call, NULL, 0) : NULL;
free(extra);
session_of(s, submission, session);
fire_init(&f, "PostToolUse", session, submission, -ref);
f.ordinary = 1;
rc = with ? pic_hook_fire_run(s, &f, names, with) : -1;
free(with);
if (rc == 0 && (text = updated_text(s, &f, &failed)) != NULL) {
free(*result);
*result = text;
}
pic_hook_fire_free(&f);
return rc == 0 && !failed ? 0 : -1;
}
int pic_hooks_post_bash(pic_store *s, const char *command, char **output, int is_error, int *replaced) {
pic_hook_fire f;
const char *names[4];
char *input, *extra = NULL, *text = NULL;
int rc, failed = 0;
*replaced = 0;
if (!s->hooks || !pic_hooks_has(s->hooks, "PostToolUse")) {
return 0;
}
pic_hooks_tool_names("bash", names);
input = hk_sql_text(s, "SELECT json_object('command', ?1)", command, NULL, NULL, 0);
extra = input ? pic_hooks_tool_extra(s, "bash", input, "", *output, is_error) : NULL;
free(input);
/* Not journaled yet, so nothing to hold back: what the hooks leave is
* what is journaled. Their runs belong to no call (ref 0). */
fire_init(&f, "PostToolUse", "", 0, 0);
rc = extra ? pic_hook_fire_run(s, &f, names, extra) : -1;
free(extra);
if (rc == 0) {
text = f.unfinished ? withheld(f.unfinished) : updated_text(s, &f, &failed);
if (failed || (f.unfinished && !text)) {
rc = -1;
} else if (text) {
free(*output);
*output = text;
*replaced = 1;
}
}
pic_hook_fire_free(&f);
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 ? hk_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 hk_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 = hk_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;
}
void pic_hook_answer_free(pic_hook_answer *a) {
free(a->reason);
free(a->context);
memset(a, 0, sizeof *a);
}
int pic_hooks_ask(pic_store *s, const char *event, int64_t submission, int64_t ref, const char *name,
pic_hook_answerer answer, const char *facts, pic_hook_answer *out) {
sqlite3_stmt *q = NULL;
char session[64];
int64_t started;
int ok = 0;
memset(out, 0, sizeof *out);
if (sqlite3_prepare_v2(s->db,
"SELECT id, reason, context FROM pic_hook_run WHERE event = ?1 AND submission_id = ?2 AND ref = ?3"
" AND command IS NOT NULL AND state = 'done' ORDER BY id LIMIT 1",
-1, &q, NULL) != SQLITE_OK) {
return hk_sql_fail(s);
}
sqlite3_bind_text(q, 1, event, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 2, submission);
sqlite3_bind_int64(q, 3, ref);
if (sqlite3_step(q) == SQLITE_ROW) { /* a journaled answer stands */
out->id = sqlite3_column_int64(q, 0);
out->reason = dup_str((const char *)sqlite3_column_text(q, 1));
out->context = dup_str((const char *)sqlite3_column_text(q, 2));
}
sqlite3_finalize(q);
if (out->id || !answer) {
return 0;
}
started = sql_int(s, "SELECT CAST(unixepoch('subsec') * 1000 AS INTEGER)", NULL, NULL, 0, 0);
if (answer(s->db, submission, ref, facts, out) != 0) {
pic_hook_answer_free(out);
(void)snprintf(s->err, sizeof s->err, "%s: %s could not answer", event, name);
return -1;
}
if (!out->reason && !out->context) {
return 0;
}
session_of(s, submission, session);
if (pic_begin(s) != 0) {
pic_hook_answer_free(out);
return -1;
}
if (sqlite3_prepare_v2(s->db,
"INSERT INTO pic_hook_run(event, session_id, submission_id, ref, owner, command, duration_ms, state,"
" reason, context, created_ms) VALUES(?1, nullif(?2, ''), ?3, ?4, ?5, ?6,"
" max(0, CAST(unixepoch('subsec') * 1000 AS INTEGER) - ?7), 'done', ?8, ?9,"
" CAST(unixepoch('subsec') * 1000 AS INTEGER))",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, event, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, session, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 3, submission);
sqlite3_bind_int64(q, 4, ref);
bind_opt_text(q, 5, s->hooks ? s->hooks->owner : NULL);
sqlite3_bind_text(q, 6, name, -1, SQLITE_STATIC);
sqlite3_bind_int64(q, 7, started);
bind_opt_text(q, 8, out->reason);
bind_opt_text(q, 9, out->context);
ok = sqlite3_step(q) == SQLITE_DONE;
}
if (!ok) {
(void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
}
sqlite3_finalize(q);
out->id = ok ? sqlite3_last_insert_rowid(s->db) : 0;
if (!ok || pic_commit(s) != 0) {
pic_rollback(s);
pic_hook_answer_free(out);
return -1;
}
pic_fault("after-policy-answer");
return 0;
}
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 hk_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 = hk_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 = hk_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 = hk_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 = hk_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 hk_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 : hk_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 hk_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 : hk_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 hk_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 : hk_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], origin[300] = "user", *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,"
" coalesce((SELECT i.sender FROM pic_inbox i WHERE i.queued_id = pic_queued.id), 'user')"
" FROM pic_queued WHERE id = ?",
-1, &q, NULL) != SQLITE_OK) {
return hk_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);
(void)snprintf(origin, sizeof origin, "%s", (const char *)sqlite3_column_text(q, 5));
}
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, origin, &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)hk_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 hk_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;
}
}
}