feat(masks): add prompt-scoped tool profiles
0b1200cab8c02d13ab486794da57147f5e29d6c5
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
- Parent 1: 5b29c1c2f71e
bugabingas pi extensions
0b1200cab8c02d13ab486794da57147f5e29d6c5
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
+587 / −95 text lines
+8 / −6 text lines
Switch model and thinking level together.Switch model and thinking level together, with optional temporary prompt tool profiles.- `input` detects masked templates and defers busy follow-ups.- `before_agent_start` equips a prompt mask.- `input` detects masked templates, equips their profiles before system-prompt construction, and defers busy follow-ups.- `turn_end` restores after successful completion; `agent_settled` restores after recovery and starts the next deferred prompt.tools: [read, grep, find, ls]The mask lasts through tools and automatic retries, then restores before the next ordinary follow-up.Failed mask switches abort the prompt; failed restoration blocks later prompts until restoration succeeds.`tools` is optional and applies only to masked templates. When present, it must be a nonempty array of unique, nonempty names registered when the prompt dispatches. Invalid or unknown names reject the prompt before model, thinking, or tools change.The mask and optional tool profile last through tool calls, automatic retries, and continuing compaction, then restore before the next ordinary follow-up. A tool profile replaces the active set for the run and restores the exact pre-prompt set; tool activation during that run is temporary. Omitting `tools` leaves tool state untouched.Failed profile switches abort the prompt and roll back every changed component. Failed restoration blocks later prompts until restoration succeeds.+426 / −50 text lines
reply = await onRequest(request, requests.length - 1); const beforeHandler = extension().handlers.get("before_agent_start")[0]; it("applies a masked prompt tool profile and restores the exact snapshot", async () => { const cwd = writeSettings({ masks: { items: [ { name: "focused", model: "openai/gpt-4o", thinkingLevel: "high", }, ], }, }); writePrompt( "review", "---\nmask: focused\ntools: [read, ls]\n---\nReview it.", ); t = await createTestSession({ cwd, extensions: [extensionPath()] }); const model = context().modelRegistry.find("openai", "gpt-4o"); if (!model) throw new Error("missing harness model"); model.reasoning = true; const runtime = t.session.extensionRunner.runtime; const originalTools = runtime.getActiveTools(); expect( await extension().handlers.get("input")[0]( { type: "input", text: "/review", source: "interactive" }, context(), ), ).toEqual({ action: "continue" }); expect(runtime.getActiveTools()).toEqual(["read", "ls"]); await extension().handlers.get("agent_start")[0]( { type: "agent_start" }, context(), ); runtime.setActiveTools(["read", "ls", "bash"]); await extension().handlers.get("agent_settled")[0]( { type: "agent_settled" }, context(), ); expect(runtime.getActiveTools()).toEqual(originalTools); }); it("sends a consistent tool profile and system prompt to the provider", async () => { const toolSets: string[][] = []; const systemPrompts: string[] = []; const requests = await queuedSession( async (_request, _index, tools, systemPrompt) => { toolSets.push(tools); systemPrompts.push(systemPrompt); return undefined; }, ); writePrompt( "review", "---\nmask: focused\ntools: [read, ls]\n---\nReview $1.", ); await t?.session.prompt("/review profiled"); await settled(1, requests); expect(toolSets).toEqual([["read", "ls"]]); expect(systemPrompts[0]).toContain("- read:"); expect(systemPrompts[0]).toContain("- ls:"); expect(systemPrompts[0]).not.toContain("- bash:"); expect(t?.session.extensionRunner.runtime.getActiveTools()).toEqual([ "read", "bash", "edit", "write", ]); }); it("leaves tools alone when masked prompt frontmatter omits them", async () => { const cwd = writeSettings({ masks: { items: [ { name: "focused", model: "openai/gpt-4o", thinkingLevel: "high", }, ], }, }); writePrompt("review", "---\nmask: focused\n---\nReview it."); t = await createTestSession({ cwd, extensions: [extensionPath()] }); const runtime = t.session.extensionRunner.runtime; await extension().handlers.get("input")[0]( { type: "input", text: "/review", source: "interactive" }, context(), ); await extension().handlers.get("agent_start")[0]( { type: "agent_start" }, context(), ); runtime.setActiveTools(["read", "ls"]); await extension().handlers.get("agent_settled")[0]( { type: "agent_settled" }, context(), ); expect(runtime.getActiveTools()).toEqual(["read", "ls"]); }); it("rejects invalid prompt tool profiles before changing the mask", async () => { const cwd = writeSettings({ masks: { items: [ { name: "focused", model: "openai/gpt-4o-mini", thinkingLevel: "high", }, ], }, }); writePrompt( "review", "---\nmask: focused\ntools: [read, absent]\n---\nReview it.", ); t = await createTestSession({ cwd, extensions: [extensionPath()] }); const runtime = t.session.extensionRunner.runtime; const originalTools = runtime.getActiveTools(); const originalModel = t.session.model.id; expect( await extension().handlers.get("input")[0]( { type: "input", text: "/review", source: "interactive" }, context(), ), ).toEqual({ action: "handled" }); expect(runtime.getActiveTools()).toEqual(originalTools); expect(t.session.model.id).toBe(originalModel); expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([ 'Prompt /review: unknown tool "absent"', "error", ]); }); it("rolls back model, thinking, and tools when tool application fails", async () => { const cwd = writeSettings({ masks: { items: [ { name: "focused", model: "openai/gpt-4o-mini", thinkingLevel: "high", }, ], }, }); writePrompt( "review", "---\nmask: focused\ntools: [read, ls]\n---\nReview it.", ); t = await createTestSession({ cwd, extensions: [extensionPath()] }); const runtime = t.session.extensionRunner.runtime; const originalTools = runtime.getActiveTools(); const setActiveTools = runtime.setActiveTools.bind(runtime); vi.spyOn(runtime, "setActiveTools").mockImplementation((tools) => { setActiveTools(tools); if (tools.join(",") === "read,ls") throw new Error("profile failure"); }); expect( await extension().handlers.get("input")[0]( { type: "input", text: "/review", source: "interactive" }, context(), ), ).toEqual({ action: "handled" }); expect(runtime.getActiveTools()).toEqual(originalTools); expect(t.session.model.id).toBe("gpt-4o"); expect(t.session.thinkingLevel).toBe("off"); }); it("restores tools even when model restoration fails", async () => { const cwd = writeSettings({ masks: { items: [ { name: "focused", model: "openai/gpt-4o-mini", thinkingLevel: "high", }, ], }, }); writePrompt( "review", "---\nmask: focused\ntools: [read, ls]\n---\nReview it.", ); t = await createTestSession({ cwd, extensions: [extensionPath()] }); const runtime = t.session.extensionRunner.runtime; const originalTools = runtime.getActiveTools(); const setModel = runtime.setModel.bind(runtime); let failRestore = false; vi.spyOn(runtime, "setModel").mockImplementation(async (model) => { if (failRestore && model.id === "gpt-4o") return false; return setModel(model); }); await extension().handlers.get("input")[0]( { type: "input", text: "/review", source: "interactive" }, context(), ); await extension().handlers.get("agent_start")[0]( { type: "agent_start" }, context(), ); failRestore = true; await extension().handlers.get("agent_settled")[0]( { type: "agent_settled" }, context(), ); expect(runtime.getActiveTools()).toEqual(originalTools); expect(t.events.uiCallsFor("notify").at(-1)?.args[0]).toContain( "Failed to restore prompt mask", ); }); it("restores after tree navigation races temporary profile application", async () => { const cwd = writeSettings({ masks: { items: [ { name: "focused", model: "openai/gpt-4o-mini", thinkingLevel: "high", }, ], }, }); writePrompt( "review", "---\nmask: focused\ntools: [read, ls]\n---\nReview it.", ); t = await createTestSession({ cwd, extensions: [extensionPath()] }); const runtime = t.session.extensionRunner.runtime; const originalTools = runtime.getActiveTools(); const setModel = runtime.setModel.bind(runtime); const entered = Promise.withResolvers<void>(); const release = Promise.withResolvers<void>(); vi.spyOn(runtime, "setModel").mockImplementation(async (model) => { if (model.id === "gpt-4o-mini") { entered.resolve(); await release.promise; } return setModel(model); }); const applying = extension().handlers.get("input")[0]( { type: "input", text: "/review", source: "interactive" }, context(), ); await entered.promise; const resetting = extension().handlers.get("session_tree")[0]( { type: "session_tree" }, context(), ); release.resolve(); await Promise.all([applying, resetting]); expect(t.session.model.id).toBe("gpt-4o"); expect(t.session.thinkingLevel).toBe("off"); expect(runtime.getActiveTools()).toEqual(originalTools); }); it("keeps reset joined to profile application after a manual switch is rejected", async () => { const cwd = writeSettings({ masks: { items: [ { name: "focused", model: "openai/gpt-4o-mini", thinkingLevel: "high", }, ], }, }); writePrompt( "review", "---\nmask: focused\ntools: [read, ls]\n---\nReview it.", ); t = await createTestSession({ cwd, extensions: [extensionPath()] }); const runtime = t.session.extensionRunner.runtime; const originalTools = runtime.getActiveTools(); const setModel = runtime.setModel.bind(runtime); const entered = Promise.withResolvers<void>(); const release = Promise.withResolvers<void>(); vi.spyOn(runtime, "setModel").mockImplementation(async (model) => { if (model.id === "gpt-4o-mini") { entered.resolve(); await release.promise; } return setModel(model); }); const applying = extension().handlers.get("input")[0]( { type: "input", text: "/review", source: "interactive" }, context(), ); await entered.promise; await extension().commands.get("masks").handler("focused", context()); const resetting = extension().handlers.get("session_tree")[0]( { type: "session_tree" }, context(), ); release.resolve(); await Promise.all([applying, resetting]); expect(t.session.model.id).toBe("gpt-4o"); expect(runtime.getActiveTools()).toEqual(originalTools); }); it("cancels later deferred masks when a queued tool profile is invalid", async () => { const requests = await queuedSession(async (_request, index) => { if (index === 0) { await queue("/review invalid"); await queue("/plan later"); } return undefined; }); writePrompt( "review", "---\nmask: focused\ntools: [read, absent]\n---\nReview $1.", ); await t?.session.prompt("start"); await settled(1, requests); expect( t?.events .uiCallsFor("notify") .some((call) => String(call.args[0]).includes("Cancelled 1 deferred")), ).toBe(true); }); it("cancels later deferred masks when queued profile application fails", async () => { const requests = await queuedSession(async (_request, index) => { if (index === 0) { await queue("/review unavailable"); await queue("/plan stale"); } return undefined; }); const runtime = t?.session.extensionRunner.runtime; const setModel = runtime.setModel.bind(runtime); vi.spyOn(runtime, "setModel").mockImplementation(async (model) => model.id === "gpt-4o-mini" ? false : setModel(model), ); await t?.session.prompt("start"); await settled(1, requests); expect( t?.events .uiCallsFor("notify") .some((call) => String(call.args[0]).includes("Cancelled 1 deferred")), ).toBe(true); }); it.each(["input", "equip"])( "rejects competing preflights during %s without losing the mask", async (stage) => { const requests = await queuedSession(async () => undefined); const entered = Promise.withResolvers<void>(); const release = Promise.withResolvers<void>(); if (stage === "input") { extension() .handlers.get("before_agent_start") .unshift(async () => { entered.resolve(); await release.promise; }); } else { const runtime = t?.session.extensionRunner.runtime; const setModel = runtime.setModel.bind(runtime); vi.spyOn(runtime, "setModel").mockImplementation(async (model) => { entered.resolve(); await release.promise; return setModel(model); }); } const first = t?.session.prompt("/review first"); await entered.promise; try { await t?.session.prompt("ordinary concurrent prompt"); await t?.session.prompt("/plan second"); } finally { release.resolve(); } await first; expect(requests).toEqual([ { text: "Review first.", model: "gpt-4o-mini", thinking: "high" }, ]); expect(t?.session.model.id).toBe("gpt-4o"); expect(t?.session.thinkingLevel).toBe("off"); }, ); it("rejects competing prompts during profile application without losing the mask", async () => { const requests = await queuedSession(async () => undefined); const entered = Promise.withResolvers<void>(); const release = Promise.withResolvers<void>(); const runtime = t?.session.extensionRunner.runtime; const setModel = runtime.setModel.bind(runtime); vi.spyOn(runtime, "setModel").mockImplementation(async (model) => { entered.resolve(); await release.promise; return setModel(model); }); const first = t?.session.prompt("/review first"); await entered.promise; try { await t?.session.prompt("ordinary concurrent prompt"); await t?.session.prompt("/plan second"); } finally { release.resolve(); } await first; expect(requests).toEqual([ { text: "Review first.", model: "gpt-4o-mini", thinking: "high" }, ]); expect(t?.session.model.id).toBe("gpt-4o"); expect(t?.session.thinkingLevel).toBe("off"); }); it("blocks prompt dispatch while a manual mask switch is applying", async () => { const requests = await queuedSession(async () => undefined); const entered = Promise.withResolvers<void>(); const release = Promise.withResolvers<void>(); const runtime = t?.session.extensionRunner.runtime; const setModel = runtime.setModel.bind(runtime); vi.spyOn(runtime, "setModel").mockImplementation(async (model) => { entered.resolve(); await release.promise; return setModel(model); }); const manual = t?.session.prompt("/masks focused"); await entered.promise; try { await t?.session.prompt("/plan blocked"); } finally { release.resolve(); } await manual; expect(requests).toHaveLength(0); expect(t?.session.model.id).toBe("gpt-4o-mini"); expect(t?.session.thinkingLevel).toBe("high"); }); it("validates prompt tool profile shape and uniqueness", () => { const registered = new Set(["read", "ls"]); expect(__test.parsePromptTools(["read", "ls"], registered)).toEqual({ tools: ["read", "ls"], }); expect(__test.parsePromptTools([], registered).error).toMatch( /non-empty array/, ); expect(__test.parsePromptTools([" "], registered).error).toMatch( /non-empty string/, ); expect(__test.parsePromptTools(["read", "read"], registered).error).toMatch( /duplicates/, ); });+152 / −38 text lines
function parsePromptTools( value: unknown, registeredTools: ReadonlySet<string>,): { tools?: string[]; error?: string } { if (!Array.isArray(value) || value.length === 0) return { error: "tools must be a non-empty array" }; const tools: string[] = []; const seen = new Set<string>(); for (const [index, item] of value.entries()) { const name = nonEmptyString(item); if (!name) return { error: `tools[${index}] must be a non-empty string` }; if (seen.has(name)) return { error: `tools duplicates "${name}"` }; if (!registeredTools.has(name)) return { error: `unknown tool "${name}"` }; seen.add(name); tools.push(name); } return { tools };} let pendingMask: Mask | undefined; let abortNextRun = false; async function readyForManualMask(ctx: ExtensionContext): Promise<boolean> { if (preparing || restoring || applyPromise) { ctx.ui.notify("Prompt mask transition in progress", "warning"); return false; } if (!restoreState) return true; if (!ctx.isIdle()) { ctx.ui.notify("Temporary prompt mask is active", "warning"); return false; } await restoreTemporaryMask(ctx); return restoreState === undefined; } async function applyManualMask( mask: Mask, ctx: ExtensionContext, ): Promise<void> { if (manualTransition) { ctx.ui.notify("Prompt mask transition in progress", "warning"); return; } manualTransition = true; let ownedPromise: Promise<boolean> | undefined; try { if (!(await readyForManualMask(ctx))) return; ownedPromise = applyMask(pi, mask, ctx); applyPromise = ownedPromise; await ownedPromise; } finally { if (applyPromise === ownedPromise) applyPromise = undefined; manualTransition = false; } } if (!(await readyForManualMask(ctx))) return; handler: async (ctx) => applyManualMask(mask, ctx), "Masked prompt is preparing; retry after it starts, or /reload after a dispatch failure", "Masked prompt is transitioning; retry after it starts, or /reload after a dispatch failure", preparing = true; preparing = false; pendingMask = undefined; pendingMask = mask; preparing = true; return { action: "continue" }; }); pi.on("before_agent_start", async (_event, ctx) => { const mask = pendingMask; pendingMask = undefined; if (!mask) return; let tools: string[] | undefined; if (Object.hasOwn(frontmatter, "tools")) { const parsed = parsePromptTools( frontmatter.tools, new Set(pi.getAllTools().map((tool) => tool.name)), ); if (parsed.error) { if (event.source === "extension") cancelQueue(ctx); ctx.ui.notify(`Prompt /${commandName}: ${parsed.error}`, "error"); return { action: "handled" }; } tools = parsed.tools; } const generation = transitionGeneration; preparing = true; applyPromise = (async () => { if (!(await applyMask(pi, mask, ctx))) return false; if (!tools) return true; pi.setActiveTools(tools); const active = pi.getActiveTools(); if ( active.length !== tools.length || active.some((name, index) => name !== tools[index]) ) throw new Error("tool profile could not be applied exactly"); return true; })(); let applied = false; abortNextRun = true; if (restorePromise) return restorePromise; try { if (!(await pi.setModel(previous.model))) throw new Error("Model unavailable"); pi.setThinkingLevel(previous.thinkingLevel); restoreState = undefined; } catch (error) { restoring = true; restorePromise = (async () => { const failures: string[] = []; if (previous.modelPending) { try { if (!(await pi.setModel(previous.model))) throw new Error("model unavailable"); pi.setThinkingLevel(previous.thinkingLevel); previous.modelPending = false; } catch (error) { failures.push(`model: ${String(error)}`); } } if (previous.toolsPending && previous.tools) { try { pi.setActiveTools(previous.tools); const active = pi.getActiveTools(); if ( active.length !== previous.tools.length || active.some((name, index) => name !== previous.tools?.[index]) ) throw new Error("tool snapshot could not be restored exactly"); previous.toolsPending = false; } catch (error) { failures.push(`tools: ${String(error)}`); } } if (!previous.modelPending && !previous.toolsPending) { if (restoreState === previous) restoreState = undefined; return; } `Failed to restore model after prompt mask: ${String(error)}`, `Failed to restore prompt mask: ${failures.join("; ")}`, await applyPromise; parsePromptTools,+1 / −1 text lines