repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

fix(masks): preserve masks through recovery and queued work

47c455158deff60694ab85eb016dcfd7e90eaf76

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (3)

extensions/masks/README.md

Modified
14 14 - `/masks` opens the fuzzy mask picker.
15 15 - `/masks <name>` equips one mask directly.
16 +- `/masks-cancel` discards deferred masked prompts without interrupting the current run.
17 18 Tools:
18 19 none.
20 21 Hooks:
22 -- `input` detects prompt templates declaring a mask.
23 +- `input` detects masked templates and defers busy follow-ups.
23 24 - `before_agent_start` equips a prompt mask.
24 -- `agent_end` restores the previous model and thinking level.
25 +- `turn_end` restores after successful completion; `agent_settled` restores after recovery and starts the next deferred prompt.
25 26 - `session_start` reports invalid mask settings.
27 28 Settings:
50 51 Settings are global because masks describe personal model access and bindings.
51 52 Run `/reload` after changing them.
53 -Prompt templates may equip a mask for one agent run:
54 +Prompt templates may equip a mask for one prompt and its tool loop:
55 56 ```markdown
63 64 `mask` must exactly match a configured mask name.
64 -The mask lasts through the prompt's tool loop and is restored at `agent_end`.
65 -Masked prompts cannot be queued while another agent run is active.
65 +The mask lasts through tools and automatic retries, then restores before the next ordinary follow-up.
66 +Failed mask switches abort the prompt; failed restoration blocks later prompts until restoration succeeds.
68 +Busy masked follow-ups use an extension-owned FIFO queue, shown in the footer.
69 +They run after Pi's native queue drains, not in mixed submission order.
70 +Templates and masks are resolved at execution; attached images are preserved.
71 +Steering a masked template is rejected because it would change the current run's model.
72 +Abort, error, tree navigation, and session shutdown discard deferred prompts.
73 +Pi's native queue editor does not manage this queue; use `/masks-cancel`.
75 +Pi provides no dispatch acknowledgement: rejected or failed dispatches can lose a prompt and stall the remaining queue.
76 +Concurrent input during masked preparation is rejected instead of risking the wrong model.
77 +If dispatch fails during preparation, `/reload` clears the reservation and deferred queue.
67 79 ## Behavior

extensions/masks/__tests__/harness.test.ts

Modified
2 2 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3 3 import { tmpdir } from "node:os";
4 4 import { join } from "node:path";
5 5 import { fileURLToPath } from "node:url";
6 -import { afterEach, describe, expect, it } from "vitest";
6 +import { afterEach, describe, expect, it, vi } from "vitest";
7 7 import { createTestSession, type TestSession } from "../../../test/harness";
8 8 import { __test } from "../index.ts";
38 38 return t.session.extensionRunner.createCommandContext();
41 +type Request = { text: string; model: string; thinking: string | undefined };
43 +async function queuedSession(
44 + onRequest: (
45 + request: Request,
46 + index: number,
47 + ) => Promise<Record<string, unknown> | undefined>,
48 +): Promise<Request[]> {
49 + const cwd = writeSettings({
50 + masks: {
51 + items: [
52 + { name: "focused", model: "openai/gpt-4o-mini", thinkingLevel: "high" },
53 + { name: "quick", model: "openai/gpt-4o", thinkingLevel: "low" },
54 + ],
55 + },
56 + });
57 + writePrompt("review", "---\nmask: focused\n---\nReview $1.");
58 + writePrompt("plan", "---\nmask: quick\n---\nPlan $1.");
59 + writeFileSync(join(cwd, "fixture.txt"), "fixture");
60 + t = await createTestSession({ cwd, extensions: [extensionPath()] });
61 + for (const name of ["gpt-4o", "gpt-4o-mini"]) {
62 + context().modelRegistry.find("openai", name).reasoning = true;
63 + }
64 + t.session.settingsManager.setRetryEnabled(false);
65 + const requests: Request[] = [];
66 + t.session.agent.streamFn = async (model: any, ctx: any, options: any) => {
67 + const request = {
68 + text: ctx.messages
69 + .filter((m: any) => m.role === "user")
70 + .at(-1)
71 + ?.content.filter((p: any) => p.type === "text")
72 + .map((p: any) => p.text)
73 + .join(""),
74 + model: model.id,
75 + thinking: options.reasoning,
76 + };
77 + let reply: Record<string, unknown> | undefined;
78 + if (!options.signal.aborted) {
79 + requests.push(request);
80 + reply = await onRequest(request, requests.length - 1);
81 + }
82 + const message = {
83 + role: "assistant",
84 + content: [{ type: "text", text: "Done." }],
85 + api: model.api,
86 + provider: model.provider,
87 + model: model.id,
88 + usage: {
89 + input: 1,
90 + output: 1,
91 + cacheRead: 0,
92 + cacheWrite: 0,
93 + totalTokens: 2,
94 + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
95 + },
96 + stopReason: options.signal.aborted ? "aborted" : "stop",
97 + timestamp: Date.now(),
98 + ...reply,
99 + };
100 + return {
101 + async *[Symbol.asyncIterator]() {
102 + yield { type: "done", reason: message.stopReason, message };
103 + },
104 + result: async () => message,
105 + };
106 + };
107 + return requests;
110 +async function queue(text: string): Promise<void> {
111 + await t?.session.sendUserMessage(text, {
112 + expandPromptTemplates: true,
113 + deliverAs: "followUp",
114 + });
117 +async function settled(count: number, requests: Request[]): Promise<void> {
118 + await expect.poll(() => requests.length).toBe(count);
119 + await expect.poll(() => t?.session.isIdle).toBe(true);
41 122 afterEach(() => {
123 + vi.restoreAllMocks();
42 124 t?.dispose();
43 125 t = undefined;
44 126 if (root) rmSync(root, { recursive: true, force: true });
82 164 if (!model) throw new Error("missing harness model");
83 165 model.reasoning = true;
85 - expect([...extension().commands.keys()]).toEqual(["masks"]);
167 + expect([...extension().commands.keys()]).toEqual(["masks-cancel", "masks"]);
86 168 expect([...extension().shortcuts.keys()]).toEqual([
87 169 "alt+m",
88 170 "alt+1",
141 223 const inputHandler = extension().handlers.get("input")[0];
142 224 const beforeHandler = extension().handlers.get("before_agent_start")[0];
143 - const endHandler = extension().handlers.get("agent_end")[0];
225 + const endHandler = extension().handlers.get("agent_settled")[0];
144 226 expect(
145 227 await inputHandler(
146 228 { type: "input", text: "/review", source: "interactive" },
161 243 expect(t.session.thinkingLevel).toBe("high");
163 - await endHandler({ type: "agent_end", messages: [] }, context());
245 + await endHandler({ type: "agent_settled" }, context());
164 246 expect(t.session.model.provider).toBe("openai");
165 247 expect(t.session.model.id).toBe("gpt-4o");
166 248 expect(t.session.thinkingLevel).toBe("off");
169 - it("rejects masked prompt templates queued mid-run", async () => {
251 + it("defers masked follow-ups without changing the running model", async () => {
170 252 const cwd = writeSettings({
171 253 masks: {
172 254 items: [
194 276 expect(result).toEqual({ action: "handled" });
195 - expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
196 - "Prompt /review: masked prompts cannot be queued mid-run",
277 + expect(t.session.thinkingLevel).toBe("off");
278 + expect(t.events.uiCallsFor("setStatus").at(-1)?.args).toEqual([
279 + "masks-queue",
280 + "masks: 1 deferred · /masks-cancel",
281 + ]);
282 + });
284 + it("runs deferred masks FIFO after native follow-ups and restores between them", async () => {
285 + const requests = await queuedSession(async (_request, index) => {
286 + if (index === 0) {
287 + await queue("/review first");
288 + await queue("ordinary follow-up");
289 + await queue("/plan second");
290 + expect(t?.session.model.id).toBe("gpt-4o");
292 + return undefined;
293 + });
294 + await t?.session.prompt("start");
295 + await settled(4, requests);
296 + expect(requests).toEqual([
297 + { text: "start", model: "gpt-4o", thinking: undefined },
298 + { text: "ordinary follow-up", model: "gpt-4o", thinking: undefined },
299 + { text: "Review first.", model: "gpt-4o-mini", thinking: "high" },
300 + { text: "Plan second.", model: "gpt-4o", thinking: "low" },
301 + ]);
302 + expect(t?.session.model.id).toBe("gpt-4o");
303 + expect(t?.session.thinkingLevel).toBe("off");
304 + });
306 + it("keeps the mask through tools, then restores before an ordinary follow-up", async () => {
307 + const requests = await queuedSession(async (_request, index) => {
308 + if (index === 0) {
309 + await queue("ordinary follow-up");
310 + return {
311 + content: [
313 + type: "toolCall",
314 + id: "read-fixture",
315 + name: "read",
316 + arguments: { path: "fixture.txt" },
317 + },
318 + ],
319 + stopReason: "toolUse",
320 + };
322 + return undefined;
323 + });
324 + await t?.session.prompt("/review first");
325 + await settled(3, requests);
326 + expect(
327 + requests.map(({ model, thinking }) => ({ model, thinking })),
328 + ).toEqual([
329 + { model: "gpt-4o-mini", thinking: "high" },
330 + { model: "gpt-4o-mini", thinking: "high" },
331 + { model: "gpt-4o", thinking: undefined },
332 + ]);
333 + });
335 + it.each(["aborted", "error"])(
336 + "discards deferred masks on %s and restores",
337 + async (stopReason) => {
338 + const requests = await queuedSession(async () => {
339 + await queue("/plan later");
340 + return { stopReason, errorMessage: "test failure" };
341 + });
342 + await t?.session.prompt("/review now");
343 + await settled(1, requests);
344 + expect(t?.session.model.id).toBe("gpt-4o");
345 + expect(t?.session.thinkingLevel).toBe("off");
346 + expect(t?.events.uiCallsFor("notify").at(-1)?.args).toEqual([
347 + "Cancelled 1 deferred masked prompts",
348 + "warning",
349 + ]);
350 + },
351 + );
353 + it("cancels deferred prompts explicitly without stopping the current run", async () => {
354 + const requests = await queuedSession(async () => {
355 + await queue("/plan later");
356 + await t?.session.prompt("/masks-cancel");
357 + expect(context().signal?.aborted).toBe(false);
358 + return undefined;
359 + });
360 + await t?.session.prompt("/review now");
361 + await settled(1, requests);
362 + expect(t?.session.thinkingLevel).toBe("off");
363 + });
365 + it("rejects steering without changing the active mask", async () => {
366 + const requests = await queuedSession(async () => {
367 + await t?.session.sendUserMessage("/plan later", {
368 + expandPromptTemplates: true,
369 + deliverAs: "steer",
370 + });
371 + expect(t?.session.thinkingLevel).toBe("high");
372 + return undefined;
373 + });
374 + await t?.session.prompt("/review now");
375 + await settled(1, requests);
376 + expect(t?.events.uiCallsFor("notify").at(-1)?.args).toEqual([
377 + "Prompt /plan: use follow-up delivery, not steering",
197 378 "warning",
382 + it.each(["session_tree", "session_shutdown"])(
383 + "clears deferred prompts on %s",
384 + async (type) => {
385 + const requests = await queuedSession(async () => undefined);
386 + await extension().handlers.get("input")[0](
388 + type: "input",
389 + text: "/plan later",
390 + source: "extension",
391 + streamingBehavior: "followUp",
392 + },
393 + { ...context(), isIdle: () => false },
394 + );
395 + await extension().handlers.get(type)[0](
396 + { type, reason: "reload" },
397 + context(),
398 + );
399 + await extension().handlers.get("agent_settled")[0](
400 + { type: "agent_settled" },
401 + context(),
402 + );
403 + expect(requests).toHaveLength(0);
404 + expect(t?.events.uiCallsFor("setStatus").at(-1)?.args).toEqual([
405 + "masks-queue",
406 + undefined,
407 + ]);
408 + },
409 + );
411 + it("does not run the prompt under the wrong model when equipping fails", async () => {
412 + const requests = await queuedSession(async () => undefined);
413 + vi.spyOn(t?.session.extensionRunner.runtime, "setModel").mockResolvedValue(
414 + false,
415 + );
416 + await t?.session.prompt("/review now");
417 + expect(requests).toHaveLength(0);
418 + expect(
419 + t?.events
420 + .uiCallsFor("notify")
421 + .some((call) => String(call.args[0]).includes("no credentials")),
422 + ).toBe(true);
423 + });
425 + it("cancels deferred prompts and aborts when restoration fails", async () => {
426 + const requests = await queuedSession(async () => {
427 + await queue("/plan later");
428 + vi.spyOn(
429 + t?.session.extensionRunner.runtime,
430 + "setModel",
431 + ).mockRejectedValue(new Error("offline"));
432 + return undefined;
433 + });
434 + await t?.session.prompt("/review now");
435 + await settled(1, requests);
436 + expect(
437 + t?.events
438 + .uiCallsFor("notify")
439 + .some((call) => String(call.args[0]).includes("Failed to restore")),
440 + ).toBe(true);
441 + });
443 + it("retains the mask through automatic retry", async () => {
444 + const requests = await queuedSession(async (_request, index) =>
445 + index === 0
446 + ? { stopReason: "error", errorMessage: "503 service unavailable" }
447 + : undefined,
448 + );
449 + vi.spyOn(t?.session.settingsManager, "getRetrySettings").mockReturnValue({
450 + enabled: true,
451 + maxRetries: 1,
452 + baseDelayMs: 1,
453 + });
454 + await t?.session.prompt("/review retry");
455 + await settled(2, requests);
456 + expect(
457 + requests.map(({ model, thinking }) => ({ model, thinking })),
458 + ).toEqual([
459 + { model: "gpt-4o-mini", thinking: "high" },
460 + { model: "gpt-4o-mini", thinking: "high" },
461 + ]);
462 + expect(t?.session.model.id).toBe("gpt-4o");
463 + expect(t?.session.thinkingLevel).toBe("off");
464 + });
466 + it("keeps the mask for overflow recovery instead of skipping the same-model check", async () => {
467 + const requests = await queuedSession(async (_request, index) =>
468 + index === 0
469 + ? {
470 + stopReason: "error",
471 + errorMessage: "maximum context length exceeded",
473 + : undefined,
474 + );
475 + const compact = vi
476 + .spyOn(t?.session, "_runAutoCompaction")
477 + .mockImplementation(async () => {
478 + expect(t?.session.model.id).toBe("gpt-4o-mini");
479 + return true;
480 + });
481 + await t?.session.prompt("/review overflow");
482 + await settled(2, requests);
483 + expect(compact).toHaveBeenCalledWith("overflow", true);
484 + expect(requests[1]).toEqual({
485 + text: "Review overflow.",
486 + model: "gpt-4o-mini",
487 + thinking: "high",
488 + });
489 + expect(t?.session.thinkingLevel).toBe("off");
490 + });
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 + });
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();
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 + );
531 + it("blocks later prompts until a failed restoration succeeds", async () => {
532 + let failRestore = true;
533 + const requests = await queuedSession(async () => undefined);
534 + const runtime = t?.session.extensionRunner.runtime;
535 + const setModel = runtime.setModel.bind(runtime);
536 + vi.spyOn(runtime, "setModel").mockImplementation(async (model: any) => {
537 + if (model.id === "gpt-4o" && failRestore) return false;
538 + return setModel(model);
539 + });
540 + await t?.session.prompt("/review first");
541 + await t?.session.prompt("ordinary blocked prompt");
542 + await t?.session.prompt("/plan blocked");
543 + expect(requests).toHaveLength(1);
544 + failRestore = false;
545 + await t?.session.prompt("ordinary recovered prompt");
546 + expect(requests[1]).toEqual({
547 + text: "ordinary recovered prompt",
548 + model: "gpt-4o",
549 + thinking: undefined,
550 + });
551 + });
553 + it("cancels deferred prompts on a late abort after a successful response", async () => {
554 + const requests = await queuedSession(async () => {
555 + await queue("/plan later");
556 + return undefined;
557 + });
558 + const runtime = t?.session.extensionRunner.runtime;
559 + const setModel = runtime.setModel.bind(runtime);
560 + vi.spyOn(runtime, "setModel").mockImplementation(async (model: any) => {
561 + if (model.id === "gpt-4o") context().abort();
562 + return setModel(model);
563 + });
564 + await t?.session.prompt("/review now");
565 + await settled(1, requests);
566 + expect(t?.events.uiCallsFor("notify").at(-1)?.args).toEqual([
567 + "Cancelled 1 deferred masked prompts",
568 + "warning",
569 + ]);
570 + expect(t?.session.thinkingLevel).toBe("off");
571 + });
573 + it("restores before a native follow-up after a terminating tool batch", async () => {
574 + const requests = await queuedSession(async (_request, index) => {
575 + if (index !== 0) return undefined;
576 + await queue("ordinary follow-up");
577 + return {
578 + content: [
580 + type: "toolCall",
581 + id: "blocked-read",
582 + name: "read",
583 + arguments: { path: "fixture.txt" },
584 + },
585 + ],
586 + stopReason: "toolUse",
587 + };
588 + });
589 + extension().handlers.set("tool_call", [
590 + async () => ({ block: true, terminate: true, reason: "Finished" }),
591 + ]);
592 + await t?.session.prompt("/review now");
593 + await settled(2, requests);
594 + expect(requests[1]).toEqual({
595 + text: "ordinary follow-up",
596 + model: "gpt-4o",
597 + thinking: undefined,
598 + });
599 + });
601 + it("preserves images and repeated masked follow-ups", async () => {
602 + const image = {
603 + type: "image",
604 + mimeType: "image/png",
605 + data: "fixture-image",
606 + };
607 + const requests = await queuedSession(async (_request, index) => {
608 + if (index === 0) {
609 + await t?.session.sendUserMessage(
610 + [{ type: "text", text: "/review same" }, image],
612 + expandPromptTemplates: true,
613 + deliverAs: "followUp",
614 + },
615 + );
616 + await queue("/review same");
618 + return undefined;
619 + });
620 + await t?.session.prompt("start");
621 + await settled(3, requests);
622 + expect(requests.slice(1)).toEqual([
623 + { text: "Review same.", model: "gpt-4o-mini", thinking: "high" },
624 + { text: "Review same.", model: "gpt-4o-mini", thinking: "high" },
625 + ]);
626 + expect(t?.events.messages).toContainEqual(
627 + expect.objectContaining({
628 + role: "user",
629 + content: [{ type: "text", text: "Review same." }, image],
630 + }),
631 + );
632 + });
634 + it("defers busy input during recovery when Pi omits streamingBehavior", async () => {
635 + const requests = await queuedSession(async () => undefined);
636 + await extension().handlers.get("input")[0](
637 + { type: "input", text: "/plan later", source: "extension" },
638 + { ...context(), isIdle: () => false },
639 + );
640 + await extension().handlers.get("agent_settled")[0](
641 + { type: "agent_settled" },
642 + context(),
643 + );
644 + await settled(1, requests);
645 + expect(requests[0]).toEqual({
646 + text: "Plan later.",
647 + model: "gpt-4o",
648 + thinking: "low",
649 + });
650 + });
201 652 it("fuzzy-matches non-prefix mask queries", () => {
202 653 const parsed = __test.parseMasksSettings({
203 654 items: [

extensions/masks/index.ts

Modified
2 2 import { readFileSync } from "node:fs";
3 3 import type {
4 4 ExtensionAPI,
5 5 ExtensionContext,
6 + InputEvent,
6 7 } from "@earendil-works/pi-coding-agent";
7 8 import {
8 9 DynamicBorder,
20 21 const SETTINGS_KEY = "masks";
21 22 const DEFAULT_PICKER_SHORTCUT = "alt+m";
23 +type ThinkingLevel = Parameters<ExtensionAPI["setThinkingLevel"]>[0];
22 24 const THINKING_LEVELS = [
23 25 "off",
24 26 "minimal",
27 29 "high",
28 30 "xhigh",
29 31 "max",
30 -] as const;
32 +] as const satisfies readonly ThinkingLevel[];
32 -type ThinkingLevel = (typeof THINKING_LEVELS)[number];
33 34 type Shortcut = Parameters<ExtensionAPI["registerShortcut"]>[0];
35 36 interface Mask {
282 283 export default function masksExtension(pi: ExtensionAPI): void {
283 284 const { config, errors } = readMasksSettings();
284 285 let pendingMask: Mask | undefined;
286 + const deferred: Pick<InputEvent, "text" | "images">[] = [];
287 + let abortNextRun = false;
288 + let preparing = false;
289 + let detachAbort: (() => void) | undefined;
290 + const terminatingTools = new Set<string>();
285 291 let restoreState:
287 293 model: NonNullable<ExtensionContext["model"]>;
290 296 | undefined;
298 + function showQueue(ctx: ExtensionContext): void {
299 + ctx.ui.setStatus(
300 + "masks-queue",
301 + deferred.length
302 + ? `masks: ${deferred.length} deferred · /masks-cancel`
303 + : undefined,
304 + );
307 + function cancelQueue(ctx: ExtensionContext): void {
308 + const count = deferred.length;
309 + deferred.length = 0;
310 + showQueue(ctx);
311 + if (count)
312 + ctx.ui.notify(`Cancelled ${count} deferred masked prompts`, "warning");
315 + pi.registerCommand("masks-cancel", {
316 + description:
317 + "Cancel deferred masked prompts without interrupting the current run",
318 + handler: async (_args, ctx) => cancelQueue(ctx),
319 + });
292 321 async function chooseMask(ctx: ExtensionContext): Promise<void> {
293 322 if (config.items.length === 0) {
294 323 ctx.ui.notify("No masks configured in settings.json", "warning");
342 - pi.on("input", (event, ctx) => {
371 + pi.on("input", async (event, ctx) => {
372 + if (preparing) {
373 + ctx.ui.notify(
374 + "Masked prompt is preparing; retry after it starts, or /reload after a dispatch failure",
375 + "warning",
376 + );
377 + return { action: "handled" };
379 + if (ctx.isIdle() && restoreState) {
380 + preparing = true;
381 + await restoreTemporaryMask(ctx);
382 + preparing = false;
383 + if (restoreState) return { action: "handled" };
343 385 pendingMask = undefined;
344 386 const commandName = promptCommandName(event.text);
345 387 if (!commandName) return { action: "continue" };
378 420 return { action: "handled" };
380 422 if (!ctx.isIdle()) {
381 - ctx.ui.notify(
382 - `Prompt /${commandName}: masked prompts cannot be queued mid-run`,
383 - "warning",
384 - );
423 + if (event.streamingBehavior === "steer") {
424 + ctx.ui.notify(
425 + `Prompt /${commandName}: use follow-up delivery, not steering`,
426 + "warning",
427 + );
428 + return { action: "handled" };
430 + deferred.push({ text: event.text, images: event.images });
431 + showQueue(ctx);
385 432 return { action: "handled" };
387 434 pendingMask = mask;
435 + preparing = true;
388 436 return { action: "continue" };
397 445 `Mask "${mask.name}": no current model to restore`,
398 446 "error",
448 + abortNextRun = true;
400 449 return;
402 - const previous = {
451 + restoreState = {
403 452 model: ctx.model,
404 453 thinkingLevel: pi.getThinkingLevel(),
406 - if (await applyMask(pi, mask, ctx)) restoreState = previous;
455 + try {
456 + abortNextRun = !(await applyMask(pi, mask, ctx));
457 + } catch (error) {
458 + abortNextRun = true;
459 + ctx.ui.notify(`Failed to equip prompt mask: ${String(error)}`, "error");
461 + });
463 + pi.on("agent_start", (_event, ctx) => {
464 + preparing = false;
465 + detachAbort?.();
466 + const signal = ctx.signal;
467 + const cancel = () => cancelQueue(ctx);
468 + signal?.addEventListener("abort", cancel, { once: true });
469 + detachAbort = () => signal?.removeEventListener("abort", cancel);
470 + if (signal?.aborted) cancel();
471 + if (!abortNextRun) return;
472 + abortNextRun = false;
473 + cancelQueue(ctx);
474 + ctx.abort();
409 477 async function restoreTemporaryMask(ctx: ExtensionContext): Promise<void> {
410 478 const previous = restoreState;
411 - restoreState = undefined;
412 479 if (!previous) return;
413 - if (!(await pi.setModel(previous.model))) {
414 - ctx.ui.notify("Failed to restore model after prompt mask", "error");
415 - 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) {
486 + cancelQueue(ctx);
487 + ctx.ui.notify(
488 + `Failed to restore model after prompt mask: ${String(error)}`,
489 + "error",
490 + );
491 + ctx.abort();
417 - pi.setThinkingLevel(previous.thinkingLevel);
420 - pi.on("agent_end", async (_event, ctx) => restoreTemporaryMask(ctx));
495 + pi.on("turn_start", () => terminatingTools.clear());
496 + pi.on("tool_execution_end", (event) => {
497 + if (event.result.terminate === true) terminatingTools.add(event.toolCallId);
498 + });
499 + pi.on("turn_end", async (event, ctx) => {
500 + if (event.message.role !== "assistant") return;
501 + const tools = event.message.content.filter(
502 + (part) => part.type === "toolCall",
503 + );
504 + if (
505 + tools.length
506 + ? tools.every((tool) => terminatingTools.has(tool.id))
507 + : event.message.stopReason === "stop"
508 + ) {
509 + await restoreTemporaryMask(ctx);
511 + });
512 + pi.on("agent_end", async (event, ctx) => {
513 + if (
514 + event.messages.some(
515 + (message) =>
516 + message.role === "assistant" &&
517 + (message.stopReason === "aborted" || message.stopReason === "error"),
520 + cancelQueue(ctx);
521 + });
522 + pi.on("agent_settled", async (_event, ctx) => {
523 + if (!ctx.isIdle()) return;
524 + await restoreTemporaryMask(ctx);
525 + detachAbort?.();
526 + detachAbort = undefined;
527 + if (restoreState || preparing || !ctx.isIdle()) return;
528 + const next = deferred.shift();
529 + if (!next) return;
530 + showQueue(ctx);
531 + pi.sendUserMessage(
532 + [{ type: "text", text: next.text }, ...(next.images ?? [])],
533 + { expandPromptTemplates: true, deliverAs: "followUp" },
534 + );
535 + });
421 536 pi.on("session_start", (_event, ctx) => {
422 537 for (const error of errors) ctx.ui.notify(error, "warning");
424 - pi.on("session_shutdown", async (_event, ctx) => {
539 + async function reset(ctx: ExtensionContext): Promise<void> {
425 540 pendingMask = undefined;
541 + abortNextRun = false;
542 + preparing = false;
543 + detachAbort?.();
544 + detachAbort = undefined;
545 + cancelQueue(ctx);
426 546 await restoreTemporaryMask(ctx);
427 - });
548 + pi.on("session_tree", async (_event, ctx) => reset(ctx));
549 + pi.on("session_shutdown", async (_event, ctx) => reset(ctx));
430 552 export const __test = {