/* 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 #include #include #include #include #include #include #include #include #include #include #include #include "hooks.h" #include "input.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 journal[PATH_MAX]; /* transcript_path */ 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 *journal, const char *owner, FILE *warn) { pic_hooks *h = hooks_new(workspace); char cwd[PATH_MAX]; if (!h || load_all(h, workspace, warn) != 0 || h->n == 0) { pic_hooks_free(h); return NULL; } if (journal[0] != '/' && getcwd(cwd, sizeof cwd)) { (void)snprintf(h->journal, sizeof h->journal, "%s/%s", cwd, journal); } else { (void)snprintf(h->journal, sizeof h->journal, "%s", journal); } 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; } /* ---- running a command ------------------------------------------------------ */ typedef struct { char *p; size_t n, cap; } obuf; static void obuf_add(obuf *b, const char *src, size_t n) { if (b->n + n > HOOK_OUT_MAX) { n = HOOK_OUT_MAX - b->n; } if (n == 0) { return; } if (b->n + n + 1 > b->cap) { size_t cap = (b->n + n + 1) * 2; char *grown = realloc(b->p, cap); if (!grown) { return; } b->p = grown; b->cap = cap; } memcpy(b->p + b->n, src, n); b->n += n; b->p[b->n] = '\0'; } typedef struct { int started, exited, code, timed_out; long ms; obuf out, err; char why[160]; } proc; static long now_ms(void) { return (long)(pic_platform_get()->mono_ns() / 1000000u); } /* The journal's lock and files must not outlive pic in a hook's process. */ static void close_inherited(void) { long max = sysconf(_SC_OPEN_MAX); if (max < 0 || max > 4096) { max = 4096; } for (int fd = 3; fd < (int)max; fd++) { (void)close(fd); } } /* Reads what FD has; closes it at EOF or on an error. */ static void pump(int *fd, obuf *b) { while (*fd >= 0) { char buf[4096]; ssize_t n = read(*fd, buf, sizeof buf); if (n > 0) { obuf_add(b, buf, (size_t)n); } else if (n < 0 && errno == EINTR) { continue; } else { if (n == 0 || errno != EAGAIN) { close(*fd); *fd = -1; } return; } } } static void close_fd(int *fd) { if (*fd >= 0) { close(*fd); *fd = -1; } } static void run_command(const char *command, const char *cwd, const char *input, int seconds, proc *r) { int in[2] = {-1, -1}, out[2] = {-1, -1}, err[2] = {-1, -1}, status = 0; size_t sent = 0, len = strlen(input); long start = now_ms(), deadline = start + seconds * 1000L; pid_t pid; memset(r, 0, sizeof *r); if (pipe(in) != 0 || pipe(out) != 0 || pipe(err) != 0) { (void)snprintf(r->why, sizeof r->why, "cannot start: %s", strerror(errno)); close_fd(&in[0]), close_fd(&in[1]), close_fd(&out[0]), close_fd(&out[1]), close_fd(&err[0]), close_fd(&err[1]); return; } pid = fork(); if (pid == 0) { sigset_t none; (void)setpgid(0, 0); (void)dup2(in[0], STDIN_FILENO); (void)dup2(out[1], STDOUT_FILENO); (void)dup2(err[1], STDERR_FILENO); close_inherited(); (void)signal(SIGPIPE, SIG_DFL); (void)signal(SIGINT, SIG_DFL); (void)signal(SIGTERM, SIG_DFL); (void)signal(SIGHUP, SIG_DFL); (void)signal(SIGQUIT, SIG_DFL); sigemptyset(&none); (void)sigprocmask(SIG_SETMASK, &none, NULL); if (chdir(cwd) != 0) { _exit(126); } (void)setenv("PIC_HOOK", "1", 1); execl("/bin/sh", "sh", "-c", command, (char *)NULL); _exit(127); } close_fd(&in[0]); close_fd(&out[1]); close_fd(&err[1]); if (pid < 0) { (void)snprintf(r->why, sizeof r->why, "cannot start: %s", strerror(errno)); close_fd(&in[1]), close_fd(&out[0]), close_fd(&err[0]); return; } (void)setpgid(pid, pid); r->started = 1; (void)fcntl(in[1], F_SETFL, fcntl(in[1], F_GETFL) | O_NONBLOCK); (void)fcntl(out[0], F_SETFL, fcntl(out[0], F_GETFL) | O_NONBLOCK); (void)fcntl(err[0], F_SETFL, fcntl(err[0], F_GETFL) | O_NONBLOCK); if (len == 0) { close_fd(&in[1]); } /* Waits start at 1ms and double to 50ms, as bash's supervisor's do. */ for (int wait_ms = 1;; wait_ms = wait_ms < 50 ? wait_ms * 2 : 50) { struct pollfd p[3] = {{in[1], POLLOUT, 0}, {out[0], POLLIN, 0}, {err[0], POLLIN, 0}}; long left; if (waitpid(pid, &status, WNOHANG) == pid) { r->exited = 1; break; } if ((left = deadline - now_ms()) <= 0) { r->timed_out = 1; break; } if (poll(p, 3, (int)(left < wait_ms ? left : wait_ms)) < 0 && errno != EINTR) { (void)snprintf(r->why, sizeof r->why, "poll: %s", strerror(errno)); break; } if (in[1] >= 0 && p[0].revents) { ssize_t w = write(in[1], input + sent, len - sent); if (w > 0) { sent += (size_t)w; } if (sent == len || (w < 0 && errno != EAGAIN && errno != EINTR)) { close_fd(&in[1]); /* all of it, or the hook stopped reading */ } } pump(&out[0], &r->out); pump(&err[0], &r->err); } if (!r->exited) { /* its whole process group, whatever it started */ (void)kill(-pid, SIGKILL); while (waitpid(pid, &status, 0) < 0 && errno == EINTR) { } } /* What it wrote before it exited; a background child holding the pipes * is not waited for. */ pump(&out[0], &r->out); pump(&err[0], &r->err); close_fd(&in[1]), close_fd(&out[0]), close_fd(&err[0]); r->ms = now_ms() - start; if (r->exited && !WIFEXITED(status)) { r->exited = 0; (void)snprintf(r->why, sizeof r->why, "terminated by signal %d", WIFSIGNALED(status) ? WTERMSIG(status) : 0); } else if (r->exited) { r->code = WEXITSTATUS(status); } } /* An async hook runs on its own, timeout and all, in a process that does not * hold pic's journal or output: pic goes on at once. */ static void run_async(const char *command, const char *cwd, const char *input, int seconds) { pid_t a = fork(); if (a == 0) { proc r; int null = open("/dev/null", O_RDWR); if (null >= 0) { (void)dup2(null, STDIN_FILENO); (void)dup2(null, STDOUT_FILENO); (void)dup2(null, STDERR_FILENO); } close_inherited(); (void)setsid(); (void)signal(SIGINT, SIG_IGN); (void)signal(SIGHUP, SIG_IGN); if (fork() != 0) { _exit(0); } run_command(command, cwd, input, seconds, &r); _exit(0); } if (a > 0) { while (waitpid(a, NULL, 0) < 0 && errno == EINTR) { } } } /* ---- firing an event ---------------------------------------------------------- */ static int is(const char *a, const char *b) { return strcmp(a, b) == 0; } static char *trimmed(const obuf *b) { const char *p = b->p ? b->p : ""; 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 proc *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; 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->journal, -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; } int pic_hook_fire_run(pic_store *s, pic_hook_fire *f, const char *name, const char *alt, const char *extra) { pic_hooks *h = s->hooks; char *input = NULL; for (size_t i = 0; h && i < h->n; i++) { const hook *k = &h->list[i]; int seen = 0; pic_hook_run *r; proc p; if (!is(k->event, f->event) || !matches(k, name, alt)) { 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) { continue; } if ((!input && !(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 (k->async) { run_async(k->command, h->workspace, input, k->seconds); r->error = dup_str("async: not waited for"); continue; } run_command(k->command, h->workspace, input, k->seconds, &p); judge(s, f->event, &p, k->seconds, r); free(p.out.p); free(p.err.p); 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); return 0; } 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); } } int pic_hook_fire_record(pic_store *s, const pic_hook_fire *f, int marker, int64_t entry) { sqlite3_stmt *q = NULL; int rc = 0; size_t n = f->n ? f->n : marker ? 1 : 0; if (n == 0) { return 0; } if (sqlite3_prepare_v2(s->db, "INSERT INTO pic_hook_run(event, session_id, submission_id, ref, owner, command, exit_code," " duration_ms, error, outcome, reason, context, entry_seq, created_ms)" " VALUES(?1, nullif(?2, ''), nullif(?3, 0), ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, nullif(?13, 0)," " CAST(unixepoch('subsec') * 1000 AS INTEGER))", -1, &q, NULL) != SQLITE_OK) { (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db)); return -1; } for (size_t i = 0; i < n && rc == 0; i++) { const pic_hook_run *r = f->n ? &f->runs[i] : NULL; 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, r ? r->command : NULL); if (r && r->exited) { sqlite3_bind_int(q, 7, r->code); } else { sqlite3_bind_null(q, 7); } sqlite3_bind_int64(q, 8, r ? r->ms : 0); bind_opt_text(q, 9, r ? r->error : NULL); bind_opt_text(q, 10, r ? r->outcome : NULL); bind_opt_text(q, 11, r ? r->reason : NULL); bind_opt_text(q, 12, r ? r->context : NULL); sqlite3_bind_int64(q, 13, entry); if (sqlite3_step(q) != SQLITE_DONE) { (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db)); rc = -1; } sqlite3_reset(q); } sqlite3_finalize(q); 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; } /* Journals F in a transaction of its own. */ static int record_alone(pic_store *s, const pic_hook_fire *f, int marker) { if (pic_begin(s) != 0 || pic_hook_fire_record(s, f, marker, 0) != 0 || pic_commit(s) != 0) { pic_rollback(s); return -1; } return 0; } 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); extra = sql_text(s, "SELECT json_object('source', ?1)", source, NULL, NULL, 0); rc = extra && pic_hook_fire_run(s, &f, source, NULL, extra) == 0 ? record_alone(s, &f, 1) : -1; free(extra); pic_hook_fire_free(&f); return rc; } int pic_hooks_prompt(pic_store *s, const char *session, const char *prompt) { pic_hook_fire f; char *extra; int rc; 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, NULL, extra) == 0 ? 0 : -1; free(extra); if (rc == 0 && f.blocked) { /* the prompt is erased, and what was added for it */ for (size_t i = 0; i < f.n; i++) { free(f.runs[i].context); f.runs[i].context = NULL; } } if (rc == 0) { rc = record_alone(s, &f, 0); } if (rc == 0 && f.blocked) { (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); extra = sql_text(s, "SELECT json_object('reason', ?1)", reason, NULL, NULL, 0); rc = extra && pic_hook_fire_run(s, &f, reason, NULL, extra) == 0 ? record_alone(s, &f, 1) : -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); for (size_t i = 0; i < n; i++) { if (rc == 0) { rc = pic_hooks_session_end(s, ids[i], reason); } free(ids[i]); } 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"}}; 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); fire_init(&f, "PostToolUse", session, submission, c->effect); rc = extra && pic_hook_fire_run(s, &f, c->tool, pic_hooks_cc_name(c->tool), extra) == 0 ? record_alone(s, &f, 0) : -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); rc = pic_hook_fire_run(s, &f, "compact", NULL, "{\"source\":\"compact\"}") == 0 ? record_alone(s, &f, 1) : -1; 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); 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, trigger, NULL, fields) == 0 ? record_alone(s, &f, 1) : -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 session_id = (SELECT session_id FROM pic_submission WHERE id = ?1)" " AND event IN ('SessionStart','UserPromptSubmit','PostToolUse')" " AND (context IS NOT NULL OR (event = 'PostToolUse' AND outcome = 'block')) 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("\n%s%s%s%s%s%s\n", 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; }