/** * Skill content: reads a SKILL.md file and formats it the way pi's own `/skill:name` * expansion does, so the tool result is indistinguishable from the built-in command. */ import { readFile, readdir } from "node:fs/promises"; import { join, relative, sep } from "node:path"; import type { Skill } from "./registry.ts"; export const MAX_BODY_CHARS = 256 * 1024; export const MAX_BUNDLED_FILES = 60; export const MAX_LISTING_DEPTH = 2; const MAX_SCANNED_FILES = 1000; const IGNORED_DIRECTORIES = new Set(["node_modules", ".git"]); const FRONTMATTER_PATTERN = /^---[ \t]*\r?\n(?:[\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)/; /** Removes a leading YAML frontmatter block. Unterminated frontmatter is left untouched. */ export function stripFrontmatter(raw: string): string { const match = FRONTMATTER_PATTERN.exec(raw); const body = match ? raw.slice(match[0].length) : raw; return body.trim(); } export interface SkillFileContent { body: string; truncated: boolean; } export async function readSkillFile(skill: Skill): Promise { let raw: string; try { raw = await readFile(skill.filePath, "utf8"); } catch (error) { const reason = error instanceof Error ? error.message : String(error); throw new Error(`Failed to read skill "${skill.name}" at ${skill.filePath}: ${reason}`); } let body = stripFrontmatter(raw); let truncated = false; if (body.length > MAX_BODY_CHARS) { body = body.slice(0, MAX_BODY_CHARS); truncated = true; } return { body, truncated }; } export interface BundledFileListing { files: string[]; more: number; } /** Lists files next to SKILL.md (two levels deep), skipping hidden entries and dependency dirs. */ export async function listBundledFiles(baseDir: string): Promise { const state: { files: string[]; count: number } = { files: [], count: 0 }; await collectFiles(baseDir, baseDir, 0, state); return { files: state.files, more: Math.max(0, state.count - state.files.length), }; } async function collectFiles( dir: string, baseDir: string, depth: number, state: { files: string[]; count: number }, ): Promise { if (state.count >= MAX_SCANNED_FILES) return; let entries; try { entries = await readdir(dir, { withFileTypes: true }); } catch { return; } entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); for (const entry of entries) { if (state.count >= MAX_SCANNED_FILES) return; if (entry.name.startsWith(".")) continue; const fullPath = join(dir, entry.name); const relativePath = toPosixPath(relative(baseDir, fullPath)); if (relativePath === "SKILL.md") continue; if (entry.isDirectory()) { if (IGNORED_DIRECTORIES.has(entry.name)) continue; if (depth < MAX_LISTING_DEPTH) { await collectFiles(fullPath, baseDir, depth + 1, state); } continue; } state.count++; if (state.files.length < MAX_BUNDLED_FILES) { state.files.push(relativePath); } } } function toPosixPath(value: string): string { return sep === "/" ? value : value.split(sep).join("/"); } export interface FormatSkillResultInput { skill: Skill; body: string; args?: string | undefined; bundledFiles?: BundledFileListing | undefined; truncated?: boolean | undefined; } /** Formats the model-facing result, mirroring pi's `/skill:name` expansion. */ export function formatSkillResult(input: FormatSkillResultInput): string { const { skill, body, args, bundledFiles, truncated } = input; const parts: string[] = [ ``, `References are relative to ${skill.baseDir}.`, "", body, "", ]; const trimmedArgs = args?.trim(); if (trimmedArgs) { parts.push("", trimmedArgs); } if (truncated) { parts.push( "", `Note: this skill file exceeds ${MAX_BODY_CHARS} characters; the instructions above are truncated. Read the remainder at ${skill.filePath}.`, ); } if (bundledFiles && bundledFiles.files.length > 0) { parts.push("", `Bundled files (relative to ${skill.baseDir}):`); for (const file of bundledFiles.files) { parts.push(`- ${file}`); } if (bundledFiles.more > 0) { parts.push(`- … (${bundledFiles.more} more)`); } } return parts.join("\n"); } const XML_ESCAPES: Record = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", }; export function escapeXmlAttribute(value: string): string { return value.replace(/[&<>"']/g, (character) => XML_ESCAPES[character] ?? character); }