repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(masks): add prompt-scoped tool profiles

0b1200cab8c02d13ab486794da57147f5e29d6c5

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (4)

+587 / −95 text lines

Diff layout

extensions/masks/README.md

Modified

+8 / −6 text lines

11# masks
3Switch model and thinking level together.
3Switch model and thinking level together, with optional temporary prompt tool profiles.
55## Install / load
2121Hooks:
23- `input` detects masked templates and defers busy follow-ups.
24- `before_agent_start` equips a prompt mask.
23- `input` detects masked templates, equips their profiles before system-prompt construction, and defers busy follow-ups.
2524- `turn_end` restores after successful completion; `agent_settled` restores after recovery and starts the next deferred prompt.
2625- `session_start` reports invalid mask settings.
5756---
5857description: Review this change
5958mask: terra
59tools: [read, grep, find, ls]
6060---
6161Review the current change.
6262```
6464`mask` must exactly match a configured mask name.
65The mask lasts through tools and automatic retries, then restores before the next ordinary follow-up.
66Failed mask switches abort the prompt; failed restoration blocks later prompts until restoration succeeds.
65`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.
67The 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.
68Failed profile switches abort the prompt and roll back every changed component. Failed restoration blocks later prompts until restoration succeeds.
6870Busy masked follow-ups use an extension-owned FIFO queue, shown in the footer.
6971They run after Pi's native queue drains, not in mixed submission order.
7274Abort, error, tree navigation, and session shutdown discard deferred prompts.
7375Pi's native queue editor does not manage this queue; use `/masks-cancel`.
75Pi provides no dispatch acknowledgement: rejected or failed dispatches can lose a prompt and stall the remaining queue.
77Pi provides no dispatch acknowledgement: prompt expansion failures can lose a prompt and stall the remaining queue.
7678Concurrent input during masked preparation is rejected instead of risking the wrong model.
7779If dispatch fails during preparation, `/reload` clears the reservation and deferred queue.

extensions/masks/__tests__/harness.test.ts

Modified

+426 / −50 text lines

4444 onRequest: (
4545 request: Request,
4646 index: number,
47 tools: string[],
48 systemPrompt: string,
4749 ) => Promise<Record<string, unknown> | undefined>,
4850): Promise<Request[]> {
4951 const cwd = writeSettings({
7779 let reply: Record<string, unknown> | undefined;
7880 if (!options.signal.aborted) {
7981 requests.push(request);
80 reply = await onRequest(request, requests.length - 1);
82 reply = await onRequest(
83 request,
84 requests.length - 1,
85 ctx.tools.map((tool: { name: string }) => tool.name),
86 ctx.systemPrompt,
87 );
8188 }
8289 const message = {
8390 role: "assistant",
221228 model.reasoning = true;
223230 const inputHandler = extension().handlers.get("input")[0];
224 const beforeHandler = extension().handlers.get("before_agent_start")[0];
225231 const endHandler = extension().handlers.get("agent_settled")[0];
226232 expect(
227233 await inputHandler(
230236 ),
231237 ).toEqual({ action: "continue" });
233 await beforeHandler(
234 {
235 type: "before_agent_start",
236 prompt: "Review it.",
237 images: undefined,
238 systemPrompt: "",
239 systemPromptOptions: {},
240 },
241 context(),
242 );
243239 expect(t.session.thinkingLevel).toBe("high");
245241 await endHandler({ type: "agent_settled" }, context());
248244 expect(t.session.thinkingLevel).toBe("off");
249245 });
247 it("applies a masked prompt tool profile and restores the exact snapshot", async () => {
248 const cwd = writeSettings({
249 masks: {
250 items: [
251 {
252 name: "focused",
253 model: "openai/gpt-4o",
254 thinkingLevel: "high",
255 },
256 ],
257 },
258 });
259 writePrompt(
260 "review",
261 "---\nmask: focused\ntools: [read, ls]\n---\nReview it.",
262 );
263 t = await createTestSession({ cwd, extensions: [extensionPath()] });
264 const model = context().modelRegistry.find("openai", "gpt-4o");
265 if (!model) throw new Error("missing harness model");
266 model.reasoning = true;
267 const runtime = t.session.extensionRunner.runtime;
268 const originalTools = runtime.getActiveTools();
270 expect(
271 await extension().handlers.get("input")[0](
272 { type: "input", text: "/review", source: "interactive" },
273 context(),
274 ),
275 ).toEqual({ action: "continue" });
276 expect(runtime.getActiveTools()).toEqual(["read", "ls"]);
277 await extension().handlers.get("agent_start")[0](
278 { type: "agent_start" },
279 context(),
280 );
282 runtime.setActiveTools(["read", "ls", "bash"]);
283 await extension().handlers.get("agent_settled")[0](
284 { type: "agent_settled" },
285 context(),
286 );
287 expect(runtime.getActiveTools()).toEqual(originalTools);
288 });
290 it("sends a consistent tool profile and system prompt to the provider", async () => {
291 const toolSets: string[][] = [];
292 const systemPrompts: string[] = [];
293 const requests = await queuedSession(
294 async (_request, _index, tools, systemPrompt) => {
295 toolSets.push(tools);
296 systemPrompts.push(systemPrompt);
297 return undefined;
298 },
299 );
300 writePrompt(
301 "review",
302 "---\nmask: focused\ntools: [read, ls]\n---\nReview $1.",
303 );
305 await t?.session.prompt("/review profiled");
306 await settled(1, requests);
307 expect(toolSets).toEqual([["read", "ls"]]);
308 expect(systemPrompts[0]).toContain("- read:");
309 expect(systemPrompts[0]).toContain("- ls:");
310 expect(systemPrompts[0]).not.toContain("- bash:");
311 expect(t?.session.extensionRunner.runtime.getActiveTools()).toEqual([
312 "read",
313 "bash",
314 "edit",
315 "write",
316 ]);
317 });
319 it("leaves tools alone when masked prompt frontmatter omits them", async () => {
320 const cwd = writeSettings({
321 masks: {
322 items: [
323 {
324 name: "focused",
325 model: "openai/gpt-4o",
326 thinkingLevel: "high",
327 },
328 ],
329 },
330 });
331 writePrompt("review", "---\nmask: focused\n---\nReview it.");
332 t = await createTestSession({ cwd, extensions: [extensionPath()] });
333 const runtime = t.session.extensionRunner.runtime;
334 await extension().handlers.get("input")[0](
335 { type: "input", text: "/review", source: "interactive" },
336 context(),
337 );
338 await extension().handlers.get("agent_start")[0](
339 { type: "agent_start" },
340 context(),
341 );
342 runtime.setActiveTools(["read", "ls"]);
343 await extension().handlers.get("agent_settled")[0](
344 { type: "agent_settled" },
345 context(),
346 );
347 expect(runtime.getActiveTools()).toEqual(["read", "ls"]);
348 });
350 it("rejects invalid prompt tool profiles before changing the mask", async () => {
351 const cwd = writeSettings({
352 masks: {
353 items: [
354 {
355 name: "focused",
356 model: "openai/gpt-4o-mini",
357 thinkingLevel: "high",
358 },
359 ],
360 },
361 });
362 writePrompt(
363 "review",
364 "---\nmask: focused\ntools: [read, absent]\n---\nReview it.",
365 );
366 t = await createTestSession({ cwd, extensions: [extensionPath()] });
367 const runtime = t.session.extensionRunner.runtime;
368 const originalTools = runtime.getActiveTools();
369 const originalModel = t.session.model.id;
371 expect(
372 await extension().handlers.get("input")[0](
373 { type: "input", text: "/review", source: "interactive" },
374 context(),
375 ),
376 ).toEqual({ action: "handled" });
377 expect(runtime.getActiveTools()).toEqual(originalTools);
378 expect(t.session.model.id).toBe(originalModel);
379 expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
380 'Prompt /review: unknown tool "absent"',
381 "error",
382 ]);
383 });
385 it("rolls back model, thinking, and tools when tool application fails", async () => {
386 const cwd = writeSettings({
387 masks: {
388 items: [
389 {
390 name: "focused",
391 model: "openai/gpt-4o-mini",
392 thinkingLevel: "high",
393 },
394 ],
395 },
396 });
397 writePrompt(
398 "review",
399 "---\nmask: focused\ntools: [read, ls]\n---\nReview it.",
400 );
401 t = await createTestSession({ cwd, extensions: [extensionPath()] });
402 const runtime = t.session.extensionRunner.runtime;
403 const originalTools = runtime.getActiveTools();
404 const setActiveTools = runtime.setActiveTools.bind(runtime);
405 vi.spyOn(runtime, "setActiveTools").mockImplementation((tools) => {
406 setActiveTools(tools);
407 if (tools.join(",") === "read,ls") throw new Error("profile failure");
408 });
410 expect(
411 await extension().handlers.get("input")[0](
412 { type: "input", text: "/review", source: "interactive" },
413 context(),
414 ),
415 ).toEqual({ action: "handled" });
416 expect(runtime.getActiveTools()).toEqual(originalTools);
417 expect(t.session.model.id).toBe("gpt-4o");
418 expect(t.session.thinkingLevel).toBe("off");
419 });
421 it("restores tools even when model restoration fails", async () => {
422 const cwd = writeSettings({
423 masks: {
424 items: [
425 {
426 name: "focused",
427 model: "openai/gpt-4o-mini",
428 thinkingLevel: "high",
429 },
430 ],
431 },
432 });
433 writePrompt(
434 "review",
435 "---\nmask: focused\ntools: [read, ls]\n---\nReview it.",
436 );
437 t = await createTestSession({ cwd, extensions: [extensionPath()] });
438 const runtime = t.session.extensionRunner.runtime;
439 const originalTools = runtime.getActiveTools();
440 const setModel = runtime.setModel.bind(runtime);
441 let failRestore = false;
442 vi.spyOn(runtime, "setModel").mockImplementation(async (model) => {
443 if (failRestore && model.id === "gpt-4o") return false;
444 return setModel(model);
445 });
447 await extension().handlers.get("input")[0](
448 { type: "input", text: "/review", source: "interactive" },
449 context(),
450 );
451 await extension().handlers.get("agent_start")[0](
452 { type: "agent_start" },
453 context(),
454 );
455 failRestore = true;
456 await extension().handlers.get("agent_settled")[0](
457 { type: "agent_settled" },
458 context(),
459 );
460 expect(runtime.getActiveTools()).toEqual(originalTools);
461 expect(t.events.uiCallsFor("notify").at(-1)?.args[0]).toContain(
462 "Failed to restore prompt mask",
463 );
464 });
466 it("restores after tree navigation races temporary profile application", async () => {
467 const cwd = writeSettings({
468 masks: {
469 items: [
470 {
471 name: "focused",
472 model: "openai/gpt-4o-mini",
473 thinkingLevel: "high",
474 },
475 ],
476 },
477 });
478 writePrompt(
479 "review",
480 "---\nmask: focused\ntools: [read, ls]\n---\nReview it.",
481 );
482 t = await createTestSession({ cwd, extensions: [extensionPath()] });
483 const runtime = t.session.extensionRunner.runtime;
484 const originalTools = runtime.getActiveTools();
485 const setModel = runtime.setModel.bind(runtime);
486 const entered = Promise.withResolvers<void>();
487 const release = Promise.withResolvers<void>();
488 vi.spyOn(runtime, "setModel").mockImplementation(async (model) => {
489 if (model.id === "gpt-4o-mini") {
490 entered.resolve();
491 await release.promise;
492 }
493 return setModel(model);
494 });
495 const applying = extension().handlers.get("input")[0](
496 { type: "input", text: "/review", source: "interactive" },
497 context(),
498 );
499 await entered.promise;
500 const resetting = extension().handlers.get("session_tree")[0](
501 { type: "session_tree" },
502 context(),
503 );
504 release.resolve();
505 await Promise.all([applying, resetting]);
506 expect(t.session.model.id).toBe("gpt-4o");
507 expect(t.session.thinkingLevel).toBe("off");
508 expect(runtime.getActiveTools()).toEqual(originalTools);
509 });
511 it("keeps reset joined to profile application after a manual switch is rejected", async () => {
512 const cwd = writeSettings({
513 masks: {
514 items: [
515 {
516 name: "focused",
517 model: "openai/gpt-4o-mini",
518 thinkingLevel: "high",
519 },
520 ],
521 },
522 });
523 writePrompt(
524 "review",
525 "---\nmask: focused\ntools: [read, ls]\n---\nReview it.",
526 );
527 t = await createTestSession({ cwd, extensions: [extensionPath()] });
528 const runtime = t.session.extensionRunner.runtime;
529 const originalTools = runtime.getActiveTools();
530 const setModel = runtime.setModel.bind(runtime);
531 const entered = Promise.withResolvers<void>();
532 const release = Promise.withResolvers<void>();
533 vi.spyOn(runtime, "setModel").mockImplementation(async (model) => {
534 if (model.id === "gpt-4o-mini") {
535 entered.resolve();
536 await release.promise;
537 }
538 return setModel(model);
539 });
540 const applying = extension().handlers.get("input")[0](
541 { type: "input", text: "/review", source: "interactive" },
542 context(),
543 );
544 await entered.promise;
545 await extension().commands.get("masks").handler("focused", context());
546 const resetting = extension().handlers.get("session_tree")[0](
547 { type: "session_tree" },
548 context(),
549 );
550 release.resolve();
551 await Promise.all([applying, resetting]);
552 expect(t.session.model.id).toBe("gpt-4o");
553 expect(runtime.getActiveTools()).toEqual(originalTools);
554 });
556 it("cancels later deferred masks when a queued tool profile is invalid", async () => {
557 const requests = await queuedSession(async (_request, index) => {
558 if (index === 0) {
559 await queue("/review invalid");
560 await queue("/plan later");
561 }
562 return undefined;
563 });
564 writePrompt(
565 "review",
566 "---\nmask: focused\ntools: [read, absent]\n---\nReview $1.",
567 );
568 await t?.session.prompt("start");
569 await settled(1, requests);
570 expect(
571 t?.events
572 .uiCallsFor("notify")
573 .some((call) => String(call.args[0]).includes("Cancelled 1 deferred")),
574 ).toBe(true);
575 });
577 it("cancels later deferred masks when queued profile application fails", async () => {
578 const requests = await queuedSession(async (_request, index) => {
579 if (index === 0) {
580 await queue("/review unavailable");
581 await queue("/plan stale");
582 }
583 return undefined;
584 });
585 const runtime = t?.session.extensionRunner.runtime;
586 const setModel = runtime.setModel.bind(runtime);
587 vi.spyOn(runtime, "setModel").mockImplementation(async (model) =>
588 model.id === "gpt-4o-mini" ? false : setModel(model),
589 );
590 await t?.session.prompt("start");
591 await settled(1, requests);
592 expect(
593 t?.events
594 .uiCallsFor("notify")
595 .some((call) => String(call.args[0]).includes("Cancelled 1 deferred")),
596 ).toBe(true);
597 });
251599 it("defers masked follow-ups without changing the running model", async () => {
252600 const cwd = writeSettings({
253601 masks: {
489837 expect(t?.session.thinkingLevel).toBe("off");
490838 });
492 it.each(["input", "equip"])(
493 "rejects competing preflights during %s without losing the mask",
494 async (stage) => {
495 const requests = await queuedSession(async () => undefined);
496 const entered = Promise.withResolvers<void>();
497 const release = Promise.withResolvers<void>();
498 if (stage === "input") {
499 extension()
500 .handlers.get("before_agent_start")
501 .unshift(async () => {
502 entered.resolve();
503 await release.promise;
504 });
505 } else {
506 const runtime = t?.session.extensionRunner.runtime;
507 const setModel = runtime.setModel.bind(runtime);
508 vi.spyOn(runtime, "setModel").mockImplementation(async (model) => {
509 entered.resolve();
510 await release.promise;
511 return setModel(model);
512 });
513 }
514 const first = t?.session.prompt("/review first");
515 await entered.promise;
516 try {
517 await t?.session.prompt("ordinary concurrent prompt");
518 await t?.session.prompt("/plan second");
519 } finally {
520 release.resolve();
521 }
522 await first;
523 expect(requests).toEqual([
524 { text: "Review first.", model: "gpt-4o-mini", thinking: "high" },
525 ]);
526 expect(t?.session.model.id).toBe("gpt-4o");
527 expect(t?.session.thinkingLevel).toBe("off");
528 },
529 );
840 it("rejects competing prompts during profile application without losing the mask", async () => {
841 const requests = await queuedSession(async () => undefined);
842 const entered = Promise.withResolvers<void>();
843 const release = Promise.withResolvers<void>();
844 const runtime = t?.session.extensionRunner.runtime;
845 const setModel = runtime.setModel.bind(runtime);
846 vi.spyOn(runtime, "setModel").mockImplementation(async (model) => {
847 entered.resolve();
848 await release.promise;
849 return setModel(model);
850 });
851 const first = t?.session.prompt("/review first");
852 await entered.promise;
853 try {
854 await t?.session.prompt("ordinary concurrent prompt");
855 await t?.session.prompt("/plan second");
856 } finally {
857 release.resolve();
858 }
859 await first;
860 expect(requests).toEqual([
861 { text: "Review first.", model: "gpt-4o-mini", thinking: "high" },
862 ]);
863 expect(t?.session.model.id).toBe("gpt-4o");
864 expect(t?.session.thinkingLevel).toBe("off");
865 });
867 it("blocks prompt dispatch while a manual mask switch is applying", async () => {
868 const requests = await queuedSession(async () => undefined);
869 const entered = Promise.withResolvers<void>();
870 const release = Promise.withResolvers<void>();
871 const runtime = t?.session.extensionRunner.runtime;
872 const setModel = runtime.setModel.bind(runtime);
873 vi.spyOn(runtime, "setModel").mockImplementation(async (model) => {
874 entered.resolve();
875 await release.promise;
876 return setModel(model);
877 });
878 const manual = t?.session.prompt("/masks focused");
879 await entered.promise;
880 try {
881 await t?.session.prompt("/plan blocked");
882 } finally {
883 release.resolve();
884 }
885 await manual;
886 expect(requests).toHaveLength(0);
887 expect(t?.session.model.id).toBe("gpt-4o-mini");
888 expect(t?.session.thinkingLevel).toBe("high");
889 });
531891 it("blocks later prompts until a failed restoration succeeds", async () => {
532892 let failRestore = true;
7621122 ]);
7631123 });
1125 it("validates prompt tool profile shape and uniqueness", () => {
1126 const registered = new Set(["read", "ls"]);
1127 expect(__test.parsePromptTools(["read", "ls"], registered)).toEqual({
1128 tools: ["read", "ls"],
1129 });
1130 expect(__test.parsePromptTools([], registered).error).toMatch(
1131 /non-empty array/,
1132 );
1133 expect(__test.parsePromptTools([" "], registered).error).toMatch(
1134 /non-empty string/,
1135 );
1136 expect(__test.parsePromptTools(["read", "read"], registered).error).toMatch(
1137 /duplicates/,
1138 );
1139 });
7651141 it("keeps a model id containing slashes", () => {
7661142 expect(__test.splitModelRef("provider/org/model")).toEqual([
7671143 "provider",

extensions/masks/index.ts

Modified

+152 / −38 text lines

255255 return /^\/([^\s]+)(?:\s|$)/u.exec(text)?.[1];
258function parsePromptTools(
259 value: unknown,
260 registeredTools: ReadonlySet<string>,
261): { tools?: string[]; error?: string } {
262 if (!Array.isArray(value) || value.length === 0)
263 return { error: "tools must be a non-empty array" };
264 const tools: string[] = [];
265 const seen = new Set<string>();
266 for (const [index, item] of value.entries()) {
267 const name = nonEmptyString(item);
268 if (!name) return { error: `tools[${index}] must be a non-empty string` };
269 if (seen.has(name)) return { error: `tools duplicates "${name}"` };
270 if (!registeredTools.has(name)) return { error: `unknown tool "${name}"` };
271 seen.add(name);
272 tools.push(name);
273 }
274 return { tools };
275}
258277async function applyMask(
259278 pi: ExtensionAPI,
260279 mask: Mask,
283302export default function masksExtension(pi: ExtensionAPI): void {
284303 const { config, errors } = readMasksSettings();
285 let pendingMask: Mask | undefined;
286304 const deferred: Pick<InputEvent, "text" | "images">[] = [];
287 let abortNextRun = false;
288305 let preparing = false;
306 let transitionGeneration = 0;
307 let manualTransition = false;
308 let restoring = false;
309 let applyPromise: Promise<boolean> | undefined;
310 let restorePromise: Promise<void> | undefined;
289311 let detachAbort: (() => void) | undefined;
290312 const terminatingTools = new Set<string>();
291313 let restoreState:
292314 | {
293315 model: NonNullable<ExtensionContext["model"]>;
294316 thinkingLevel: ThinkingLevel;
317 tools?: string[];
318 modelPending: boolean;
319 toolsPending: boolean;
295320 }
296321 | undefined;
318343 handler: async (_args, ctx) => cancelQueue(ctx),
319344 });
346 async function readyForManualMask(ctx: ExtensionContext): Promise<boolean> {
347 if (preparing || restoring || applyPromise) {
348 ctx.ui.notify("Prompt mask transition in progress", "warning");
349 return false;
350 }
351 if (!restoreState) return true;
352 if (!ctx.isIdle()) {
353 ctx.ui.notify("Temporary prompt mask is active", "warning");
354 return false;
355 }
356 await restoreTemporaryMask(ctx);
357 return restoreState === undefined;
358 }
360 async function applyManualMask(
361 mask: Mask,
362 ctx: ExtensionContext,
363 ): Promise<void> {
364 if (manualTransition) {
365 ctx.ui.notify("Prompt mask transition in progress", "warning");
366 return;
367 }
368 manualTransition = true;
369 let ownedPromise: Promise<boolean> | undefined;
370 try {
371 if (!(await readyForManualMask(ctx))) return;
372 ownedPromise = applyMask(pi, mask, ctx);
373 applyPromise = ownedPromise;
374 await ownedPromise;
375 } finally {
376 if (applyPromise === ownedPromise) applyPromise = undefined;
377 manualTransition = false;
378 }
379 }
321381 async function chooseMask(ctx: ExtensionContext): Promise<void> {
382 if (!(await readyForManualMask(ctx))) return;
322383 if (config.items.length === 0) {
323384 ctx.ui.notify("No masks configured in settings.json", "warning");
324385 return;
334395 const index = selected === undefined ? -1 : options.indexOf(selected);
335396 mask = index >= 0 ? config.items[index] : undefined;
336397 }
337 if (mask) await applyMask(pi, mask, ctx);
398 if (mask) await applyManualMask(mask, ctx);
338399 }
340401 pi.registerShortcut(config.pickerShortcut as Shortcut, {
345406 if (!mask.shortcut) continue;
346407 pi.registerShortcut(mask.shortcut as Shortcut, {
347408 description: `Equip mask ${mask.name}`,
348 handler: async (ctx) => {
349 await applyMask(pi, mask, ctx);
350 },
409 handler: async (ctx) => applyManualMask(mask, ctx),
351410 });
352411 }
364423 ctx.ui.notify(`Unknown mask "${name}"`, "error");
365424 return;
366425 }
367 await applyMask(pi, mask, ctx);
426 await applyManualMask(mask, ctx);
368427 },
369428 });
371430 pi.on("input", async (event, ctx) => {
372 if (preparing) {
431 if (preparing || manualTransition || restoring || applyPromise) {
373432 ctx.ui.notify(
374 "Masked prompt is preparing; retry after it starts, or /reload after a dispatch failure",
433 "Masked prompt is transitioning; retry after it starts, or /reload after a dispatch failure",
375434 "warning",
376435 );
377436 return { action: "handled" };
378437 }
379438 if (ctx.isIdle() && restoreState) {
380 preparing = true;
381439 await restoreTemporaryMask(ctx);
382 preparing = false;
383440 if (restoreState) return { action: "handled" };
384441 }
385 pendingMask = undefined;
386442 const commandName = promptCommandName(event.text);
387443 if (!commandName) return { action: "continue" };
388444 const command = pi
431487 showQueue(ctx);
432488 return { action: "handled" };
433489 }
434 pendingMask = mask;
435 preparing = true;
436 return { action: "continue" };
437 });
439 pi.on("before_agent_start", async (_event, ctx) => {
440 const mask = pendingMask;
441 pendingMask = undefined;
442 if (!mask) return;
490 let tools: string[] | undefined;
491 if (Object.hasOwn(frontmatter, "tools")) {
492 const parsed = parsePromptTools(
493 frontmatter.tools,
494 new Set(pi.getAllTools().map((tool) => tool.name)),
495 );
496 if (parsed.error) {
497 if (event.source === "extension") cancelQueue(ctx);
498 ctx.ui.notify(`Prompt /${commandName}: ${parsed.error}`, "error");
499 return { action: "handled" };
500 }
501 tools = parsed.tools;
502 }
443503 if (!ctx.model) {
444504 ctx.ui.notify(
445505 `Mask "${mask.name}": no current model to restore`,
446506 "error",
447507 );
448 abortNextRun = true;
449 return;
508 return { action: "handled" };
450509 }
451510 restoreState = {
452511 model: ctx.model,
453512 thinkingLevel: pi.getThinkingLevel(),
513 ...(tools ? { tools: [...pi.getActiveTools()] } : {}),
514 modelPending: true,
515 toolsPending: tools !== undefined,
454516 };
517 const generation = transitionGeneration;
518 preparing = true;
519 applyPromise = (async () => {
520 if (!(await applyMask(pi, mask, ctx))) return false;
521 if (!tools) return true;
522 pi.setActiveTools(tools);
523 const active = pi.getActiveTools();
524 if (
525 active.length !== tools.length ||
526 active.some((name, index) => name !== tools[index])
527 )
528 throw new Error("tool profile could not be applied exactly");
529 return true;
530 })();
531 let applied = false;
455532 try {
456 abortNextRun = !(await applyMask(pi, mask, ctx));
533 applied = await applyPromise;
457534 } catch (error) {
458 abortNextRun = true;
459535 ctx.ui.notify(`Failed to equip prompt mask: ${String(error)}`, "error");
536 } finally {
537 applyPromise = undefined;
460538 }
539 if (!applied || generation !== transitionGeneration) {
540 if (!applied) cancelQueue(ctx);
541 await restoreTemporaryMask(ctx);
542 preparing = false;
543 return { action: "handled" };
544 }
545 return { action: "continue" };
461546 });
463548 pi.on("agent_start", (_event, ctx) => {
468553 signal?.addEventListener("abort", cancel, { once: true });
469554 detachAbort = () => signal?.removeEventListener("abort", cancel);
470555 if (signal?.aborted) cancel();
471 if (!abortNextRun) return;
472 abortNextRun = false;
473 cancelQueue(ctx);
474 ctx.abort();
475556 });
477558 async function restoreTemporaryMask(ctx: ExtensionContext): Promise<void> {
559 if (restorePromise) return restorePromise;
478560 const previous = restoreState;
479561 if (!previous) return;
480 try {
481 if (!(await pi.setModel(previous.model)))
482 throw new Error("Model unavailable");
483 pi.setThinkingLevel(previous.thinkingLevel);
484 restoreState = undefined;
485 } catch (error) {
562 restoring = true;
563 restorePromise = (async () => {
564 const failures: string[] = [];
565 if (previous.modelPending) {
566 try {
567 if (!(await pi.setModel(previous.model)))
568 throw new Error("model unavailable");
569 pi.setThinkingLevel(previous.thinkingLevel);
570 previous.modelPending = false;
571 } catch (error) {
572 failures.push(`model: ${String(error)}`);
573 }
574 }
575 if (previous.toolsPending && previous.tools) {
576 try {
577 pi.setActiveTools(previous.tools);
578 const active = pi.getActiveTools();
579 if (
580 active.length !== previous.tools.length ||
581 active.some((name, index) => name !== previous.tools?.[index])
582 )
583 throw new Error("tool snapshot could not be restored exactly");
584 previous.toolsPending = false;
585 } catch (error) {
586 failures.push(`tools: ${String(error)}`);
587 }
588 }
589 if (!previous.modelPending && !previous.toolsPending) {
590 if (restoreState === previous) restoreState = undefined;
591 return;
592 }
486593 cancelQueue(ctx);
487594 ctx.ui.notify(
488 `Failed to restore model after prompt mask: ${String(error)}`,
595 `Failed to restore prompt mask: ${failures.join("; ")}`,
489596 "error",
490597 );
491598 ctx.abort();
599 })();
600 try {
601 await restorePromise;
602 } finally {
603 restorePromise = undefined;
604 restoring = false;
492605 }
493606 }
537650 for (const error of errors) ctx.ui.notify(error, "warning");
538651 });
539652 async function reset(ctx: ExtensionContext): Promise<void> {
540 pendingMask = undefined;
541 abortNextRun = false;
653 transitionGeneration++;
542654 preparing = false;
543655 detachAbort?.();
544656 detachAbort = undefined;
545657 cancelQueue(ctx);
658 await applyPromise;
546659 await restoreTemporaryMask(ctx);
547660 }
548661 pi.on("session_tree", async (_event, ctx) => reset(ctx));
554667 chooseFuzzyMask,
555668 fuzzyMasks,
556669 parseMasksSettings,
670 parsePromptTools,
557671 promptCommandName,
558672 splitModelRef,
559673};

extensions/masks/package.json

Modified

+1 / −1 text lines

77 "@earendil-works/pi-tui": "*"
88 },
99 "license": "MIT",
10 "description": "Named model and thinking combinations for Pi.",
10 "description": "Named model and thinking combinations with prompt-scoped tool profiles for Pi.",
1111 "keywords": [
1212 "pi",
1313 "pi-extension"