import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { afterEach, expect, it } from "vitest"; import { fauxAssistantMessage, fauxProvider } from "@earendil-works/pi-ai/providers/faux"; import { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, type ResolvedSkillInfo } from "@selesai/code"; import type { Skill } from "../../core/skills.ts"; import type { SkillInvocationState } from "../../core/skill-invocation.ts"; import skillsIndexExtension, { compactSkillIndex, eligibleSkills, showSkill, SKILL_REQUEST_MESSAGE_TYPE, skillRequestNotice, skillVisibility } from "./index.ts"; const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); function rootDir() { const root = mkdtempSync(join(tmpdir(), "selesai-skills-index-")); roots.push(root); return root; } function resolved(name: string, filePath: string, description = `${name} procedure`, disableModelInvocation = false): ResolvedSkillInfo { return { name, filePath, description, scope: "user", disableModelInvocation }; } function promptSkill(name: string): Skill { return { name, description: `${name} procedure`, filePath: `/skills/${name}/SKILL.md`, baseDir: `/skills/${name}`, sourceInfo: { path: `/skills/${name}/SKILL.md`, source: "user", scope: "user", origin: "top-level" }, disableModelInvocation: false }; } it("keeps first eligible resolution and excludes model-ineligible entries", () => { const first = resolved("review", "/first"); expect(eligibleSkills([resolved("hidden", "/hidden", "Hidden", true), first, resolved("review", "/second")])).toEqual([first]); }); it("collapses only a nonempty index with an available show tool without mutating it", () => { const skills = [promptSkill("review"), promptSkill("research")]; expect(compactSkillIndex(skills, false)).toBe(skills); expect(compactSkillIndex([], true)).toEqual([]); const index = compactSkillIndex(skills, true); expect(index).toHaveLength(1); expect(index[0].description).toContain("skill_show"); expect(index[0].description).not.toContain("capability_discover"); expect(skills).toHaveLength(2); }); it("lists and filters metadata without opening files, bounds results, and supports Unicode", async () => { const skills = [resolved("review", "/absent", "Check code"), resolved("日本語", "/absent", "日本語 手順")]; const list = await showSkill(skills, { limit: 1 }); expect(list.details).toMatchObject({ loaded: false, total: 2, truncated: true }); expect(list.content[0].text).toContain("Narrow query"); expect((await showSkill(skills, { query: "日本語 手順" })).content[0].text).toContain("日本語"); expect((await showSkill(skills, { query: "review missing" })).content[0].text).toBe("No eligible skills match."); }); it("loads full instructions and reports relative-reference directory", async () => { const path = join(rootDir(), "SKILL.md"); const body = "---\nname: review\ndescription: Review\n---\nRead examples/example.ts.\n"; writeFileSync(path, body); const result = await showSkill([resolved("review", path)], { name: "review" }); expect(result.details).toMatchObject({ loaded: true, complete: true, filePath: path }); expect(result.content[0].text).toContain(body); expect(result.content[0].text).toContain(join(path, "..")); }); it("rejects arbitrary paths, disabled names, missing files, and cancellation", async () => { const hidden = resolved("hidden", "/absent", "Hidden", true); await expect(showSkill([hidden], { name: "hidden" })).rejects.toThrow("model-ineligible"); await expect(showSkill([], { name: "../../secret" })).rejects.toThrow("Unknown"); await expect(showSkill([resolved("missing", "/absent")], { name: "missing" })).rejects.toThrow(); const controller = new AbortController(); controller.abort(); await expect(showSkill([], {}, controller.signal)).rejects.toThrow(); }); it.each(["bytes", "lines"])("marks %s truncation honestly and supplies the original path", async (mode) => { const path = join(rootDir(), "SKILL.md"); writeFileSync(path, mode === "bytes" ? "x".repeat(60_000) : "instruction\n".repeat(2100)); const result = await showSkill([resolved("large", path)], { name: "large" }); expect(result.details).toMatchObject({ loaded: true, complete: false, filePath: path }); expect(result.content[0].text).toContain("Instructions are incomplete"); expect(result.content[0].text).not.toContain("full instructions are embedded"); expect(Buffer.byteLength(result.content[0].text)).toBeLessThan(53_000); }); function invocation(overrides: Partial = {}): SkillInvocationState { return { mode: "explicit", alwaysAvailable: [], open: false, requested: [], ...overrides }; } it("grants every eligible skill in auto mode or an open turn, and only the allowlist otherwise", () => { expect(skillVisibility(undefined)).toBeUndefined(); expect(skillVisibility(invocation({ mode: "auto" }))).toBeUndefined(); expect(skillVisibility(invocation({ open: true }))).toBeUndefined(); const closed = skillVisibility(invocation({ alwaysAvailable: ["plan"] }))!; expect(closed("plan")).toBe(true); expect(closed("design")).toBe(false); expect(eligibleSkills([resolved("plan", "/p"), resolved("design", "/d")], closed).map((skill) => skill.name)).toEqual(["plan"]); }); it("refuses a gated skill with turn guidance and hides it from listings", async () => { const path = join(rootDir(), "SKILL.md"); writeFileSync(path, "---\nname: design\ndescription: Design\n---\nUse beige.\n"); const skills = [resolved("design", path, "Design taste")]; const closed = skillVisibility(invocation()); await expect(showSkill(skills, { name: "design" }, undefined, closed)).rejects.toThrow("not available this turn"); await expect(showSkill(skills, { name: "nope" }, undefined, closed)).rejects.toThrow("Unknown"); expect((await showSkill(skills, {}, undefined, closed)).content[0].text).toContain("user has not asked for a skill"); expect((await showSkill(skills, { query: "zzz" }, undefined, skillVisibility(invocation({ alwaysAvailable: ["design"] })))).content[0].text).toBe("No eligible skills match."); const opened = await showSkill(skills, { name: "design" }, undefined, skillVisibility(invocation({ open: true }))); expect(opened.content[0].text).toContain("Use beige."); expect(opened.content[0].text).toContain("Explicit user requirements"); }); it("announces an open turn through skill_show, or lists files for the read tool", () => { const skills = [resolved("design", "/skills/design/SKILL.md", "Design "), resolved("hidden", "/h", "Hidden", true)]; const viaShow = skillRequestNotice({ requested: ["design"], showAvailable: true, skills }); expect(viaShow).toContain("tools.skill_show"); expect(viaShow).toContain("`design`"); expect(viaShow).toContain("Explicit user requirements"); const viaRead = skillRequestNotice({ requested: [], showAvailable: false, skills }); expect(viaRead).toContain("- design — Design <taste> (/skills/design/SKILL.md)"); expect(viaRead).not.toContain("hidden"); expect(viaRead).not.toContain("The user named"); const many = Array.from({ length: 52 }, (_, index) => resolved(`s${index}`, `/s${index}`)); expect(skillRequestNotice({ requested: [], showAvailable: false, skills: many })).toContain("(2 more not listed.)"); }); function fakePi(state: SkillInvocationState | undefined, active: string[] = ["codemode"]) { const handlers = new Map any>(); const tools: Array<{ execute: (...args: any[]) => Promise }> = []; const pi = { registerTool: (tool: any) => tools.push(tool), on: (name: string, handler: (event: any) => any) => handlers.set(name, handler), getActiveTools: () => active, setSkillsIndexFilter: () => {}, getResolvedSkills: () => [resolved("design", "/absent", "Design")], ...(state ? { getSkillInvocation: () => state } : {}), }; skillsIndexExtension(pi as never); handlers.get("session_start")!({}); const start = (messageType = "user") => handlers.get("before_agent_start")!({ messageType }); const input = (event: { source: string; streamingBehavior?: string }) => handlers.get("input")!(event); return { start, input, show: (args: object) => tools[0].execute("id", args) }; } it("injects one notice per user-typed request, only when an explicit-mode turn is open", () => { const open = fakePi(invocation({ open: true, requested: ["design"] })); open.input({ source: "interactive" }); expect(open.start("custom")).toBeUndefined(); const result = open.start(); expect(result.message).toMatchObject({ customType: SKILL_REQUEST_MESSAGE_TYPE, display: false, details: { requested: ["design"] } }); expect(open.start()).toBeUndefined(); open.input({ source: "extension" }); expect(open.start()).toBeUndefined(); open.input({ source: "interactive", streamingBehavior: "steer" }); expect(open.start()).toBeUndefined(); for (const state of [undefined, invocation({ mode: "auto", open: true }), invocation()]) { const session = fakePi(state); session.input({ source: "rpc" }); expect(session.start()).toBeUndefined(); } const readOnly = fakePi(invocation({ open: true }), []); readOnly.input({ source: "interactive" }); expect(String(readOnly.start().message.content)).toContain("read tool"); }); it("gates skill_show on the host state and stays open on older hosts", async () => { await expect(fakePi(invocation()).show({ name: "design" })).rejects.toThrow("not available this turn"); await expect(fakePi(undefined).show({ name: "design" })).rejects.toThrow("ENOENT"); }); async function realSession(options: { withCodemode: boolean; skillInvocation?: { mode?: "explicit" | "auto"; alwaysAvailable?: string[] } }) { const root = rootDir(); const cwd = join(root, "project"); const agentDir = join(root, "agent"); mkdirSync(cwd); mkdirSync(join(agentDir, "skills", "review"), { recursive: true }); writeFileSync(join(agentDir, "skills", "review", "SKILL.md"), "---\nname: review\ndescription: Review code carefully\n---\nFull review instructions.\n"); const settingsManager = SettingsManager.inMemory({ compaction: { enabled: false }, retry: { enabled: false }, ...(options.skillInvocation ? { skillInvocation: options.skillInvocation } : {}) }); const modelRuntime = await ModelRuntime.create({ authPath: join(agentDir, "auth.json"), modelsPath: null, allowModelNetwork: false }); const faux = fauxProvider({ provider: "faux-skills-index", models: [{ id: "skills", contextWindow: 200_000 }] }); modelRuntime.registerProvider(faux.provider.id, { name: faux.provider.name, api: faux.api, apiKey: "faux", streamSimple: faux.provider.streamSimple, models: [...faux.models] }); await modelRuntime.refresh({ allowNetwork: false }); const model = modelRuntime.getModel(faux.provider.id, "skills"); if (!model) throw new Error("Missing faux model"); const loader = new DefaultResourceLoader({ cwd, agentDir, settingsManager, noExtensions: true, additionalExtensionPaths: [fileURLToPath(new URL("./index.ts", import.meta.url)), fileURLToPath(new URL("../codemode/index.ts", import.meta.url))], noContextFiles: true, noThemes: true, noPromptTemplates: true }); await loader.reload(); expect(loader.getExtensions().errors).toEqual([]); const { session } = await createAgentSession({ cwd, agentDir, model, modelRuntime, resourceLoader: loader, sessionManager: SessionManager.inMemory(), settingsManager, tools: options.withCodemode ? ["read", "codemode"] : ["read"] }); return { session, loader, faux }; } function skillRequestMessages(session: Awaited>["session"]) { return session.messages.filter((message) => message.role === "custom" && message.customType === SKILL_REQUEST_MESSAGE_TYPE); } it("explicit mode advertises no skill, opens one turn when the user says skill, and closes on the next", async () => { const { session, faux } = await realSession({ withCodemode: true }); try { await session.bindExtensions({}); expect(session.systemPrompt).not.toContain("Review code carefully"); expect(session.systemPrompt).not.toContain(""); faux.setResponses([fauxAssistantMessage("ok"), fauxAssistantMessage("ok")]); await session.prompt("bikin modal glass biru, pake skill review"); expect(session.getSkillInvocationState()).toMatchObject({ mode: "explicit", open: true }); const notices = skillRequestMessages(session); expect(notices).toHaveLength(1); expect(String(notices[0].content)).toContain("tools.skill_show"); await session.prompt("sekarang ganti warnanya"); expect(session.getSkillInvocationState().open).toBe(false); expect(skillRequestMessages(session)).toHaveLength(1); } finally { session.dispose(); } }); it("explicit mode keeps alwaysAvailable skills in the index", async () => { const { session } = await realSession({ withCodemode: true, skillInvocation: { alwaysAvailable: ["review"] } }); try { await session.bindExtensions({}); expect(session.systemPrompt).toContain("skill_show"); } finally { session.dispose(); } }); // skill_show is deferred: the index is compact only when codemode can reach it. it.each([false, true])("real SDK preserves loadout and resolved catalog in auto mode (codemode active=%s)", async (withCodemode) => { const excluded = !withCodemode; const { session, loader } = await realSession({ withCodemode, skillInvocation: { mode: "auto" } }); try { const baseline = session.getActiveToolNames(); expect(baseline).not.toContain("skill_show"); await session.bindExtensions({}); expect(session.getActiveToolNames()).toEqual(baseline); expect(session.systemPrompt).toContain(excluded ? "Review code carefully" : "skill_show"); expect(session.systemPrompt).not.toContain(excluded ? "" : "Review code carefully"); expect(loader.getSkills().skills.some((skill) => skill.name === "review")).toBe(true); await session.extensionRunner.emit({ type: "agent_settled" }); expect(session.getActiveToolNames()).toEqual(baseline); } finally { session.dispose(); } });