Skip to content
pi-c Documentation
Login

Documentation

/* The tool registry and the tools in play (toolreg.h). Pi's tool selection (--tools,
 * --exclude-tools, --no-tools, --no-builtin-tools and the defaultTools setting) is kept as given
 * and applied to whatever is registered, again whenever the registry changes. Plain C: no
 * operating system here. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "toolreg.h"

#define TR_MAX 256

static int tr_always(void) { return 1; }

static char *tr_core_run(void *state, const char *workspace, const char *tool, const pic_tool_args *args,
                         const pic_tool_hooks *hooks, int *is_error) {
    (void)state;
    return pic_tool_run(workspace, tool, args, hooks, is_error);
}

/* Core's own: write's bytes come from its input and edit journals its plan, so both replay;
 * bash's command may do anything, so it does not. */
static const pic_tool_def tr_read = {"read", pic_tool_schema_read, 1, 0, PIC_TIER_CORE, 1, tr_always, tr_core_run, NULL, 1};
static const pic_tool_def tr_bash = {"bash", pic_tool_schema_bash, 0, 0, PIC_TIER_CORE, 1, tr_always, tr_core_run, NULL, 0};
static const pic_tool_def tr_edit = {"edit", pic_tool_schema_edit, 1, 0, PIC_TIER_CORE, 1, tr_always, tr_core_run, NULL, 0};
static const pic_tool_def tr_write = {"write", pic_tool_schema_write, 1, 0, PIC_TIER_CORE, 1, tr_always, tr_core_run,
                                      NULL, 0};

static const pic_tool_def *tr_tools[TR_MAX] = {&tr_read, &tr_bash, &tr_edit, &tr_write};
static size_t tr_n = 4;
static unsigned long tr_gen = 1; /* bumped by every change to the registry or the selection */
static const pic_tool_def *tr_deferred[TR_MAX]; /* the registered tools marked deferred */
static pic_defer_reach tr_reach[TR_MAX];         /* what each of them waits for */
static size_t tr_ndeferred;
static const pic_tool_def *tr_standers[TR_MAX]; /* tools that stand for MCP servers, and how */
static char *(*tr_stand_fn[TR_MAX])(const char *input);
static size_t tr_nstanders;

static void tr_unstand(const pic_tool_def *d) {
    for (size_t i = 0; i < tr_nstanders; i++) {
        if (tr_standers[i] == d) {
            memmove(tr_standers + i, tr_standers + i + 1, (tr_nstanders - i - 1) * sizeof tr_standers[0]);
            memmove(tr_stand_fn + i, tr_stand_fn + i + 1, (tr_nstanders - i - 1) * sizeof tr_stand_fn[0]);
            tr_nstanders--;
            return;
        }
    }
}

int pic_tool_stand_for(const pic_tool_def *def, char *(*fn)(const char *input)) {
    size_t i;
    for (i = 0; i < tr_n && tr_tools[i] != def; i++) {
    }
    if (i == tr_n || !fn || tr_nstanders == TR_MAX) {
        return -1;
    }
    tr_unstand(def);
    tr_standers[tr_nstanders] = def;
    tr_stand_fn[tr_nstanders++] = fn;
    return 0;
}

char *pic_tool_stands_for(const pic_tool_def *def, const char *input) {
    for (size_t i = 0; def && i < tr_nstanders; i++) {
        if (tr_standers[i] == def) {
            return tr_stand_fn[i](input ? input : "{}");
        }
    }
    return NULL;
}

static int tr_is_deferred(const pic_tool_def *d) {
    for (size_t i = 0; i < tr_ndeferred; i++) {
        if (tr_deferred[i] == d) {
            return 1;
        }
    }
    return 0;
}

static void tr_undefer(const pic_tool_def *d) {
    for (size_t i = 0; i < tr_ndeferred; i++) {
        if (tr_deferred[i] == d) {
            memmove(tr_deferred + i, tr_deferred + i + 1, (tr_ndeferred - i - 1) * sizeof tr_deferred[0]);
            memmove(tr_reach + i, tr_reach + i + 1, (tr_ndeferred - i - 1) * sizeof tr_reach[0]);
            tr_ndeferred--;
            return;
        }
    }
}

int pic_tool_register(const pic_tool_def *def) {
    if (!def || !def->name || !*def->name || !def->schema || !def->run) {
        return -1;
    }
    for (size_t i = 0; i < tr_n; i++) {
        if (strcmp(tr_tools[i]->name, def->name) == 0) {
            tr_undefer(tr_tools[i]);
            tr_unstand(tr_tools[i]);
            tr_tools[i] = def;
            tr_gen++;
            return 0;
        }
    }
    if (tr_n == TR_MAX) {
        return -1;
    }
    tr_tools[tr_n++] = def;
    tr_gen++;
    return 0;
}

int pic_tool_unregister(const char *name) {
    for (size_t i = 0; name && i < tr_n; i++) {
        if (strcmp(tr_tools[i]->name, name) == 0) {
            tr_undefer(tr_tools[i]);
            tr_unstand(tr_tools[i]);
            memmove(tr_tools + i, tr_tools + i + 1, (tr_n - i - 1) * sizeof tr_tools[0]);
            tr_n--;
            tr_gen++;
            return 0;
        }
    }
    return -1;
}

int pic_tool_defer(const pic_tool_def *def, pic_defer_reach reach) {
    size_t i;
    for (i = 0; i < tr_n && tr_tools[i] != def; i++) {
    }
    if (i == tr_n || tr_ndeferred == TR_MAX) {
        return -1;
    }
    tr_undefer(def);
    tr_reach[tr_ndeferred] = reach;
    tr_deferred[tr_ndeferred++] = def;
    tr_gen++;
    return 0;
}

int pic_tool_deferred(const pic_tool_def *def) { return tr_is_deferred(def); }

int pic_tool_has_deferred(pic_defer_reach reach) {
    for (size_t i = 0; i < tr_ndeferred; i++) {
        if (tr_reach[i] == reach) {
            return 1;
        }
    }
    return 0;
}

static int tr_index(const char *name) {
    for (size_t i = 0; name && i < tr_n; i++) {
        if (strcmp(tr_tools[i]->name, name) == 0) {
            return (int)i;
        }
    }
    return -1;
}

const pic_tool_def *pic_tool_named(const char *name) {
    int i = tr_index(name);
    return i < 0 ? NULL : tr_tools[i];
}

int pic_tool_replay_safe(const char *tool) {
    const pic_tool_def *d = pic_tool_named(tool);
    return d && d->replay_safe;
}

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

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

/* Pi's comma list: trimmed, empty entries dropped. -1 when too long. */
static int tr_split(const char *csv, tr_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 tr_star(const char *pat, const char *s) {
    if (!*pat) {
        return !*s;
    }
    if (*pat == '*') {
        for (;; s++) {
            if (tr_star(pat + 1, s)) {
                return 1;
            }
            if (!*s) {
                return 0;
            }
        }
    }
    return *pat == *s && tr_star(pat + 1, s + 1);
}

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

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

/* Pi's applyToolModifiers over registry indexes in SEL. */
static void tr_modify(const tr_names *entries, int *sel, size_t *n) {
    for (size_t i = 0; i < entries->n; i++) {
        const char *e = entries->v[i];
        int b;
        size_t at;
        if (!tr_is_modifier(e)) {
            continue;
        }
        b = tr_index(e + 1);
        for (at = 0; at < *n && sel[at] != b; at++) {
        }
        if (b < 0) {
            continue; /* not registered: 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 *tr_list_error(const tr_names *l, char *buf, size_t cap) {
    size_t mods = 0;
    for (size_t i = 0; i < l->n; i++) {
        mods += tr_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;
}

/* What was configured, kept as given. */
static char *tr_spec_tools, *tr_spec_exclude, *tr_spec_saved;
static int tr_spec_no_tools, tr_spec_no_builtin;

static unsigned long tr_active_gen;
static size_t tr_nactive;
static const pic_tool_def *tr_active[TR_MAX]; /* in the order tools are declared */

static int tr_on_by_default(const pic_tool_def *d) { return d->by_default && d->by_default(); }

/* The tools in play now, from the configuration and the registry. */
static void tr_select(void) {
    tr_names t, x, d;
    int sel[TR_MAX], seen[TR_MAX] = {0};
    size_t nsel = 0, mods = 0;
    const char *tools = tr_spec_tools, *saved = tr_spec_saved;
    if (tr_active_gen == tr_gen) {
        return;
    }
    t.n = x.n = d.n = 0;
    if (tools) {
        (void)tr_split(tools, &t);
    }
    if (tr_spec_exclude) {
        (void)tr_split(tr_spec_exclude, &x);
    }
    if (saved) {
        (void)tr_split(saved, &d);
    }
    for (size_t i = 0; i < t.n; i++) {
        mods += tr_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 (size_t b = 0; b < tr_n; b++) {
                if (tr_matches(t.v[i], tr_tools[b]->name) && !seen[b]) {
                    seen[b] = 1;
                    sel[nsel++] = (int)b;
                }
            }
        }
    } else {
        /* The defaults: no built-in tools under --no-tools or --no-builtin-tools; else the
         * defaultTools setting (plain names replace the built-in defaults, +name and -name
         * change them), else the built-in defaults. Other registered tools that are on by
         * default follow, except under --no-tools. --tools +name/-name changes those. */
        if (!tr_spec_no_tools && !tr_spec_no_builtin) {
            size_t plain = 0;
            for (size_t i = 0; i < d.n; i++) {
                plain += tr_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 = tr_is_modifier(d.v[i]) ? -1 : tr_index(d.v[i]);
                    if (b >= 0 && !seen[b]) {
                        seen[b] = 1;
                        sel[nsel++] = b;
                    }
                }
            } else {
                for (size_t b = 0; b < tr_n; b++) {
                    if (tr_tools[b]->builtin && tr_on_by_default(tr_tools[b])) {
                        seen[b] = 1;
                        sel[nsel++] = (int)b;
                    }
                }
            }
        }
        if (!tr_spec_no_tools) {
            for (size_t b = 0; b < tr_n; b++) {
                if (!tr_tools[b]->builtin && !seen[b] && tr_on_by_default(tr_tools[b])) {
                    seen[b] = 1;
                    sel[nsel++] = (int)b;
                }
            }
            if (!tr_spec_no_builtin && saved) {
                tr_modify(&d, sel, &nsel);
            }
        }
        if (tools) {
            tr_modify(&t, sel, &nsel);
        }
    }
    tr_nactive = 0;
    for (size_t i = 0; i < nsel; i++) {
        int drop = 0;
        for (size_t k = 0; k < x.n; k++) {
            drop |= tr_matches(x.v[k], tr_tools[sel[i]]->name);
        }
        if (!drop) {
            tr_active[tr_nactive++] = tr_tools[sel[i]];
        }
    }
    /* A deferred tool is reachable through tool_search whatever the tool list names (Pi), unless
     * it is excluded, or the list has an mcp__ entry and so filters MCP tools too. */
    if (!tr_spec_no_tools) {
        int filtered = 0;
        for (size_t i = 0; i < t.n; i++) {
            filtered |= strncmp(t.v[i] + (tr_is_modifier(t.v[i]) ? 1 : 0), "mcp__", 5) == 0;
        }
        for (size_t b = 0; b < tr_n && !filtered; b++) {
            int in = 0, drop = 0;
            for (size_t i = 0; i < tr_nactive; i++) {
                in |= tr_active[i] == tr_tools[b];
            }
            for (size_t k = 0; k < x.n; k++) {
                drop |= tr_matches(x.v[k], tr_tools[b]->name);
            }
            if (tr_is_deferred(tr_tools[b]) && !in && !drop && tr_nactive < TR_MAX) {
                tr_active[tr_nactive++] = tr_tools[b];
            }
        }
    }
    tr_active_gen = tr_gen;
}

static int tr_keep(char **slot, const char *v) {
    size_t n = v ? strlen(v) + 1 : 0;
    free(*slot);
    *slot = NULL;
    if (v && (*slot = malloc(n))) {
        memcpy(*slot, v, n);
    }
    return v && !*slot ? -1 : 0;
}

int pic_toolset_configure(const char *tools, const char *exclude, int no_tools, int no_builtin, const char *saved,
                          char *err, size_t errcap) {
    tr_names t;
    const char *why;
    char detail[256];
    if (strlen(tools ? tools : "") >= sizeof t.buf || strlen(exclude ? exclude : "") >= sizeof t.buf ||
        strlen(saved ? saved : "") >= sizeof t.buf) {
        (void)snprintf(err, errcap, "tool list is too long");
        return -1;
    }
    if (tools && tr_split(tools, &t) == 0 && (why = tr_list_error(&t, detail, sizeof detail))) {
        (void)snprintf(err, errcap, "--tools: %s", why);
        return -1;
    }
    if (tr_keep(&tr_spec_tools, tools) != 0 || tr_keep(&tr_spec_exclude, exclude) != 0 ||
        tr_keep(&tr_spec_saved, saved) != 0) {
        (void)snprintf(err, errcap, "out of memory");
        return -1;
    }
    tr_spec_no_tools = no_tools;
    tr_spec_no_builtin = no_builtin;
    tr_gen++;
    tr_select(); /* now, in pic itself: a tool's default may read a setting */
    return 0;
}

int pic_toolset_on(const char *name) {
    tr_select();
    for (size_t i = 0; i < tr_nactive; i++) {
        if (strcmp(tr_active[i]->name, name) == 0) {
            return 1;
        }
    }
    return 0;
}

size_t pic_toolset_deferred(const pic_tool_def **out, size_t cap) {
    size_t n = 0;
    tr_select();
    for (size_t i = 0; i < tr_nactive && n < cap; i++) {
        if (tr_is_deferred(tr_active[i])) {
            out[n++] = tr_active[i];
        }
    }
    return n;
}

int pic_toolset_sequential(const char *name) {
    const pic_tool_def *d = pic_tool_named(name);
    return d && d->sequential;
}

size_t pic_toolset_names(const char **out, size_t cap) {
    size_t n;
    tr_select();
    for (n = 0; n < tr_nactive && n < cap; n++) {
        out[n] = tr_active[n]->name;
    }
    return n;
}

char *pic_toolset_schemas(void) {
    size_t len = 3;
    char *out, *p;
    tr_select();
    for (size_t i = 0; i < tr_nactive; i++) {
        len += strlen(tr_active[i]->schema) + 1;
    }
    if (!(out = malloc(len))) {
        return NULL;
    }
    p = out;
    *p++ = '[';
    for (size_t i = 0, first = 1; i < tr_nactive; i++) {
        size_t n = strlen(tr_active[i]->schema);
        if (tr_is_deferred(tr_active[i])) {
            continue;
        }
        if (!first) {
            *p++ = ',';
        }
        first = 0;
        memcpy(p, tr_active[i]->schema, n);
        p += n;
    }
    *p++ = ']';
    *p = '\0';
    return out;
}

char *pic_toolset_run(const char *workspace, const char *tool, const pic_tool_args *args, const pic_tool_hooks *hooks,
                      int *is_error) {
    const pic_tool_def *d;
    *is_error = 0;
    if (!pic_toolset_on(tool) || !(d = pic_tool_named(tool))) {
        const char *fmt = "Tool %s not found";
        int n;
        char *out;
        if (hooks->started == NULL || hooks->started(hooks->ctx, NULL, 0) != 0) {
            return NULL;
        }
        n = snprintf(NULL, 0, fmt, tool);
        if (n < 0 || !(out = malloc((size_t)n + 1))) {
            return NULL;
        }
        (void)snprintf(out, (size_t)n + 1, fmt, tool);
        *is_error = 1;
        return out;
    }
    return d->run(d->state, workspace, tool, args, hooks, is_error);
}