import { cachedOverlaps, checkSkillOverlaps, type OverlapCheck, type SkillOverlap } from "./skill-overlaps.js"; import { currentSkillSet } from "./skill-set.js"; import { describeSkill, loadSkill, skillFolders, type FoundSkill, type SkillEntry, type SkillSet } from "./skills-manifest.js"; import type { Orchestrator } from "./orchestrator.js"; type Scope = "global" | "project"; type Option = { title: string; description: string }; /** What the skills screens borrow from /pp: its dialogs and its config writes. */ export interface SkillsMenuKit { select(ctx: any, question: string, options: Option[]): Promise; askText(ctx: any, question: string): Promise; pickScope(ctx: any): Promise; readLayer(scope: Scope): Record; write(scope: Scope, keyPath: string[], value: unknown): void; clear(scope: Scope, keyPath: string[]): void; report(ctx: any, title: string, text: string): Promise; layerSetting(ctx: any, title: string, keyPath: string[], description: string): Promise; notify(ctx: any, message: string, level: "info" | "warning"): void; } const BACK = "Back"; const ATTENTION = "⚠ "; const entryPath = (name: string) => ["skills", "entries", name]; function layerEntry(kit: SkillsMenuKit, scope: Scope, name: string): SkillEntry | null | undefined { const entries = kit.readLayer(scope)?.skills?.entries; if (!entries || typeof entries !== "object" || !(name in entries)) return undefined; return entries[name]; } /** * Saves a skill's whole entry where the user picks. An entry left empty is * removed; in the project, where a global entry would show through, it is * cancelled with null instead. */ async function saveEntry(kit: SkillsMenuKit, orchestrator: Orchestrator, ctx: any, name: string, next: SkillEntry): Promise { const scope = await kit.pickScope(ctx); if (!scope) return; const empty = Object.keys(next).length === 0; if (!empty) kit.write(scope, entryPath(name), next); else if (scope === "project" && layerEntry(kit, "global", name)) kit.write(scope, entryPath(name), null); else kit.clear(scope, entryPath(name)); if (scope === "project" && !(orchestrator.lastCtx?.isProjectTrusted?.() ?? true)) { kit.notify(ctx, `Saved in this project, but pi does not trust it, so its skill settings do not apply until it does.`, "warning"); } if (scope === "global" && layerEntry(kit, "project", name) !== undefined) { kit.notify(ctx, `Saved globally, but this project has its own setting for ${name}, which still applies here.`, "warning"); } const target = next.replaces; if (target) { const conflict = currentSkillSet(orchestrator).issues.find((issue) => issue.kind === "replacement-conflict" && issue.skill === target); if (conflict) kit.notify(ctx, conflict.message, "warning"); } } function currentEntry(set: SkillSet, name: string): SkillEntry { return { ...(set.entries.get(name)?.entry ?? {}) }; } function without(entry: SkillEntry, ...keys: Array): SkillEntry { const next = { ...entry }; for (const key of keys) delete next[key]; return next; } /** One row per skill: what it is, and what has been done to it. */ function skillTags(set: SkillSet, skill: FoundSkill): string[] { const entry = set.entries.get(skill.name)?.entry; const tags: string[] = []; if (entry?.enabled === false) tags.push("OFF"); const resolved = set.byName.get(skill.name); if (skill.layer === "bundled") { if (resolved?.replaces === skill.name) tags.push(`replaced by ${resolved.base.name}`); const extensions = resolved?.extensions.length ?? 0; if (extensions > 0) tags.push(`+${extensions} extension${extensions === 1 ? "" : "s"}`); } else if (entry?.extends || entry?.replaces) { // As set, even where it does not apply now: the skill is off, or lost to another replacement. const applies = entry.extends ? resolved?.extensions.includes(skill) === true : resolved?.base === skill && resolved.replaces === entry.replaces; tags.push(`${entry.extends ? `extends ${entry.extends}` : `replaces ${entry.replaces}`}${applies || entry.enabled === false ? "" : " (not applied)"}`); } if (entry?.standalone) tags.push("keep both"); if (skill.hidden) tags.push("by name only"); return tags; } function attentionFor(set: SkillSet, overlaps: SkillOverlap[]): Map { const attention = new Map(); for (const issue of set.issues) { if (issue.skill && issue.kind !== "shadowed" && issue.kind !== "reserved-name") attention.set(issue.skill, issue.message); if (issue.kind === "replacement-conflict") { for (const [name, { entry }] of set.entries) if (entry.replaces === issue.skill) attention.set(name, issue.message); } } for (const overlap of overlaps) attention.set(overlap.user, `Overlaps ${overlap.bundled}: ${overlap.reason || "both apply to the same step"}. Extend, replace or keep both.`); return attention; } /** /pp → Skills: every skill found, what the agent gets, and the settings that link them. */ export async function showSkillsMenu(kit: SkillsMenuKit, orchestrator: Orchestrator, ctx: any): Promise { let filter = ""; for (;;) { const set = currentSkillSet(orchestrator); const check = cachedOverlaps(ctx, set); const overlaps = check?.status === "checked" ? check.overlaps : []; const attention = attentionFor(set, overlaps); const skills = [...set.found.values()] .filter((skill) => !filter || `${skill.name} ${skill.description}`.toLowerCase().includes(filter.toLowerCase())) .sort((left, right) => Number(attention.has(right.name)) - Number(attention.has(left.name)) || left.name.localeCompare(right.name)); const rows = new Map(); const options: Option[] = []; for (const skill of skills) { const title = `${attention.has(skill.name) ? ATTENTION : ""}${[`${skill.name} [${skill.layer}]`, ...skillTags(set, skill)].join(" · ")}`; rows.set(title, skill); options.push({ title, description: attention.get(skill.name) ?? skill.description }); } // Problems with no skill to hang on: files that could not be read, folders cut short, trust. const general = set.issues.filter((issue) => !issue.skill && issue.kind !== "shadowed"); const header = `Skills — ${set.found.size} found · ${set.catalog.length} in the agent's catalog${attention.size ? ` · ${attention.size} need attention` : ""}`; const choice = await kit.select(ctx, header, [ ...(general.length ? [{ title: `${ATTENTION}${general.length} problem${general.length === 1 ? "" : "s"} reading skills`, description: general[0]!.message }] : []), ...options, { title: filter ? `Search: "${filter}"` : "Search…", description: filter ? "Change or clear the filter" : "Show only skills whose name or description matches" }, { title: "Check overlaps…", description: overlapSummary(check) }, { title: "Sources…", description: "Turn whole sources on or off, and see the folders searched" }, { title: BACK, description: "Return to the previous menu" }, ]); if (!choice || choice === BACK) return; if (choice.startsWith(ATTENTION) && choice.endsWith("reading skills")) { await kit.report(ctx, "pi-pi · skill problems", general.map((issue) => `- ${issue.message}`).join("\n")); continue; } if (choice.startsWith("Search")) { const typed = await kit.askText(ctx, "Filter skills by name or description (empty to clear):"); if (typed !== undefined) filter = typed.trim(); continue; } if (choice === "Check overlaps…") { await showOverlaps(kit, orchestrator, ctx); continue; } if (choice === "Sources…") { await showSources(kit, orchestrator, ctx); continue; } const skill = rows.get(choice); if (skill) await showSkill(kit, orchestrator, ctx, skill.name); } } function overlapSummary(check: OverlapCheck | undefined): string { if (!check) return "Ask the session's model which of your skills compete with pi-pi's"; if (check.status === "skipped") return `Last check skipped: ${check.reason}`; return check.overlaps.length === 0 ? "None unsettled from the last check; run again after adding skills" : `${check.overlaps.length} unsettled from the last check; run again to refresh`; } async function showSkill(kit: SkillsMenuKit, orchestrator: Orchestrator, ctx: any, name: string): Promise { for (;;) { const set = currentSkillSet(orchestrator); const skill = set.found.get(name); if (!skill) return; const entry = currentEntry(set, name); const resolved = set.byName.get(name); const check = cachedOverlaps(ctx, set); const overlaps = check?.status === "checked" ? check.overlaps.filter((overlap) => overlap.user === name || overlap.bundled === name) : []; const trusted = orchestrator.lastCtx?.isProjectTrusted?.() ?? true; const options: Option[] = [ ...overlaps.map((overlap) => ({ title: `${ATTENTION}Overlaps: ${overlap.user} ↔ ${overlap.bundled}`, description: `${overlap.reason || "Both apply to the same step"} Extend, replace or keep both.` })), { title: `Enabled: ${entry.enabled === false ? "OFF" : "ON"}`, description: entry.enabled === false ? "Turn it back on" : "Turn it off: the agent no longer sees or loads it" }, ]; const bundled = skill.layer === "bundled"; const users = [...set.found.values()].filter((candidate) => candidate.layer !== "bundled"); if (bundled) { options.push({ title: "Extend with…", description: "Add one of your skills to the end of this one's text" }); options.push({ title: "Replace with…", description: "Have the agent use one of your skills in its place" }); for (const linked of users) { const link = set.entries.get(linked.name)?.entry; if (link?.extends === name) options.push({ title: `Remove extension: ${linked.name}`, description: `${linked.name} becomes a skill of its own again` }); if (link?.replaces === name) options.push({ title: `Remove replacement: ${linked.name}`, description: `pi-pi's ${name} comes back` }); } } else { if (entry.extends || entry.replaces) { options.push({ title: "Stand alone", description: `Stop ${entry.extends ? `extending ${entry.extends}` : `replacing ${entry.replaces}`}` }); } options.push({ title: "Extend a pi-pi skill…", description: "Add this skill's text to the end of one of pi-pi's" }); options.push({ title: "Replace a pi-pi skill…", description: "Have the agent use this skill in place of one of pi-pi's" }); options.push({ title: `Keep both: ${entry.standalone ? "ON" : "OFF"}`, description: "Overlaps with pi-pi's skills are not reported for it" }); if (!entry.extends && !entry.replaces) { options.push({ title: `Subagents: ${(entry.audience ?? skill.audience) === "any" ? "yes" : "no"}`, description: "Whether it can be handed to a subagent" }); } } options.push({ title: "View what the agent gets", description: resolved ? describeSkill(resolved) : "Not loadable while it is turned off" }); for (const scope of ["global", "project"] as const) { const own = layerEntry(kit, scope, name); if (own === undefined) continue; const shown = own === null ? "cancels the global setting here" : JSON.stringify(own); options.push({ title: `Reset ${scope} setting`, description: scope === "project" && !trusted ? `${shown} (not applied: pi does not trust this project)` : shown }); } options.push({ title: BACK, description: "Return to the skills list" }); const choice = await kit.select(ctx, `${name} [${skill.layer}] · ${skill.filePath}`, options); if (!choice || choice === BACK) return; const overlap = overlaps.find((candidate) => choice === `${ATTENTION}Overlaps: ${candidate.user} ↔ ${candidate.bundled}`); if (overlap) await showOverlap(kit, orchestrator, ctx, overlap); else if (choice.startsWith("Enabled:")) await saveEntry(kit, orchestrator, ctx, name, entry.enabled === false ? without(entry, "enabled") : { ...entry, enabled: false }); else if (choice === "Extend with…" || choice === "Replace with…") { const picked = await pickSkill(kit, ctx, set, `${choice.replace("…", "")} ${name}:`, users); if (picked) await saveEntry(kit, orchestrator, ctx, picked, { ...without(currentEntry(set, picked), "extends", "replaces", "audience"), [choice === "Extend with…" ? "extends" : "replaces"]: name }); } else if (choice.startsWith("Remove extension: ") || choice.startsWith("Remove replacement: ")) { const linked = choice.slice(choice.indexOf(": ") + 2); await saveEntry(kit, orchestrator, ctx, linked, without(currentEntry(set, linked), "extends", "replaces")); } else if (choice === "Stand alone") await saveEntry(kit, orchestrator, ctx, name, without(entry, "extends", "replaces")); else if (choice === "Extend a pi-pi skill…" || choice === "Replace a pi-pi skill…") { const targets = [...set.found.values()].filter((candidate) => candidate.layer === "bundled"); const picked = await pickSkill(kit, ctx, set, `${choice.startsWith("Extend") ? "Extend" : "Replace"} which of pi-pi's skills with ${name}?`, targets); if (picked) await saveEntry(kit, orchestrator, ctx, name, { ...without(entry, "extends", "replaces", "audience"), [choice.startsWith("Extend") ? "extends" : "replaces"]: picked }); } else if (choice.startsWith("Keep both:")) await saveEntry(kit, orchestrator, ctx, name, entry.standalone ? without(entry, "standalone") : { ...entry, standalone: true }); else if (choice.startsWith("Subagents:")) { const shared = (entry.audience ?? skill.audience) === "any"; const next: SkillEntry = shared ? { ...entry, audience: "main" } : { ...entry, audience: "any" }; if (next.audience === skill.audience) delete next.audience; await saveEntry(kit, orchestrator, ctx, name, next); } else if (choice === "View what the agent gets") { if (resolved) await kit.report(ctx, `pi-pi · skill ${resolved.name}`, loadSkill(set, resolved.name).document); } else if (choice.startsWith("Reset ")) { const scope = choice.includes("global") ? "global" : "project"; const sure = await kit.select(ctx, "Confirm reset?", [ { title: "Yes, reset", description: `Remove ${name}'s ${scope} setting` }, { title: BACK, description: "Cancel" }, ]); if (sure === "Yes, reset") kit.clear(scope, entryPath(name)); } } } async function pickSkill(kit: SkillsMenuKit, ctx: any, set: SkillSet, question: string, skills: FoundSkill[]): Promise { if (skills.length === 0) { await kit.report(ctx, "pi-pi · skills", "There is no skill to pick: install one under a skill folder (see Sources…)."); return undefined; } const effect = (skill: FoundSkill) => { const tags = skillTags(set, skill); if (skill.layer === "bundled") tags.push(skill.audience === "any" ? "goes to subagents" : "main agent only"); return tags.length ? `${tags.join(" · ")} — ` : ""; }; const choice = await kit.select(ctx, question, [ ...skills.map((skill) => ({ title: `${skill.name} [${skill.layer}]`, description: `${effect(skill)}${skill.description}` })), { title: BACK, description: "Pick nothing" }, ]); if (!choice || choice === BACK) return undefined; return choice.slice(0, choice.lastIndexOf(" [")); } async function showOverlaps(kit: SkillsMenuKit, orchestrator: Orchestrator, ctx: any): Promise { const check = await checkSkillOverlaps(ctx, currentSkillSet(orchestrator), { fresh: true }); if (check.status === "skipped") { await kit.report(ctx, "pi-pi · skill overlaps", `Skill overlap check skipped: ${check.reason}.`); return; } const unchecked = check.unchecked.length ? ` Not checked, past the limit: ${check.unchecked.join(", ")}.` : ""; if (check.overlaps.length === 0) { await kit.report(ctx, "pi-pi · skill overlaps", `None of your skills competes with pi-pi's.${unchecked}`); return; } for (;;) { // Only the pairs still unsettled: one linked or kept just now drops out. const current = cachedOverlaps(ctx, currentSkillSet(orchestrator)); const overlaps = current?.status === "checked" ? current.overlaps : []; if (overlaps.length === 0) return; const choice = await kit.select(ctx, `Skills that compete with pi-pi's.${unchecked}`, [ ...overlaps.map((overlap) => ({ title: `${overlap.user} ↔ ${overlap.bundled}`, description: overlap.reason || "Both apply to the same step" })), { title: BACK, description: "Return to the skills list" }, ]); if (!choice || choice === BACK) return; const overlap = overlaps.find((candidate) => choice === `${candidate.user} ↔ ${candidate.bundled}`); if (overlap) await showOverlap(kit, orchestrator, ctx, overlap); } } async function showOverlap(kit: SkillsMenuKit, orchestrator: Orchestrator, ctx: any, overlap: SkillOverlap): Promise { const { user, bundled } = overlap; const choice = await kit.select(ctx, `${user} overlaps pi-pi's ${bundled}${overlap.reason ? `: ${overlap.reason}` : ""}`, [ { title: `Extend ${bundled} with ${user}`, description: `The agent gets pi-pi's ${bundled}, then ${user}, which wins where they disagree` }, { title: `Replace ${bundled} with ${user}`, description: `The agent uses ${user} wherever pi-pi's skills call for ${bundled}` }, { title: "Keep both", description: `Leave them separate; this overlap is no longer reported` }, { title: "View both", description: "Read the two skills' texts" }, { title: BACK, description: "Decide later" }, ]); if (!choice || choice === BACK) return; const set = currentSkillSet(orchestrator); const entry = without(currentEntry(set, user), "extends", "replaces", "audience"); if (choice.startsWith("Extend ")) await saveEntry(kit, orchestrator, ctx, user, { ...entry, extends: bundled }); else if (choice.startsWith("Replace ")) await saveEntry(kit, orchestrator, ctx, user, { ...entry, replaces: bundled }); else if (choice === "Keep both") await saveEntry(kit, orchestrator, ctx, user, { ...currentEntry(set, user), standalone: true }); else if (choice === "View both") { const text = (name: string) => { try { return loadSkill(set, name).document; } catch (error: any) { return error?.message ?? String(error); } }; await kit.report(ctx, `pi-pi · ${user} and ${bundled}`, `${text(bundled)}\n\n${text(user)}`); } } async function showSources(kit: SkillsMenuKit, orchestrator: Orchestrator, ctx: any): Promise { const layers = [ { key: "loadBundled", layer: "bundled", label: "pi-pi's skills" }, { key: "loadGlobal", layer: "global", label: "Your global skills" }, { key: "loadProject", layer: "project", label: "This project's skills" }, ] as const; for (;;) { const toggles = orchestrator.config.skills; const trusted = orchestrator.lastCtx?.isProjectTrusted?.() ?? true; const choice = await kit.select(ctx, "Skill sources", [ ...layers.map(({ key, layer, label }) => ({ title: `${label}: ${toggles[key] ? "ON" : "OFF"}`, description: `${skillFolders(layer, orchestrator.cwd).join(", ")}${layer === "project" && !trusted ? " (ignored: pi does not trust this project)" : ""}`, })), { title: "List folders", description: "Every folder searched, and whether it exists" }, { title: BACK, description: "Return to the skills list" }, ]); if (!choice || choice === BACK) return; const picked = layers.find(({ label }) => choice.startsWith(`${label}:`)); if (picked) { await kit.layerSetting(ctx, picked.label, ["skills", picked.key], `Load ${picked.label.toLowerCase()}`); continue; } const { existsSync } = await import("node:fs"); const lines = layers.flatMap(({ layer, label }) => [`${label}:`, ...skillFolders(layer, orchestrator.cwd).map((folder) => ` ${existsSync(folder) ? "✓" : "·"} ${folder}`)]); await kit.report(ctx, "pi-pi · skill folders", [...lines, "", "Precedence: project, then global, then pi-pi's; within one, the folder listed first.", process.env.PI_SKILLS_DIR ? `PI_SKILLS_DIR is set, so it is the only global folder.` : ""].join("\n").trim()); } }