Artifact eae3215acd3af06cec9af4cb1c7d14d19d7ed53d04c8ad8a1a5028d71409479e:
- File
src/tools.c
— part of check-in
[6b33552ab9]
at
2026-11-20 01:33:41
on branch tui-round-3
— TUI round 3: steering keys, live output, retry countdown, durable !cmd
Enter steers a running reply and Alt+Enter queues a follow-up (Shift+Enter or Ctrl+J for a newline); the queue shows Pi's labels, delivered steering appears where it lands, returned messages go back to the editor, and Esc aborts over the command pipe with signals as the fallback. The running bash block shows its output as it arrives; retries count down and Esc cancels the wait. pic bash CMD (optionally --no-context, -c or a conversation id) runs a command and journals it as Pi's bash execution message, so !cmd survives a restart and reaches the model as Pi does. The footer shows cost when usage carries one. (user: dmestas, size: 42431) [annotate] [blame] [check-ins using]
/* Tools: Pi's default set (read, write, edit, bash) with Pi's inputs, limits * and messages. Each runs outside any database transaction and returns a * malloc'd result with *is_error set. hooks->started() commits that the effect * has begun; it is called exactly once, before any external effect, and a * nonzero return means nothing ran (the tool then returns NULL). * * read, write and edit are replay-safe: write's bytes come from its input, * and edit computes the new file content first and journals it as the plan * when it commits "started", so a replay writes the same bytes. bash is not. */ #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <poll.h> #include <signal.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "net.h" #include "pic.h" #include "platform.h" #define MAX_LINES 2000 #define MAX_BYTES 51200 #define READ_FILE_CAP (256u << 20) 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; } /* An error result: is_error set, text formatted. */ static char *fail(int *is_error, const char *fmt, ...) { va_list ap; char *out; int n; *is_error = 1; 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, "read") == 0 || strcmp(tool, "write") == 0 || strcmp(tool, "edit") == 0; } const char pic_tool_schemas[] = "[{\"name\":\"read\",\"description\":\"Read the contents of a file. For text files, output is truncated to 2000 " "lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue " "with offset until complete.\",\"input_schema\":{\"type\":\"object\",\"properties\":{" "\"path\":{\"type\":\"string\",\"description\":\"Path to the file to read (relative or absolute)\"}," "\"offset\":{\"type\":\"number\",\"description\":\"Line number to start reading from (1-indexed)\"}," "\"limit\":{\"type\":\"number\",\"description\":\"Maximum number of lines to read\"}},\"required\":[\"path\"]}}," "{\"name\":\"bash\",\"description\":\"Execute a bash command in the current working directory. Returns stdout and " "stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is " "kept in the journal and named in the truncation notice; read it by that name. Optionally provide a timeout in seconds.\",\"input_schema\":{\"type\":\"object\"," "\"properties\":{\"command\":{\"type\":\"string\",\"description\":\"Bash command to execute\"}," "\"timeout\":{\"type\":\"number\",\"description\":\"Timeout in seconds (optional)\"}},\"required\":[\"command\"]}}," "{\"name\":\"edit\",\"description\":\"Edit a single file using exact text replacement. Every edits[].oldText must " "match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby " "lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions " "just to connect distant changes.\",\"input_schema\":{\"type\":\"object\",\"properties\":{" "\"path\":{\"type\":\"string\",\"description\":\"Path to the file to edit (relative or absolute)\"}," "\"edits\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{" "\"oldText\":{\"type\":\"string\",\"description\":\"Exact text to find; must be unique in the original file\"}," "\"newText\":{\"type\":\"string\",\"description\":\"Replacement text\"}},\"required\":[\"oldText\",\"newText\"]}}}," "\"required\":[\"path\",\"edits\"]}}," "{\"name\":\"write\",\"description\":\"Write content to a file. Creates the file if it doesn't exist, overwrites " "if it does. Automatically creates parent directories.\",\"input_schema\":{\"type\":\"object\",\"properties\":{" "\"path\":{\"type\":\"string\",\"description\":\"Path to the file to write (relative or absolute)\"}," "\"content\":{\"type\":\"string\",\"description\":\"Content to write to the file\"}}," "\"required\":[\"path\",\"content\"]}}]"; /* ---- files ------------------------------------------------------------------ */ /* 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); } 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; } /* Pi's path rules: a leading '@' is dropped, '~' is the home directory, * absolute paths are used as given and relative ones are under the * workspace. There is no sandbox. */ static char *resolve(const char *workspace, const char *path) { const char *home = getenv("HOME"); if (path[0] == '@') { path++; } if (home && (strcmp(path, "~") == 0 || strncmp(path, "~/", 2) == 0)) { return format("%s%s", home, path + 1); } if (path[0] == '/') { return format("%s", path); } return format("%s/%s", workspace, path); } static void sync_dir_of(const char *path) { char *dir = format("%s", path), *slash; int fd; if (!dir) { return; } slash = strrchr(dir, '/'); if (slash == dir) { slash[1] = '\0'; } else if (slash) { *slash = '\0'; } fd = open(slash ? dir : ".", O_RDONLY | O_CLOEXEC); if (fd >= 0) { (void)durable_sync(fd); close(fd); } free(dir); } /* mkdir -p for path's parent: 0 or an errno value. */ static int make_parents(const pic_executor *ex, const char *path) { char *p = format("%s", path); int rc = 0; if (!p) { return ENOMEM; } for (char *s = strchr(p + 1, '/'); s && rc == 0; s = strchr(s + 1, '/')) { *s = '\0'; rc = ex->mkdir(ex->state, p); rc = rc == EEXIST ? 0 : rc; *s = '/'; } free(p); return rc; } /* Replaces path with bytes atomically and durably: temp file, sync, rename, * then sync the directory so the rename survives power loss. */ static int replace_file(const char *path, const char *bytes, size_t len, mode_t mode) { char *tmp = format("%s.pic-tmp", path); int fd, e; if (!tmp) { return ENOMEM; } fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, mode); if (fd < 0) { e = errno; free(tmp); return e; } if (write_all(fd, bytes, len) != 0 || durable_sync(fd) != 0) { e = errno; close(fd); unlink(tmp); free(tmp); return e; } close(fd); if (rename(tmp, path) != 0) { e = errno; unlink(tmp); free(tmp); return e; } free(tmp); sync_dir_of(path); return 0; } /* Reads a whole regular file of at most max bytes. NULL with *err set to an * errno value. */ static char *slurp(const char *path, size_t max, size_t *len, int *err) { struct stat st; char *buf; size_t used = 0; int fd = open(path, O_RDONLY | O_CLOEXEC); if (fd < 0) { *err = errno; return NULL; } if (fstat(fd, &st) != 0 || S_ISDIR(st.st_mode) || (size_t)st.st_size > max) { *err = S_ISDIR(st.st_mode) ? EISDIR : EFBIG; close(fd); return NULL; } buf = malloc((size_t)st.st_size + 1); while (buf) { ssize_t n = read(fd, buf + used, (size_t)st.st_size - used); if (n < 0 && errno == EINTR) { continue; } if (n <= 0) { break; } used += (size_t)n; if (used == (size_t)st.st_size) { break; } } close(fd); if (!buf) { *err = ENOMEM; return NULL; } buf[used] = '\0'; *len = used; return buf; } /* ---- the host executor's files ---------------------------------------------- */ static int host_stat(void *state, const char *name, pic_file_stat *st) { struct stat sb; (void)state; if (stat(name, &sb) != 0) { return errno; } st->is_dir = S_ISDIR(sb.st_mode); st->size = (uint64_t)sb.st_size; st->mode = (unsigned)(sb.st_mode & 07777); return 0; } static int host_read(void *state, const char *name, size_t max, int flags, char **buf, size_t *len) { int err = 0; (void)state; if ((flags & PIC_FILE_WRITABLE) && access(name, R_OK | W_OK) != 0) { return errno; } *buf = slurp(name, max, len, &err); return *buf ? 0 : err; } static int host_write(void *state, const char *name, const char *src, size_t n, unsigned mode) { (void)state; return replace_file(name, src, n, (mode_t)mode); } static int host_remove(void *state, const char *name) { (void)state; return unlink(name) == 0 ? 0 : errno; } /* The new directory's entry is made durable. */ static int host_mkdir(void *state, const char *name) { (void)state; if (mkdir(name, 0755) != 0) { return errno; } sync_dir_of(name); return 0; } static int host_list(void *state, const char *name, int (*cb)(void *cb_state, const char *entry), void *cb_state) { DIR *d; struct dirent *e; int rc = 0; (void)state; if (!(d = opendir(name))) { return errno; } while (rc == 0 && (errno = 0, e = readdir(d))) { if (strcmp(e->d_name, ".") != 0 && strcmp(e->d_name, "..") != 0) { rc = cb(cb_state, e->d_name); } } if (rc == 0 && errno != 0) { rc = errno; } closedir(d); return rc; } static const char *errno_name(int e) { switch (e) { case ENOENT: return "ENOENT"; case EACCES: return "EACCES"; case EISDIR: return "EISDIR"; case ENOTDIR: return "ENOTDIR"; case EFBIG: return "EFBIG"; case ENOMEM: return "ENOMEM"; default: return "EIO"; } } /* Pi's formatSize. */ static void format_size(size_t n, char *out, size_t cap) { if (n < 1024) { (void)snprintf(out, cap, "%zuB", n); } else if (n < 1024 * 1024) { (void)snprintf(out, cap, "%.1fKB", (double)n / 1024.0); } else { (void)snprintf(out, cap, "%.1fMB", (double)n / (1024.0 * 1024.0)); } } /* ---- read ------------------------------------------------------------------- */ static char *tool_read(const char *workspace, const pic_tool_args *a, const pic_tool_hooks *h, int *is_error) { const pic_executor *ex = pic_executor_get(); char *path, *data, *out = NULL, size[32]; size_t len = 0, total = 1, start, line, pos, sel_start, bytes = 0, kept = 0, i, line_start, end_line; int err = 0, by_bytes = 0; if (h->started(h->ctx, NULL, 0) != 0) { return NULL; } if (a->bad_input) { return fail(is_error, "%s", a->bad_input); } if (!a->path) { return fail(is_error, "read needs a string input path"); } if (h->fetch && (strncmp(a->path, "pic:output/", 11) == 0 || strncmp(a->path, "pic:bash/", 9) == 0)) { /* A command's full output, kept in the journal. */ path = strdup(a->path); data = path ? h->fetch(h->ctx, a->path, &len) : NULL; err = ENOENT; } else { if (!(path = resolve(workspace, a->path))) { return NULL; } err = ex->read(ex->state, path, READ_FILE_CAP, 0, &data, &len); } if (!data) { out = fail(is_error, "%s: %s, read '%s'", errno_name(err), strerror(err), path ? path : a->path); free(path); return out; } for (i = 0; i < len; i++) { total += data[i] == '\n'; } if (a->has_offset && a->offset < 1) { out = fail(is_error, "Offset must be at least 1"); goto done; } start = a->has_offset ? (size_t)a->offset - 1 : 0; if (start >= total) { out = fail(is_error, "Offset %ld is beyond end of file (%zu lines total)", a->offset, total); goto done; } /* Find the byte where line `start` begins. */ for (pos = 0, line = 0; line < start; pos++) { line += data[pos] == '\n'; } sel_start = pos; end_line = a->has_limit && a->limit > 0 && start + (size_t)a->limit < total ? start + (size_t)a->limit : total; /* Keep whole lines while within both limits (Pi's truncateHead). */ for (line = start, line_start = pos; line < end_line; line++) { size_t line_end = line_start; while (line_end < len && data[line_end] != '\n') { line_end++; } { size_t cost = (line_end - line_start) + (kept > 0 ? 1 : 0); if (kept == MAX_LINES) { break; } if (bytes + cost > MAX_BYTES) { by_bytes = 1; if (kept == 0) { format_size(line_end - line_start, size, sizeof size); out = format("[Line %zu is %s, exceeds 50KB limit. Use bash: sed -n '%zup' %s | head -c %d]", start + 1, size, start + 1, a->path, MAX_BYTES); goto done; } break; } bytes += cost; } kept++; line_start = line_end + 1; } { size_t shown_end = start + kept; out = format("%.*s", (int)bytes, data + sel_start); if (out && shown_end < end_line) { char *more = format("%s\n\n[Showing lines %zu-%zu of %zu%s. Use offset=%zu to continue.]", out, start + 1, shown_end, total, by_bytes ? " (50KB limit)" : "", shown_end + 1); free(out); out = more; } else if (out && end_line < total) { char *more = format("%s\n\n[%zu more lines in file. Use offset=%zu to continue.]", out, total - end_line, end_line + 1); free(out); out = more; } } done: free(data); free(path); return out; } /* ---- write ------------------------------------------------------------------ */ static char *tool_write(const char *workspace, const pic_tool_args *a, const pic_tool_hooks *h, int *is_error) { const pic_executor *ex = pic_executor_get(); char *path; int e; if (h->started(h->ctx, NULL, 0) != 0) { return NULL; } if (a->bad_input) { return fail(is_error, "%s", a->bad_input); } if (!a->path || !a->content) { return fail(is_error, "write needs string inputs path and content"); } if (!(path = resolve(workspace, a->path))) { return NULL; } if ((e = make_parents(ex, path)) != 0) { free(path); return fail(is_error, "Could not create directories for %s: %s", a->path, strerror(e)); } e = ex->write(ex->state, path, a->content, strlen(a->content), 0644); free(path); if (e != 0) { return fail(is_error, "Could not write %s: %s", a->path, strerror(e)); } return format("Successfully wrote to %s", a->path); } /* ---- edit ------------------------------------------------------------------- */ /* Copies s with every CRLF turned into LF. */ static char *to_lf(const char *s, size_t n, size_t *out_len) { char *out = malloc(n + 1); size_t j = 0; if (!out) { return NULL; } for (size_t i = 0; i < n; i++) { if (s[i] == '\r' && i + 1 < n && s[i + 1] == '\n') { continue; } out[j++] = s[i]; } out[j] = '\0'; *out_len = j; return out; } typedef struct { size_t pos, old_len, index; const char *new_text; size_t new_len; char *old_lf, *new_lf; } match; static int by_pos(const void *a, const void *b) { const match *x = a, *y = b; return x->pos < y->pos ? -1 : x->pos > y->pos; } static size_t count_occurrences(const char *hay, size_t n, const char *needle, size_t m, size_t *first) { size_t count = 0, at = 0; *first = 0; while (m > 0 && at + m <= n) { const char *hit = memmem(hay + at, n - at, needle, m); if (!hit) { break; } if (count++ == 0) { *first = (size_t)(hit - hay); } at = (size_t)(hit - hay) + m; } return count; } /* Computes the edited file (the plan) or an error text. */ static char *plan_edit(const char *path_shown, const char *orig, size_t orig_len, const pic_tool_args *a, size_t *plan_len, char **error) { int bom = orig_len >= 3 && memcmp(orig, "\xEF\xBB\xBF", 3) == 0; const char *body = orig + (bom ? 3 : 0); size_t body_len = orig_len - (bom ? 3 : 0), lf_len = 0, out_len = 0, at = 0; int crlf = memmem(body, body_len, "\r\n", 2) != NULL; char *lf = to_lf(body, body_len, &lf_len), *out = NULL, *plan = NULL; match *m = calloc(a->nedits ? a->nedits : 1, sizeof *m); *error = NULL; if (!lf || !m) { goto done; } for (size_t i = 0; i < a->nedits; i++) { size_t n, first; m[i].index = i; if (!(m[i].old_lf = to_lf(a->old_text[i], strlen(a->old_text[i]), &m[i].old_len)) || !(m[i].new_lf = to_lf(a->new_text[i], strlen(a->new_text[i]), &m[i].new_len))) { goto done; } m[i].new_text = m[i].new_lf; if (m[i].old_len == 0) { *error = a->nedits == 1 ? format("oldText must not be empty in %s.", path_shown) : format("edits[%zu].oldText must not be empty in %s.", i, path_shown); goto done; } n = count_occurrences(lf, lf_len, m[i].old_lf, m[i].old_len, &first); if (n == 0) { *error = a->nedits == 1 ? format("Could not find the exact text in %s. The old text must match exactly " "including all whitespace and newlines.", path_shown) : format("Could not find edits[%zu] in %s. The oldText must match exactly " "including all whitespace and newlines.", i, path_shown); goto done; } if (n > 1) { *error = a->nedits == 1 ? format("Found %zu occurrences of the text in %s. The text must be unique. Please " "provide more context to make it unique.", n, path_shown) : format("Found %zu occurrences of edits[%zu] in %s. Each oldText must be unique. " "Please provide more context to make it unique.", n, i, path_shown); goto done; } m[i].pos = first; } qsort(m, a->nedits, sizeof *m, by_pos); for (size_t i = 1; i < a->nedits; i++) { if (m[i].pos < m[i - 1].pos + m[i - 1].old_len) { size_t x = m[i - 1].index < m[i].index ? m[i - 1].index : m[i].index; size_t y = m[i - 1].index < m[i].index ? m[i].index : m[i - 1].index; *error = format("edits[%zu] and edits[%zu] overlap in %s. Merge them into one edit or target disjoint " "regions.", x, y, path_shown); goto done; } } { size_t cap = lf_len + 1; for (size_t i = 0; i < a->nedits; i++) { cap += m[i].new_len; } if (!(out = malloc(cap))) { goto done; } for (size_t i = 0; i < a->nedits; i++) { memcpy(out + out_len, lf + at, m[i].pos - at); out_len += m[i].pos - at; memcpy(out + out_len, m[i].new_text, m[i].new_len); out_len += m[i].new_len; at = m[i].pos + m[i].old_len; } memcpy(out + out_len, lf + at, lf_len - at); out_len += lf_len - at; } if (out_len == lf_len && memcmp(out, lf, lf_len) == 0) { *error = format("No changes made to %s. The replacement produced identical content.", path_shown); goto done; } /* Restore the file's BOM and line endings. */ { size_t extra = 0, j = 0; for (size_t i = 0; crlf && i < out_len; i++) { extra += out[i] == '\n'; } if (!(plan = malloc(out_len + extra + 4))) { goto done; } if (bom) { memcpy(plan, "\xEF\xBB\xBF", 3); j = 3; } for (size_t i = 0; i < out_len; i++) { if (crlf && out[i] == '\n') { plan[j++] = '\r'; } plan[j++] = out[i]; } plan[j] = '\0'; *plan_len = j; } done: for (size_t i = 0; m && i < a->nedits; i++) { free(m[i].old_lf); free(m[i].new_lf); } free(m); free(lf); free(out); if (!plan && !*error) { *error = format("out of memory"); } return plan; } static char *tool_edit(const char *workspace, const pic_tool_args *a, const pic_tool_hooks *h, int *is_error) { const pic_executor *ex = pic_executor_get(); char *path, *orig = NULL, *plan, *error = NULL, *out; size_t len = 0, plan_len = 0; pic_file_stat st; int e; if (h->plan) { /* An earlier attempt computed and journaled the result: write it. */ if (h->started(h->ctx, h->plan, h->plan_len) != 0) { return NULL; } if (!a->path || !(path = resolve(workspace, a->path))) { return fail(is_error, "edit replay lost its path"); } e = ex->write(ex->state, path, h->plan, h->plan_len, ex->stat(ex->state, path, &st) == 0 ? st.mode : 0644); free(path); return e != 0 ? fail(is_error, "Could not write %s: %s", a->path, strerror(e)) : format("Successfully replaced %zu block(s) in %s.", a->nedits, a->path); } if (a->bad_input || !a->path || a->nedits == 0) { if (h->started(h->ctx, NULL, 0) != 0) { return NULL; } return fail(is_error, "%s", a->bad_input ? a->bad_input : !a->path ? "edit needs a string input path" : "Edit tool input is invalid. edits must contain at least one replacement."); } if (!(path = resolve(workspace, a->path))) { return NULL; } if ((e = ex->read(ex->state, path, READ_FILE_CAP, PIC_FILE_WRITABLE, &orig, &len)) != 0) { free(path); if (h->started(h->ctx, NULL, 0) != 0) { return NULL; } return fail(is_error, "Could not edit file: %s. Error code: %s.", a->path, errno_name(e)); } plan = plan_edit(a->path, orig, len, a, &plan_len, &error); free(orig); if (h->started(h->ctx, plan, plan ? plan_len : 0) != 0) { free(plan); free(error); free(path); return NULL; } if (!plan) { free(path); *is_error = 1; return error; } e = ex->write(ex->state, path, plan, plan_len, ex->stat(ex->state, path, &st) == 0 ? st.mode : 0644); free(plan); free(path); out = e != 0 ? fail(is_error, "Could not write %s: %s", a->path, strerror(e)) : format("Successfully replaced %zu block(s) in %s.", a->nedits, a->path); return out; } /* ---- bash ------------------------------------------------------------------- */ static long now_ms(void) { return (long)(pic_platform_get()->mono_ns() / 1000000); } /* The most of a command's output pic keeps in the journal: its last 16MB. */ #define FULL_KEEP (16u * 1024 * 1024) /* Pi's BASH_UPDATE_THROTTLE_MS: the least between two live-output updates. */ #define PARTIAL_MS 100 /* The last MAX_BYTES of output, plus totals, and the last FULL_KEEP bytes of * it, which go to pic in case the result has to be truncated. */ typedef struct { char ring[MAX_BYTES]; size_t head, filled, total_bytes, newlines; char last; char *full; size_t full_len, full_cap; int full_failed; } tail_buf; static void full_add(tail_buf *t, const char *p, size_t n) { if (t->full_failed) { return; } if (n > FULL_KEEP) { p += n - FULL_KEEP; n = FULL_KEEP; t->full_len = 0; } if (t->full_len + n > 2 * (size_t)FULL_KEEP) { memmove(t->full, t->full + t->full_len - (FULL_KEEP - n), FULL_KEEP - n); t->full_len = FULL_KEEP - n; } if (t->full_len + n > t->full_cap) { size_t cap = t->full_cap ? t->full_cap : 65536; char *grown; while (cap < t->full_len + n) { cap *= 2; } if (!(grown = realloc(t->full, cap))) { t->full_failed = 1; return; } t->full = grown; t->full_cap = cap; } memcpy(t->full + t->full_len, p, n); t->full_len += n; } static void tail_add(tail_buf *t, const char *p, size_t n) { full_add(t, p, n); for (size_t i = 0; i < n; i++) { char c = p[i] == '\0' ? ' ' : p[i]; /* results are text; a NUL would cut them */ t->ring[t->head] = c; t->head = (t->head + 1) % MAX_BYTES; t->filled += t->filled < MAX_BYTES; t->newlines += c == '\n'; t->last = c; } t->total_bytes += n; } /* Pi's tail truncation: the last whole lines within 2000 lines and 50KB. */ static char *tail_text(tail_buf *t, const char *where, char **notice) { char *all = malloc(t->filled + 1); size_t len = t->filled, total_lines, kept_lines = 0, s = 0; int by_bytes = t->total_bytes > t->filled; *notice = NULL; if (!all) { return NULL; } for (size_t i = 0; i < len; i++) { all[i] = t->ring[(t->head + MAX_BYTES - len + i) % MAX_BYTES]; } if (len > 0 && all[len - 1] == '\n') { len--; /* a final newline ends the last line; it is not another one */ } all[len] = '\0'; total_lines = t->total_bytes == 0 ? 0 : t->newlines - (t->last == '\n') + 1; if (by_bytes) { char *nl = memchr(all, '\n', len); if (!nl) { char size[32], whole[32]; format_size(len, size, sizeof size); format_size(t->total_bytes, whole, sizeof whole); *notice = format("[Showing last %s of line %zu (line is %s)%s]", size, total_lines, whole, where); return all; } s = (size_t)(nl - all) + 1; /* drop the partial first line */ } for (size_t i = s; i < len; i++) { kept_lines += all[i] == '\n'; } kept_lines += len > s; while (kept_lines > MAX_LINES) { char *nl = memchr(all + s, '\n', len - s); s = (size_t)(nl - all) + 1; kept_lines--; } if (kept_lines < total_lines) { *notice = format("[Showing lines %zu-%zu of %zu%s%s]", total_lines - kept_lines + 1, total_lines, total_lines, t->total_bytes > t->filled ? " (50KB limit)" : "", where); } memmove(all, all + s, len - s + 1); return all; } /* 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 report goes back to pic on report_fd: 'O' or 'E', the result's * length (uint64, native) and text, then the length of the full output and its * last FULL_KEEP bytes (length 0 when the result was not cut). */ static int send_report(int report_fd, char status, const char *result, const char *full, size_t full_len) { uint64_t n = strlen(result); if (write_all(report_fd, &status, 1) != 0 || write_all(report_fd, (const char *)&n, sizeof n) != 0 || write_all(report_fd, result, (size_t)n) != 0) { return -1; } n = full_len; return write_all(report_fd, (const char *)&n, sizeof n) == 0 && write_all(report_fd, full, full_len) == 0 ? 0 : -1; } /* A 'P' frame: the output so far (Pi's tail truncation, no notice). */ static void send_partial(int report_fd, tail_buf *t) { char *notice, *text = tail_text(t, "", ¬ice); if (text) { uint64_t n = strlen(text); char status = 'P'; if (write_all(report_fd, &status, 1) == 0 && write_all(report_fd, (const char *)&n, sizeof n) == 0) { (void)write_all(report_fd, text, (size_t)n); } } free(text); free(notice); } static void supervise(const char *workspace, const char *command, int seconds, int gate_fd, int report_fd, const char *output_name) { char go = 0, *out, *notice, *result; int pipefd[2], status = 0, exited = 0, timed_out = 0, aborted = 0, output_open = 1, is_error; long deadline = now_ms() + (long)seconds * 1000, last_partial = 0; int dirty = 0; tail_buf *t = calloc(1, sizeof *t); const char *shell = access("/bin/bash", X_OK) == 0 ? "/bin/bash" : "/bin/sh"; pid_t child; (void)signal(SIGPIPE, SIG_IGN); if (read(gate_fd, &go, 1) != 1 || go != 'g' || !t || 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)send_report(report_fd, 'E', result, "", 0); } _exit(0); } if (child == 0) { (void)setpgid(0, 0); if (chdir(workspace) != 0) { _exit(126); } { /* No input, as in Pi: stdin may be pic's command channel. */ int null_fd = open("/dev/null", O_RDONLY); if (null_fd >= 0) { (void)dup2(null_fd, STDIN_FILENO); close(null_fd); } } (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(shell, shell, "-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); /* The command's exit is noticed by waitpid between polls. Waits start at * 1ms and double to 50ms, so a quick command returns almost at once and a * long one costs little CPU. */ for (int wait_ms = 1;; wait_ms = wait_ms < 50 ? wait_ms * 2 : 50) { 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 < wait_ms ? (int)left : wait_ms) < 0 && errno != EINTR) { break; } if (p[0].revents) { /* After "go" pic sends only "c" (Ctrl-C: abort the command and report); * otherwise readable means pic exited. */ char cmd = 0; if (read(gate_fd, &cmd, 1) == 1 && cmd == 'c') { aborted = 1; break; } (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) { tail_add(t, buf, (size_t)n); dirty = 1; } else if (n == 0 || errno != EINTR) { output_open = n != 0; /* EOF closes; EAGAIN waits for more */ break; } } if (dirty && now_ms() - last_partial >= PARTIAL_MS) { dirty = 0; last_partial = now_ms(); send_partial(report_fd, t); } } /* 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) { tail_add(t, buf, (size_t)n); } else if (n == 0 || errno != EINTR) { break; } } close(pipefd[0]); { char *where = output_name && !t->full_failed ? format(". Full output: %s (read it with the read tool; to search it, rerun the command " "with a filter)%s", output_name, t->total_bytes > FULL_KEEP ? " (only the last 16MB was kept)" : "") : strdup(""); out = tail_text(t, where ? where : "", ¬ice); free(where); } if (t->full_failed || !output_name) { t->full_len = 0; /* nothing to name, so nothing to send */ } is_error = aborted || timed_out || !WIFEXITED(status) || WEXITSTATUS(status) != 0; { char status_line[96] = ""; if (aborted) { (void)snprintf(status_line, sizeof status_line, "\n\nCommand aborted"); } else if (timed_out) { (void)snprintf(status_line, sizeof status_line, "\n\nCommand timed out after %d seconds", seconds); } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { (void)snprintf(status_line, sizeof status_line, "\n\nCommand exited with code %d", WEXITSTATUS(status)); } else if (!WIFEXITED(status)) { (void)snprintf(status_line, sizeof status_line, "\n\nCommand terminated by signal %d", WIFSIGNALED(status) ? WTERMSIG(status) : 0); } result = format("%s%s%s%s", out && *out ? out : "(no output)", notice ? "\n\n" : "", notice ? notice : "", status_line); } if (result) { size_t keep = t->full_len < FULL_KEEP ? t->full_len : FULL_KEEP; (void)send_report(report_fd, is_error ? 'E' : 'O', result, notice ? t->full + (t->full_len - keep) : "", notice ? keep : 0); } _exit(0); } /* Reads exactly n bytes of the supervisor's report. Ctrl-C meanwhile tells * the supervisor to kill the command; it still reports. -1 on EOF or error. */ static int pull(int report_fd, int gate_fd, int *told, char *dst, size_t n) { for (size_t got = 0; got < n;) { struct pollfd p[2] = {{report_fd, POLLIN, 0}, {pic_side_ready ? pic_side_fd : -1, POLLIN, 0}}; ssize_t r; if (pic_interrupted && !*told) { *told = write_all(gate_fd, "c", 1) == 0; } if (poll(p, 2, 200) <= 0) { continue; } if (p[1].revents) { pic_side_ready(); } if (p[0].revents == 0) { continue; } r = read(report_fd, dst + got, n - got); if (r < 0 && errno == EINTR) { continue; } if (r <= 0) { return -1; } got += (size_t)r; } return 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 *host_run(void *state, const char *workspace, const char *command, int seconds, const pic_tool_hooks *h, int *is_error) { int gate[2], report[2]; sigset_t stop, saved; pid_t sup; (void)state; char *buf = NULL, *full = NULL; char head[1 + sizeof(uint64_t)]; uint64_t rlen = 0, flen = 0; int told = 0; if (pipe(gate) != 0) { return h->started(h->ctx, NULL, 0) == 0 ? fail(is_error, "error: cannot start command") : NULL; } if (pipe(report) != 0) { close(gate[0]); close(gate[1]); return h->started(h->ctx, NULL, 0) == 0 ? fail(is_error, "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, seconds, gate[0], report[1], h->output_name); } (void)sigprocmask(SIG_SETMASK, &saved, NULL); close(gate[0]); close(report[1]); if (sup < 0 || h->started(h->ctx, NULL, 0) != 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, NULL, 0) == 0 ? fail(is_error, "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 (write_all(gate[1], "g", 1) != 0) { close(gate[1]); close(report[0]); while (waitpid(sup, NULL, 0) < 0 && errno == EINTR) { } return fail(is_error, "error: cannot release command"); } /* A dead or short-writing supervisor leaves a frame that does not parse: * the outcome is lost, as when nothing came back at all. */ if (h->partial) { h->partial(h->partial_ctx, ""); } while (pull(report[0], gate[1], &told, head, sizeof head) == 0) { memcpy(&rlen, head + 1, sizeof rlen); if (head[0] == 'P') { /* live output: emit it and keep waiting */ char *text = rlen <= MAX_BYTES + 1024 ? malloc((size_t)rlen + 1) : NULL; if (!text || pull(report[0], gate[1], &told, text, (size_t)rlen) != 0) { free(text); break; } text[rlen] = '\0'; if (h->partial) { h->partial(h->partial_ctx, text); } free(text); continue; } if (rlen <= 2 * MAX_BYTES + 1024 && (buf = malloc((size_t)rlen + 1)) && pull(report[0], gate[1], &told, buf, (size_t)rlen) == 0 && pull(report[0], gate[1], &told, (char *)&flen, sizeof flen) == 0 && flen <= FULL_KEEP && (flen == 0 || ((full = malloc((size_t)flen)) && pull(report[0], gate[1], &told, full, (size_t)flen) == 0))) { buf[rlen] = '\0'; } else { free(buf); free(full); buf = full = NULL; } break; } close(report[0]); while (waitpid(sup, NULL, 0) < 0 && errno == EINTR) { } close(gate[1]); if (!buf) { return fail(is_error, "error: command supervisor produced no result"); } *is_error = head[0] == 'E'; if (full && h->output) { h->output->data = full; h->output->len = (size_t)flen; } else { free(full); } return buf; } static const pic_executor host = {host_stat, host_read, host_write, host_remove, host_mkdir, host_list, host_run, NULL}; static const pic_executor *current = &host; const pic_executor *pic_executor_host(void) { return &host; } const pic_executor *pic_executor_get(void) { return current; } void pic_executor_set(const pic_executor *e) { current = e ? e : &host; } char *pic_tool_run(const char *workspace, const char *tool, const pic_tool_args *args, const pic_tool_hooks *hooks, int *is_error) { *is_error = 0; if (strcmp(tool, "read") == 0) { return tool_read(workspace, args, hooks, is_error); } if (strcmp(tool, "write") == 0) { return tool_write(workspace, args, hooks, is_error); } if (strcmp(tool, "edit") == 0) { return tool_edit(workspace, args, hooks, is_error); } if (strcmp(tool, "bash") == 0) { int seconds = hooks->exec_seconds; if (hooks->started == NULL) { return NULL; } if (args->bad_input || !args->command) { return hooks->started(hooks->ctx, NULL, 0) == 0 ? fail(is_error, "%s", args->bad_input ? args->bad_input : "bash needs a string input command") : NULL; } if (args->has_timeout) { if (args->timeout <= 0 || args->timeout > 86400) { return hooks->started(hooks->ctx, NULL, 0) == 0 ? fail(is_error, "Invalid timeout: must be a finite number of seconds") : NULL; } seconds = (int)args->timeout; } const pic_executor *ex = pic_executor_get(); return ex->run(ex->state, workspace, args->command, seconds, hooks, is_error); } return hooks->started(hooks->ctx, NULL, 0) == 0 ? fail(is_error, "Tool %s not found", tool) : NULL; }