import { readFile } from "node:fs/promises"; import { dirname } from "node:path"; import type { ExtensionAPI, SlashCommandInfo } from "@earendil-works/pi-coding-agent"; import { parseSkillBlock, SkillInvocationMessageComponent, stripFrontmatter, } from "@earendil-works/pi-coding-agent"; import type { AutocompleteItem, AutocompleteProvider, AutocompleteSuggestions, } from "@earendil-works/pi-tui"; import { fuzzyFilter } from "@earendil-works/pi-tui"; export interface SkillRef { name: string; filePath: string; baseDir: string; description?: string; } export interface ResolvedSkillBlock { name: string; text: string; } export const SKILL_MESSAGE_TYPE = "skill"; /** * Candidates like `$code-review`: a `$` followed by a valid skill name * (lowercase letters, digits, single hyphens). `(?` slash commands; their sourceInfo points at SKILL.md. */ export function skillsFromCommands(commands: readonly SlashCommandInfo[]): Map { const skills = new Map(); for (const command of commands) { if (command.source !== "skill") continue; const name = command.name.startsWith("skill:") ? command.name.slice(6) : command.name; const filePath = command.sourceInfo.path; if (!filePath) continue; skills.set(name, { name, filePath, baseDir: dirname(filePath), description: command.description, }); } return skills; } /** * Resolve `$skill-name` tokens into the same `` block pi emits for * `/skill:name`, once per skill in first-reference order. Tokens without a * matching loaded skill are ignored. */ export async function expandSkillTokens( text: string, skills: ReadonlyMap, ): Promise<{ expanded: string[]; failed: string[]; blocks: ResolvedSkillBlock[]; }> { const expanded: string[] = []; const failed: string[] = []; const blocks: ResolvedSkillBlock[] = []; const seen = new Set(); for (const match of text.matchAll(SKILL_TOKEN_PATTERN)) { const name = match[1]; const skill = skills.get(name); if (!skill || seen.has(name)) continue; seen.add(name); try { const content = await readFile(skill.filePath, "utf-8"); const body = stripFrontmatter(content).trim(); blocks.push({ name, text: `\nReferences are relative to ${skill.baseDir}.\n\n${body}\n`, }); expanded.push(name); } catch { failed.push(name); } } return { expanded, failed, blocks }; } const MAX_SUGGESTIONS = 20; /** Token before the cursor that opens a `$skill` completion: `$` at line start or after whitespace, never `$$`. */ const SKILL_COMPLETION_PATTERN = /(?:^|[\s])\$([a-z0-9-]*)$/; export function createSkillAutocompleteProvider( current: AutocompleteProvider, getSkills: () => ReadonlyMap, ): AutocompleteProvider { return { triggerCharacters: ["$"], async getSuggestions( lines, cursorLine, cursorCol, options, ): Promise { const beforeCursor = (lines[cursorLine] ?? "").slice(0, cursorCol); const match = beforeCursor.match(SKILL_COMPLETION_PATTERN); // A second `$` just before the token means the user typed `$$name` (literal escape). if (!match || beforeCursor.endsWith("$$" + match[1])) { return current.getSuggestions(lines, cursorLine, cursorCol, options); } const skills = getSkills(); if (options.signal.aborted || skills.size === 0) { return current.getSuggestions(lines, cursorLine, cursorCol, options); } const query = match[1]; const refs = [...skills.values()]; const candidates = query ? fuzzyFilter(refs, query, (skill) => skill.name) : refs; const items: AutocompleteItem[] = candidates.slice(0, MAX_SUGGESTIONS).map((skill) => ({ value: `$${skill.name}`, label: `$${skill.name}`, description: skill.description, })); if (items.length === 0) { return current.getSuggestions(lines, cursorLine, cursorCol, options); } return { prefix: `$${query}`, items }; }, applyCompletion(lines, cursorLine, cursorCol, item, prefix) { if (!prefix.startsWith("$")) { return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix); } const line = lines[cursorLine] ?? ""; const beforePrefix = line.slice(0, cursorCol - prefix.length); const afterCursor = line.slice(cursorCol); // Add a separating space only when one isn't already after the cursor. const separator = /^\s/.test(afterCursor) ? "" : " "; const newLine = `${beforePrefix + item.value + separator}${afterCursor}`; const newLines = [...lines]; newLines[cursorLine] = newLine; return { lines: newLines, cursorLine, cursorCol: beforePrefix.length + item.value.length + separator.length, }; }, shouldTriggerFileCompletion(lines, cursorLine, cursorCol) { return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true; }, }; } export default function piSkill(pi: ExtensionAPI) { pi.registerMessageRenderer(SKILL_MESSAGE_TYPE, (message, { expanded }) => { const text = typeof message.content === "string" ? message.content : message.content .filter((part) => part.type === "text") .map((part) => part.text) .join(""); const skillBlock = parseSkillBlock(text); if (!skillBlock) return undefined; const component = new SkillInvocationMessageComponent(skillBlock); component.setExpanded(expanded); return component; }); pi.on("session_start", (_event, ctx) => { ctx.ui.addAutocompleteProvider((current) => createSkillAutocompleteProvider(current, () => skillsFromCommands(pi.getCommands())), ); }); pi.on("input", async (event, ctx) => { if (!event.text.includes("$")) return; const skills = skillsFromCommands(pi.getCommands()); if (skills.size === 0) return; const { blocks, failed } = await expandSkillTokens(event.text, skills); for (const name of failed) { ctx.ui.notify(`Failed to read skill "${name}"`, "warning"); } if (blocks.length === 0) return; // Queued items are delivered one at a time, so a separate message would give // the block a model turn of its own. This is the shape Pi uses for /skill:. if (event.streamingBehavior) { const text = [...blocks.map((block) => block.text), event.text].join("\n\n"); return { action: "transform", text }; } for (const block of blocks) { const message = { customType: SKILL_MESSAGE_TYPE, content: block.text, display: true, details: { name: block.name }, }; pi.sendMessage(message); } // Keep the user's original `$skill` references visible while each skill's // full instructions travel in their own context-bearing, collapsible block. return { action: "continue" }; }); }