Artifact 66519e92815677d2e5706ed4c58dc50882638e85576a50bcefb5315323affc31:
- File
src/tools.c
— part of check-in
[417d9dcb01]
at
2026-11-18 18:04:16
on branch stage-2
— Wire the Messages API provider into the durable loop
The journal moves to schema 2: assistant entries hold the provider content verbatim, one turn may carry several tool calls with their call ids, and every provider request is a journaled generation. An interrupted request fails that attempt and the turn is asked again, up to three attempts. The provider builds requests from the journal, retries only before a stream starts, and reads the key just before sending it. A local fake server drives fourteen end-to-end cases, including a crash mid-stream and a check that the key never reaches the journal or output; the crash matrix grows to cover generations and parallel calls. (user: dmestas, size: 12636) [annotate] [blame] [check-ins using]
/* Tools. Each runs outside any database transaction and returns a malloc'd result. * hooks->started() commits that the effect has begun; it is called exactly once, * before any external effect, and a nonzero return means nothing ran. */ #include <errno.h> #include <fcntl.h> #include <poll.h> #include <signal.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include "pic.h" static char *format(const char *fmt, ...) { va_list ap; char *out; int n; va_start(ap, fmt); n = vsnprintf(NULL, 0, fmt, ap); va_end(ap); if (n < 0 || !(out = malloc((size_t)n + 1))) { return NULL; } va_start(ap, fmt); (void)vsnprintf(out, (size_t)n + 1, fmt, ap); va_end(ap); return out; } int pic_tool_replay_safe(const char *tool) { return strcmp(tool, "write") == 0; } /* Durable on macOS too: plain fsync there does not flush the drive cache. */ static int durable_sync(int fd) { #ifdef F_FULLFSYNC if (fcntl(fd, F_FULLFSYNC) == 0) { return 0; } #endif return fsync(fd); } /* Flat file names only: no directories, so no traversal or symlinked parents. */ static int valid_name(const char *name, size_t len) { if (len == 0 || len > 255 || (len == 1 && name[0] == '.') || (len == 2 && memcmp(name, "..", 2) == 0)) { return 0; } return memchr(name, '/', len) == NULL; } static int write_all(int fd, const char *p, size_t n) { while (n > 0) { ssize_t w = write(fd, p, n); if (w < 0) { if (errno == EINTR) { continue; } return -1; } p += w; n -= (size_t)w; } return 0; } const char pic_tool_schemas[] = "[{\"name\":\"write\",\"description\":\"Replace a text file in the workspace with the given text plus a final " "newline. Flat file names only (no directories).\",\"input_schema\":{\"type\":\"object\",\"properties\":{" "\"path\":{\"type\":\"string\",\"description\":\"File name in the workspace\"}," "\"text\":{\"type\":\"string\",\"description\":\"Full new contents\"}},\"required\":[\"path\",\"text\"]}}," "{\"name\":\"exec\",\"description\":\"Run a shell command in the workspace with /bin/sh -c. Returns its " "combined output and exit status. It is never re-run automatically if interrupted.\",\"input_schema\":{" "\"type\":\"object\",\"properties\":{\"command\":{\"type\":\"string\"}},\"required\":[\"command\"]}}]"; /* Replaces NAME atomically and durably, so running it twice has the effect * of running it once. */ static char *tool_write(const char *workspace, const char *file, const char *text, const pic_tool_hooks *h) { char name[256], path[4096], tmp[4200]; size_t len; int fd, dir; if (h->started(h->ctx) != 0) { return NULL; } if (!file || !text) { return format("error: write needs string inputs path and text"); } len = strlen(file); if (!valid_name(file, len)) { return format("error: invalid file name"); } memcpy(name, file, len); name[len] = '\0'; if (snprintf(path, sizeof path, "%s/%s", workspace, name) >= (int)sizeof path || snprintf(tmp, sizeof tmp, "%s.pic-tmp", path) >= (int)sizeof tmp) { return format("error: path too long"); } fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0644); if (fd < 0) { return format("error: cannot create %s: %s", name, strerror(errno)); } if (write_all(fd, text, strlen(text)) != 0 || write_all(fd, "\n", 1) != 0 || durable_sync(fd) != 0) { int e = errno; close(fd); unlink(tmp); return format("error: cannot write %s: %s", name, strerror(e)); } close(fd); if (rename(tmp, path) != 0) { int e = errno; unlink(tmp); return format("error: cannot replace %s: %s", name, strerror(e)); } /* The rename itself must survive power loss before the effect is "done". */ dir = open(workspace, O_RDONLY | O_CLOEXEC); if (dir < 0 || durable_sync(dir) != 0) { int e = errno; if (dir >= 0) { close(dir); } return format("error: cannot sync workspace: %s", strerror(e)); } close(dir); return format("wrote %s (%zu bytes)", name, strlen(text) + 1); } static long now_ms(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } /* Runs inside the supervisor process. Starts the command in its own process * group only after pic says go, ends when the command itself exits (not when * its output closes) or at the deadline, and kills the whole group if pic dies * first. The result goes back to pic on report_fd. */ static void supervise(const char *workspace, const char *command, int seconds, int gate_fd, int report_fd) { char go = 0, *out = malloc(PIC_OUTPUT_CAP + 1), *result; int pipefd[2], status = 0, exited = 0, timed_out = 0, truncated = 0, output_open = 1; size_t used = 0; long deadline = now_ms() + (long)seconds * 1000; pid_t child; (void)signal(SIGPIPE, SIG_IGN); if (read(gate_fd, &go, 1) != 1 || go != 'g' || !out || pipe(pipefd) != 0) { _exit(0); /* pic died before committing "started", or no resources: nothing ran */ } child = fork(); if (child < 0) { result = format("error: fork failed: %s", strerror(errno)); if (result) { (void)write_all(report_fd, result, strlen(result)); } _exit(0); } if (child == 0) { (void)setpgid(0, 0); if (chdir(workspace) != 0) { _exit(126); } (void)dup2(pipefd[1], STDOUT_FILENO); (void)dup2(pipefd[1], STDERR_FILENO); close(pipefd[0]); close(pipefd[1]); close(gate_fd); close(report_fd); (void)signal(SIGPIPE, SIG_DFL); (void)signal(SIGINT, SIG_DFL); (void)signal(SIGTERM, SIG_DFL); (void)signal(SIGHUP, SIG_DFL); execl("/bin/sh", "sh", "-c", command, (char *)NULL); _exit(127); } (void)setpgid(child, child); close(pipefd[1]); (void)fcntl(pipefd[0], F_SETFL, fcntl(pipefd[0], F_GETFL) | O_NONBLOCK); for (;;) { struct pollfd p[2] = {{gate_fd, POLLIN, 0}, {output_open ? pipefd[0] : -1, POLLIN, 0}}; long left = deadline - now_ms(); if (waitpid(child, &status, WNOHANG) == child) { exited = 1; break; } if (left <= 0) { timed_out = 1; break; } if (poll(p, 2, left < 50 ? (int)left : 50) < 0 && errno != EINTR) { break; } if (p[0].revents) { /* pic sends nothing after "go": readable means pic exited. */ (void)kill(-child, SIGKILL); (void)waitpid(child, &status, 0); _exit(0); } while (output_open) { char buf[4096]; ssize_t n = read(pipefd[0], buf, sizeof buf); if (n > 0) { size_t take = (size_t)n < PIC_OUTPUT_CAP - used ? (size_t)n : PIC_OUTPUT_CAP - used; memcpy(out + used, buf, take); used += take; truncated |= take < (size_t)n; } else if (n == 0 || errno != EINTR) { output_open = n != 0; /* EOF closes; EAGAIN waits for more */ break; } } } /* Descendants do not outlive the command, whatever they did with the pipe. */ (void)kill(-child, SIGKILL); if (!exited) { while (waitpid(child, &status, 0) < 0 && errno == EINTR) { } } /* Keep what the command wrote after the last poll. */ while (output_open) { char buf[4096]; ssize_t n = read(pipefd[0], buf, sizeof buf); if (n > 0) { size_t take = (size_t)n < PIC_OUTPUT_CAP - used ? (size_t)n : PIC_OUTPUT_CAP - used; memcpy(out + used, buf, take); used += take; truncated |= take < (size_t)n; } else if (n == 0 || errno != EINTR) { break; } } close(pipefd[0]); for (size_t i = 0; i < used; i++) { if (out[i] == '\0') { out[i] = ' '; /* results are text; a NUL would silently cut them */ } } out[used] = '\0'; if (timed_out) { result = format("timeout after %ds%s\n%s", seconds, truncated ? " (output truncated)" : "", out); } else if (WIFEXITED(status)) { result = format("exit=%d%s\n%s", WEXITSTATUS(status), truncated ? " (output truncated)" : "", out); } else { result = format("signal=%d%s\n%s", WIFSIGNALED(status) ? WTERMSIG(status) : 0, truncated ? " (output truncated)" : "", out); } if (result) { (void)write_all(report_fd, result, strlen(result)); } _exit(0); } /* pic forks a supervisor before committing "started"; the supervisor only * starts the command after the commit. The supervisor also keeps pic's * single-writer lock open until it exits, so a restarted pic cannot recover * while a killed command's group is still being torn down. */ static char *tool_exec(const char *workspace, const char *command, const pic_tool_hooks *h) { int gate[2], report[2]; sigset_t stop, saved; pid_t sup; char *buf; size_t used = 0, cap = PIC_OUTPUT_CAP + 256; if (pipe(gate) != 0) { return h->started(h->ctx) == 0 ? format("error: cannot start command") : NULL; } if (pipe(report) != 0) { close(gate[0]); close(gate[1]); return h->started(h->ctx) == 0 ? format("error: cannot start command") : NULL; } /* The supervisor shares pic's process group, so a terminal Ctrl-C or a * group-wide TERM/HUP reaches it too. It must outlive pic long enough to * kill the command, so it ignores them and relies on the gate alone. The * signals stay blocked across fork so none lands before "ignore" is set. */ sigemptyset(&stop); sigaddset(&stop, SIGINT); sigaddset(&stop, SIGTERM); sigaddset(&stop, SIGHUP); (void)sigprocmask(SIG_BLOCK, &stop, &saved); sup = fork(); if (sup == 0) { (void)signal(SIGINT, SIG_IGN); /* also discards any already pending */ (void)signal(SIGTERM, SIG_IGN); (void)signal(SIGHUP, SIG_IGN); (void)sigprocmask(SIG_SETMASK, &saved, NULL); close(gate[1]); close(report[0]); supervise(workspace, command, h->exec_seconds, gate[0], report[1]); } (void)sigprocmask(SIG_SETMASK, &saved, NULL); close(gate[0]); close(report[1]); if (sup < 0 || h->started(h->ctx) != 0) { close(gate[1]); close(report[0]); if (sup > 0) { while (waitpid(sup, NULL, 0) < 0 && errno == EINTR) { } return NULL; } return h->started(h->ctx) == 0 ? format("error: fork failed") : NULL; } /* Allocate before releasing: once "g" is sent the command may run, and its * outcome must not then be reported as a failure to start. */ if (!(buf = malloc(cap + 1)) || write_all(gate[1], "g", 1) != 0) { free(buf); close(gate[1]); close(report[0]); while (waitpid(sup, NULL, 0) < 0 && errno == EINTR) { } return format("error: cannot release command"); } for (;;) { ssize_t n = read(report[0], buf + used, cap - used); if (n < 0 && errno == EINTR) { continue; } if (n <= 0) { break; } used += (size_t)n; if (used == cap) { break; } } buf[used] = '\0'; close(report[0]); while (waitpid(sup, NULL, 0) < 0 && errno == EINTR) { } close(gate[1]); if (used == 0) { free(buf); return format("error: command supervisor produced no result"); } return buf; } char *pic_tool_run(const char *workspace, const char *tool, const pic_tool_args *args, const pic_tool_hooks *hooks) { if (strcmp(tool, "write") == 0) { return tool_write(workspace, args->path, args->text, hooks); } if (strcmp(tool, "exec") == 0) { if (!args->command) { return hooks->started(hooks->ctx) == 0 ? format("error: exec needs a string input command") : NULL; } return tool_exec(workspace, args->command, hooks); } return hooks->started(hooks->ctx) == 0 ? format("error: unknown tool %s", tool) : NULL; }