/** * Skill registry: derives the skill list from what pi already resolved. * * pi advertises skills in the system prompt (``) and exposes the resolved * objects on the `before_agent_start` event (`systemPromptOptions.skills`). This module reads * either source and never scans skill directories on its own, so the tool cannot disagree * with pi's discovery rules (settings, packages, project trust, extension-discovered paths). */ import { dirname } from "node:path"; export interface Skill { name: string; description: string; filePath: string; baseDir: string; disableModelInvocation: boolean; } export interface SkillRegistry { skills: Skill[]; source: "options" | "prompt"; } const MAX_LISTED_NAMES = 40; function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null; } function asString(value: unknown): string | undefined { return typeof value === "string" && value.trim() !== "" ? value : undefined; } /** * Builds a registry from a `before_agent_start` event. Returns `undefined` when the event * carries no usable skill information, so callers keep their previous registry instead of * wiping it on an unexpected shape. */ export function registryFromEvent(event: unknown): SkillRegistry | undefined { if (!isRecord(event)) { return undefined; } const options = isRecord(event.systemPromptOptions) ? event.systemPromptOptions : undefined; if (options && Array.isArray(options.skills)) { return { skills: normalizeSkills(options.skills), source: "options" }; } const prompt = typeof event.systemPrompt === "string" ? event.systemPrompt : undefined; if (prompt !== undefined) { const skills = parseAvailableSkills(prompt); if (skills !== undefined) { return { skills, source: "prompt" }; } } return undefined; } /** Normalizes raw skill objects, dropping invalid entries and keeping the first name collision. */ export function normalizeSkills(rawSkills: readonly unknown[]): Skill[] { const skills: Skill[] = []; const seen = new Set(); for (const raw of rawSkills) { if (!isRecord(raw)) continue; const name = asString(raw.name); const filePath = asString(raw.filePath); if (!name || !filePath) continue; const key = name.toLowerCase(); if (seen.has(key)) continue; seen.add(key); skills.push({ name, description: typeof raw.description === "string" ? raw.description : "", filePath, baseDir: asString(raw.baseDir) ?? dirname(filePath), disableModelInvocation: raw.disableModelInvocation === true, }); } return skills; } /** * Parses pi's `` prompt section. Returns `undefined` when the section is * absent, which callers treat as "no information" rather than "zero skills". */ export function parseAvailableSkills(systemPrompt: string): Skill[] | undefined { const start = systemPrompt.indexOf(""); if (start === -1) return undefined; const end = systemPrompt.indexOf("", start); if (end === -1) return undefined; const section = systemPrompt.slice(start, end); const rawSkills: unknown[] = []; const blockPattern = /([\s\S]*?)<\/skill>/g; for (const block of section.matchAll(blockPattern)) { const body = block[1] ?? ""; rawSkills.push({ name: readTag(body, "name"), description: readTag(body, "description") ?? "", filePath: readTag(body, "location"), disableModelInvocation: false, }); } return normalizeSkills(rawSkills); } function readTag(block: string, tag: string): string | undefined { const match = new RegExp(`<${tag}>([\\s\\S]*?)`).exec(block); if (!match) return undefined; const value = unescapeXml(match[1] ?? "").trim(); return value === "" ? undefined : value; } const XML_UNESCAPES: Record = { "&": "&", "<": "<", ">": ">", """: '"', "'": "'", }; export function unescapeXml(value: string): string { return value.replace(/&(amp|lt|gt|quot|apos);/g, (match) => XML_UNESCAPES[match] ?? match); } /** * Normalizes a skill name as models pass it: `grilling`, ` Grilling `, `/skill:grilling`, * or `skill:grilling`. Arguments after the name are not stripped, so they fail to resolve. */ export function normalizeSkillName(query: string): string { return query .trim() .replace(/^\/?skill:/i, "") .trim() .toLowerCase(); } export function findSkill(registry: readonly Skill[], query: string): Skill | undefined { const normalized = normalizeSkillName(query); if (!normalized) return undefined; return registry.find((skill) => skill.name.toLowerCase() === normalized); } /** Builds the failure message for an unknown skill, including available names and a suggestion. */ export function unknownSkillError(registry: readonly Skill[], query: string): Error { const requested = query.trim(); const label = requested === "" ? "(empty)" : requested; const names = registry.slice(0, MAX_LISTED_NAMES).map((skill) => skill.name); const listed = names.length > 0 ? names.join(", ") : "(none)"; const more = registry.length > MAX_LISTED_NAMES ? ", …" : ""; const suggestion = suggestSkillName(registry, query); const hint = suggestion ? ` Did you mean "${suggestion}"?` : ""; return new Error( `Unknown skill "${label}". Available skills: ${listed}${more} (${registry.length} total).${hint} Call skill with an exact name from .`, ); } export function noSkillsError(): Error { return new Error( "No skills are available in this session. pi lists skills under ; load one only when its description matches the task.", ); } export function notIndexedError(): Error { return new Error("Skills are not indexed yet; retry the skill tool on the next turn."); } /** Closest name by edit distance, if it is close enough to be a useful hint. */ export function suggestSkillName(registry: readonly Skill[], query: string): string | undefined { const normalized = normalizeSkillName(query); if (!normalized) return undefined; let best: { name: string; distance: number } | undefined; for (const skill of registry) { const distance = editDistance(normalized, skill.name.toLowerCase()); if (best === undefined || distance < best.distance) { best = { name: skill.name, distance }; } } const threshold = Math.max(2, Math.floor(normalized.length / 3)); if (!best || best.distance === 0 || best.distance > threshold) return undefined; return best.name; } function editDistance(a: string, b: string): number { const previous: number[] = Array.from({ length: b.length + 1 }, (_, index) => index); const current: number[] = new Array(b.length + 1).fill(0); for (let i = 1; i <= a.length; i++) { current[0] = i; for (let j = 1; j <= b.length; j++) { const substitution = (previous[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1); const insertion = (current[j - 1] ?? 0) + 1; const deletion = (previous[j] ?? 0) + 1; current[j] = Math.min(substitution, insertion, deletion); } for (let j = 0; j <= b.length; j++) { previous[j] = current[j] ?? 0; } } return previous[b.length] ?? 0; }