Skip to content
pi-c Documentation
Login

Documentation

/* The tool selection (Pi's --tools, --exclude-tools, --no-tools, --no-builtin-tools
 * and the defaultTools setting) and Pi's optional read-only tools: grep, find
 * and ls. They walk and read through the executor's list, stat and read, so
 * they work with any executor and shell out to nothing (Pi runs rg and fd).
 * Ignore files come from ignore.c; every result is Pi's own text, limits and
 * notices (packages/coding-agent/src/core/tools/{grep,find,ls,truncate}.ts).
 *
 * Differences from Pi, all in the walk and the regex:
 *  - ripgrep's Rust regex becomes POSIX ERE (REG_ENHANCED on macOS): \d \D \w \W
 *    \s \S, (?:...), a leading (?i) and lazy quantifiers (only whether a line
 *    matches counts, so they are read as greedy) are translated; look-around,
 *    named groups, \p{..}, inline flags past the first and Unicode case folding
 *    are not there. An invalid pattern reports regcomp's message under a
 *    "regex parse error" heading, not rg's own.
 *  - Files come in sorted path order (rg and fd are parallel and unordered).
 *  - .git folders are never entered (rg and fd with --hidden do enter them).
 *    Ignore files are read in the search folder and below, always, as rg and fd
 *    read them only inside a git repository and also read the folders above.
 *  - Symlinks are followed (the executor cannot tell a link from its target); a
 *    walk stops at 64 folders deep. Files over 64 MB and binary files (a NUL
 *    byte) are skipped, a file that cannot be read too.
 *  - ls sorts by ASCII case-insensitive order, not ICU's localeCompare.
 *  - A missing required input says "grep needs a string input pattern", as
 *    pic's other tools do, not Pi's schema-validation text. */
#include <ctype.h>
#include <errno.h>
#include <regex.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "ignore.h"
#include "pic.h"

#define MAX_BYTES 51200
#define GREP_LINE_MAX 500
#define WALK_DEPTH 64
#define FILE_CAP (64u << 20)

/* ---- the tool selection ------------------------------------------------------ */

#define NTOOLS 7
static const char *const builtin[NTOOLS] = {"read", "bash", "edit", "write", "grep", "find", "ls"};
static const char *const default_tools[] = {"read", "bash", "edit", "write"};

static int configured;
static size_t nactive;
static int active[NTOOLS]; /* indexes into builtin, in the order tools are declared */

static int builtin_index(const char *name) {
    for (int i = 0; i < NTOOLS; i++) {
        if (strcmp(builtin[i], name) == 0) {
            return i;
        }
    }
    return -1;
}

typedef struct {
    char buf[2048];
    const char *v[96];
    size_t n;
} names;

/* Pi's comma list: trimmed, empty entries dropped. -1 when too long. */
static int split_names(const char *csv, names *out) {
    char *p;
    out->n = 0;
    if (strlen(csv) >= sizeof out->buf) {
        return -1;
    }
    (void)snprintf(out->buf, sizeof out->buf, "%s", csv);
    for (p = out->buf; *p;) {
        char *end = strchr(p, ','), *e;
        if (end) {
            *end = '\0';
        }
        while (*p == ' ' || *p == '\t') {
            p++;
        }
        e = p + strlen(p);
        while (e > p && (e[-1] == ' ' || e[-1] == '\t')) {
            *--e = '\0';
        }
        if (*p && out->n < sizeof out->v / sizeof out->v[0]) {
            out->v[out->n++] = p;
        }
        if (!end) {
            break;
        }
        p = end + 1;
    }
    return 0;
}

/* Pi's createToolNameMatcher: an entry is a name, or a pattern when it has '*'. */
static int star_match(const char *pat, const char *s) {
    if (!*pat) {
        return !*s;
    }
    if (*pat == '*') {
        for (;; s++) {
            if (star_match(pat + 1, s)) {
                return 1;
            }
            if (!*s) {
                return 0;
            }
        }
    }
    return *pat == *s && star_match(pat + 1, s + 1);
}

static int entry_matches(const char *entry, const char *name) {
    return strchr(entry, '*') ? star_match(entry, name) : strcmp(entry, name) == 0;
}

static int is_modifier(const char *e) { return e[0] == '+' || e[0] == '-'; }

/* Pi's applyToolModifiers over builtin indexes in SEL. */
static void apply_modifiers(const names *entries, int sel[NTOOLS], size_t *n) {
    for (size_t i = 0; i < entries->n; i++) {
        const char *e = entries->v[i];
        int b;
        size_t at;
        if (!is_modifier(e)) {
            continue;
        }
        b = builtin_index(e + 1);
        for (at = 0; at < *n && sel[at] != b; at++) {
        }
        if (b < 0) {
            continue; /* not a built-in: nothing to add or remove */
        }
        if (e[0] == '+' && at == *n) {
            sel[(*n)++] = b;
        } else if (e[0] == '-' && at < *n) {
            memmove(sel + at, sel + at + 1, (*n - at - 1) * sizeof sel[0]);
            (*n)--;
        }
    }
}

/* Pi's getToolListError. */
static const char *list_error(const names *l, char *buf, size_t cap) {
    size_t mods = 0;
    for (size_t i = 0; i < l->n; i++) {
        mods += is_modifier(l->v[i]) ? 1u : 0u;
    }
    if (mods == 0) {
        return NULL;
    }
    if (mods < l->n) {
        return "tool names cannot be mixed with +name or -name entries";
    }
    for (size_t i = 0; i < l->n; i++) {
        if (strchr(l->v[i], '*')) {
            (void)snprintf(buf, cap, "+name and -name entries take exact tool names, not patterns: %s", l->v[i]);
            return buf;
        }
    }
    return NULL;
}

int pic_toolset_configure(const char *tools, const char *exclude, int no_tools, int no_builtin, const char *saved,
                          char *err, size_t errcap) {
    names t, x, d;
    int sel[NTOOLS], seen[NTOOLS] = {0};
    size_t nsel = 0, mods = 0;
    const char *why;
    char detail[256];
    t.n = x.n = d.n = 0;
    if ((tools && split_names(tools, &t) != 0) || (exclude && split_names(exclude, &x) != 0) ||
        (saved && split_names(saved, &d) != 0)) {
        (void)snprintf(err, errcap, "tool list is too long");
        return -1;
    }
    if (tools && (why = list_error(&t, detail, sizeof detail))) {
        (void)snprintf(err, errcap, "--tools: %s", why);
        return -1;
    }
    for (size_t i = 0; i < t.n; i++) {
        mods += is_modifier(t.v[i]) ? 1u : 0u;
    }
    if (tools && !mods) {
        /* A plain list replaces the selection, patterns included; its order is
         * the order the tools are declared in. */
        for (size_t i = 0; i < t.n; i++) {
            for (int b = 0; b < NTOOLS; b++) {
                if (entry_matches(t.v[i], builtin[b]) && !seen[b]) {
                    seen[b] = 1;
                    sel[nsel++] = b;
                }
            }
        }
    } else {
        /* The defaults: none under --no-tools or --no-builtin-tools; else the
         * defaultTools setting (plain names replace Pi's four, +name and -name
         * change them), else the four. --tools +name/-name changes those. */
        if (!no_tools && !no_builtin) {
            size_t plain = 0;
            for (size_t i = 0; i < d.n; i++) {
                plain += is_modifier(d.v[i]) ? 0u : 1u;
            }
            if (saved && (plain > 0 || d.n == 0)) {
                for (size_t i = 0; i < d.n; i++) {
                    int b = is_modifier(d.v[i]) ? -1 : builtin_index(d.v[i]);
                    if (b >= 0 && !seen[b]) {
                        seen[b] = 1;
                        sel[nsel++] = b;
                    }
                }
            } else {
                for (size_t i = 0; i < sizeof default_tools / sizeof default_tools[0]; i++) {
                    sel[nsel++] = builtin_index(default_tools[i]);
                }
            }
            if (saved) {
                apply_modifiers(&d, sel, &nsel);
            }
        }
        if (tools) {
            apply_modifiers(&t, sel, &nsel);
        }
    }
    nactive = 0;
    for (size_t i = 0; i < nsel; i++) {
        int drop = 0;
        for (size_t k = 0; k < x.n; k++) {
            drop |= entry_matches(x.v[k], builtin[sel[i]]);
        }
        if (!drop) {
            active[nactive++] = sel[i];
        }
    }
    configured = 1;
    return 0;
}

static void ensure_default(void) {
    if (!configured) {
        nactive = 0;
        for (size_t i = 0; i < sizeof default_tools / sizeof default_tools[0]; i++) {
            active[nactive++] = builtin_index(default_tools[i]);
        }
        configured = 1;
    }
}

int pic_toolset_on(const char *name) {
    ensure_default();
    for (size_t i = 0; i < nactive; i++) {
        if (strcmp(builtin[active[i]], name) == 0) {
            return 1;
        }
    }
    return 0;
}

/* Pi's executionMode per tool, by builtin index: Pi's built-in tools all
 * leave it unset ("parallel"), and edits and writes to one file wait for each
 * other instead (Pi's file mutation queue; pic_par_run). */
static const unsigned char sequential[NTOOLS] = {0};

int pic_toolset_sequential(const char *name) {
    int i = builtin_index(name);
    return i >= 0 && sequential[i];
}

size_t pic_toolset_names(const char **out, size_t cap) {
    size_t n;
    ensure_default();
    for (n = 0; n < nactive && n < cap; n++) {
        out[n] = builtin[active[n]];
    }
    return n;
}

static const char schema_grep[] =
    "{\"name\":\"grep\",\"description\":\"Search file contents for a pattern. Returns matching lines with file paths "
    "and line numbers. Respects .gitignore. Output is truncated to 100 matches or 50KB (whichever is hit first). Long "
    "lines are truncated to 500 chars.\",\"input_schema\":{\"type\":\"object\",\"properties\":{"
    "\"pattern\":{\"type\":\"string\",\"description\":\"Search pattern (regex or literal string)\"},"
    "\"path\":{\"type\":\"string\",\"description\":\"Directory or file to search (default: current directory)\"},"
    "\"glob\":{\"type\":\"string\",\"description\":\"Filter files by glob pattern relative to path, e.g. "
    "'src/**/*.ts'. Without '/', e.g. '*.ts', it matches file names at any depth\"},"
    "\"ignoreCase\":{\"type\":\"boolean\",\"description\":\"Case-insensitive search (default: false)\"},"
    "\"literal\":{\"type\":\"boolean\",\"description\":\"Treat pattern as literal string instead of regex (default: "
    "false)\"},"
    "\"context\":{\"type\":\"number\",\"description\":\"Number of lines to show before and after each match "
    "(default: 0)\"},"
    "\"limit\":{\"type\":\"number\",\"description\":\"Maximum number of matches to return (default: 100)\"}},"
    "\"required\":[\"pattern\"]}}";
static const char schema_find[] =
    "{\"name\":\"find\",\"description\":\"Search for files by glob pattern. Returns matching file paths relative to the "
    "search directory. Respects .gitignore. Output is truncated to 1000 results or 50KB (whichever is hit "
    "first).\",\"input_schema\":{\"type\":\"object\",\"properties\":{"
    "\"pattern\":{\"type\":\"string\",\"description\":\"Glob pattern relative to the search directory, e.g. "
    "'src/**/*.ts'. Without '/', e.g. '*.ts', it matches file names at any depth\"},"
    "\"path\":{\"type\":\"string\",\"description\":\"Directory to search in (default: current directory)\"},"
    "\"limit\":{\"type\":\"number\",\"description\":\"Maximum number of results (default: 1000)\"}},"
    "\"required\":[\"pattern\"]}}";
static const char schema_ls[] =
    "{\"name\":\"ls\",\"description\":\"List directory contents. Returns entries sorted alphabetically, with '/' suffix "
    "for directories. Includes dotfiles. Output is truncated to 500 entries or 50KB (whichever is hit "
    "first).\",\"input_schema\":{\"type\":\"object\",\"properties\":{"
    "\"path\":{\"type\":\"string\",\"description\":\"Directory to list (default: current directory)\"},"
    "\"limit\":{\"type\":\"number\",\"description\":\"Maximum number of entries to return (default: 500)\"}}}}";

char *pic_toolset_schemas(void) {
    const char *frag[NTOOLS] = {pic_tool_schema_read, pic_tool_schema_bash, pic_tool_schema_edit,
                                pic_tool_schema_write, schema_grep,         schema_find,
                                schema_ls};
    size_t len = 3;
    char *out, *p;
    ensure_default();
    for (size_t i = 0; i < nactive; i++) {
        len += strlen(frag[active[i]]) + 1;
    }
    if (!(out = malloc(len))) {
        return NULL;
    }
    p = out;
    *p++ = '[';
    for (size_t i = 0; i < nactive; i++) {
        size_t n = strlen(frag[active[i]]);
        if (i) {
            *p++ = ',';
        }
        memcpy(p, frag[active[i]], n);
        p += n;
    }
    *p++ = ']';
    *p = '\0';
    return out;
}

/* ---- text buffer, paths, truncation ------------------------------------------- */

typedef struct {
    char *p;
    size_t len, cap;
    int oom;
} sbuf;

static void sb_add(sbuf *b, const char *s, size_t n) {
    if (b->oom) {
        return;
    }
    if (b->len + n + 1 > b->cap) {
        size_t cap = b->cap ? b->cap : 1024;
        char *p;
        while (cap < b->len + n + 1) {
            cap *= 2;
        }
        if (!(p = realloc(b->p, cap))) {
            b->oom = 1;
            return;
        }
        b->p = p;
        b->cap = cap;
    }
    memcpy(b->p + b->len, s, n);
    b->len += n;
    b->p[b->len] = '\0';
}

static void sb_adds(sbuf *b, const char *s) { sb_add(b, s, strlen(s)); }

static void sb_addf(sbuf *b, const char *fmt, ...) {
    char tmp[512];
    va_list ap;
    int n;
    va_start(ap, fmt);
    n = vsnprintf(tmp, sizeof tmp, fmt, ap);
    va_end(ap);
    if (n < 0) {
        b->oom = 1;
    } else if ((size_t)n < sizeof tmp) {
        sb_add(b, tmp, (size_t)n);
    } else {
        char *big = malloc((size_t)n + 1);
        if (!big) {
            b->oom = 1;
            return;
        }
        va_start(ap, fmt);
        (void)vsnprintf(big, (size_t)n + 1, fmt, ap);
        va_end(ap);
        sb_add(b, big, (size_t)n);
        free(big);
    }
}

static char *fmt_dup(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;
}

static char *fail_(int *is_error, const char *fmt, const char *a, const char *b) {
    *is_error = 1;
    return fmt_dup(fmt, a, b);
}

/* Pi's resolveToCwd: a leading '@' dropped, '~' the home, relative under the
 * workspace, then made canonical (no ".", ".." or doubled slashes). */
static char *resolve_path(const char *workspace, const char *path) {
    const char *home = getenv("HOME");
    char *raw, *out, *w;
    size_t n;
    if (!path || !*path) {
        path = ".";
    }
    if (path[0] == '@') {
        path++;
    }
    if (home && (strcmp(path, "~") == 0 || strncmp(path, "~/", 2) == 0)) {
        raw = fmt_dup("%s%s", home, path + 1);
    } else if (path[0] == '/') {
        raw = fmt_dup("%s", path);
    } else {
        raw = fmt_dup("%s/%s", workspace, path);
    }
    if (!raw) {
        return NULL;
    }
    n = strlen(raw);
    if (!(out = malloc(n + 2))) {
        free(raw);
        return NULL;
    }
    w = out;
    for (const char *r = raw; *r;) {
        const char *e;
        size_t len;
        while (*r == '/') {
            r++;
        }
        if (!*r) {
            break;
        }
        for (e = r; *e && *e != '/'; e++) {
        }
        len = (size_t)(e - r);
        if (len == 1 && r[0] == '.') {
            /* nothing */
        } else if (len == 2 && r[0] == '.' && r[1] == '.') {
            while (w > out && w[-1] != '/') {
                w--;
            }
            if (w > out) {
                w--;
            }
        } else {
            *w++ = '/';
            memcpy(w, r, len);
            w += len;
        }
        r = e;
    }
    if (w == out) {
        *w++ = '/';
    }
    *w = '\0';
    free(raw);
    return out;
}

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

/* Pi's truncateHead (no line limit): whole lines while they fit in 50KB.
 * STORED bytes are held of TOTAL. Returns 1 when text was cut; *len is the kept
 * length (0 when the first line alone is too long). */
static int truncate_head(const char *p, size_t stored, size_t total, size_t *len) {
    size_t out = 0, at = 0;
    int first = 1;
    if (total <= MAX_BYTES) {
        *len = stored;
        return 0;
    }
    while (at < stored) {
        size_t e = at, cost;
        while (e < stored && p[e] != '\n') {
            e++;
        }
        cost = (e - at) + (first ? 0 : 1);
        if (out + cost > MAX_BYTES) {
            break;
        }
        out += cost;
        first = 0;
        at = e + 1;
    }
    *len = out;
    return 1;
}

/* The result text: TEXT (TOTAL bytes it would have kept in full) cut to 50KB,
 * then the "[notice. notice]" Pi appends. EXTRA is the notices before the size one. */
static char *finish_text(const sbuf *text, size_t total, const char *extra1, const char *extra2, int *is_error) {
    sbuf out = {0};
    size_t kept = 0;
    char size[32];
    int cut = truncate_head(text->p ? text->p : "", text->len, total, &kept), notices = 0;
    (void)is_error;
    if (kept > text->len) {
        kept = text->len;
    }
    sb_add(&out, text->p ? text->p : "", kept);
    if (extra1 || cut || extra2) {
        sb_adds(&out, "\n\n[");
        if (extra1) {
            sb_adds(&out, extra1);
            notices++;
        }
        if (cut) {
            format_size_(MAX_BYTES, size, sizeof size);
            sb_addf(&out, "%s%s limit reached", notices++ ? ". " : "", size);
        }
        if (extra2) {
            sb_addf(&out, "%s%s", notices++ ? ". " : "", extra2);
        }
        sb_adds(&out, "]");
    }
    if (out.oom) {
        free(out.p);
        return NULL;
    }
    return out.p ? out.p : fmt_dup("%s", "");
}

/* ---- globs ------------------------------------------------------------------- */

/* A glob as ripgrep and fd read one: a star and ? stop at a slash, a double star
 * crosses it (as a segment of its own, in front of or after a slash, it spans
 * folders), [a-z] and [!a-z] classes, \ escapes; {a,b} is expanded beforehand. */
static int gclass(const char *p, const char *end_unused, char c, int ic, const char **next) {
    int neg = 0, hit = 0;
    (void)end_unused;
    p++;
    if (*p == '!' || *p == '^') {
        neg = 1;
        p++;
    }
    for (int first = 1; *p && (*p != ']' || first); first = 0) {
        unsigned char lo = (unsigned char)*p, hi = lo;
        if (lo == '\\' && p[1]) {
            lo = hi = (unsigned char)p[1];
            p++;
        }
        if (p[1] == '-' && p[2] && p[2] != ']') {
            hi = (unsigned char)p[2];
            p += 2;
        }
        {
            unsigned char ch = (unsigned char)c;
            if (ic) {
                ch = (unsigned char)tolower(ch);
                lo = (unsigned char)tolower(lo);
                hi = (unsigned char)tolower(hi);
            }
            hit |= ch >= lo && ch <= hi;
        }
        p++;
    }
    if (*p != ']') {
        return -1; /* an unclosed class matches nothing */
    }
    *next = p + 1;
    return hit != neg;
}

static int gmatch(const char *start, const char *p, const char *s, int ic) {
    while (*p) {
        int at_seg = p == start || p[-1] == '/';
        if (p[0] == '*' && p[1] == '*' && at_seg && p[2] == '/') {
            const char *q = p + 3;
            for (;;) {
                if (gmatch(start, q, s, ic)) {
                    return 1;
                }
                s = strchr(s, '/');
                if (!s) {
                    return 0;
                }
                s++;
            }
        }
        if (p[0] == '*' && p[1] == '*' && at_seg && !p[2]) {
            return 1;
        }
        if (p[0] == '/' && p[1] == '*' && p[2] == '*' && !p[3]) {
            return s[0] == '/';
        }
        if (p[0] == '*') {
            int cross = p[1] == '*';
            const char *q = p + (cross ? 2 : 1);
            for (;; s++) {
                if (gmatch(start, q, s, ic)) {
                    return 1;
                }
                if (!*s || (!cross && *s == '/')) {
                    return 0;
                }
            }
        }
        if (!*s) {
            return 0;
        }
        if (p[0] == '?') {
            if (*s == '/') {
                return 0;
            }
            p++;
            s++;
        } else if (p[0] == '[') {
            const char *next = NULL;
            int r = *s == '/' ? 0 : gclass(p, NULL, *s, ic, &next);
            if (r < 0 || !r) {
                return 0;
            }
            p = next;
            s++;
        } else {
            char pc = p[0] == '\\' && p[1] ? p[1] : p[0];
            if (p[0] == '\\' && p[1]) {
                p++;
            }
            if (ic ? tolower((unsigned char)pc) != tolower((unsigned char)*s) : pc != *s) {
                return 0;
            }
            p++;
            s++;
        }
    }
    return !*s;
}

#define MAX_ALTS 64
typedef struct {
    char *alt[MAX_ALTS];
    size_t n;
    int nocase, has_slash;
} globs;

static int glob_push(globs *g, const char *pat, size_t len) {
    char *c;
    if (g->n == MAX_ALTS || !(c = malloc(len + 1))) {
        return -1;
    }
    memcpy(c, pat, len);
    c[len] = '\0';
    g->alt[g->n++] = c;
    return 0;
}

/* Expands the first {a,b,c} of PAT (nested ones through the recursion). */
static int glob_expand(globs *g, const char *pat, size_t len) {
    size_t open = (size_t)-1, depth = 0, close = (size_t)-1;
    for (size_t i = 0; i < len; i++) {
        if (pat[i] == '\\') {
            i++;
        } else if (pat[i] == '{') {
            if (depth++ == 0) {
                open = i;
            }
        } else if (pat[i] == '}' && depth > 0 && --depth == 0) {
            close = i;
            break;
        }
    }
    if (open == (size_t)-1 || close == (size_t)-1) {
        return glob_push(g, pat, len);
    }
    {
        size_t start = open + 1, d = 0;
        for (size_t i = open + 1; i <= close; i++) {
            if (pat[i] == '\\') {
                i++;
            } else if (pat[i] == '{') {
                d++;
            } else if (pat[i] == '}' && i != close) {
                d--;
            } else if ((pat[i] == ',' && d == 0) || i == close) {
                char *piece = malloc(open + (i - start) + (len - close) + 1);
                int rc;
                if (!piece) {
                    return -1;
                }
                memcpy(piece, pat, open);
                memcpy(piece + open, pat + start, i - start);
                memcpy(piece + open + (i - start), pat + close + 1, len - close - 1);
                rc = glob_expand(g, piece, open + (i - start) + (len - close - 1));
                free(piece);
                if (rc != 0) {
                    return -1;
                }
                start = i + 1;
            }
        }
    }
    return 0;
}

static void globs_free(globs *g) {
    for (size_t i = 0; i < g->n; i++) {
        free(g->alt[i]);
    }
    g->n = 0;
}

static int globs_init(globs *g, const char *pat, int nocase) {
    memset(g, 0, sizeof *g);
    g->nocase = nocase;
    g->has_slash = strchr(pat, '/') != NULL;
    return glob_expand(g, pat, strlen(pat));
}

/* Whether any alternative takes S whole. */
static int globs_match(const globs *g, const char *s) {
    for (size_t i = 0; i < g->n; i++) {
        const char *p = g->alt[i];
        if (gmatch(p, p, s, g->nocase)) {
            return 1;
        }
    }
    return 0;
}

/* gitignore's reading of a --glob: a pattern with a '/' is anchored at the
 * search folder, one without names a file or folder at any depth, and a match
 * on a folder covers what is under it. */
static int globs_cover(const globs *g, const char *rel) {
    for (const char *e = rel;; e++) {
        if (*e == '/' || !*e) {
            size_t n = (size_t)(e - rel);
            char *prefix = malloc(n + 1);
            int hit = 0;
            if (prefix) {
                const char *base;
                memcpy(prefix, rel, n);
                prefix[n] = '\0';
                base = strrchr(prefix, '/');
                for (size_t i = 0; i < g->n && !hit; i++) {
                    const char *p = g->alt[i];
                    if (p[0] == '/') {
                        hit = gmatch(p + 1, p + 1, prefix, g->nocase);
                    } else if (strchr(p, '/')) {
                        hit = gmatch(p, p, prefix, g->nocase);
                    } else {
                        hit = gmatch(p, p, base ? base + 1 : prefix, g->nocase);
                    }
                }
                free(prefix);
            }
            if (hit) {
                return 1;
            }
            if (!*e) {
                return 0;
            }
        }
    }
}

/* ---- the walk ---------------------------------------------------------------- */

typedef struct {
    const pic_executor *ex;
    pic_ignore ig;
    int oom;
} walker;

/* 0: go on; 1: do not enter this folder; 2: stop the walk. */
typedef int (*visit_fn)(void *ctx, const char *rel, const char *abs, int is_dir);

typedef struct {
    char **v;
    size_t n, cap;
} entries;

static int collect(void *state, const char *entry) {
    entries *e = state;
    if (e->n == e->cap) {
        size_t cap = e->cap ? e->cap * 2 : 64;
        char **p = realloc(e->v, cap * sizeof *p);
        if (!p) {
            return ENOMEM;
        }
        e->v = p;
        e->cap = cap;
    }
    if (!(e->v[e->n] = strdup(entry))) {
        return ENOMEM;
    }
    e->n++;
    return 0;
}

static int by_name(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }

static void load_ignores(walker *w, const char *dir, const char *rel, int root) {
    char path[4096], prefix[4096];
    if (snprintf(prefix, sizeof prefix, "%s%s", rel, *rel ? "/" : "") >= (int)sizeof prefix) {
        return;
    }
    for (size_t i = 0; i < PIC_IGNORE_NAMES + (root ? PIC_IGNORE_SETTINGS : 0); i++) {
        int settings = i >= PIC_IGNORE_NAMES;
        const char *name = settings ? pic_ignore_settings[i - PIC_IGNORE_NAMES] : pic_ignore_names[i];
        char *txt = NULL;
        size_t len = 0;
        if (snprintf(path, sizeof path, "%s/%s", strcmp(dir, "/") == 0 ? "" : dir, name) >= (int)sizeof path) {
            continue;
        }
        if (w->ex->read(w->ex->state, path, PIC_IGNORE_MAX, 0, &txt, &len) == 0 && txt) {
            if ((settings ? pic_ignore_add_glob(&w->ig, txt, len, "")
                          : pic_ignore_add_named(&w->ig, name, txt, len, prefix)) != 0) {
                w->oom = 1;
            }
            free(txt);
        }
    }
}

/* Visits what is under ABSDIR in sorted order, folders before their contents. */
static int walk_dir(walker *w, const char *absdir, const char *rel, int depth, visit_fn fn, void *ctx) {
    entries list = {0};
    size_t mark = w->ig.n;
    int rc = 0;
    if (w->ex->list(w->ex->state, absdir, collect, &list) != 0 && list.n == 0) {
        return 0;
    }
    qsort(list.v, list.n, sizeof *list.v, by_name);
    load_ignores(w, absdir, rel, depth == 0);
    for (size_t i = 0; i < list.n && rc == 0; i++) {
        char child_rel[4096], child_abs[4096];
        pic_file_stat st;
        int is_dir, r;
        if (strcmp(list.v[i], ".git") == 0) {
            continue;
        }
        if (snprintf(child_rel, sizeof child_rel, "%s%s%s", rel, *rel ? "/" : "", list.v[i]) >= (int)sizeof child_rel ||
            snprintf(child_abs, sizeof child_abs, "%s/%s", strcmp(absdir, "/") == 0 ? "" : absdir, list.v[i]) >=
                (int)sizeof child_abs) {
            continue;
        }
        if (w->ex->stat(w->ex->state, child_abs, &st) != 0) {
            continue; /* a broken link, or gone since the listing */
        }
        is_dir = st.is_dir;
        if (pic_ignore_ignored(&w->ig, child_rel, is_dir)) {
            continue;
        }
        r = fn(ctx, child_rel, child_abs, is_dir);
        if (r == 2) {
            rc = 2;
        } else if (r == 0 && is_dir && depth < WALK_DEPTH) {
            rc = walk_dir(w, child_abs, child_rel, depth + 1, fn, ctx);
        }
    }
    for (size_t i = 0; i < list.n; i++) {
        free(list.v[i]);
    }
    free(list.v);
    pic_ignore_truncate(&w->ig, mark);
    return rc;
}

/* ---- ls ---------------------------------------------------------------------- */

static int ci_name_cmp(const void *a, const void *b) {
    const unsigned char *x = (const unsigned char *)*(char *const *)a, *y = (const unsigned char *)*(char *const *)b;
    for (; *x && *y; x++, y++) {
        int cx = tolower(*x), cy = tolower(*y);
        if (cx != cy) {
            return cx - cy;
        }
    }
    if (*x != *y) {
        return *x ? 1 : -1;
    }
    return strcmp(*(char *const *)a, *(char *const *)b);
}

static char *tool_ls(const char *workspace, const pic_tool_args *a, int *is_error) {
    const pic_executor *ex = pic_executor_get();
    char *dir = resolve_path(workspace, a->path), *res;
    pic_file_stat st;
    entries list = {0};
    sbuf text = {0};
    long limit = a->has_limit && a->limit > 1 ? a->limit : (a->has_limit ? 1 : 500), found = 0;
    int err, reached = 0;
    char note[96];
    if (!dir) {
        return NULL;
    }
    if (ex->stat(ex->state, dir, &st) != 0) {
        res = fail_(is_error, "Path not found: %s%s", dir, "");
        free(dir);
        return res;
    }
    if (!st.is_dir) {
        res = fail_(is_error, "Not a directory: %s%s", dir, "");
        free(dir);
        return res;
    }
    if ((err = ex->list(ex->state, dir, collect, &list)) != 0 && err != ENOMEM) {
        char *msg = fmt_dup("%s: %s, scandir '%s'", pic_errno_name(err), strerror(err), dir);
        res = fail_(is_error, "Cannot read directory: %s%s", msg ? msg : "", "");
        free(msg);
        free(dir);
        for (size_t i = 0; i < list.n; i++) {
            free(list.v[i]);
        }
        free(list.v);
        return res;
    }
    qsort(list.v, list.n, sizeof *list.v, ci_name_cmp);
    for (size_t i = 0; i < list.n; i++) {
        char child[4096];
        pic_file_stat cs;
        if (found >= limit) {
            reached = 1;
            break;
        }
        if (snprintf(child, sizeof child, "%s/%s", strcmp(dir, "/") == 0 ? "" : dir, list.v[i]) >= (int)sizeof child ||
            ex->stat(ex->state, child, &cs) != 0) {
            continue;
        }
        if (found++) {
            sb_adds(&text, "\n");
        }
        sb_adds(&text, list.v[i]);
        if (cs.is_dir) {
            sb_adds(&text, "/");
        }
    }
    for (size_t i = 0; i < list.n; i++) {
        free(list.v[i]);
    }
    free(list.v);
    free(dir);
    if (found == 0) {
        free(text.p);
        return fmt_dup("(empty directory)");
    }
    (void)snprintf(note, sizeof note, "%ld entries limit reached. Use limit=%ld for more", limit, limit * 2);
    res = finish_text(&text, text.len, reached ? note : NULL, NULL, is_error);
    free(text.p);
    return res;
}

/* ---- find -------------------------------------------------------------------- */

typedef struct {
    globs g;
    int absolute, path_mode;
    long limit, found;
    int reached;
    sbuf out;
} find_st;

static int find_visit(void *ctx, const char *rel, const char *abs, int is_dir) {
    find_st *f = ctx;
    const char *subject = f->absolute ? abs : f->path_mode ? rel : (strrchr(rel, '/') ? strrchr(rel, '/') + 1 : rel);
    if (!globs_match(&f->g, subject)) {
        return 0;
    }
    if (f->found == f->limit) {
        f->reached = 1;
        return 2;
    }
    if (f->found++) {
        sb_adds(&f->out, "\n");
    }
    sb_adds(&f->out, rel);
    if (is_dir) {
        sb_adds(&f->out, "/");
    }
    return 0;
}

static char *tool_find(const char *workspace, const pic_tool_args *a, int *is_error) {
    const pic_executor *ex = pic_executor_get();
    char *root = resolve_path(workspace, a->path), *res, note[96];
    const char *pat = a->pattern;
    pic_file_stat st;
    find_st f;
    walker w;
    int lowercase = 1;
    size_t n;
    if (!root) {
        return NULL;
    }
    if (ex->stat(ex->state, root, &st) != 0) {
        res = fail_(is_error, "Path not found: %s%s", root, "");
        free(root);
        return res;
    }
    if (!st.is_dir) {
        res = fail_(is_error, "Not a directory: %s%s", root, "");
        free(root);
        return res;
    }
    while (pat[0] == '.' && pat[1] == '/') {
        pat += 2;
    }
    for (const char *c = pat; *c; c++) {
        lowercase &= !isupper((unsigned char)*c);
    }
    memset(&f, 0, sizeof f);
    f.limit = a->has_limit && a->limit > 1 ? a->limit : (a->has_limit ? 1 : 1000);
    f.path_mode = strchr(pat, '/') != NULL;
    f.absolute = pat[0] == '/';
    if (globs_init(&f.g, pat, f.absolute ? 0 : lowercase) != 0) {
        globs_free(&f.g);
        free(root);
        return NULL;
    }
    memset(&w, 0, sizeof w);
    w.ex = ex;
    (void)walk_dir(&w, root, "", 0, find_visit, &f);
    pic_ignore_free(&w.ig);
    globs_free(&f.g);
    free(root);
    if (f.found == 0) {
        free(f.out.p);
        return fmt_dup("No files found matching pattern");
    }
    n = f.out.len;
    (void)snprintf(note, sizeof note, "%ld results limit reached. Use limit=%ld for more, or refine pattern", f.limit,
                   f.limit * 2);
    res = finish_text(&f.out, n, f.reached ? note : NULL, NULL, is_error);
    free(f.out.p);
    return res;
}

/* ---- grep -------------------------------------------------------------------- */

/* The pattern as POSIX ERE: see the header. */
static char *rx_translate(const char *p, int *icase) {
    size_t n = strlen(p);
    char *out = malloc(n * 4 + 8), *w = out;
    int inbr = 0;
    if (!out) {
        return NULL;
    }
    if (strncmp(p, "(?i)", 4) == 0) {
        *icase = 1;
        p += 4;
    }
    while (*p) {
        char c = *p;
        if (inbr) {
            if (c == '\\' && p[1]) {
                const char *cls = p[1] == 'd' ? "0-9" : p[1] == 'w' ? "[:alnum:]_" : p[1] == 's' ? "[:space:]" : NULL;
                if (cls) {
                    w = stpcpy(w, cls);
                } else {
                    *w++ = p[1];
                }
                p += 2;
            } else if (c == '[' && p[1] == ':') {
                const char *end = strstr(p + 2, ":]");
                size_t k = end ? (size_t)(end + 2 - p) : 1;
                memcpy(w, p, k);
                w += k;
                p += k;
            } else {
                inbr = c != ']';
                *w++ = c;
                p++;
            }
            continue;
        }
        if (c == '[') {
            *w++ = c;
            p++;
            if (*p == '^') {
                *w++ = *p++;
            }
            if (*p == ']') {
                *w++ = *p++;
            }
            inbr = 1;
        } else if (c == '\\' && p[1]) {
            const char *cls = NULL;
            switch (p[1]) {
            case 'd': cls = "[0-9]"; break;
            case 'D': cls = "[^0-9]"; break;
            case 'w': cls = "[[:alnum:]_]"; break;
            case 'W': cls = "[^[:alnum:]_]"; break;
            case 's': cls = "[[:space:]]"; break;
            case 'S': cls = "[^[:space:]]"; break;
            default: break;
            }
            if (cls) {
                w = stpcpy(w, cls);
            } else {
                *w++ = '\\';
                *w++ = p[1];
            }
            p += 2;
        } else if (c == '(' && p[1] == '?' && p[2] == ':') {
            *w++ = '(';
            p += 3;
        } else if (c == '*' || c == '+' || c == '?' || c == '}') {
            *w++ = c;
            p++;
            if (*p == '?') {
                p++; /* lazy: a line either matches or not */
            }
        } else {
            *w++ = c;
            p++;
        }
    }
    *w = '\0';
    return out;
}

typedef struct {
    const pic_executor *ex;
    int is_dir;
    regex_t re;
    int use_re;
    const char *lit;
    size_t litlen;
    int icase;
    globs gl;
    int have_glob, glob_exclude;
    long limit, ctx, matches, trailing_end;
    int hit_limit, reached, lines_cut, oom;
    char win_file[4096];
    sbuf out;
    size_t total;
    char *line;
    size_t line_cap;
} grep_st;

static int lit_find(const char *h, size_t hn, const char *nd, size_t nn, int ic) {
    if (nn == 0) {
        return 1;
    }
    for (size_t i = 0; i + nn <= hn; i++) {
        size_t k = 0;
        while (k < nn && (ic ? tolower((unsigned char)h[i + k]) == tolower((unsigned char)nd[k]) : h[i + k] == nd[k])) {
            k++;
        }
        if (k == nn) {
            return 1;
        }
    }
    return 0;
}

static int line_matches(grep_st *g, const char *s, size_t n) {
    if (g->use_re) {
        if (n + 1 > g->line_cap) {
            char *p = realloc(g->line, n + 1024);
            if (!p) {
                g->oom = 1;
                return 0;
            }
            g->line = p;
            g->line_cap = n + 1024;
        }
        memcpy(g->line, s, n);
        g->line[n] = '\0';
        return regexec(&g->re, g->line, 0, NULL, 0) == 0;
    }
    return lit_find(s, n, g->lit, g->litlen, g->icase);
}

/* Pi's truncateLine: 500 characters, then a mark. */
static void push_line(grep_st *g, const char *file, long lineno, int match, const char *s, size_t n) {
    size_t chars = 0, keep = n;
    char head[64];
    int hn;
    if (n && s[n - 1] == '\r') {
        n--;
        keep = n;
    }
    for (size_t i = 0; i < n; i++) {
        if (((unsigned char)s[i] & 0xC0) != 0x80 && ++chars > GREP_LINE_MAX) {
            keep = i;
            break;
        }
    }
    hn = snprintf(head, sizeof head, "%c%ld%c ", match ? ':' : '-', lineno, match ? ':' : '-');
    if (g->total > 0) {
        g->total += 1;
        if (g->out.len <= MAX_BYTES) {
            sb_adds(&g->out, "\n");
        }
    }
    {
        size_t fl = strlen(file), cut = keep < n ? 15 : 0;
        g->total += fl + (size_t)hn + keep + cut;
        if (g->out.len <= MAX_BYTES || g->out.len == 0) {
            sb_add(&g->out, file, fl);
            sb_add(&g->out, head, (size_t)hn);
            sb_add(&g->out, s, keep);
            if (keep < n) {
                sb_adds(&g->out, "... [truncated]");
            }
        }
        if (keep < n) {
            g->lines_cut = 1;
        }
    }
}

static size_t line_end(const char *data, size_t len, size_t from) {
    const char *nl = memchr(data + from, '\n', len - from);
    return nl ? (size_t)(nl - data) : len;
}

/* One file's lines. 0: go on, 2: the search is over. */
static int grep_file(grep_st *g, const char *shown, char *data, size_t len) {
    size_t *start = NULL, nl = 0, cap = 0;
    long after = 0, lastp = -1;
    int rc = 0;
    for (size_t i = 0; i < len; i = line_end(data, len, i) + 1) { /* no empty line after a final newline */
        if (nl == cap) {
            size_t *p = realloc(start, (cap ? cap * 2 : 256) * sizeof *p);
            if (!p) {
                free(start);
                g->oom = 1;
                return 2;
            }
            start = p;
            cap = cap ? cap * 2 : 256;
        }
        start[nl++] = i;
    }
    for (size_t L = 0; L < nl && rc == 0; L++) {
        const char *s = data + start[L];
        size_t n = line_end(data, len, start[L]) - start[L];
        int m = line_matches(g, s, n);
        if (g->oom) {
            rc = 2;
        } else if (!g->hit_limit) {
            if (m) {
                long from = (long)L - g->ctx;
                if (from <= lastp) {
                    from = lastp + 1;
                }
                if (from < 0) {
                    from = 0;
                }
                for (long k = from; k < (long)L; k++) {
                    push_line(g, shown, k + 1, 0, data + start[k], line_end(data, len, start[k]) - start[k]);
                }
                push_line(g, shown, (long)L + 1, 1, s, n);
                lastp = (long)L;
                after = g->ctx;
                if (++g->matches >= g->limit) {
                    g->hit_limit = 1;
                    g->trailing_end = (long)L + g->ctx;
                    (void)snprintf(g->win_file, sizeof g->win_file, "%s", shown);
                }
            } else if (after > 0) {
                push_line(g, shown, (long)L + 1, 0, s, n);
                lastp = (long)L;
                after--;
            }
        } else if (strcmp(g->win_file, shown) != 0) {
            if (m) {
                g->reached = 1;
                rc = 2;
            }
        } else {
            int in_window = (long)L <= g->trailing_end;
            if (in_window) {
                push_line(g, shown, (long)L + 1, 0, s, n);
            }
            if (m) {
                g->reached = 1;
            }
            if (g->reached && !(in_window && (long)L < g->trailing_end)) {
                rc = 2;
            }
        }
    }
    free(start);
    return rc ? rc : (g->reached ? 2 : 0);
}

typedef struct {
    grep_st *g;
} grep_walk;

static int grep_visit(void *ctx, const char *rel, const char *abs, int is_dir) {
    grep_st *g = ((grep_walk *)ctx)->g;
    char *data = NULL;
    size_t len = 0;
    int rc;
    if (g->have_glob && g->glob_exclude) {
        if (globs_cover(&g->gl, rel)) {
            return is_dir ? 1 : 0;
        }
    }
    if (is_dir) {
        return 0;
    }
    if (g->have_glob && !g->glob_exclude && !globs_cover(&g->gl, rel)) {
        return 0;
    }
    if (g->ex->read(g->ex->state, abs, FILE_CAP, 0, &data, &len) != 0 || !data) {
        return 0;
    }
    if (memchr(data, '\0', len)) {
        free(data);
        return 0;
    }
    rc = grep_file(g, rel, data, len);
    free(data);
    return rc;
}

static char *tool_grep(const char *workspace, const pic_tool_args *a, int *is_error) {
    const pic_executor *ex = pic_executor_get();
    char *root = resolve_path(workspace, a->path), *res = NULL, *xl = NULL, note[160], note2[96];
    pic_file_stat st;
    grep_st g;
    grep_walk gw = {&g};
    walker w;
    const char *glob = a->glob;
    size_t total;
    if (!root) {
        return NULL;
    }
    if (ex->stat(ex->state, root, &st) != 0) {
        res = fail_(is_error, "Path not found: %s%s", root, "");
        free(root);
        return res;
    }
    memset(&g, 0, sizeof g);
    g.ex = ex;
    g.is_dir = st.is_dir;
    g.icase = a->ignore_case;
    g.ctx = a->has_context && a->context > 0 ? a->context : 0;
    g.limit = a->has_limit && a->limit > 1 ? a->limit : (a->has_limit ? 1 : 100);
    if (a->literal) {
        g.lit = a->pattern;
        g.litlen = strlen(a->pattern);
    } else {
        int icase = a->ignore_case, rc;
        int flags = REG_EXTENDED | REG_NOSUB;
        char msg[200];
        xl = rx_translate(a->pattern, &icase);
#ifdef REG_ENHANCED
        flags |= REG_ENHANCED;
#endif
        if (icase) {
            flags |= REG_ICASE;
        }
        if (!xl) {
            free(root);
            return NULL;
        }
        if ((rc = regcomp(&g.re, xl, flags)) != 0) {
            (void)regerror(rc, &g.re, msg, sizeof msg);
            *is_error = 1;
            res = fmt_dup("regex parse error:\n    %s\nerror: %s", a->pattern, msg);
            free(xl);
            free(root);
            return res;
        }
        g.use_re = 1;
    }
    if (glob && st.is_dir) {
        /* Pi drops leading "./" after an optional '!'. */
        if (glob[0] == '!') {
            g.glob_exclude = 1;
            glob++;
        }
        while (glob[0] == '.' && glob[1] == '/') {
            glob += 2;
        }
        if (globs_init(&g.gl, glob, 0) != 0) {
            globs_free(&g.gl);
        } else {
            g.have_glob = 1;
        }
    }
    memset(&w, 0, sizeof w);
    w.ex = ex;
    if (st.is_dir) {
        (void)walk_dir(&w, root, "", 0, grep_visit, &gw);
    } else {
        char *data = NULL;
        size_t len = 0;
        const char *base = strrchr(root, '/');
        if (ex->read(ex->state, root, FILE_CAP, 0, &data, &len) == 0 && data) {
            if (!memchr(data, '\0', len)) {
                (void)grep_file(&g, base ? base + 1 : root, data, len);
            }
            free(data);
        }
    }
    pic_ignore_free(&w.ig);
    globs_free(&g.gl);
    if (g.use_re) {
        regfree(&g.re);
    }
    free(xl);
    free(root);
    free(g.line);
    if (g.oom || g.out.oom) {
        free(g.out.p);
        return NULL;
    }
    if (g.matches == 0) {
        free(g.out.p);
        return fmt_dup("No matches found");
    }
    total = g.total;
    (void)snprintf(note, sizeof note, "%ld matches limit reached. Use limit=%ld for more, or refine pattern", g.limit,
                   g.limit * 2);
    (void)snprintf(note2, sizeof note2, "Some lines truncated to %d chars. Use read tool to see full lines", GREP_LINE_MAX);
    res = finish_text(&g.out, total, g.reached ? note : NULL, g.lines_cut ? note2 : NULL, is_error);
    free(g.out.p);
    return res;
}

/* ---- dispatch ---------------------------------------------------------------- */

char *pic_toolset_run(const char *workspace, const char *tool, const pic_tool_args *args, const pic_tool_hooks *hooks,
                      int *is_error) {
    int search = strcmp(tool, "grep") == 0 || strcmp(tool, "find") == 0 || strcmp(tool, "ls") == 0;
    char *out;
    if (!pic_toolset_on(tool)) {
        *is_error = 0;
        if (hooks->started == NULL || hooks->started(hooks->ctx, NULL, 0) != 0) {
            return NULL;
        }
        return fail_(is_error, "Tool %s not found%s", tool, "");
    }
    if (!search) {
        return pic_tool_run(workspace, tool, args, hooks, is_error);
    }
    *is_error = 0;
    if (hooks->started == NULL || hooks->started(hooks->ctx, NULL, 0) != 0) {
        return NULL;
    }
    if (args->bad_input) {
        return fail_(is_error, "%s%s", args->bad_input, "");
    }
    if (strcmp(tool, "ls") == 0) {
        out = tool_ls(workspace, args, is_error);
    } else if (!args->pattern) {
        return fail_(is_error, "%s needs a string input pattern%s", tool, "");
    } else {
        out = strcmp(tool, "grep") == 0 ? tool_grep(workspace, args, is_error) : tool_find(workspace, args, is_error);
    }
    return out ? out : fail_(is_error, "out of memory%s%s", "", "");
}