Skip to content
pi-c Artifact [cdf3c0cc28]
Login

Artifact [cdf3c0cc28]

Artifact cdf3c0cc287c235579d2cdb29585b73e5fe52704eaafca2691fe02bb433eb57a:


/* 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 <time.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 *tl_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 ||
           strcmp(tool, "grep") == 0 || strcmp(tool, "find") == 0 || strcmp(tool, "ls") == 0;
}

#define SCHEMA_READ \
    "{\"name\":\"read\",\"description\":\"Read the contents of a file. Supports text files and images (jpg, png, gif, " \
    "webp, bmp). Images are sent as attachments. 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\"]}}"
#define SCHEMA_BASH \
    "{\"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\"]}}"
#define SCHEMA_EDIT \
    "{\"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\"]}}"
#define SCHEMA_WRITE \
    "{\"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\"]}}"

const char pic_tool_schema_read[] = SCHEMA_READ;
const char pic_tool_schema_bash[] = SCHEMA_BASH;
const char pic_tool_schema_edit[] = SCHEMA_EDIT;
const char pic_tool_schema_write[] = SCHEMA_WRITE;
const char pic_tool_schemas[] = "[" SCHEMA_READ "," SCHEMA_BASH "," SCHEMA_EDIT "," SCHEMA_WRITE "]";

/* ---- 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);
}

/* A path with "." and ".." segments and repeated slashes taken out, as Node's
 * path.resolve does, in place. A relative path (a relative --workspace) stays
 * relative: no slash is put in front of its first segment, so the result is
 * never longer than the input. */
static void normalize(char *p) {
    size_t o = 0;
    int absolute = p[0] == '/';
    for (size_t i = 0; p[i];) {
        size_t n = 0;
        while (p[i] == '/') {
            i++;
        }
        while (p[i + n] && p[i + n] != '/') {
            n++;
        }
        if (n == 0) {
            break;
        }
        if (n == 2 && p[i] == '.' && p[i + 1] == '.') {
            while (o > 0 && p[--o] != '/') {
            }
        } else if (!(n == 1 && p[i] == '.')) {
            if (o > 0 || absolute) {
                p[o++] = '/';
            }
            memmove(p + o, p + i, n);
            o += n;
        }
        i += n;
    }
    if (o == 0) {
        p[o++] = absolute ? '/' : '.';
    }
    p[o] = '\0';
}

/* The file PATH names, by Pi's rules, as one key for every spelling of it
 * (Pi's file-mutation-queue key): its real path, or, for a file not there
 * yet, its folder's real path and its name; else the normalized path. */
char *pic_tool_path_key(const char *workspace, const char *path) {
    char *resolved = resolve(workspace, path), *real, *slash;
    if (!resolved) {
        return NULL;
    }
    normalize(resolved);
    if ((real = realpath(resolved, NULL))) {
        free(resolved);
        return real;
    }
    slash = strrchr(resolved, '/');
    if (slash && slash != resolved) {
        *slash = '\0';
        real = realpath(resolved, NULL);
        *slash = '/';
        if (real) {
            char *key = format("%s%s", strcmp(real, "/") == 0 ? "" : real, slash);
            free(real);
            free(resolved);
            return key;
        }
    }
    return resolved;
}

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 *tl_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 = tl_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_rmdir(void *state, const char *name) {
    (void)state;
    if (rmdir(name) != 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;
}

const char *pic_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 void (*tl_read_seen)(const char *path);

void pic_tool_read_observer(void (*fn)(const char *path)) { tl_read_seen = fn; }

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 tl_fail(is_error, "%s", a->bad_input);
    }
    if (!a->path) {
        return tl_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 = tl_fail(is_error, "%s: %s, read '%s'", pic_errno_name(err), strerror(err), path ? path : a->path);
        free(path);
        return out;
    }
    if (tl_read_seen && strncmp(a->path, "pic:", 4) != 0) {
        tl_read_seen(path);
    }
    if (!h->fetch || strncmp(a->path, "pic:output/", 11) != 0) {
        /* An image goes back as an attachment after a note, as Pi's read
         * sends it; Pi sniffs the first 4100 bytes. */
        const char *mime = pic_image_sniff((const unsigned char *)data, len < 4100 ? len : 4100);
        if (mime) {
            pic_image img = {NULL, (const unsigned char *)data, len, 0, 0};
            int rc = pic_image_check(&img, NULL, NULL, 0);
            if (rc != PIC_IMAGE_OK) { /* broken, BMP or too large: Pi's note, no image */
                out = format("Read image file [%s]\n%s", mime, pic_image_note(rc));
            } else if (!h->image) { /* a caller that keeps no images */
                out = format("Read image file [%s]", mime);
            } else if ((out = format("Read image file [%s]", mime))) {
                h->image->mime = img.mime;
                h->image->data = (unsigned char *)data;
                h->image->len = len;
                h->image->width = img.width;
                h->image->height = img.height;
                data = NULL;
            }
            goto done;
        }
    }
    for (i = 0; i < len; i++) {
        total += data[i] == '\n';
    }
    if (a->has_offset && a->offset < 1) {
        out = tl_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 = tl_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 tl_fail(is_error, "%s", a->bad_input);
    }
    if (!a->path || !a->content) {
        return tl_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 tl_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 tl_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;
} tool_match;

static int by_pos(const void *a, const void *b) {
    const tool_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;
    tool_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 tl_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 ? tl_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 tl_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 tl_fail(is_error, "Could not edit file: %s. Error code: %s.", a->path, pic_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 ? tl_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 tl_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, "", &notice);
    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);
}

/* Reports to `pic ps` when a sink is set; never fails what it reports. */
static const pic_proc_sink *proc_sink;

void pic_proc_sink_set(const pic_proc_sink *sink) { proc_sink = sink; }
const pic_proc_sink *pic_proc_sink_get(void) { return proc_sink; }

static long long proc_started(const char *kind, const char *command, pid_t pid) {
    return proc_sink ? proc_sink->start(kind, command, (long)pid, (long)pid) : -1;
}

/* The wait status of a process, as an exit code or a signal. */
static void proc_ended(long long id, int status, int killed) {
    if (proc_sink && id >= 0) {
        proc_sink->end(id, !killed && WIFEXITED(status) ? WEXITSTATUS(status) : -1,
                       killed ? SIGKILL : WIFSIGNALED(status) ? WTERMSIG(status) : 0);
    }
}

/* A frame with no text: STATUS and a number, for `pic ps`. */
static void send_note(int report_fd, char status, uint64_t n) {
    if (write_all(report_fd, &status, 1) == 0) {
        (void)write_all(report_fd, (const char *)&n, sizeof n);
    }
}

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 = tl_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);
    send_note(report_fd, 'S', (uint64_t)child); /* pic records it: no database after a fork */
    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 - tl_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 && tl_now_ms() - last_partial >= PARTIAL_MS) {
            dirty = 0;
            last_partial = tl_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) {
        }
    }
    send_note(report_fd, 'X', (uint64_t)(unsigned)status | (uint64_t)!exited << 32);
    /* 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 : "", &notice);
        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[3] = {{report_fd, POLLIN, 0}, {pic_side_ready ? pic_side_fd : -1, POLLIN, 0},
                              {pic_watch_ready ? pic_watch_fd : -1, POLLIN, 0}};
        ssize_t r;
        if (pic_interrupted && !*told) {
            *told = write_all(gate_fd, "c", 1) == 0;
        }
        if (poll(p, 3, 200) <= 0) {
            continue;
        }
        if (p[1].revents && pic_side_ready) {
            pic_side_ready();
        }
        if (p[2].revents && pic_watch_ready) {
            pic_watch_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)];
    long long proc_h = -1;
    uint64_t rlen = 0, flen = 0;
    int told = 0;
    if (pipe(gate) != 0) {
        return h->started(h->ctx, NULL, 0) == 0 ? tl_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 ? tl_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 ? tl_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 tl_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] == 'S') { /* the command started: its pid */
            proc_h = proc_started(h->proc_kind ? h->proc_kind : "bash", command, (pid_t)rlen);
            continue;
        }
        if (head[0] == 'X') { /* it ended: the wait status, and whether it was killed */
            proc_ended(proc_h, (int)(unsigned)rlen, (int)(rlen >> 32));
            continue;
        }
        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 tl_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;
}

/* ---- hook commands: the host's spawn ---------------------------------------- */
/* Host only: every process hooks start is started here (spawn, below, and
 * pic_host_exec_start for the terminal's signal-time SessionEnd). A build
 * without processes leaves spawn NULL and drops this section. */

typedef struct {
    char *p;
    size_t n, cap, max;
} sp_buf;

static void sp_add(sp_buf *b, const char *src, size_t n) {
    if (b->n + n > b->max) {
        n = b->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';
}

/* Closes every descriptor above stderr but KEEP and KEEP2: the journal's
 * lock and files must not outlive pic in a hook's process. The open ones
 * are listed from /dev/fd, so only they are closed. */
static void sp_close_inherited(int keep, int keep2) {
    int fds[1024];
    size_t n = 0;
    DIR *d = opendir("/dev/fd");
    if (d) {
        struct dirent *e;
        int self = dirfd(d);
        while ((e = readdir(d)) != NULL && n < sizeof fds / sizeof fds[0]) {
            char *end;
            long fd = strtol(e->d_name, &end, 10);
            if (*end == '\0' && end != e->d_name && fd > 2 && fd != self && fd != keep && fd != keep2) {
                fds[n++] = (int)fd;
            }
        }
        closedir(d);
        for (size_t i = 0; i < n; i++) {
            (void)close(fds[i]);
        }
        return;
    }
    for (int fd = 3; fd < 1024; fd++) {
        if (fd != keep && fd != keep2) {
            (void)close(fd);
        }
    }
}

/* Reads what FD has, at most BUDGET bytes (a background child may write
 * without end); closes it at EOF or on an error. */
static void sp_pump(int *fd, sp_buf *b, size_t budget) {
    while (*fd >= 0 && budget > 0) {
        char buf[4096];
        ssize_t n = read(*fd, buf, budget < sizeof buf ? budget : sizeof buf);
        if (n > 0) {
            sp_add(b, buf, (size_t)n);
            budget -= (size_t)n;
        } else if (n < 0 && errno == EINTR) {
            continue;
        } else {
            if (n == 0 || errno != EAGAIN) {
                close(*fd);
                *fd = -1;
            }
            return;
        }
    }
}

static void sp_close(int *fd) {
    if (*fd >= 0) {
        close(*fd);
        *fd = -1;
    }
}

static void sp_write(int fd, const void *p, size_t n) {
    const char *c = p;
    while (n > 0) {
        ssize_t w = write(fd, c, n);
        if (w < 0 && errno == EINTR) {
            continue;
        }
        if (w <= 0) {
            return;
        }
        c += w;
        n -= (size_t)w;
    }
}

/* The watchdog: a process of its own (stdin, stdout and stderr already the
 * hook's) that starts the command in a process group of its own. It kills
 * that whole group at the deadline, or when LIFE closes or is written to
 * (pic died, or Ctrl-C), and at no other time: once the command returns,
 * anything it left running in the background is its author's. It reports
 * on REPORT: 'X' and the wait status, 'T' (timed out), 'D' (pic gone or
 * interrupted) or 'F' (no fork), then exits. */
static void sp_watchdog(const pic_spawn_req *q, int life, int report) {
    long deadline = tl_now_ms() + q->seconds * 1000L;
    int status = 0, null;
    char tag = 'X';
    pid_t g;
    (void)signal(SIGINT, SIG_IGN); /* a terminal's Ctrl-C reaches pic, which says so on LIFE */
    (void)signal(SIGTERM, SIG_IGN);
    (void)signal(SIGHUP, SIG_IGN);
    (void)signal(SIGPIPE, SIG_IGN);
    g = fork();
    if (g == 0) {
        sigset_t none;
        (void)setpgid(0, 0);
        close(life);
        close(report);
        (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(q->cwd) != 0) {
            _exit(126);
        }
        for (const char *const *e = q->env; e && *e; e++) {
            const char *eq = strchr(*e, '=');
            char name[128];
            if (eq && (size_t)(eq - *e) < sizeof name) {
                memcpy(name, *e, (size_t)(eq - *e));
                name[eq - *e] = '\0';
                (void)setenv(name, eq + 1, 1);
            }
        }
        execl("/bin/sh", "sh", "-c", q->command, (char *)NULL);
        _exit(127);
    }
    if (g < 0) {
        tag = 'F';
        sp_write(report, &tag, 1);
        _exit(0);
    }
    (void)setpgid(g, g);
    {
        char note[1 + sizeof g] = {'G'}; /* pic records it: no database after a fork */
        memcpy(note + 1, &g, sizeof g);
        sp_write(report, note, sizeof note);
    }
    /* pic sees the end of the output from the command alone. */
    if ((null = open("/dev/null", O_RDWR)) >= 0) {
        (void)dup2(null, STDIN_FILENO);
        (void)dup2(null, STDOUT_FILENO);
        (void)dup2(null, STDERR_FILENO);
        close(null);
    }
    for (int wait_ms = 1;; wait_ms = wait_ms < 50 ? wait_ms * 2 : 50) {
        struct pollfd p = {life, POLLIN, 0};
        long left;
        if (waitpid(g, &status, WNOHANG) == g) {
            break;
        }
        if ((left = deadline - tl_now_ms()) <= 0) {
            tag = 'T';
            break;
        }
        if (poll(&p, 1, (int)(left < wait_ms ? left : wait_ms)) > 0 && p.revents) {
            tag = 'D';
            break;
        }
    }
    if (tag != 'X') {
        (void)kill(-g, SIGKILL);
        while (waitpid(g, &status, 0) < 0 && errno == EINTR) {
        }
    }
    sp_write(report, &tag, 1);
    sp_write(report, &status, sizeof status);
    _exit(0);
}

/* The watchdog tells its parent the hook's pid ('G' and the pid, first on
 * the report pipe). A sync hook's parent is pic, which records it; a detached
 * one's is the process running it on its own, which passes the pid to pic on
 * detach_fd (pic is the only process that writes the database). */
static int detach_fd = -1;

typedef struct {
    int seen;
    long long handle;
} sp_note;

static void sp_noted(const pic_spawn_req *q, sp_note *n, pid_t g) {
    if (n->seen) {
        return;
    }
    n->seen = 1;
    if (q->detached) {
        if (detach_fd >= 0) {
            sp_write(detach_fd, &g, sizeof g);
        }
    } else {
        n->handle = proc_started("sync-hook", q->command, g);
    }
}

/* The next tag on the report pipe, taking a 'G' on the way; 0 at its end. */
static char sp_next_tag(int report, const pic_spawn_req *q, sp_note *n) {
    for (;;) {
        char tag;
        ssize_t got;
        pid_t g;
        while ((got = read(report, &tag, 1)) < 0 && errno == EINTR) {
        }
        if (got != 1) {
            return 0;
        }
        if (tag != 'G') {
            return tag;
        }
        if (read(report, &g, sizeof g) != (ssize_t)sizeof g) {
            return 0;
        }
        sp_noted(q, n, g);
    }
}

static void sp_run(const pic_spawn_req *q, pic_spawn_result *r) {
    int in[2] = {-1, -1}, out[2] = {-1, -1}, err[2] = {-1, -1}, life[2] = {-1, -1}, report[2] = {-1, -1};
    size_t sent = 0, len = q->input ? q->input_len : 0;
    long start = tl_now_ms(), backstop = start + q->seconds * 1000L + 5000;
    sp_buf ob = {NULL, 0, 0, q->out_cap}, eb = {NULL, 0, 0, q->out_cap};
    pid_t pid;
    sp_note note = {0, -1};
    char pending = 0; /* a tag read early, in place of the hook's pid */
    if (pipe(in) != 0 || pipe(out) != 0 || pipe(err) != 0 || pipe(life) != 0 || pipe(report) != 0) {
        (void)snprintf(r->why, sizeof r->why, "cannot start: %s", strerror(errno));
        sp_close(&in[0]), sp_close(&in[1]), sp_close(&out[0]), sp_close(&out[1]), sp_close(&err[0]), sp_close(&err[1]);
        sp_close(&life[0]), sp_close(&life[1]), sp_close(&report[0]), sp_close(&report[1]);
        return;
    }
    pid = fork();
    if (pid == 0) {
        (void)dup2(in[0], STDIN_FILENO);
        (void)dup2(out[1], STDOUT_FILENO);
        (void)dup2(err[1], STDERR_FILENO);
        sp_close_inherited(life[0], report[1]);
        sp_watchdog(q, life[0], report[1]);
    }
    sp_close(&in[0]), sp_close(&out[1]), sp_close(&err[1]), sp_close(&life[0]), sp_close(&report[1]);
    if (pid < 0) {
        (void)snprintf(r->why, sizeof r->why, "cannot start: %s", strerror(errno));
        sp_close(&in[1]), sp_close(&out[0]), sp_close(&err[0]), sp_close(&life[1]), sp_close(&report[0]);
        return;
    }
    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) {
        sp_close(&in[1]);
    }
    for (int wait_ms = 1;; wait_ms = wait_ms < 50 ? wait_ms * 2 : 50) {
        struct pollfd p[4] = {{in[1], POLLOUT, 0}, {out[0], POLLIN, 0}, {err[0], POLLIN, 0},
                              {note.seen || pending ? -1 : report[0], POLLIN, 0}};
        if (waitpid(pid, NULL, WNOHANG) == pid) {
            break;
        }
        if (life[1] >= 0 && q->cancelled && q->cancelled(q->ctx)) { /* Ctrl-C: the watchdog ends the hook */
            sp_write(life[1], "c", 1);
            sp_close(&life[1]);
        }
        if (tl_now_ms() > backstop) { /* the watchdog itself is stuck */
            (void)kill(pid, SIGKILL);
            while (waitpid(pid, NULL, 0) < 0 && errno == EINTR) {
            }
            break;
        }
        if (poll(p, 4, wait_ms) < 0 && errno != EINTR) {
            (void)snprintf(r->why, sizeof r->why, "poll: %s", strerror(errno));
        }
        if (p[3].revents & POLLIN) {
            char tag = 0;
            pid_t g;
            if (read(report[0], &tag, 1) == 1 && tag == 'G' && read(report[0], &g, sizeof g) == (ssize_t)sizeof g) {
                sp_noted(q, &note, g);
            } else {
                pending = tag ? tag : 'F';
            }
        }
        if (in[1] >= 0 && p[0].revents) {
            ssize_t w = write(in[1], q->input + sent, len - sent);
            if (w > 0) {
                sent += (size_t)w;
            }
            if (sent == len || (w < 0 && errno != EAGAIN && errno != EINTR)) {
                sp_close(&in[1]); /* all of it, or the hook stopped reading */
            }
        }
        sp_pump(&out[0], &ob, q->out_cap);
        sp_pump(&err[0], &eb, q->out_cap);
    }
    /* What it wrote before it exited; a background child holding the pipes
     * is neither waited for nor read without end. */
    sp_pump(&out[0], &ob, q->out_cap);
    sp_pump(&err[0], &eb, q->out_cap);
    {
        char tag = pending ? pending : sp_next_tag(report[0], q, &note);
        int status = 0;
        ssize_t got = tag ? 1 : 0;
        if (got == 1 && tag == 'X' && read(report[0], &status, sizeof status) == (ssize_t)sizeof status) {
            proc_ended(note.handle, status, 0);
            if (WIFEXITED(status)) {
                r->exited = 1;
                r->code = WEXITSTATUS(status);
            } else {
                (void)snprintf(r->why, sizeof r->why, "terminated by signal %d", WIFSIGNALED(status) ? WTERMSIG(status) : 0);
            }
        } else if (got == 1 && tag == 'T') {
            r->timed_out = 1;
            proc_ended(note.handle, 0, 1);
        } else if (got == 1 && tag == 'D') {
            r->cancelled = 1;
            proc_ended(note.handle, 0, 1);
            (void)snprintf(r->why, sizeof r->why, "interrupted (Ctrl-C); its process group was killed");
        } else {
            (void)snprintf(r->why, sizeof r->why, got == 1 && tag == 'F' ? "cannot start: fork failed" : "its watchdog died");
        }
    }
    sp_close(&in[1]), sp_close(&out[0]), sp_close(&err[0]), sp_close(&life[1]), sp_close(&report[0]);
    r->out = ob.p;
    r->out_len = ob.n;
    r->err = eb.p;
    r->err_len = eb.n;
    r->ms = tl_now_ms() - start;
}

/* A detached command runs on its own, watchdog and all, in a process that
 * holds neither pic's files nor its output: pic goes on at once. */
static void sp_detach(const pic_spawn_req *q, pic_spawn_result *r) {
    int pf[2] = {-1, -1};
    pid_t a, g = 0;
    if (pipe(pf) != 0) {
        pf[0] = pf[1] = -1;
    }
    a = fork();
    if (a == 0) {
        pic_spawn_req own = *q;
        pic_spawn_result ignored;
        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);
        }
        sp_close_inherited(pf[1], -1);
        detach_fd = pf[1];
        (void)setsid();
        (void)signal(SIGINT, SIG_IGN);
        (void)signal(SIGHUP, SIG_IGN);
        own.cancelled = NULL;
        if (fork() != 0) {
            _exit(0);
        }
        memset(&ignored, 0, sizeof ignored);
        sp_run(&own, &ignored);
        _exit(0);
    }
    if (a < 0) {
        (void)snprintf(r->why, sizeof r->why, "cannot start: %s", strerror(errno));
        return;
    }
    if (pf[1] >= 0) {
        close(pf[1]);
    }
    while (waitpid(a, NULL, 0) < 0 && errno == EINTR) {
    }
    r->started = 1;
    /* The hook's pid, once its watchdog has forked it (a moment); the end of a
     * detached hook is not seen, `pic ps` finds it by the pid's liveness. */
    if (pf[0] >= 0) {
        struct pollfd p = {pf[0], POLLIN, 0};
        if (poll(&p, 1, 2000) > 0 && read(pf[0], &g, sizeof g) == (ssize_t)sizeof g) {
            (void)proc_started("async-hook", q->command, g);
        }
        close(pf[0]);
    }
}

extern char **environ;

int pic_host_exec_prepare(pic_host_exec *x, const char *const *argv, const char *extra) {
    size_t n = 0, k = 0;
    memset(x, 0, sizeof *x);
    while (environ[n]) {
        n++;
    }
    for (; argv[k] && k + 1 < sizeof x->argv / sizeof x->argv[0]; k++) {
        x->argv[k] = (char *)(uintptr_t)argv[k];
    }
    if (argv[k] || !(x->envp = calloc(n + 2, sizeof *x->envp))) {
        memset(x, 0, sizeof *x);
        return -1;
    }
    memcpy(x->envp, environ, n * sizeof *x->envp);
    (void)snprintf(x->extra, sizeof x->extra, "%s", extra);
    x->envp[n] = x->extra;
#ifdef PIC_FAULTS
    x->delay_ms = getenv("PIC_LAUNCH_DELAY_MS") ? atol(getenv("PIC_LAUNCH_DELAY_MS")) : 0;
#endif
    return 0;
}

/* Called as the terminal dies of a signal (its stop_check), so it allocates
 * nothing. The terminal dies right after: as the pty's session leader, its
 * death sends SIGHUP to its process group, which the child is in until
 * setsid(). So every signal is blocked across fork(); the child drops the
 * handlers it inherited, ignores SIGHUP, leaves the session, and only then
 * unblocks, discarding a SIGHUP already pending. */
void pic_host_exec_start(const pic_host_exec *x, int wait_for) {
    sigset_t all, saved;
    pid_t child;
    if (!x->envp) {
        return;
    }
    sigfillset(&all);
    (void)sigprocmask(SIG_BLOCK, &all, &saved);
    child = fork();
    if (child != 0) {
        (void)sigprocmask(SIG_SETMASK, &saved, NULL);
        return;
    }
    {
        static const int reset[] = {SIGINT, SIGTERM, SIGQUIT, SIGSEGV, SIGABRT, SIGBUS, SIGWINCH, SIGPIPE};
        sigset_t none;
        int null = open("/dev/null", O_RDWR);
        (void)signal(SIGHUP, SIG_IGN);
        for (size_t i = 0; i < sizeof reset / sizeof reset[0]; i++) {
            (void)signal(reset[i], SIG_DFL);
        }
        if (x->delay_ms > 0) { /* tests: the terminal is dead and its pty hung up by now */
            struct timespec pause = {x->delay_ms / 1000, (x->delay_ms % 1000) * 1000000L};
            (void)nanosleep(&pause, NULL);
        }
        (void)setsid();
        sigemptyset(&none);
        (void)sigprocmask(SIG_SETMASK, &none, NULL);
        if (null >= 0) {
            (void)dup2(null, STDIN_FILENO);
            (void)dup2(null, STDOUT_FILENO);
            (void)dup2(null, STDERR_FILENO);
        }
        /* The cancelled request holds the journal until it exits: wait for
         * it (at most a minute), then end the conversations either way; pic
         * hooks end waits for the journal itself, too. */
        for (int i = 0; wait_for > 0 && kill(wait_for, 0) == 0 && i < 1200; i++) {
            struct timespec pause = {0, 50000000};
            (void)nanosleep(&pause, NULL);
        }
        execve(x->argv[0], x->argv, x->envp);
        _exit(127);
    }
}

static int host_spawn(void *state, const pic_spawn_req *req, pic_spawn_result *res) {
    (void)state;
    memset(res, 0, sizeof *res);
    if (req->detached) {
        sp_detach(req, res);
    } else {
        sp_run(req, res);
    }
    return res->started ? 0 : -1;
}

static const pic_executor tl_host = {host_stat, host_read, host_write, host_remove, host_mkdir, host_rmdir, host_list,
                                   host_run, host_spawn, NULL};
static const pic_executor *tl_current = &tl_host;

const pic_executor *pic_executor_host(void) { return &tl_host; }
const pic_executor *pic_executor_get(void) { return tl_current; }
void pic_executor_set(const pic_executor *e) { tl_current = e ? e : &tl_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
                       ? tl_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
                           ? tl_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 ? tl_fail(is_error, "Tool %s not found", tool) : NULL;
}