/** * skill-manager - Interactively manage which skills Pi loads: per-skill toggles * at both global and per-project scope. * * Config model (each scope persisted independently): * Global: /skill-manage.json -> { disabled: string[] } * Project: /.pi/skill-manage.json -> { modes: { [skill]: "disabled"|"enabled"|"inherit" } } * (No master switch; each project entry defaults to "inherit", following global.) * * Resolution rules: * - Per skill: project modes override (disabled forces off, enabled forces on, * inherit/missing follows global.disabled). * - Project-level skills (source=project*) have no global counterpart, so in * project scope they only offer disabled/enabled. * - Skills visible to the model = discovered skills where isEnabled is true. * * Disable effects: * - before_agent_start clears/filters systemPromptOptions.skills so the * section no longer appears. * - input blocks disabled /skill: commands. * * Usage: * /skill-manager open the interactive panel: up/down navigate, Tab switch * global/project, Space/Enter toggle, S/Esc close and save. * pi --skills-off disable all skills for this session (no file written). */ import type { ExtensionAPI, ExtensionContext, ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent"; import { matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component, type TUI, } from "@earendil-works/pi-tui"; import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; type Scope = "global" | "project"; type ProjectMode = "disabled" | "enabled" | "inherit"; // Global skills (source = user* family) offer three states in project scope; // project-level skills (source = project* family) offer only two. const PROJECT_MODES: ProjectMode[] = ["disabled", "enabled", "inherit"]; const PROJECT_SOURCE_PREFIXES = ["project", "project-settings", "project-package"]; const SKILL_MODES_FOR_ALL = ["disabled", "enabled"]; interface GlobalConfig { disabled: string[]; } interface ProjectConfig { // Per-skill three-state; missing/unspecified = inherit global. modes: Record; } interface SkillItem { name: string; description: string; source?: string; } const DEFAULT_GLOBAL: GlobalConfig = { disabled: [] }; const DEFAULT_PROJECT: ProjectConfig = { modes: {} }; function normalizeDisabled(v: unknown): string[] { return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []; } function globalStateFile(): string { const agentDir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"); return join(agentDir, "skill-manage.json"); } function projectStateFile(cwd: string): string { return join(cwd, ".pi", "skill-manage.json"); } function scopeFile(cwd: string, scope: Scope): string { return scope === "global" ? globalStateFile() : projectStateFile(cwd); } function readGlobal(cwd: string): GlobalConfig { try { const raw = JSON.parse(readFileSync(globalStateFile(cwd), "utf8")) as Record; return { disabled: normalizeDisabled(raw.disabled), }; } catch { return { ...DEFAULT_GLOBAL, disabled: [] }; } } function readProject(cwd: string): ProjectConfig { try { const raw = JSON.parse(readFileSync(projectStateFile(cwd), "utf8")) as Record; const modes: Record = {}; if (raw.modes && typeof raw.modes === "object") { for (const [name, v] of Object.entries(raw.modes as Record)) { if (v === "disabled" || v === "enabled" || v === "inherit") modes[name] = v; } } return { modes }; } catch { return { ...DEFAULT_PROJECT, modes: {} }; } } function writeScope(cwd: string, scope: Scope, payload: object): void { try { const file = scopeFile(cwd, scope); mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, JSON.stringify({ ...payload, updatedAt: new Date().toISOString() }, null, 2) + "\n"); } catch (err) { console.warn(`[skill-manager] Failed to write ${scope} config (effective this session only): ${String(err)}`); } } function removeScopeFile(cwd: string, scope: Scope): void { try { unlinkSync(scopeFile(cwd, scope)); } catch { /* file does not exist; ignore */ } } /** Persist: delete the file when returning to defaults, otherwise write it. */ function persistGlobal(cwd: string, cfg: GlobalConfig): void { const isDefault = cfg.disabled.length === 0; if (isDefault) removeScopeFile(cwd, "global"); else writeScope(cwd, "global", { disabled: cfg.disabled }); } function persistProject(cwd: string, cfg: ProjectConfig): void { const isDefault = Object.values(cfg.modes).every((m) => m === "inherit"); if (isDefault) removeScopeFile(cwd, "project"); else writeScope(cwd, "project", { modes: cfg.modes }); } interface Effective { // Session-level switch (--skills-off); the global master switch was removed. flagOff: boolean; isEnabled: (name: string) => boolean; global: GlobalConfig; project: ProjectConfig; } /** Project-level skill (source = project*) offers only two states in project scope. */ function isProjectLevelSkill(source: string | undefined): boolean { return !!source && PROJECT_SOURCE_PREFIXES.includes(source); } function effective(cwd: string, flagOff: boolean | undefined): Effective { const global = readGlobal(cwd); const project = readProject(cwd); return { flagOff: !!flagOff, global, project, isEnabled(name: string): boolean { // Session-level --skills-off disables everything. const mode = project.modes[name] ?? "inherit"; if (!flagOff) { if (mode === "disabled") return false; if (mode === "enabled") return true; } // inherit / (missing) -> follow global.disabled return !global.disabled.includes(name) && !flagOff; }, }; } export default function (pi: ExtensionAPI) { let flagOff: boolean | undefined; // --skills-off, session only function statusText(ctx: ExtensionContext): void { if (!ctx.hasUI) return; const eff = effective(ctx.cwd, flagOff); const label = eff.flagOff ? "skills: OFF (--skills-off)" : "skills: on"; ctx.ui.setStatus("skill-manage", label); } pi.registerFlag("skills-off", { description: "Disable all skill loading for this session (does not write config)", type: "boolean", }); pi.on("session_start", (_event, ctx) => { flagOff = pi.getFlag("skills-off") === true ? true : undefined; statusText(ctx); }); // Core: filter the skills list for this run. pi.on("before_agent_start", (event, ctx) => { const eff = effective(ctx.cwd, flagOff); event.systemPromptOptions.skills = (event.systemPromptOptions.skills ?? []).filter( (s) => eff.isEnabled(s.name), ); }); // Block disabled /skill: commands. pi.on("input", (event, ctx) => { const m = event.text.trimStart().match(/^\/skill:([\w.-]+)/i); if (!m) return; const name = m[1]; const eff = effective(ctx.cwd, flagOff); if (!eff.isEnabled(name)) { let where: string; if (eff.flagOff) where = "--skills-off is active"; else { const mode = eff.project.modes[name] ?? "inherit"; if (mode === "disabled") where = `skill "${name}" is disabled in project`; else where = `skill "${name}" is disabled in global`; } if (ctx.hasUI) { ctx.ui.notify(`skill not enabled: ${where}. Restore it via /skill-manager.`, "warning"); } return { action: "handled" }; } }); pi.registerCommand("skill-manager", { description: "Interactively manage skill loading: toggle individual skills, Tab to switch global/project scope", async handler(_args, ctx) { if (ctx.mode !== "tui" || !ctx.hasUI) { const eff = effective(ctx.cwd, flagOff); const total = ctx.getSystemPromptOptions().skills?.length ?? 0; ctx.ui.notify( `/skill-manager requires an interactive terminal. Current config: project per-skill=${ Object.entries(eff.project.modes) .filter(([, m]) => m !== "inherit") .map(([n, m]) => `${n}:${m}`) .join(", ") || "(all inherit)" }, ${total} skill(s) discovered.`, "warning", ); return; } await openManager(ctx, flagOff); }, }); } async function openManager(ctx: ExtensionCommandContext, flagOff: boolean | undefined): Promise { const cwd = ctx.cwd; const skills = (ctx.getSystemPromptOptions().skills ?? []) .map((s) => ({ name: s.name, description: s.description, source: (s as { source?: string }).source })) .sort((a, b) => a.name.localeCompare(b.name)); const initial = { global: readGlobal(cwd), project: readProject(cwd), }; await ctx.ui.custom((tui, theme, _kb, done) => { return new SkillManagerComponent(tui, theme, skills, initial, cwd, done); }, { overlay: true, overlayOptions: { anchor: "center", width: "80%", minWidth: 60, maxHeight: 26 }, }); ctx.ui.setStatus("skill-manage", undefined); const eff = effective(cwd, flagOff); const visible = (ctx.getSystemPromptOptions().skills ?? []).filter((s) => eff.isEnabled(s.name)).length; ctx.ui.notify( `skill config saved. ${visible}/${ctx.getSystemPromptOptions().skills?.length ?? 0} skill(s) visible to the model.`, "info", ); } class SkillManagerComponent implements Component { private readonly tui: TUI; private readonly theme: Theme; private readonly skills: SkillItem[]; private readonly cwd: string; private readonly done: () => void; private global: GlobalConfig; private project: ProjectConfig; private activeScope: Scope = "global"; private cursor: Record = { global: 0, project: 0 }; private offset = 0; private readonly maxRows = 12; // visible rows in the list window constructor( tui: TUI, theme: Theme, skills: SkillItem[], initial: { global: GlobalConfig; project: ProjectConfig }, cwd: string, done: () => void, ) { this.tui = tui; this.theme = theme; this.skills = skills; this.global = { ...initial.global, disabled: [...initial.global.disabled] }; this.project = { modes: { ...initial.project.modes } }; this.cwd = cwd; this.done = done; } private isGlobal(): boolean { return this.activeScope === "global"; } /** Modes to cycle for a skill in project scope (project-level skills: only two). */ private projectModesFor(name: string): ProjectMode[] { const item = this.skills.find((s) => s.name === name); return isProjectLevelSkill(item?.source) ? SKILL_MODES_FOR_ALL : PROJECT_MODES; } /** Number of entries in the current scope (no master switch). */ private rowCount(): number { return this.skills.length; } /** Build the content lines for a skill (selected skill expands its description). */ private skillContentLines(index: number, innerW: number): string[] { const th = this.theme; const isGlobal = this.isGlobal(); const item = this.skills[index]; if (!item) return []; const isSel = this.cursor[this.activeScope] === index; let mark: string; let tail = ""; if (isGlobal) { const enabled = !this.global.disabled.includes(item.name); mark = enabled ? th.fg("success", "●") : th.fg("warning", "○"); } else { const m = this.project.modes[item.name] ?? "inherit"; const modes = this.projectModesFor(item.name); mark = m === "disabled" ? th.fg("warning", "◆") : m === "enabled" ? th.fg("success", "●") : th.fg("dim", "◇"); const levelTag = isProjectLevelSkill(item.source) ? th.fg("dim", "[project]") : ""; tail = ` ${levelTag}${th.fg("dim", "[")}${modes .map((o) => (o === m ? th.fg("accent", th.bold(o)) : th.fg("dim", o))) .join("/")}${th.fg("dim", "]")}`; } const sel = th.fg("accent", "→ "); const nameStyle = isSel ? th.fg("accent", item.name) : item.name; const firstLine = `${isSel ? sel : " "}${mark} ${nameStyle}${tail}`; const lines = [firstLine]; if (isSel && item.description) { // Selected: wrap description across multiple lines; otherwise inline single line. const wrapW = Math.max(1, innerW - 5); const wrapped = wrapTextWithAnsi(th.fg("dim", item.description), wrapW); for (const w of wrapped) lines.push(th.fg("dim", ` ${w}`)); } else { lines[0] = `${firstLine}${item.description ? ` ${th.fg("dim", `— ${item.description}`)}` : ""}`; } return lines; } /** Compute layout: flattened content lines plus each skill's start/length. */ private layout(innerW: number): { lines: string[]; blockStart: number[]; blockLen: number[] } { const lines: string[] = []; const blockStart: number[] = []; const blockLen: number[] = []; for (let i = 0; i < this.skills.length; i++) { blockStart.push(lines.length); const block = this.skillContentLines(i, innerW); blockLen.push(block.length); lines.push(...block); } return { lines, blockStart, blockLen }; } private toggleRow(row: number): void { const isGlobal = this.isGlobal(); const name = this.skills[row]?.name; if (!name) return; if (isGlobal) { // global per-skill: enable/disable const disabled = this.global.disabled; const idx = disabled.indexOf(name); if (idx === -1) disabled.push(name); else disabled.splice(idx, 1); } else { // project per-skill: cycle available modes (project-level: two, global: three) const modes = this.projectModesFor(name); const cur = this.project.modes[name] ?? "inherit"; const next = modes[(modes.indexOf(cur) + 1) % modes.length]!; this.project.modes[name] = next; } } private clampCursor(): void { // Only clamp the cursor to valid items; the visible window is computed in // physical lines during render. const max = this.rowCount() - 1; this.cursor[this.activeScope] = Math.max(0, Math.min(max, this.cursor[this.activeScope])); this.offset = Math.max(0, Math.min(this.offset, Math.max(0, this.rowCount() - this.maxRows))); } private close(): void { persistGlobal(this.cwd, this.global); persistProject(this.cwd, this.project); this.done(); } handleInput(data: string): void { if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { this.close(); return; } if (matchesKey(data, "s")) { this.close(); return; } if (matchesKey(data, "tab") || matchesKey(data, "shift+tab")) { this.activeScope = this.activeScope === "global" ? "project" : "global"; this.clampCursor(); this.tui.requestRender(); return; } if (matchesKey(data, "up")) { this.cursor[this.activeScope]--; this.clampCursor(); this.tui.requestRender(); return; } if (matchesKey(data, "down")) { this.cursor[this.activeScope]++; this.clampCursor(); this.tui.requestRender(); return; } if (matchesKey(data, "space") || matchesKey(data, "return")) { this.toggleRow(this.cursor[this.activeScope]); this.tui.requestRender(); return; } } invalidate(): void {} render(width: number): string[] { const th = this.theme; const innerW = Math.max(1, width - 2); const border = (c: string) => th.fg("border", c); const padLine = (s: string) => truncateToWidth(s, innerW, "...", true); const isGlobal = this.isGlobal(); // Title const title = ` Skill Manager `; const titleTrunc = truncateToWidth(title, innerW); const titleW = visibleWidth(titleTrunc); const padL = Math.floor((innerW - titleW) / 2); const padR = Math.max(0, innerW - titleW - padL); const lines: string[] = []; lines.push(border("╭" + "─".repeat(padL)) + th.fg("accent", titleTrunc) + border("─".repeat(padR) + "╮")); // Scope tabs const tab = (scope: Scope, label: string) => this.activeScope === scope ? th.fg("accent", th.bold(`[ ${label} ]`)) : th.fg("dim", ` ${label} `); lines.push( border("│") + padLine(` ${tab("global", "global")} ${tab("project", "project")} ${th.fg("dim", "Tab to switch")}`) + border("│"), ); lines.push(border("├") + border("─".repeat(innerW)) + border("┤")); // Effective-state summary const visibleCount = this.skills.filter((s) => { const m = this.project.modes[s.name] ?? "inherit"; if (m === "disabled") return false; if (m === "enabled") return true; return !this.global.disabled.includes(s.name); }).length; const projLabel = isGlobal ? "" : ` · project overrides=${th.fg("accent", String( Object.values(this.project.modes).filter((m) => m !== "inherit").length, ))}`; lines.push( border("│") + padLine( ` ${th.fg("accent", String(visibleCount))}/${this.skills.length} visible to model${projLabel}`, ) + border("│"), ); // List (physical-line window; the selected item may span multiple lines) const { lines: allContent, blockStart, blockLen } = this.layout(innerW); const totalLines = allContent.length; // The item block under the cursor const curBlock = this.cursor[this.activeScope]; const curStart = blockStart[curBlock] ?? 0; const curLen = blockLen[curBlock] ?? 1; // Keep the cursor block fully visible: adjust offset (physical lines) let off = this.offset; if (curStart < off) off = curStart; const blockEnd = curStart + curLen; if (off + this.maxRows < blockEnd) off = blockEnd - this.maxRows; off = Math.max(0, Math.min(off, Math.max(0, totalLines - this.maxRows))); this.offset = off; const start = off; const end = Math.min(totalLines, start + this.maxRows); for (let r = start; r < end; r++) { lines.push(border("│") + padLine(allContent[r]!) + border("│")); } // Pad to the window height for (let i = end; i < start + this.maxRows; i++) { lines.push(border("│") + padLine("") + border("│")); } if (totalLines > this.maxRows) { lines.push(border("│") + padLine(` ${th.fg("dim", `↑↓ scroll (${start + 1}-${end}/${totalLines})`)}`) + border("│")); } lines.push(border("├") + border("─".repeat(innerW)) + border("┤")); lines.push( border("│") + padLine( th.fg( "dim", isGlobal ? " ↑↓ navigate · Tab scope · Space/Enter toggle on/off · S/Esc close & save" : " ↑↓ navigate · Tab scope · Space/Enter cycle disable/enable/inherit · S/Esc close & save", ), ) + border("│"), ); lines.push(border("╰") + border("─".repeat(innerW)) + border("╯")); return lines; } }