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