Skip to content
pi-c Documentation
Login

Documentation

/* Skills (see skills.h), matching Pi's skills.ts. */
#include <limits.h>
#include <stdlib.h>
#include <string.h>

#include "ignore.h"
#include "input.h"
#include "platform.h"
#include "prompts.h"
#include "skills.h"

#define SKILL_MAX (256u * 1024u)
#define NAME_MAX_LEN 64
#define DESCRIPTION_MAX 1024
#define DEPTH_MAX 8

static int is_space(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f'; }

static void warn_at(FILE *warn, const char *path, const char *msg) {
    if (warn) {
        fprintf(warn, "pic: skill %s: %s\n", path, msg);
    }
}

/* Pi's validateName: the problems with NAME, as warnings. */
static void check_name(FILE *warn, const char *path, const char *name) {
    size_t len = strlen(name);
    int bad = 0;
    char msg[128];
    if (len > NAME_MAX_LEN) {
        (void)snprintf(msg, sizeof msg, "name exceeds 64 characters (%zu)", len);
        warn_at(warn, path, msg);
    }
    for (size_t i = 0; i < len; i++) {
        unsigned char c = (unsigned char)name[i];
        if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-')) {
            bad = 1;
        }
    }
    if (bad) {
        warn_at(warn, path, "name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)");
    }
    if (len && (name[0] == '-' || name[len - 1] == '-')) {
        warn_at(warn, path, "name must not start or end with a hyphen");
    }
    if (strstr(name, "--")) {
        warn_at(warn, path, "name must not contain consecutive hyphens");
    }
}

static void free_skill(pic_skill *k) {
    free(k->name);
    free(k->description);
    free(k->path);
    free(k->real);
    free(k->dir);
}

static int blank(const char *s) {
    for (; *s; s++) {
        if (!is_space(*s)) {
            return 0;
        }
    }
    return 1;
}

/* The folder's base name in the path PATH of its SKILL.md. */
static char *parent_name(const char *path) {
    const char *end = strrchr(path, '/'), *start = end;
    if (!end) {
        return pic_dup_n("", 0);
    }
    while (start > path && start[-1] != '/') {
        start--;
    }
    return pic_dup_n(start, (size_t)(end - start));
}

/* Pi's loadSkillFromFile. DECLARED: the file is a SKILL.md, whose problems are
 * warnings; any other .md file is a skill only with a description. Returns 0
 * (also when the file is not a skill or vanished), -1 out of memory. */
static int load_file(pic_skills *s, const char *path, int declared, int project, FILE *warn) {
    char *raw, *yaml, *body, *desc, *name, *real, *flag, rp[PATH_MAX];
    size_t len, i;
    pic_skill k;
    pic_skill *grown;
    if (!(raw = pic_input_read(path, SKILL_MAX, 0, &len, NULL))) {
        return 0;
    }
    pic_front_split(raw, &yaml, &body);
    desc = yaml ? pic_front_value(yaml, "description") : NULL;
    if (!declared && (!desc || blank(desc))) {
        free(desc);
        free(raw);
        return 0;
    }
    name = yaml ? pic_front_value(yaml, "name") : NULL;
    if (!name || !*name) {
        free(name);
        name = parent_name(path);
    }
    if (!desc || blank(desc)) {
        warn_at(warn, path, "description is required");
    } else if (strlen(desc) > DESCRIPTION_MAX) {
        char msg[80];
        (void)snprintf(msg, sizeof msg, "description exceeds 1024 characters (%zu)", strlen(desc));
        warn_at(warn, path, msg);
    }
    if (name) {
        check_name(warn, path, name);
    }
    if (!desc || !name || blank(desc)) {
        free(desc);
        free(name);
        free(raw);
        return name ? 0 : -1; /* no name is out of memory; a blank description is just no skill */
    }
    memset(&k, 0, sizeof k);
    flag = yaml ? pic_front_value(yaml, "disable-model-invocation") : NULL;
    k.hidden = flag && strcmp(flag, "true") == 0;
    free(flag);
    free(raw);
    real = realpath(path, rp) ? pic_dup_n(rp, strlen(rp)) : pic_dup_n(path, strlen(path));
    k.name = name;
    k.description = desc;
    k.path = pic_dup_n(path, strlen(path));
    k.real = real;
    k.dir = k.path ? pic_dup_n(k.path, (size_t)(strrchr(k.path, '/') - k.path)) : NULL;
    k.project = project;
    if (!k.path || !k.real || !k.dir) {
        free_skill(&k);
        return -1;
    }
    for (i = 0; i < s->n; i++) {
        if (strcmp(s->v[i].real, k.real) == 0) { /* the same file through another symlink */
            free_skill(&k);
            return 0;
        }
        if (strcmp(s->v[i].name, k.name) == 0) {
            if (warn) {
                fprintf(warn, "pic: skill %s: name \"%s\" collision, kept %s\n", path, k.name, s->v[i].path);
            }
            free_skill(&k);
            return 0;
        }
    }
    if (!(grown = realloc(s->v, (s->n + 1) * sizeof *s->v))) {
        free_skill(&k);
        return -1;
    }
    s->v = grown;
    s->v[s->n++] = k;
    return 0;
}

typedef struct {
    char **names;
    size_t n, cap;
    int oom;
} names_list;

static int collect(void *ctx, const char *name) {
    names_list *l = ctx;
    if (l->n == l->cap) {
        char **grown = realloc(l->names, (l->cap ? l->cap * 2 : 16) * sizeof *l->names);
        if (!grown) {
            l->oom = 1;
            return 1;
        }
        l->names = grown;
        l->cap = l->cap ? l->cap * 2 : 16;
    }
    if (!(l->names[l->n] = pic_dup_n(name, strlen(name)))) {
        l->oom = 1;
        return 1;
    }
    l->n++;
    return 0;
}

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

static const char *const ignore_files[] = {".gitignore", ".ignore", ".fdignore"};

/* Pi's loadSkillsFromDirInternal: SKILL.md here makes this folder a skill and
 * ends the search; otherwise root .md files (ROOT only) and subfolders. A
 * name that is not a folder (or a broken symlink) fails to list and is skipped. */
static int load_dir(pic_skills *s, const char *dir, const char *rel, pic_ignore *ig, int project, int root, int depth,
                    FILE *warn) {
    names_list l = {0};
    char path[PATH_MAX], relp[PATH_MAX];
    int rc = 0, skill_md = 0;
    size_t mark = ig->n;
    if (depth > DEPTH_MAX) {
        return 0;
    }
    if (pic_platform_get()->input_list(dir, collect, &l) != 0 && !l.n) {
        free(l.names);
        return 0;
    }
    if (l.oom) {
        rc = -1;
    }
    /* Pi: the folder's own ignore files join the rules, prefixed by its path. */
    for (size_t f = 0; f < sizeof ignore_files / sizeof *ignore_files && rc == 0; f++) {
        size_t len = 0;
        char *txt;
        char pre[PATH_MAX];
        if (snprintf(path, sizeof path, "%s/%s", dir, ignore_files[f]) >= (int)sizeof path ||
            snprintf(pre, sizeof pre, "%s%s", rel, *rel ? "/" : "") >= (int)sizeof pre) {
            continue;
        }
        if ((txt = pic_input_read(path, SKILL_MAX, 0, &len, NULL))) {
            rc = pic_ignore_add(ig, txt, len, pre);
            free(txt);
        }
    }
    qsort(l.names, l.n, sizeof *l.names, by_name);
    for (size_t i = 0; i < l.n && rc == 0; i++) {
        if (strcmp(l.names[i], "SKILL.md") == 0 && snprintf(path, sizeof path, "%s/SKILL.md", dir) < (int)sizeof path &&
            snprintf(relp, sizeof relp, "%s%sSKILL.md", rel, *rel ? "/" : "") < (int)sizeof relp &&
            !pic_ignore_ignored(ig, relp, 0)) {
            char *probe = pic_input_read(path, SKILL_MAX, 0, &(size_t){0}, NULL);
            if (probe) {
                free(probe);
                skill_md = 1;
                rc = load_file(s, path, 1, project, warn);
            }
        }
    }
    for (size_t i = 0; i < l.n && rc == 0 && !skill_md; i++) {
        const char *nm = l.names[i];
        size_t len = strlen(nm);
        if (nm[0] == '.' || strcmp(nm, "node_modules") == 0 || snprintf(path, sizeof path, "%s/%s", dir, nm) >= (int)sizeof path) {
            continue;
        }
        if (snprintf(relp, sizeof relp, "%s%s%s", rel, *rel ? "/" : "", nm) >= (int)sizeof relp) {
            continue;
        }
        if (root && len > 3 && strcmp(nm + len - 3, ".md") == 0) {
            char *probe = pic_input_read(path, SKILL_MAX, 0, &(size_t){0}, NULL);
            if (probe) {
                free(probe);
                if (!pic_ignore_ignored(ig, relp, 0)) {
                    rc = load_file(s, path, 0, project, warn);
                }
                continue;
            }
        }
        if (!pic_ignore_ignored(ig, relp, 1)) {
            rc = load_dir(s, path, relp, ig, project, 0, depth + 1, warn);
        }
    }
    for (size_t i = 0; i < l.n; i++) {
        free(l.names[i]);
    }
    free(l.names);
    pic_ignore_truncate(ig, mark);
    return rc;
}

/* A walk's root: a fresh rule set, paths relative to DIR. */
static int load_root(pic_skills *s, const char *dir, int project, FILE *warn) {
    pic_ignore ig = {0};
    int rc = load_dir(s, dir, "", &ig, project, 1, 0, warn);
    pic_ignore_free(&ig);
    return rc;
}

int pic_skills_load(pic_skills *s, const char *workspace, int project, FILE *warn) {
    const char *home = getenv("HOME");
    char dir[PATH_MAX];
    s->v = NULL;
    s->n = 0;
    if (home && *home && snprintf(dir, sizeof dir, "%s/.pic/skills", home) < (int)sizeof dir &&
        load_root(s, dir, 0, warn) != 0) {
        goto fail;
    }
    if (project && snprintf(dir, sizeof dir, "%s/.pic/skills", workspace) < (int)sizeof dir &&
        load_root(s, dir, 1, warn) != 0) {
        goto fail;
    }
    return 0;
fail:
    pic_skills_free(s);
    return -1;
}

void pic_skills_free(pic_skills *s) {
    for (size_t i = 0; i < s->n; i++) {
        free_skill(&s->v[i]);
    }
    free(s->v);
    s->v = NULL;
    s->n = 0;
}

const pic_skill *pic_skills_find(const pic_skills *s, const char *name) {
    for (size_t i = 0; i < s->n; i++) {
        if (strcmp(s->v[i].name, name) == 0) {
            return &s->v[i];
        }
    }
    return NULL;
}

static void add_xml(pic_sbuf *b, const char *s) {
    for (; *s; s++) {
        switch (*s) {
        case '&': pic_sb_add(b, "&amp;", 5); break;
        case '<': pic_sb_add(b, "&lt;", 4); break;
        case '>': pic_sb_add(b, "&gt;", 4); break;
        case '"': pic_sb_add(b, "&quot;", 6); break;
        case '\'': pic_sb_add(b, "&apos;", 6); break;
        default: pic_sb_add(b, s, 1);
        }
    }
}

#define ADDS(b, lit) pic_sb_add((b), (lit), sizeof(lit) - 1)

char *pic_skills_prompt(const pic_skills *s) {
    pic_sbuf b = {0};
    size_t shown = 0;
    for (size_t i = 0; i < s->n; i++) {
        shown += !s->v[i].hidden;
    }
    if (!shown) {
        return pic_dup_n("", 0);
    }
    ADDS(&b, "The following skills provide specialized instructions for specific tasks.\n"
             "Use the read tool to load a skill's file when the task matches its description.\n"
             "Resolve relative paths against the skill's directory (parent of SKILL.md). Use absolute paths in tool calls.\n"
             "\n<available_skills>");
    for (size_t i = 0; i < s->n; i++) {
        if (s->v[i].hidden) {
            continue;
        }
        ADDS(&b, "\n  <skill>\n    <name>");
        add_xml(&b, s->v[i].name);
        ADDS(&b, "</name>\n    <description>");
        add_xml(&b, s->v[i].description);
        ADDS(&b, "</description>\n    <location>");
        add_xml(&b, s->v[i].path);
        ADDS(&b, "</location>\n  </skill>");
    }
    ADDS(&b, "\n</available_skills>");
    return pic_sb_take(&b);
}

int pic_skills_expand(const pic_skills *s, const char *text, char **out, char *err, size_t errcap) {
    size_t nlen, len;
    char *name, *raw, *yaml, *body;
    const pic_skill *k;
    pic_sbuf b = {0};
    *out = NULL;
    if (strncmp(text, "/skill:", 7) != 0) {
        return 0;
    }
    for (nlen = 0; text[7 + nlen] && !is_space(text[7 + nlen]); nlen++) {
    }
    if (!(name = pic_dup_n(text + 7, nlen))) {
        return -1;
    }
    k = pic_skills_find(s, name);
    free(name);
    if (!k) {
        return 0; /* unknown: passes through */
    }
    text += 7 + nlen;
    while (is_space(*text)) {
        text++;
    }
    if (!(raw = pic_input_read(k->path, SKILL_MAX, 0, &len, NULL))) {
        (void)snprintf(err, errcap, "skill %s is gone or unreadable: %s", k->name, k->path);
        return -1;
    }
    pic_front_split(raw, &yaml, &body);
    ADDS(&b, "<skill name=\"");
    pic_sb_add(&b, k->name, strlen(k->name));
    ADDS(&b, "\" location=\"");
    pic_sb_add(&b, k->path, strlen(k->path));
    ADDS(&b, "\">\nReferences are relative to ");
    pic_sb_add(&b, k->dir, strlen(k->dir));
    ADDS(&b, ".\n\n");
    pic_sb_add(&b, body, strlen(body));
    ADDS(&b, "\n</skill>");
    if (*text) {
        size_t n = strlen(text);
        while (n && is_space(text[n - 1])) {
            n--;
        }
        ADDS(&b, "\n\n");
        pic_sb_add(&b, text, n);
    }
    free(raw);
    *out = pic_sb_take(&b);
    return *out ? 1 : -1;
}

void pic_skills_print(const pic_skills *s, FILE *out, int json) {
    if (json) {
        fputc('[', out);
    }
    for (size_t i = 0; i < s->n; i++) {
        const pic_skill *k = &s->v[i];
        const char *scope = k->project ? "project" : "user";
        if (json) {
            fputs(i ? ",\n{\"name\":" : "\n{\"name\":", out);
            pic_json_str(out, k->name);
            fprintf(out, ",\"scope\":\"%s\",\"description\":", scope);
            pic_json_str(out, k->description);
            fputs(",\"path\":", out);
            pic_json_str(out, k->path);
            fprintf(out, ",\"disableModelInvocation\":%s}", k->hidden ? "true" : "false");
        } else {
            fprintf(out, "%s\t%s\t", k->name, scope);
            pic_flat(out, k->description);
            fprintf(out, "\t%s\n", k->path);
        }
    }
    if (json) {
        fputs(s->n ? "\n]\n" : "]\n", out);
    }
}