Skip to content
pi-c Documentation
Login

Documentation

/* Skills (see skills.h), matching Pi's skills.ts. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

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

#define SKILL_MAX (256u * 1024u)
#define NAME_MAX_LEN 64
#define DESCRIPTION_MAX 1024
#define DEPTH_MAX 8
#define DESC_CAP 1536       /* one description in a listing over its budget */
#define DEFAULT_WINDOW 200000 /* tokens, when the model's window is not known */
#define USE_BUSY_MS 250    /* how long recording a use waits for the database */
#define WARN_NAMES 12      /* skills a budget warning names */

static int sk_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 sk_blank(const char *s) {
    for (; *s; s++) {
        if (!sk_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 || sk_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 || sk_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 || sk_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 sk_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 sk_by_name(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }

/* 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 sk_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, sk_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 < PIC_IGNORE_NAMES + (root ? PIC_IGNORE_SETTINGS : 0) && rc == 0; f++) {
        size_t len = 0;
        char *txt;
        char pre[PATH_MAX];
        int settings = f >= PIC_IGNORE_NAMES;
        const char *name = settings ? pic_ignore_settings[f - PIC_IGNORE_NAMES] : pic_ignore_names[f];
        if (snprintf(path, sizeof path, "%s/%s", dir, name) >= (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 = settings ? pic_ignore_add_glob(ig, txt, len, "") : pic_ignore_add_named(ig, name, txt, len, pre);
            free(txt);
        }
    }
    qsort(l.names, l.n, sizeof *l.names, sk_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 = sk_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 = sk_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)

/* ---- use, kept in picu_skill_use ------------------------------------------- */

/* The clock for use and decay, in ms: PIC_SKILLS_NOW_MS (a test seam) or the wall clock. */
static long long sk_now_ms(void) {
    const char *e = getenv("PIC_SKILLS_NOW_MS");
    char *end;
    long long v;
    if (e && *e) {
        v = strtoll(e, &end, 10);
        if (!*end && v >= 0) {
            return v;
        }
    }
    return (long long)(pic_platform_get()->wall_ns() / 1000000);
}

/* Counts one load of the skill NAME at PATH. Best effort: a failure (no home,
 * a locked database) is ignored, and the wait is short. */
static void sk_record_use(const char *name, const char *path) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (!db) {
        return;
    }
    (void)pic_busy_wait(db, USE_BUSY_MS);
    if (sqlite3_prepare_v2(db,
                           "INSERT INTO picu_skill_use(name, path, uses, last_ms) VALUES(?1, ?2, 1, ?3)"
                           " ON CONFLICT(name, path) DO UPDATE SET uses = uses + 1, last_ms = excluded.last_ms",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 3, sk_now_ms());
        (void)sqlite3_step(q);
    }
    sqlite3_finalize(q);
    (void)pic_userdb_settings(db);
}

void pic_skills_note_read(const char *path) {
    size_t len = strlen(path), n;
    const char *slash = strrchr(path, '/');
    char *raw, *yaml, *body, *desc, *name;
    int declared;
    if (!slash || len < 4 || strcmp(path + len - 3, ".md") != 0 || !strstr(path, "/.pic/skills/")) {
        return;
    }
    declared = strcmp(slash + 1, "SKILL.md") == 0;
    if (!declared && !(slash - path >= 12 && strncmp(slash - 12, "/.pic/skills", 12) == 0)) {
        return; /* a root .md file of a skills folder is a skill; nothing else is */
    }
    if (!(raw = pic_input_read(path, SKILL_MAX, 0, &n, NULL))) {
        return;
    }
    pic_front_split(raw, &yaml, &body);
    desc = yaml ? pic_front_value(yaml, "description") : NULL;
    if (declared || (desc && !sk_blank(desc))) {
        name = yaml ? pic_front_value(yaml, "name") : NULL;
        if (!name || !*name) {
            free(name);
            name = parent_name(path);
        }
        if (name && *name) {
            sk_record_use(name, path);
        }
        free(name);
    }
    free(desc);
    free(raw);
}

/* uses x max(0.5^(days since last use / 7), 0.1), as Claude Code ranks skills. */
static double sk_use_score(sqlite3 *db, const pic_skill *k, long long now_ms) {
    sqlite3_stmt *q = NULL;
    double score = 0;
    if (!db || sqlite3_prepare_v2(db, "SELECT uses, last_ms FROM picu_skill_use WHERE name = ?1 AND path = ?2", -1, &q,
                                  NULL) != SQLITE_OK) {
        return 0;
    }
    sqlite3_bind_text(q, 1, k->name, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, k->path, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        double days = (double)(now_ms - sqlite3_column_int64(q, 1)) / 86400000.0, decay;
        if (days < 0) {
            days = 0;
        }
        decay = pow(0.5, days / 7.0);
        score = (double)sqlite3_column_int64(q, 0) * (decay > 0.1 ? decay : 0.1);
    }
    sqlite3_finalize(q);
    return score;
}

/* ---- the listing and its budget -------------------------------------------- */

/* The characters the listing may take: the skillBudget setting (0: no limit),
 * else 1% of the model's context window (WINDOW tokens; 0: not known, taken as
 * 200000) at 4 characters a token. */
static size_t sk_listing_budget(long window) {
    char *v = pic_userdb(NULL, 0) ? pic_setting("skillBudget") : NULL;
    char *end;
    long long n = -1;
    if (v) {
        n = strtoll(v, &end, 10);
        if (!*v || *end || n < 0) {
            n = -1;
        }
        free(v);
    }
    if (n >= 0) {
        return n == 0 ? (size_t)-1 : (size_t)n;
    }
    return (size_t)(window > 0 ? window : DEFAULT_WINDOW) / 100 * 4;
}

/* The description cut to the per-entry cap at a word, with an ellipsis, or
 * NULL when it is short enough. */
static char *sk_trim_description(const char *d) {
    size_t len = strlen(d), cut = DESC_CAP;
    pic_sbuf b = {0};
    if (len <= DESC_CAP) {
        return NULL;
    }
    while (cut > 0 && ((unsigned char)d[cut] & 0xC0) == 0x80) { /* not inside a UTF-8 character */
        cut--;
    }
    for (size_t i = cut; i > DESC_CAP / 2; i--) {
        if (sk_is_space(d[i])) {
            cut = i;
            break;
        }
    }
    while (cut > 0 && sk_is_space(d[cut - 1])) {
        cut--;
    }
    pic_sb_add(&b, d, cut);
    pic_sb_add(&b, "\xe2\x80\xa6", 3);
    return pic_sb_take(&b);
}

/* One <skill> entry; D NULL: by name and location only. */
static char *sk_entry_text(const pic_skill *k, const char *d) {
    pic_sbuf b = {0};
    ADDS(&b, "\n  <skill>\n    <name>");
    add_xml(&b, k->name);
    if (d) {
        ADDS(&b, "</name>\n    <description>");
        add_xml(&b, d);
        ADDS(&b, "</description>\n    <location>");
    } else {
        ADDS(&b, "</name>\n    <location>");
    }
    add_xml(&b, k->path);
    ADDS(&b, "</location>\n  </skill>");
    return pic_sb_take(&b);
}

typedef struct {
    size_t skill;  /* index into pic_skills.v */
    double score;
} sk_ranked;

static int sk_by_rank(const void *a, const void *b) {
    const sk_ranked *x = a, *y = b;
    if (x->score != y->score) {
        return x->score > y->score ? -1 : 1;
    }
    return x->skill < y->skill ? -1 : x->skill > y->skill;
}

#define SK_LIST_HEAD "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"
#define SK_LIST_NOTE "Some skills are shown by name only to save context: read the SKILL.md at its location, or run /skill:NAME, to load one.\n"
#define SK_LIST_OPEN "\n<available_skills>"
#define SK_LIST_CLOSE "\n</available_skills>"

static void sk_name_list(pic_sbuf *b, const pic_skills *s, const size_t *idx, size_t n, size_t max) {
    for (size_t i = 0; i < n && i < max; i++) {
        pic_sb_add(b, i ? ", " : "", i ? 2 : 0);
        pic_sb_add(b, s->v[idx[i]].name, strlen(s->v[idx[i]].name));
    }
    if (n > max) {
        char more[48];
        int k = snprintf(more, sizeof more, " and %zu more", n - max);
        pic_sb_add(b, more, (size_t)k);
    }
}

char *pic_skills_prompt(const pic_skills *s, long window, char **warning) {
    size_t shown = 0, budget, total, nr = 0, nbare = 0, ntrim = 0;
    sk_ranked *order = NULL;
    char **full = NULL, **trim = NULL, **bare = NULL;
    int *mode = NULL; /* 0: whole, 1: description cut, 2: name only */
    pic_sbuf b = {0};
    char *out = NULL;
    if (warning) {
        *warning = NULL;
    }
    for (size_t i = 0; i < s->n; i++) {
        shown += !s->v[i].hidden;
    }
    if (!shown) {
        return pic_dup_n("", 0);
    }
    order = calloc(shown, sizeof *order);
    full = calloc(s->n, sizeof *full);
    trim = calloc(s->n, sizeof *trim);
    bare = calloc(s->n, sizeof *bare);
    mode = calloc(s->n, sizeof *mode);
    if (!order || !full || !trim || !bare || !mode) {
        goto done;
    }
    total = sizeof SK_LIST_HEAD - 1 + sizeof SK_LIST_OPEN - 1 + sizeof SK_LIST_CLOSE - 1;
    for (size_t i = 0; i < s->n; i++) {
        if (s->v[i].hidden) {
            continue;
        }
        order[nr].skill = i;
        nr++;
        if (!(full[i] = sk_entry_text(&s->v[i], s->v[i].description))) {
            goto done;
        }
        total += strlen(full[i]);
    }
    budget = sk_listing_budget(window);
    if (total > budget) { /* first the long descriptions, then the least used skills by name only */
        sqlite3 *db = pic_userdb(NULL, 0);
        long long now = sk_now_ms();
        for (size_t r = 0; r < nr; r++) {
            size_t i = order[r].skill;
            char *d = sk_trim_description(s->v[i].description);
            if (d) {
                trim[i] = sk_entry_text(&s->v[i], d);
                free(d);
                if (!trim[i]) {
                    goto done;
                }
                total = total - strlen(full[i]) + strlen(trim[i]);
                mode[i] = 1;
                ntrim++;
            }
        }
        if (total > budget) {
            for (size_t r = 0; r < nr; r++) {
                order[r].score = sk_use_score(db, &s->v[order[r].skill], now);
            }
            qsort(order, nr, sizeof *order, sk_by_rank);
            total += sizeof SK_LIST_NOTE - 1;
            for (size_t r = nr; r > 0 && total > budget; r--) {
                size_t i = order[r - 1].skill;
                const char *cur = mode[i] == 1 ? trim[i] : full[i];
                if (!(bare[i] = sk_entry_text(&s->v[i], NULL))) {
                    goto done;
                }
                total = total - strlen(cur) + strlen(bare[i]);
                ntrim -= mode[i] == 1;
                mode[i] = 2;
                nbare++;
            }
        }
    }
    pic_sb_add(&b, SK_LIST_HEAD, sizeof SK_LIST_HEAD - 1);
    if (nbare) {
        pic_sb_add(&b, SK_LIST_NOTE, sizeof SK_LIST_NOTE - 1);
    }
    pic_sb_add(&b, SK_LIST_OPEN, sizeof SK_LIST_OPEN - 1);
    for (size_t i = 0; i < s->n; i++) {
        const char *e = mode[i] == 2 ? bare[i] : mode[i] == 1 ? trim[i] : full[i];
        if (!s->v[i].hidden) {
            pic_sb_add(&b, e, strlen(e));
        }
    }
    pic_sb_add(&b, SK_LIST_CLOSE, sizeof SK_LIST_CLOSE - 1);
    out = pic_sb_take(&b);
    if (out && warning && (nbare || ntrim)) {
        pic_sbuf w = {0};
        size_t *names = malloc(shown * sizeof *names), n;
        char num[96];
        int k = snprintf(num, sizeof num, "the skill listing is over its budget of %zu characters (skillBudget):", budget);
        pic_sb_add(&w, num, (size_t)k);
        if (names && nbare) {
            n = 0;
            for (size_t i = 0; i < s->n; i++) {
                if (mode[i] == 2) {
                    names[n++] = i;
                }
            }
            k = snprintf(num, sizeof num, " %zu shown by name only (", nbare);
            pic_sb_add(&w, num, (size_t)k);
            sk_name_list(&w, s, names, n, WARN_NAMES);
            pic_sb_add(&w, ")", 1);
        }
        if (names && ntrim) {
            n = 0;
            for (size_t i = 0; i < s->n; i++) {
                if (mode[i] == 1) {
                    names[n++] = i;
                }
            }
            k = snprintf(num, sizeof num, "%s %zu with a shortened description (", nbare ? ";" : "", ntrim);
            pic_sb_add(&w, num, (size_t)k);
            sk_name_list(&w, s, names, n, WARN_NAMES);
            pic_sb_add(&w, ")", 1);
        }
        ADDS(&w, ". Every skill still loads with /skill:NAME.");
        free(names);
        *warning = pic_sb_take(&w);
    }
done:
    for (size_t i = 0; s->n && i < s->n; i++) {
        if (full) {
            free(full[i]);
        }
        if (trim) {
            free(trim[i]);
        }
        if (bare) {
            free(bare[i]);
        }
    }
    free(full);
    free(trim);
    free(bare);
    free(mode);
    free(order);
    return out;
}

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] && !sk_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 (sk_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 && sk_is_space(text[n - 1])) {
            n--;
        }
        ADDS(&b, "\n\n");
        pic_sb_add(&b, text, n);
    }
    free(raw);
    sk_record_use(k->name, k->path);
    *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);
    }
}