@narumitw/pi-plan-mode 0.52.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/plan-mode.ts CHANGED
@@ -14,20 +14,42 @@ import {
14
14
  planModeCompleted,
15
15
  renderPlanModeCompletion,
16
16
  } from "./completion-tool.js";
17
+ import { isStaleExtensionContextError } from "./extension-runtime.js";
17
18
  import {
18
- isStaleExtensionContextError,
19
- onAgentSettled,
20
- setPlanThinkingLevel,
21
- } from "./extension-runtime.js";
19
+ createFinalizationRequestCoordinator,
20
+ FINALIZE_PLAN_PROMPT,
21
+ type FinalizationRunOutcome,
22
+ RETRY_FINALIZE_PLAN_PROMPT,
23
+ } from "./finalization-request.js";
22
24
  import {
25
+ formatHistoryImplementationPrompt,
23
26
  formatImplementationHandoff,
27
+ formatTransferredPlanPrompt,
24
28
  startFreshImplementationFromState,
25
29
  } from "./fresh-implementation.js";
30
+ import {
31
+ PlanModeHelperVisibilityPolicy,
32
+ type PlanModeHelperVisibilitySnapshot,
33
+ } from "./helper-tool-visibility.js";
26
34
  import {
27
35
  createImplementationRetentionCoordinator,
28
36
  implementationRetentionPreview,
29
37
  } from "./implementation-retention.js";
30
- import { invalidPlanMessage, latestAssistantText, parseProposedPlan } from "./message-transform.js";
38
+ import {
39
+ invalidPlanMessage,
40
+ latestAssistantStopReason,
41
+ latestAssistantText,
42
+ messageTextContent,
43
+ parseProposedPlan,
44
+ } from "./message-transform.js";
45
+ import {
46
+ createModeContractMessage,
47
+ hasModeContractArtifact,
48
+ latestModeContract,
49
+ MODE_CONTRACT_MESSAGE_TYPE,
50
+ type PlanModeContract,
51
+ reconcileModeContract,
52
+ } from "./mode-contract.js";
31
53
  import { createPlanActionController } from "./plan-action-controller.js";
32
54
  import { createPlanExportController } from "./plan-export-controller.js";
33
55
  import {
@@ -36,7 +58,6 @@ import {
36
58
  showStoredPlan,
37
59
  updatePlanModeUi,
38
60
  } from "./presentation.js";
39
- import { buildPlanModePrompt } from "./prompt.js";
40
61
  import {
41
62
  answerPlanModeQuestions,
42
63
  normalizePlanModeQuestionParams,
@@ -44,7 +65,7 @@ import {
44
65
  PLAN_MODE_QUESTION_TOOL_NAME,
45
66
  planModeQuestionCancelled,
46
67
  } from "./question-tool.js";
47
- import { withoutRequiredPlanModeTools, withRequiredPlanModeTools } from "./required-tools.js";
68
+ import { withRequiredPlanModeTools } from "./required-tools.js";
48
69
  import {
49
70
  preflightSavedPlanImplementation,
50
71
  savedPlanBlocksNewWorkflow,
@@ -53,30 +74,35 @@ import {
53
74
  awaitPlanModeSettingsWrites,
54
75
  configuredImplementationPlanRetention,
55
76
  configuredPlanModeToggleShortcut,
77
+ configuredPlanModeToolVisibility,
56
78
  configuredThinkingLevel,
57
79
  type PlanModeSettings,
80
+ type PlanModeSettingsPatch,
81
+ type PlanModeToolVisibility,
58
82
  planModeSettingsPath,
59
83
  readPlanModeSettings,
84
+ type UpdatePlanModeSettingsOptions,
85
+ updatePlanModeSettings,
60
86
  } from "./settings.js";
61
87
  import { type PlanCompletionSource, type PlanModeState, restorePlanModeState } from "./state.js";
62
88
  import {
63
89
  canSelectToolInPlanMode,
64
90
  classifyPlanModeTool,
65
91
  findBlockedCommandSegment,
92
+ findBlockedPowerShellCommandSegment,
66
93
  readCommand,
67
94
  } from "./tool-policy.js";
68
95
  import {
69
96
  compareTools,
70
97
  filterAvailableSelectedToolNames,
71
98
  snapshotPlanModeSelectedNames,
72
- snapshotPlanModeToolNames,
73
99
  toolPolicyLabel,
74
100
  } from "./tool-selection.js";
75
101
  import { WorkflowMutex, type WorkflowMutexOwner } from "./workflow-mutex.js";
76
102
 
77
103
  const STATE_ENTRY_TYPE = "plan-mode-state";
78
104
  const PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
79
- const BLOCKED_BUILTIN_TOOLS = new Set(["edit", "write"]);
105
+ const BLOCKED_MUTATING_TOOLS = new Set(["edit", "write", "update_plan"]);
80
106
  const DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
81
107
  interface ReadyPresentationIntent {
82
108
  nonce: number;
@@ -87,6 +113,10 @@ type InteractiveUi = typeof import("./interactive-ui.js");
87
113
 
88
114
  interface PlanModeDependencies {
89
115
  readSettings?(): ReturnType<typeof readPlanModeSettings>;
116
+ updateSettings?(
117
+ patch: PlanModeSettingsPatch,
118
+ options?: UpdatePlanModeSettingsOptions,
119
+ ): ReturnType<typeof updatePlanModeSettings>;
90
120
  settingsPath?: string;
91
121
  loadInteractiveUi?(): Promise<InteractiveUi>;
92
122
  }
@@ -95,8 +125,10 @@ interface PlanModeDependencies {
95
125
  // activation path cannot bypass the same atomic transition by crossing module-owned state.
96
126
  export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDependencies = {}) {
97
127
  const workflowMutex = new WorkflowMutex(pi);
128
+ const helperVisibility = new PlanModeHelperVisibilityPolicy(pi);
98
129
  let workflowOwner: WorkflowMutexOwner | undefined;
99
130
  let currentSession: object | undefined;
131
+ let currentSessionContext: ExtensionContext | undefined;
100
132
  let interactiveUiPromise: Promise<InteractiveUi> | undefined;
101
133
  const loadInteractiveUi = () => {
102
134
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
@@ -113,7 +145,10 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
113
145
  let settings: PlanModeSettings = { thinkingLevel: "inherit" };
114
146
  let toggleShortcut: ReturnType<typeof configuredPlanModeToggleShortcut>;
115
147
  const clearPlanModeShortcutHandler = () => {};
116
- let previousTools: string[] | undefined;
148
+ let activeToolBaseline: string[] = [];
149
+ let workflowAllowedToolNames: string[] | undefined;
150
+ let publishedContractMode: PlanModeContract | undefined;
151
+ let modeContractsRelevant = false;
117
152
  let readyPresentationIntent: ReadyPresentationIntent | undefined;
118
153
  let latestCommandContext: ExtensionCommandContext | undefined;
119
154
  let nextReadyPresentationNonce = 0;
@@ -124,11 +159,14 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
124
159
  let settingsWatch: ReturnType<typeof watch> | undefined;
125
160
  let settingsReloadTimer: ReturnType<typeof setTimeout> | undefined;
126
161
  const implementationRetention = createImplementationRetentionCoordinator();
162
+ const finalizationRequest = createFinalizationRequestCoordinator();
127
163
  const persistState = () => pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, state);
128
164
  const planExports = createPlanExportController({
129
165
  getState: () => state,
130
166
  getSettings: () => settings,
131
- finishReady: (ctx) => exitPlanMode(ctx),
167
+ finishReady: (ctx) => {
168
+ exitPlanMode(ctx);
169
+ },
132
170
  });
133
171
  const planActions = createPlanActionController({
134
172
  loadInteractiveUi,
@@ -141,26 +179,20 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
141
179
  finalize: requestFinalPlan,
142
180
  implementHere: startImplementation,
143
181
  implementFresh: startFreshImplementation,
144
- exportPlan: (ctx, path, signal, isCurrent) => planExports.export(path, ctx, signal, isCurrent),
182
+ exportPlan: exportPlan,
145
183
  settings: showSettings,
146
184
  save: savePlanForLater,
147
185
  stay: updateUi,
148
186
  exitReady: (ctx) => {
149
- exitPlanMode(ctx);
150
- ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
187
+ if (exitPlanMode(ctx)) {
188
+ ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
189
+ }
151
190
  },
152
191
  clearSaved: (ctx) => {
153
- exitPlanMode(ctx);
154
- ctx.ui.notify("Saved plan cleared.", "info");
192
+ if (exitPlanMode(ctx)) ctx.ui.notify("Saved plan cleared.", "info");
155
193
  },
156
194
  });
157
195
 
158
- pi.registerFlag("plan", {
159
- description: "Start in Codex-like Plan mode",
160
- type: "boolean",
161
- default: false,
162
- });
163
-
164
196
  pi.registerTool({
165
197
  name: PLAN_MODE_QUESTION_TOOL_NAME,
166
198
  label: "Plan question",
@@ -184,6 +216,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
184
216
  if (!parsed.ok) {
185
217
  return planModeQuestionCancelled([], "invalid_input", `Error: ${parsed.error}`);
186
218
  }
219
+ finalizationRequest.satisfy();
187
220
 
188
221
  if (!ctx.hasUI) {
189
222
  return planModeQuestionCancelled(
@@ -274,12 +307,12 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
274
307
  const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
275
308
  if (exportMatch) {
276
309
  const lifecycle = captureMenuLifecycle();
277
- await planExports.export(exportMatch[1], ctx, lifecycle.signal, lifecycle.isCurrent);
310
+ await exportPlan(ctx, exportMatch[1], lifecycle.signal, lifecycle.isCurrent);
278
311
  return;
279
312
  }
280
313
  if (command === "exit" || command === "off") {
281
- ctx.ui.notify(planModeDisableNotification(), "info");
282
- exitPlanMode(ctx);
314
+ const notification = planModeDisableNotification();
315
+ if (exitPlanMode(ctx)) ctx.ui.notify(notification, "info");
283
316
  return;
284
317
  }
285
318
  if (command === "tools") {
@@ -355,16 +388,21 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
355
388
  generation: number,
356
389
  ctx: ExtensionContext | undefined,
357
390
  showWarnings: boolean,
391
+ applyWatchedVisibility = false,
358
392
  ) => {
359
393
  const loadedSettings = await readPlanModeRuntimeSettings();
360
394
  if (generation !== menuGeneration || menuController.signal.aborted) {
361
395
  return undefined;
362
396
  }
363
- if (loadedSettings.kind === "loaded") {
364
- settings = loadedSettings.settings;
365
- } else {
366
- settings = { thinkingLevel: "inherit" };
397
+ const previousSettings = settings;
398
+ const nextSettings =
399
+ loadedSettings.kind === "loaded"
400
+ ? loadedSettings.settings
401
+ : ({ thinkingLevel: "inherit" } satisfies PlanModeSettings);
402
+ if (applyWatchedVisibility && ctx) {
403
+ applyWatchedHelperVisibility(previousSettings, nextSettings, ctx);
367
404
  }
405
+ settings = nextSettings;
368
406
  applyPlanModeShortcut(configuredPlanModeToggleShortcut(settings));
369
407
  if (!ctx || !showWarnings) return loadedSettings;
370
408
  if (loadedSettings.kind === "invalid") {
@@ -392,7 +430,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
392
430
  }
393
431
  settingsReloadTimer = setTimeout(() => {
394
432
  settingsReloadTimer = undefined;
395
- void applyPlanModeSettings(generation, undefined, false);
433
+ void applyPlanModeSettings(generation, currentSessionContext, false, true);
396
434
  }, 75);
397
435
  };
398
436
 
@@ -419,39 +457,66 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
419
457
 
420
458
  pi.on("session_start", async (event, ctx) => {
421
459
  const generation = ++menuGeneration;
460
+ const previousToolVisibility = configuredPlanModeToolVisibility(settings);
461
+ finalizationRequest.reset();
422
462
  currentSession = ctx.sessionManager;
463
+ currentSessionContext = ctx;
423
464
  workflowOwner = undefined;
424
465
  workflowMutex.bindSession(ctx.sessionManager);
466
+ captureToolBaseline();
425
467
  refreshStateBeforeFirstAgentStart = event.reason === "new";
426
468
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
427
469
  menuController = new AbortController();
428
470
  readyPresentationIntent = undefined;
429
471
  latestCommandContext = undefined;
430
- previousTools = undefined;
472
+ workflowAllowedToolNames = undefined;
431
473
  implementationRetention.reset();
432
474
  settings = { thinkingLevel: "inherit" };
433
- const restoredState = readRestoredState(ctx);
475
+ const branch = ctx.sessionManager.getBranch();
476
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
477
+ restoreModeContractTracking(branch, restoredState);
434
478
  state = { enabled: false, awaitingAction: false };
435
479
  await applyPlanModeSettings(generation, ctx, true);
436
480
  if (generation !== menuGeneration || menuController.signal.aborted) return;
437
481
  startPlanModeSettingsWatch(generation);
438
- const persistFlagActivation = pi.getFlag("plan") === true && !restoredState.enabled;
439
- const candidate = persistFlagActivation
440
- ? restoredState.savedPlan
441
- ? {
442
- ...restoredState,
443
- enabled: true,
444
- latestPlan: restoredState.savedPlan.plan,
445
- latestPlanSource: restoredState.savedPlan.source,
446
- awaitingAction: true,
447
- savedPlan: undefined,
448
- activeImplementation: undefined,
449
- }
450
- : { ...restoredState, enabled: true, activeImplementation: undefined }
451
- : restoredState;
452
- if (!installRestoredState(candidate, ctx)) return;
482
+ if (restoredState.enabled) {
483
+ if (!installRestoredState(restoredState, ctx, previousToolVisibility)) return;
484
+ } else {
485
+ reconcileInactiveHelperVisibility(previousToolVisibility, ctx);
486
+ if (!installRestoredState(restoredState, ctx)) return;
487
+ }
453
488
  implementationRetention.restore(state.activeImplementation);
454
- if (persistFlagActivation && state.enabled) persistState();
489
+ updateUi(ctx);
490
+ });
491
+
492
+ pi.on("session_before_tree", (event, ctx) => {
493
+ const target = ctx.sessionManager.getEntry(event.preparation.targetId);
494
+ if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {
495
+ return;
496
+ }
497
+ if (ctx.hasUI) {
498
+ ctx.ui.notify(
499
+ "Plan mode transition markers are internal. Select the adjacent conversation entry instead.",
500
+ "warning",
501
+ );
502
+ }
503
+ return { cancel: true };
504
+ });
505
+
506
+ pi.on("session_tree", (_event, ctx) => {
507
+ advanceWorkflowGeneration();
508
+ menuGeneration += 1;
509
+ menuController.abort(new DOMException("Plan-mode tree branch changed", "AbortError"));
510
+ menuController = new AbortController();
511
+ readyPresentationIntent = undefined;
512
+ latestCommandContext = undefined;
513
+ implementationRetention.reset();
514
+ const branch = ctx.sessionManager.getBranch();
515
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
516
+ restoreModeContractTracking(branch, restoredState);
517
+ if (!installRestoredState(restoredState, ctx)) return;
518
+ implementationRetention.restore(state.activeImplementation);
519
+ startPlanModeSettingsWatch(menuGeneration);
455
520
  updateUi(ctx);
456
521
  });
457
522
 
@@ -470,6 +535,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
470
535
 
471
536
  pi.on("session_shutdown", async (_event, ctx) => {
472
537
  const shutdownSession = ctx.sessionManager;
538
+ finalizationRequest.reset();
473
539
  menuGeneration += 1;
474
540
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
475
541
  readyPresentationIntent = undefined;
@@ -483,49 +549,90 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
483
549
  }
484
550
  captureManualThinkingLevel();
485
551
  persistState();
486
- if (state.enabled) {
487
- restoreTools();
488
- restoreThinkingLevel();
489
- }
552
+ if (state.enabled) restoreThinkingLevel();
490
553
  stopPlanModeSettingsWatch();
491
554
  clearUi(ctx);
492
555
  releaseWorkflowOwner();
493
556
  workflowMutex.unbindSession(ctx.sessionManager);
494
- if (currentSession === ctx.sessionManager) currentSession = undefined;
557
+ if (currentSession === ctx.sessionManager) {
558
+ currentSession = undefined;
559
+ currentSessionContext = undefined;
560
+ }
495
561
  });
496
562
 
497
563
  pi.on("tool_call", async (event) => {
498
- if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
499
- if (event.toolName === "update_plan") {
564
+ const requiredHelper =
565
+ event.toolName === PLAN_MODE_QUESTION_TOOL_NAME ||
566
+ event.toolName === PLAN_MODE_COMPLETE_TOOL_NAME;
567
+ if (!state.enabled) {
568
+ if (!requiredHelper) return;
500
569
  return {
501
570
  block: true,
502
- reason:
503
- "Plan mode blocks update_plan because it tracks execution progress rather than conversational planning.",
571
+ reason: `${event.toolName} is only available while Plan mode is active.`,
504
572
  };
505
573
  }
506
- const calledTool = toolByName(event.toolName);
507
- if (calledTool && classifyPlanModeTool(calledTool) === "blocked") {
574
+ if (!workflowMutex.isOwner(workflowOwner)) {
508
575
  return {
509
576
  block: true,
510
- reason: `Plan mode blocks built-in tool '${event.toolName}' because its policy class is blocked.`,
577
+ reason: `Plan mode blocks tool '${event.toolName}' because workflow ownership is unavailable.`,
511
578
  };
512
579
  }
513
- if (!calledTool && BLOCKED_BUILTIN_TOOLS.has(event.toolName)) {
580
+ if (BLOCKED_MUTATING_TOOLS.has(event.toolName)) {
514
581
  return {
515
582
  block: true,
516
- reason: `Plan mode blocks built-in tool '${event.toolName}' because its metadata is unavailable.`,
583
+ reason:
584
+ event.toolName === "update_plan"
585
+ ? "Plan mode blocks update_plan because it tracks execution progress rather than conversational planning."
586
+ : `Plan mode blocks mutating tool '${event.toolName}'.`,
517
587
  };
518
588
  }
519
- // Built-in-compatible overrides retain the canonical name but replace its source metadata.
520
- if (event.toolName !== "bash") return;
589
+ if (requiredHelper) return;
521
590
 
522
- const blocked = findBlockedCommandSegment(readCommand(event.input), settings.safeSubcommands);
523
- if (blocked !== undefined) {
591
+ const allowedToolNames = new Set(planModePolicyToolNames());
592
+ if (!allowedToolNames.has(event.toolName)) {
524
593
  return {
525
594
  block: true,
526
- reason: `Plan mode blocks bash commands outside its reviewed inspection policy or containing explicitly unsafe arguments.\nBlocked command: ${blocked}`,
595
+ reason: `Plan mode blocks tool '${event.toolName}' because it is unavailable or not selected by the Plan policy.`,
527
596
  };
528
597
  }
598
+ const calledTool = toolByName(event.toolName);
599
+ if (!calledTool || classifyPlanModeTool(calledTool) === "blocked") {
600
+ return {
601
+ block: true,
602
+ reason: `Plan mode blocks tool '${event.toolName}' because its safe policy metadata is unavailable.`,
603
+ };
604
+ }
605
+ if (event.toolName === "bash") {
606
+ const blocked = findBlockedCommandSegment(readCommand(event.input), settings.safeSubcommands);
607
+ if (blocked !== undefined) {
608
+ return {
609
+ block: true,
610
+ reason: `Plan mode blocks bash commands outside its reviewed inspection policy or containing explicitly unsafe arguments.\nBlocked command: ${blocked}`,
611
+ };
612
+ }
613
+ }
614
+ if (event.toolName === "powershell") {
615
+ const blocked = findBlockedPowerShellCommandSegment(
616
+ readCommand(event.input),
617
+ settings.safeSubcommands,
618
+ );
619
+ if (blocked !== undefined) {
620
+ return {
621
+ block: true,
622
+ reason: `Plan mode blocks PowerShell commands outside its reviewed inspection policy or containing explicitly unsafe syntax.\nBlocked command: ${blocked}`,
623
+ };
624
+ }
625
+ }
626
+ });
627
+
628
+ pi.on("message_start", (event) => {
629
+ if (
630
+ state.enabled &&
631
+ event.message.role === "user" &&
632
+ messageTextContent(event.message).trim() === FINALIZE_PLAN_PROMPT
633
+ ) {
634
+ finalizationRequest.request(workflowGeneration);
635
+ }
529
636
  });
530
637
 
531
638
  pi.on("context", async (event, ctx) => {
@@ -533,14 +640,21 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
533
640
  if (result.clearActiveImplementationId) {
534
641
  clearActiveImplementation(result.clearActiveImplementationId, ctx);
535
642
  }
536
- return { messages: result.messages as typeof event.messages };
643
+ const messages =
644
+ state.enabled || modeContractsRelevant
645
+ ? reconcileModeContract(result.messages, state.enabled ? "plan" : "normal")
646
+ : result.messages;
647
+ return { messages: messages as typeof event.messages };
537
648
  });
538
649
 
539
- pi.on("before_agent_start", (event, ctx) => {
650
+ pi.on("before_agent_start", (_event, ctx) => {
540
651
  if (refreshStateBeforeFirstAgentStart) {
541
652
  refreshStateBeforeFirstAgentStart = false;
542
653
  implementationRetention.reset();
543
- if (!installRestoredState(readRestoredState(ctx), ctx)) return;
654
+ const branch = ctx.sessionManager.getBranch();
655
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
656
+ restoreModeContractTracking(branch, restoredState);
657
+ if (!installRestoredState(restoredState, ctx)) return;
544
658
  implementationRetention.restore(state.activeImplementation);
545
659
  updateUi(ctx);
546
660
  }
@@ -556,10 +670,6 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
556
670
  persistState();
557
671
  updateUi(ctx);
558
672
  }
559
- applyPlanModeTools();
560
- return {
561
- systemPrompt: `${event.systemPrompt}\n\n${buildPlanModePrompt()}`,
562
- };
563
673
  });
564
674
 
565
675
  pi.on("agent_end", async (event, ctx) => {
@@ -568,6 +678,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
568
678
  const text = latestAssistantText(event.messages);
569
679
  const parsedPlan = parseProposedPlan(text);
570
680
  if (parsedPlan.kind !== "valid") {
681
+ finalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));
571
682
  if (parsedPlan.kind !== "absent") {
572
683
  ctx.ui.notify(invalidPlanMessage(parsedPlan.kind), "warning");
573
684
  }
@@ -578,12 +689,31 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
578
689
  acceptCompletedPlan(parsedPlan.plan, "legacy_proposed_plan", ctx);
579
690
  });
580
691
 
581
- onAgentSettled(pi, async (_event, ctx) => {
692
+ pi.on("agent_settled", async (_event, ctx) => {
582
693
  const settledImplementationId = implementationRetention.implementationSettled(
583
694
  state.activeImplementation,
584
695
  );
585
696
  if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);
586
697
 
698
+ if (
699
+ finalizationRequest.hasPendingRequest() &&
700
+ state.enabled &&
701
+ workflowMutex.isOwner(workflowOwner)
702
+ ) {
703
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
704
+ const action = finalizationRequest.settle(workflowGeneration);
705
+ if (action === "retry") {
706
+ if (sendPlanModeUserMessage(RETRY_FINALIZE_PLAN_PROMPT, ctx)) return;
707
+ finalizationRequest.reset();
708
+ }
709
+ if (action === "failed") {
710
+ ctx.ui.notify(
711
+ "Plan finalization ended twice without a structured question or completed plan. Plan mode remains active; revise the plan or run /plan finalize again.",
712
+ "warning",
713
+ );
714
+ }
715
+ }
716
+
587
717
  const intent = readyPresentationIntent;
588
718
  if (!intent || !readyPresentationIsCurrent(intent)) return;
589
719
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
@@ -612,6 +742,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
612
742
  ctx: ExtensionContext,
613
743
  candidate: Pick<PlanModeState, "selectedToolNames" | "selectedToolKeys"> = state,
614
744
  ) {
745
+ if (!state.enabled && !allowModeTransition(ctx, "start Plan mode")) return false;
615
746
  bindWorkflowSessionIfNeeded(ctx);
616
747
  if (state.enabled) return workflowMutex.isOwner(workflowOwner);
617
748
  const owner = workflowMutex.acquire();
@@ -619,10 +750,22 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
619
750
  workflowOwner = owner;
620
751
 
621
752
  const previousState = state;
622
- const previousToolSnapshot = previousTools;
623
- workflowGeneration += 1;
753
+ const previousHelperVisibility = helperVisibility.snapshot();
624
754
  try {
625
- previousTools = withoutRequiredPlanModeTools(safeGetActiveTools());
755
+ helperVisibility.prepareActivation(ctx);
756
+ if (!publishModeContract("plan", ctx)) {
757
+ helperVisibility.restore(previousHelperVisibility);
758
+ releaseWorkflowOwner();
759
+ return false;
760
+ }
761
+ } catch (error: unknown) {
762
+ helperVisibility.restore(previousHelperVisibility);
763
+ releaseWorkflowOwner();
764
+ return reportHelperActivationFailure(ctx, error);
765
+ }
766
+ advanceWorkflowGeneration();
767
+ try {
768
+ modeContractsRelevant = true;
626
769
  state = {
627
770
  ...state,
628
771
  enabled: true,
@@ -632,13 +775,13 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
632
775
  selectedToolNames: candidate.selectedToolNames,
633
776
  selectedToolKeys: candidate.selectedToolKeys,
634
777
  };
635
- activatePlanModeTools();
778
+ workflowAllowedToolNames = computePlanModePolicyToolNames();
636
779
  applyPlanThinkingLevel();
637
780
  persistState();
638
781
  updateUi(ctx);
639
782
  return true;
640
783
  } catch (error: unknown) {
641
- rollbackNewActivation(previousState, previousToolSnapshot, ctx);
784
+ rollbackNewActivation(previousState, ctx, undefined, previousHelperVisibility);
642
785
  throw error;
643
786
  }
644
787
  }
@@ -646,7 +789,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
646
789
  function enterPlanModeWithPrompt(prompt: string, ctx: ExtensionContext) {
647
790
  const previousState = state;
648
791
  const previousOwner = workflowOwner;
649
- const previousToolSnapshot = previousTools;
792
+ const previousHelperVisibility = helperVisibility.snapshot();
650
793
  const wasEnabled = state.enabled;
651
794
  if (!enterPlanMode(ctx)) return;
652
795
  if (!wasEnabled) {
@@ -654,13 +797,18 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
654
797
  }
655
798
  if (sendPlanModeUserMessage(prompt, ctx)) return;
656
799
  if (wasEnabled) return;
657
- rollbackNewActivation(previousState, previousToolSnapshot, ctx, previousOwner);
800
+ rollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility);
658
801
  }
659
802
 
660
803
  function exitPlanMode(ctx: ExtensionContext) {
661
- workflowGeneration += 1;
804
+ if (!allowModeTransition(ctx, "leave or clear Plan mode")) return false;
662
805
  const wasEnabled = state.enabled;
806
+ if ((wasEnabled || modeContractsRelevant) && !publishModeContract("normal", ctx)) {
807
+ return false;
808
+ }
809
+ advanceWorkflowGeneration();
663
810
  readyPresentationIntent = undefined;
811
+ workflowAllowedToolNames = undefined;
664
812
  state = {
665
813
  ...state,
666
814
  enabled: false,
@@ -672,13 +820,39 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
672
820
  manualThinkingLevel: undefined,
673
821
  };
674
822
  if (wasEnabled) {
675
- restoreTools();
676
823
  restoreThinkingLevel();
677
824
  state = { ...state, manualThinkingLevel: undefined };
678
825
  }
679
826
  persistState();
680
827
  updateUi(ctx);
681
828
  if (wasEnabled) releaseWorkflowOwner();
829
+ return true;
830
+ }
831
+
832
+ function restoreModeContractTracking(branch: unknown[], restoredState: PlanModeState) {
833
+ publishedContractMode = latestModeContract(branch)?.mode;
834
+ modeContractsRelevant =
835
+ hasModeContractArtifact(branch) ||
836
+ restoredState.enabled ||
837
+ restoredState.savedPlan !== undefined ||
838
+ restoredState.activeImplementation !== undefined;
839
+ }
840
+
841
+ function publishModeContract(mode: PlanModeContract, ctx: ExtensionContext) {
842
+ if (publishedContractMode === mode) return true;
843
+ const { role: _role, timestamp: _timestamp, ...message } = createModeContractMessage(mode);
844
+ try {
845
+ pi.sendMessage(message, { triggerTurn: false });
846
+ publishedContractMode = mode;
847
+ modeContractsRelevant = true;
848
+ return true;
849
+ } catch (error: unknown) {
850
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
851
+ const notification = `Unable to publish the ${mode === "plan" ? "Plan" : "Normal"} mode contract: ${detail}`;
852
+ if (!ctx.hasUI) throw new Error(notification, { cause: error });
853
+ ctx.ui.notify(notification, "error");
854
+ return false;
855
+ }
682
856
  }
683
857
 
684
858
  function sendPlanModeUserMessage(message: string, ctx: ExtensionContext) {
@@ -687,7 +861,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
687
861
  else pi.sendUserMessage(message, { deliverAs: "followUp" });
688
862
  return true;
689
863
  } catch (error: unknown) {
690
- const detail = error instanceof Error ? error.message : String(error);
864
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
691
865
  ctx.ui.notify(`Unable to send Plan-mode message: ${detail}`, "error");
692
866
  return false;
693
867
  }
@@ -701,6 +875,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
701
875
  updateUi(ctx);
702
876
  return;
703
877
  }
878
+ finalizationRequest.satisfy();
704
879
  if (
705
880
  state.enabled &&
706
881
  state.awaitingAction &&
@@ -740,8 +915,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
740
915
 
741
916
  function togglePlanMode(ctx: ExtensionContext) {
742
917
  if (state.enabled) {
743
- ctx.ui.notify(planModeDisableNotification(), "info");
744
- exitPlanMode(ctx);
918
+ const notification = planModeDisableNotification();
919
+ if (exitPlanMode(ctx)) ctx.ui.notify(notification, "info");
745
920
  return;
746
921
  }
747
922
  if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined)) return;
@@ -765,10 +940,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
765
940
  ctx.ui.notify("Plan mode is not active. Use /plan first.", "warning");
766
941
  return;
767
942
  }
768
- sendPlanModeUserMessage(
769
- "Finalize the current implementation plan now. If any material decision remains, use plan_mode_question instead. Otherwise call plan_mode_complete alone as your final action with the complete decision-ready plan.",
770
- ctx,
771
- );
943
+ finalizationRequest.request(workflowGeneration);
944
+ if (!sendPlanModeUserMessage(FINALIZE_PLAN_PROMPT, ctx)) finalizationRequest.reset();
772
945
  }
773
946
 
774
947
  function savePlanForLater(ctx: ExtensionContext) {
@@ -780,9 +953,12 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
780
953
  return;
781
954
  }
782
955
  const source = state.latestPlanSource ?? "legacy_proposed_plan";
956
+ if (!allowModeTransition(ctx, "save the plan and leave Plan mode")) return;
783
957
 
784
- workflowGeneration += 1;
958
+ if (!publishModeContract("normal", ctx)) return;
959
+ advanceWorkflowGeneration();
785
960
  readyPresentationIntent = undefined;
961
+ workflowAllowedToolNames = undefined;
786
962
  state = {
787
963
  ...state,
788
964
  enabled: false,
@@ -793,7 +969,6 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
793
969
  activeImplementation: undefined,
794
970
  manualThinkingLevel: undefined,
795
971
  };
796
- restoreTools();
797
972
  restoreThinkingLevel();
798
973
  state = { ...state, manualThinkingLevel: undefined };
799
974
  persistState();
@@ -813,6 +988,12 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
813
988
 
814
989
  async function startImplementation(ctx: ExtensionContext) {
815
990
  const savedPlan = state.enabled ? undefined : state.savedPlan;
991
+ const initialPlan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
992
+ if (!initialPlan) {
993
+ ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
994
+ return;
995
+ }
996
+ if (!allowModeTransition(ctx, "start plan implementation")) return;
816
997
  if (savedPlan) {
817
998
  const sessionGeneration = menuGeneration;
818
999
  const planWorkflowGeneration = workflowGeneration;
@@ -823,21 +1004,22 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
823
1004
  !state.enabled &&
824
1005
  state.savedPlan === savedPlan;
825
1006
  if (!(await preflightSavedPlanImplementation(ctx, isCurrent))) return;
1007
+ if (!allowModeTransition(ctx, "start plan implementation")) return;
826
1008
  }
827
1009
  const plan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
828
1010
  const source =
829
1011
  (state.enabled ? state.latestPlanSource : savedPlan?.source) ?? "legacy_proposed_plan";
830
- if (!plan) {
831
- ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
832
- return;
833
- }
1012
+ if (!plan) return;
834
1013
 
835
- workflowGeneration += 1;
836
1014
  const previousState = state;
837
1015
  const previousIntent = readyPresentationIntent;
838
- const previousToolSnapshot = previousTools;
839
1016
  const wasEnabled = state.enabled;
1017
+ if (!publishModeContract("normal", ctx)) return;
1018
+ advanceWorkflowGeneration();
1019
+ const retention = configuredImplementationPlanRetention(settings);
1020
+ const usesConversationHistory = retention === "clear-on-start";
840
1021
  readyPresentationIntent = undefined;
1022
+ workflowAllowedToolNames = undefined;
841
1023
  state = {
842
1024
  ...state,
843
1025
  enabled: false,
@@ -845,30 +1027,36 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
845
1027
  latestPlanSource: undefined,
846
1028
  awaitingAction: false,
847
1029
  savedPlan: undefined,
848
- activeImplementation: {
849
- id: randomUUID(),
850
- plan,
851
- source,
852
- startedAt: Date.now(),
853
- retention: configuredImplementationPlanRetention(settings),
854
- },
1030
+ activeImplementation: usesConversationHistory
1031
+ ? undefined
1032
+ : {
1033
+ id: randomUUID(),
1034
+ plan,
1035
+ source,
1036
+ startedAt: Date.now(),
1037
+ retention,
1038
+ },
855
1039
  manualThinkingLevel: undefined,
856
1040
  };
857
1041
  if (wasEnabled) {
858
- restoreTools();
859
1042
  restoreThinkingLevel();
860
1043
  state = { ...state, manualThinkingLevel: undefined };
861
1044
  }
862
1045
  persistState();
863
1046
  updateUi(ctx);
864
1047
 
865
- const sent = sendPlanModeUserMessage(formatImplementationHandoff(plan), ctx);
1048
+ const handoff = usesConversationHistory
1049
+ ? wasEnabled
1050
+ ? formatHistoryImplementationPrompt()
1051
+ : formatTransferredPlanPrompt(plan, false)
1052
+ : formatImplementationHandoff(plan);
1053
+ const sent = sendPlanModeUserMessage(handoff, ctx);
866
1054
  if (!sent) {
867
1055
  state = previousState;
868
1056
  readyPresentationIntent = previousIntent;
869
1057
  if (wasEnabled) {
870
- previousTools = previousToolSnapshot;
871
- applyPlanModeTools();
1058
+ publishModeContract("plan", ctx);
1059
+ workflowAllowedToolNames = computePlanModePolicyToolNames();
872
1060
  applyPlanThinkingLevel();
873
1061
  }
874
1062
  persistState();
@@ -880,13 +1068,28 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
880
1068
 
881
1069
  function clearActiveImplementation(id: string, ctx: ExtensionContext) {
882
1070
  if (state.activeImplementation?.id !== id) return false;
883
- workflowGeneration += 1;
1071
+ advanceWorkflowGeneration();
884
1072
  state = { ...state, activeImplementation: undefined };
885
1073
  persistState();
886
1074
  updateUi(ctx);
887
1075
  return true;
888
1076
  }
889
1077
 
1078
+ async function exportPlan(
1079
+ ctx: ExtensionContext,
1080
+ path: string | undefined,
1081
+ signal: AbortSignal,
1082
+ isCurrent: () => boolean,
1083
+ ) {
1084
+ const exitsReadyPlan = state.enabled && Boolean(state.latestPlan?.trim());
1085
+ if (exitsReadyPlan && !allowModeTransition(ctx, "export the ready plan and leave Plan mode")) {
1086
+ return false;
1087
+ }
1088
+ return planExports.export(path, ctx, signal, () => {
1089
+ return isCurrent() && (!exitsReadyPlan || ctx.isIdle());
1090
+ });
1091
+ }
1092
+
890
1093
  async function showLaunchMenu(ctx: ExtensionContext, initialScreen: "main" | "tools" = "main") {
891
1094
  const lifecycle = captureMenuLifecycle();
892
1095
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
@@ -894,21 +1097,37 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
894
1097
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
895
1098
  const tools = selectableTools();
896
1099
  await ui.showPlanLaunchMenu(ctx, {
897
- statusText: "Status: Off — normal tools are active.",
1100
+ statusText: helperVisibility.toolsAvailable()
1101
+ ? "Status: Off — Plan helper tools are visible for this runtime."
1102
+ : "Status: Off — Plan helper tools load on the first Plan start.",
898
1103
  initialScreen,
899
1104
  getSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),
900
- toolSummary: (selectedNames) =>
901
- `When started: ${snapshotPlanModeToolNames(tools, selectedNames, toolSelectionSnapshot()).join(", ")}`,
1105
+ toolSummary: (selectedNames) => {
1106
+ const allowed = tools
1107
+ .filter(
1108
+ (tool) =>
1109
+ toolIsActive(tool.name) &&
1110
+ selectedNames.has(tool.name) &&
1111
+ canSelectToolInPlanMode(tool),
1112
+ )
1113
+ .map((tool) => tool.name);
1114
+ return `Plan policy will allow: ${allowed.length > 0 ? allowed.join(", ") : "none"}.`;
1115
+ },
902
1116
  tools: tools.map((tool) => {
903
1117
  const selectable = canSelectToolInPlanMode(tool);
904
- const policy = toolPolicyLabel(tool);
1118
+ const active = toolIsActive(tool.name);
1119
+ const policy = active ? toolPolicyLabel(tool) : "not active in this Pi session";
905
1120
  const description = tool.description ?? "No description available";
906
1121
  return {
907
1122
  name: tool.name,
908
1123
  description: `${policy} · ${description}`,
909
1124
  searchText: [policy, description].join(" "),
910
- disabled: !selectable,
911
- disabledReason: selectable ? undefined : "Blocked by Plan-mode policy",
1125
+ disabled: !selectable || !active,
1126
+ disabledReason: !active
1127
+ ? "Not active in Pi; Plan mode will not activate it"
1128
+ : selectable
1129
+ ? undefined
1130
+ : "Blocked by Plan-mode policy",
912
1131
  };
913
1132
  }),
914
1133
  ...lifecycle,
@@ -923,7 +1142,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
923
1142
  },
924
1143
  startWithTools: (names, signal) => {
925
1144
  if (signal.aborted || !lifecycle.isCurrent()) return;
926
- const selectedToolNames = filterAvailableSelectedToolNames(names, tools);
1145
+ const selectedToolNames = filterAvailableSelectedToolNames(names, activePlanPolicyTools());
927
1146
  if (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: undefined })) {
928
1147
  ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
929
1148
  }
@@ -958,8 +1177,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
958
1177
  }
959
1178
  },
960
1179
  clear: () => {
961
- exitPlanMode(ctx);
962
- ctx.ui.notify("Active implementation plan cleared.", "info");
1180
+ if (exitPlanMode(ctx)) ctx.ui.notify("Active implementation plan cleared.", "info");
963
1181
  },
964
1182
  });
965
1183
  }
@@ -974,9 +1192,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
974
1192
  if (!isCurrent() || signal.aborted) return false;
975
1193
  const result = await ui.showPlanModeSettings(ctx, {
976
1194
  tools: selectableTools(),
1195
+ activeToolNames: activeToolBaseline,
977
1196
  signal,
978
1197
  isCurrent,
979
1198
  settingsPath: dependencies.settingsPath,
1199
+ updateSettings: (patch, options) => updateSettingsWithRuntime(patch, options, ctx, isCurrent),
980
1200
  onSaved: (saved) => {
981
1201
  if (!isCurrent()) return;
982
1202
  settings = saved;
@@ -989,6 +1209,83 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
989
1209
  return result.kind === "closed" && "reason" in result && result.reason === "close";
990
1210
  }
991
1211
 
1212
+ async function updateSettingsWithRuntime(
1213
+ patch: PlanModeSettingsPatch,
1214
+ options: UpdatePlanModeSettingsOptions | undefined,
1215
+ ctx: ExtensionContext,
1216
+ isCurrent: () => boolean,
1217
+ ) {
1218
+ const previousVisibility = configuredPlanModeToolVisibility(settings);
1219
+ const nextVisibility = patch.toolVisibility ?? previousVisibility;
1220
+ const persistSettings = dependencies.updateSettings ?? updatePlanModeSettings;
1221
+ if (nextVisibility === previousVisibility) {
1222
+ return persistSettings(patch, options);
1223
+ }
1224
+ if (!ctx.isIdle()) {
1225
+ throw new Error("Wait for Pi to become idle before changing Plan tool visibility.");
1226
+ }
1227
+ bindWorkflowSessionIfNeeded(ctx);
1228
+ const applicationSession = ctx.sessionManager;
1229
+ const applicationGeneration = menuGeneration;
1230
+ const applicationIsCurrent = () =>
1231
+ currentSession === applicationSession &&
1232
+ menuGeneration === applicationGeneration &&
1233
+ isCurrent();
1234
+ const retainedOwner = workflowMutex.isOwner(workflowOwner);
1235
+ const temporaryOwner = retainedOwner ? workflowOwner : workflowMutex.acquire();
1236
+ if (!temporaryOwner) {
1237
+ throw new Error(
1238
+ "Another workflow is active in this session. Plan tool visibility was not changed.",
1239
+ );
1240
+ }
1241
+ const visibilitySnapshot = helperVisibility.snapshot();
1242
+ try {
1243
+ helperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);
1244
+ const saved = await persistSettings(patch, options);
1245
+ if (!applicationIsCurrent()) {
1246
+ throw new DOMException("Plan settings session replaced", "AbortError");
1247
+ }
1248
+ settings = saved;
1249
+ applyPlanModeShortcut(configuredPlanModeToggleShortcut(saved));
1250
+ return saved;
1251
+ } catch (error) {
1252
+ if (applicationIsCurrent()) {
1253
+ try {
1254
+ helperVisibility.restore(visibilitySnapshot);
1255
+ } catch (rollbackError) {
1256
+ throw new AggregateError(
1257
+ [error, rollbackError],
1258
+ "Plan tool visibility settings failed and runtime rollback was incomplete.",
1259
+ );
1260
+ }
1261
+ }
1262
+ throw error;
1263
+ } finally {
1264
+ if (!retainedOwner) workflowMutex.release(temporaryOwner);
1265
+ if (!isCurrent()) latestCommandContext = undefined;
1266
+ }
1267
+ }
1268
+
1269
+ function allowModeTransition(ctx: ExtensionContext, action: string) {
1270
+ if (ctx.isIdle()) return true;
1271
+ const message = `Cannot ${action} while an agent run is active. Wait for the run to settle, then retry.`;
1272
+ if (!ctx.hasUI) throw new Error(message);
1273
+ ctx.ui.notify(message, "warning");
1274
+ return false;
1275
+ }
1276
+
1277
+ function advanceWorkflowGeneration() {
1278
+ workflowGeneration += 1;
1279
+ finalizationRequest.reset();
1280
+ }
1281
+
1282
+ function finalizationRunOutcome(messages: unknown): FinalizationRunOutcome {
1283
+ const stopReason = latestAssistantStopReason(messages);
1284
+ if (stopReason === undefined || stopReason === "stop") return "normal";
1285
+ if (stopReason === "aborted") return "cancelled";
1286
+ return "error";
1287
+ }
1288
+
992
1289
  function captureMenuLifecycle() {
993
1290
  const sessionGeneration = menuGeneration;
994
1291
  const planWorkflowGeneration = workflowGeneration;
@@ -1004,32 +1301,96 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1004
1301
  };
1005
1302
  }
1006
1303
 
1007
- function activatePlanModeTools() {
1008
- previousTools ??= withoutRequiredPlanModeTools(safeGetActiveTools());
1009
- applyPlanModeTools();
1304
+ function captureToolBaseline() {
1305
+ activeToolBaseline = withRequiredPlanModeTools(safeGetActiveTools());
1010
1306
  }
1011
1307
 
1012
- function applyPlanModeTools() {
1013
- pi.setActiveTools(planModeToolNames());
1308
+ function applyWatchedHelperVisibility(
1309
+ previousSettings: PlanModeSettings,
1310
+ nextSettings: PlanModeSettings,
1311
+ ctx: ExtensionContext,
1312
+ ) {
1313
+ const previousVisibility = configuredPlanModeToolVisibility(previousSettings);
1314
+ const nextVisibility = configuredPlanModeToolVisibility(nextSettings);
1315
+ if (previousVisibility === nextVisibility) return;
1316
+ if (state.enabled) {
1317
+ helperVisibility.deferVisibilityChange(nextVisibility);
1318
+ return;
1319
+ }
1320
+ try {
1321
+ if (!ctx.isIdle()) {
1322
+ helperVisibility.deferVisibilityChange(nextVisibility);
1323
+ return;
1324
+ }
1325
+ } catch {
1326
+ helperVisibility.deferVisibilityChange(nextVisibility);
1327
+ return;
1328
+ }
1329
+ const owner = workflowMutex.acquire();
1330
+ if (!owner) {
1331
+ helperVisibility.deferVisibilityChange(nextVisibility);
1332
+ return;
1333
+ }
1334
+ const snapshot = helperVisibility.snapshot();
1335
+ try {
1336
+ helperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);
1337
+ } catch (error: unknown) {
1338
+ helperVisibility.restore(snapshot);
1339
+ helperVisibility.deferVisibilityChange(nextVisibility);
1340
+ if (ctx.hasUI) {
1341
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
1342
+ ctx.ui.notify(
1343
+ `Could not apply reloaded Plan tool visibility; the current tool envelope remains unchanged until a later safe boundary: ${detail}`,
1344
+ "warning",
1345
+ );
1346
+ }
1347
+ } finally {
1348
+ workflowMutex.release(owner);
1349
+ }
1014
1350
  }
1015
1351
 
1016
- function planModeToolNames() {
1017
- const tools = selectableTools();
1018
- if (
1019
- tools.length === 0 &&
1020
- state.selectedToolNames === undefined &&
1021
- state.selectedToolKeys === undefined &&
1022
- settings.defaultPlanTools === undefined
1023
- ) {
1024
- return ["read", "bash", PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME];
1352
+ function reconcileInactiveHelperVisibility(
1353
+ previousVisibility: PlanModeToolVisibility,
1354
+ ctx: ExtensionContext,
1355
+ ) {
1356
+ const owner = workflowMutex.acquire();
1357
+ if (!owner) {
1358
+ if (ctx.hasUI) {
1359
+ ctx.ui.notify(
1360
+ "Plan tool visibility was deferred because another workflow is active in this session.",
1361
+ "warning",
1362
+ );
1363
+ }
1364
+ return false;
1365
+ }
1366
+ const snapshot = helperVisibility.snapshot();
1367
+ try {
1368
+ const visibility = configuredPlanModeToolVisibility(settings);
1369
+ helperVisibility.prepareSessionStart(visibility, previousVisibility);
1370
+ helperVisibility.reconcileInactiveState(visibility);
1371
+ return true;
1372
+ } catch (error: unknown) {
1373
+ helperVisibility.restore(snapshot);
1374
+ if (ctx.hasUI) {
1375
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
1376
+ ctx.ui.notify(`Could not apply Plan tool visibility: ${detail}`, "error");
1377
+ }
1378
+ return false;
1379
+ } finally {
1380
+ workflowMutex.release(owner);
1025
1381
  }
1382
+ }
1026
1383
 
1384
+ function planModePolicyToolNames() {
1385
+ return workflowAllowedToolNames ?? computePlanModePolicyToolNames();
1386
+ }
1387
+
1388
+ function computePlanModePolicyToolNames() {
1389
+ const tools = activePlanPolicyTools();
1027
1390
  const selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
1028
- return withRequiredPlanModeTools(
1029
- tools
1030
- .filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool))
1031
- .map((tool) => tool.name),
1032
- );
1391
+ return tools
1392
+ .filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool))
1393
+ .map((tool) => tool.name);
1033
1394
  }
1034
1395
 
1035
1396
  function toolSelectionSnapshot() {
@@ -1049,6 +1410,15 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1049
1410
  .sort(compareTools);
1050
1411
  }
1051
1412
 
1413
+ function activePlanPolicyTools() {
1414
+ const activeNames = new Set(activeToolBaseline);
1415
+ return selectableTools().filter((tool) => activeNames.has(tool.name));
1416
+ }
1417
+
1418
+ function toolIsActive(toolName: string) {
1419
+ return activeToolBaseline.includes(toolName);
1420
+ }
1421
+
1052
1422
  function safeGetAllTools() {
1053
1423
  try {
1054
1424
  return pi.getAllTools();
@@ -1057,16 +1427,10 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1057
1427
  }
1058
1428
  }
1059
1429
 
1060
- function restoreTools() {
1061
- const restoredTools = previousTools ?? DEFAULT_TOOLS;
1062
- pi.setActiveTools(withoutRequiredPlanModeTools(restoredTools));
1063
- previousTools = undefined;
1064
- }
1065
-
1066
1430
  function applyPlanThinkingLevel() {
1067
1431
  if (state.manualThinkingLevel) {
1068
1432
  if (pi.getThinkingLevel() !== state.manualThinkingLevel) {
1069
- setPlanThinkingLevel(pi, state.manualThinkingLevel);
1433
+ pi.setThinkingLevel(state.manualThinkingLevel);
1070
1434
  }
1071
1435
  return;
1072
1436
  }
@@ -1081,7 +1445,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1081
1445
  }
1082
1446
  const current = pi.getThinkingLevel();
1083
1447
  if (!state.appliedThinkingLevel) state.previousThinkingLevel = current;
1084
- if (current !== configured) setPlanThinkingLevel(pi, configured);
1448
+ if (current !== configured) pi.setThinkingLevel(configured);
1085
1449
  state.appliedThinkingLevel = pi.getThinkingLevel();
1086
1450
  }
1087
1451
 
@@ -1105,19 +1469,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1105
1469
  previousThinkingLevel &&
1106
1470
  pi.getThinkingLevel() === appliedThinkingLevel
1107
1471
  ) {
1108
- setPlanThinkingLevel(pi, previousThinkingLevel);
1472
+ pi.setThinkingLevel(previousThinkingLevel);
1109
1473
  }
1110
1474
  state = { ...state, appliedThinkingLevel: undefined, previousThinkingLevel: undefined };
1111
1475
  }
1112
1476
 
1113
- function deactivatePlanModeQuestionTool() {
1114
- const activeTools = safeGetActiveTools();
1115
- const filteredTools = withoutRequiredPlanModeTools(activeTools);
1116
- if (filteredTools.length !== activeTools.length) {
1117
- pi.setActiveTools(filteredTools);
1118
- }
1119
- }
1120
-
1121
1477
  function safeGetActiveTools() {
1122
1478
  try {
1123
1479
  return pi.getActiveTools();
@@ -1126,20 +1482,21 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1126
1482
  }
1127
1483
  }
1128
1484
 
1129
- function readRestoredState(ctx: ExtensionContext) {
1130
- return restorePlanModeState(ctx.sessionManager.getBranch(), STATE_ENTRY_TYPE);
1131
- }
1132
-
1133
- function installRestoredState(candidate: PlanModeState, ctx: ExtensionContext) {
1485
+ function installRestoredState(
1486
+ candidate: PlanModeState,
1487
+ ctx: ExtensionContext,
1488
+ previousToolVisibility?: PlanModeToolVisibility,
1489
+ ) {
1134
1490
  const previousState = state;
1135
- const previousToolSnapshot = previousTools;
1491
+ const previousWorkflowAllowedToolNames = workflowAllowedToolNames;
1136
1492
  const previousOwner = workflowOwner;
1493
+ const previousHelperVisibility = helperVisibility.snapshot();
1137
1494
  const wasEnabled = state.enabled;
1138
1495
  if (candidate.enabled && !workflowMutex.isOwner(workflowOwner)) {
1139
1496
  const owner = workflowMutex.acquire();
1140
1497
  if (!owner) {
1141
1498
  state = { enabled: false, awaitingAction: false };
1142
- previousTools = undefined;
1499
+ workflowAllowedToolNames = undefined;
1143
1500
  reportRestoredWorkflowBusy(ctx);
1144
1501
  return false;
1145
1502
  }
@@ -1147,33 +1504,43 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1147
1504
  }
1148
1505
 
1149
1506
  try {
1507
+ if (candidate.enabled) {
1508
+ const visibility = configuredPlanModeToolVisibility(settings);
1509
+ if (previousToolVisibility === undefined) {
1510
+ helperVisibility.prepareActivation(ctx);
1511
+ } else {
1512
+ try {
1513
+ helperVisibility.prepareSessionStart(visibility, previousToolVisibility);
1514
+ helperVisibility.prepareActivation(ctx);
1515
+ } catch {
1516
+ helperVisibility.restore(previousHelperVisibility);
1517
+ state = { enabled: false, awaitingAction: false };
1518
+ workflowAllowedToolNames = undefined;
1519
+ if (workflowOwner !== previousOwner) {
1520
+ workflowMutex.release(workflowOwner);
1521
+ workflowOwner = previousOwner;
1522
+ }
1523
+ reportRestoredHelpersUnavailable(ctx);
1524
+ return false;
1525
+ }
1526
+ }
1527
+ }
1150
1528
  if (wasEnabled && !candidate.enabled) {
1151
1529
  readyPresentationIntent = undefined;
1152
- restoreTools();
1153
1530
  restoreThinkingLevel();
1154
1531
  }
1155
1532
  state = candidate;
1156
- if (state.enabled) {
1157
- if (!wasEnabled) previousTools = withoutRequiredPlanModeTools(safeGetActiveTools());
1158
- activatePlanModeTools();
1159
- applyPlanThinkingLevel();
1160
- } else {
1161
- deactivatePlanModeQuestionTool();
1162
- if (wasEnabled) releaseWorkflowOwner();
1163
- }
1533
+ workflowAllowedToolNames = state.enabled ? computePlanModePolicyToolNames() : undefined;
1534
+ if (state.enabled) applyPlanThinkingLevel();
1535
+ else if (wasEnabled) releaseWorkflowOwner();
1164
1536
  return true;
1165
1537
  } catch (error: unknown) {
1166
1538
  try {
1167
- if (!wasEnabled && state.enabled) {
1168
- try {
1169
- restoreTools();
1170
- } finally {
1171
- restoreThinkingLevel();
1172
- }
1173
- }
1539
+ if (!wasEnabled && state.enabled) restoreThinkingLevel();
1174
1540
  } finally {
1175
1541
  state = previousState;
1176
- previousTools = previousToolSnapshot;
1542
+ workflowAllowedToolNames = previousWorkflowAllowedToolNames;
1543
+ helperVisibility.restore(previousHelperVisibility);
1177
1544
  if (workflowOwner !== previousOwner) {
1178
1545
  workflowMutex.release(workflowOwner);
1179
1546
  workflowOwner = previousOwner;
@@ -1185,24 +1552,22 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1185
1552
 
1186
1553
  function rollbackNewActivation(
1187
1554
  previousState: PlanModeState,
1188
- previousToolSnapshot: string[] | undefined,
1189
1555
  ctx: ExtensionContext,
1190
1556
  previousOwner?: WorkflowMutexOwner,
1557
+ previousHelperVisibility?: PlanModeHelperVisibilitySnapshot,
1191
1558
  ) {
1192
1559
  const activatedOwner = workflowOwner;
1193
1560
  readyPresentationIntent = undefined;
1194
1561
  try {
1195
1562
  if (state.enabled) {
1196
- try {
1197
- restoreTools();
1198
- } finally {
1199
- restoreThinkingLevel();
1200
- }
1563
+ publishModeContract("normal", ctx);
1564
+ restoreThinkingLevel();
1201
1565
  }
1202
1566
  } finally {
1203
1567
  state = previousState;
1204
- previousTools = previousToolSnapshot;
1568
+ workflowAllowedToolNames = undefined;
1205
1569
  try {
1570
+ if (previousHelperVisibility) helperVisibility.restore(previousHelperVisibility);
1206
1571
  persistState();
1207
1572
  updateUi(ctx);
1208
1573
  } finally {
@@ -1242,6 +1607,22 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1242
1607
  );
1243
1608
  }
1244
1609
 
1610
+ function reportRestoredHelpersUnavailable(ctx: ExtensionContext) {
1611
+ if (!ctx.hasUI) return;
1612
+ ctx.ui.notify(
1613
+ "Plan mode was not restored because its helper tools are unavailable under the active tool policy.",
1614
+ "warning",
1615
+ );
1616
+ }
1617
+
1618
+ function reportHelperActivationFailure(ctx: ExtensionContext, error: unknown) {
1619
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
1620
+ const message = `Cannot start Plan mode: ${detail}.`;
1621
+ if (!ctx.hasUI) throw new Error(message, { cause: error });
1622
+ ctx.ui.notify(message, "error");
1623
+ return false;
1624
+ }
1625
+
1245
1626
  function updateUi(ctx: ExtensionContext) {
1246
1627
  updatePlanModeUi(ctx, state, formatToolSummary);
1247
1628
  }
@@ -1259,13 +1640,23 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1259
1640
  }
1260
1641
 
1261
1642
  function formatToolSummary() {
1262
- const names = planModeToolNames();
1263
- return `Tools: ${names.length > 0 ? names.join(", ") : "none"}`;
1643
+ const names = planModePolicyToolNames();
1644
+ return `Plan policy allows: ${names.length > 0 ? names.join(", ") : "none"}. Model-visible tools stay unchanged.`;
1264
1645
  }
1265
1646
 
1266
1647
  function toolByName(toolName: string) {
1267
1648
  return safeGetAllTools().find((candidate) => candidate.name === toolName);
1268
1649
  }
1650
+
1651
+ function safeTerminalText(value: string) {
1652
+ return [...value]
1653
+ .map((character) => {
1654
+ const codePoint = character.codePointAt(0) ?? 0;
1655
+ return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? " " : character;
1656
+ })
1657
+ .join("")
1658
+ .trim();
1659
+ }
1269
1660
  }
1270
1661
 
1271
1662
  export { completePlanArguments } from "./command.js";
@@ -1276,8 +1667,13 @@ export {
1276
1667
  stripProposedPlanBlocks,
1277
1668
  stripProposedPlanBlocksFromMessage,
1278
1669
  } from "./message-transform.js";
1670
+ export {
1671
+ createModeContractMessage,
1672
+ modeContractContent,
1673
+ reconcileModeContract,
1674
+ } from "./mode-contract.js";
1279
1675
  export { buildPlanModePrompt } from "./prompt.js";
1280
1676
  export { normalizePlanModeQuestionParams } from "./question-tool.js";
1281
- export { withoutPlanModeQuestionTool, withRequiredPlanModeTools } from "./required-tools.js";
1677
+ export { withRequiredPlanModeTools } from "./required-tools.js";
1282
1678
  export { normalizePlanModeSettings, readPlanModeSettings } from "./settings.js";
1283
1679
  export { canSelectToolInPlanMode, classifyPlanModeTool, isSafeCommand } from "./tool-policy.js";