@narumitw/pi-plan-mode 0.51.1 → 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,13 +95,13 @@ import {
69
95
  compareTools,
70
96
  filterAvailableSelectedToolNames,
71
97
  snapshotPlanModeSelectedNames,
72
- snapshotPlanModeToolNames,
73
98
  toolPolicyLabel,
74
99
  } from "./tool-selection.js";
100
+ import { WorkflowMutex, type WorkflowMutexOwner } from "./workflow-mutex.js";
75
101
 
76
102
  const STATE_ENTRY_TYPE = "plan-mode-state";
77
103
  const PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
78
- const BLOCKED_BUILTIN_TOOLS = new Set(["edit", "write"]);
104
+ const BLOCKED_MUTATING_TOOLS = new Set(["edit", "write", "update_plan"]);
79
105
  const DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
80
106
  interface ReadyPresentationIntent {
81
107
  nonce: number;
@@ -86,10 +112,22 @@ type InteractiveUi = typeof import("./interactive-ui.js");
86
112
 
87
113
  interface PlanModeDependencies {
88
114
  readSettings?(): ReturnType<typeof readPlanModeSettings>;
115
+ updateSettings?(
116
+ patch: PlanModeSettingsPatch,
117
+ options?: UpdatePlanModeSettingsOptions,
118
+ ): ReturnType<typeof updatePlanModeSettings>;
89
119
  settingsPath?: string;
90
120
  loadInteractiveUi?(): Promise<InteractiveUi>;
91
121
  }
122
+
123
+ // Keep session state, persistence, tool, thinking, and mutex commits in this one closure so an
124
+ // activation path cannot bypass the same atomic transition by crossing module-owned state.
92
125
  export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDependencies = {}) {
126
+ const workflowMutex = new WorkflowMutex(pi);
127
+ const helperVisibility = new PlanModeHelperVisibilityPolicy(pi);
128
+ let workflowOwner: WorkflowMutexOwner | undefined;
129
+ let currentSession: object | undefined;
130
+ let currentSessionContext: ExtensionContext | undefined;
93
131
  let interactiveUiPromise: Promise<InteractiveUi> | undefined;
94
132
  const loadInteractiveUi = () => {
95
133
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
@@ -106,7 +144,10 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
106
144
  let settings: PlanModeSettings = { thinkingLevel: "inherit" };
107
145
  let toggleShortcut: ReturnType<typeof configuredPlanModeToggleShortcut>;
108
146
  const clearPlanModeShortcutHandler = () => {};
109
- let previousTools: string[] | undefined;
147
+ let activeToolBaseline: string[] = [];
148
+ let workflowAllowedToolNames: string[] | undefined;
149
+ let publishedContractMode: PlanModeContract | undefined;
150
+ let modeContractsRelevant = false;
110
151
  let readyPresentationIntent: ReadyPresentationIntent | undefined;
111
152
  let latestCommandContext: ExtensionCommandContext | undefined;
112
153
  let nextReadyPresentationNonce = 0;
@@ -117,11 +158,14 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
117
158
  let settingsWatch: ReturnType<typeof watch> | undefined;
118
159
  let settingsReloadTimer: ReturnType<typeof setTimeout> | undefined;
119
160
  const implementationRetention = createImplementationRetentionCoordinator();
161
+ const finalizationRequest = createFinalizationRequestCoordinator();
120
162
  const persistState = () => pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, state);
121
163
  const planExports = createPlanExportController({
122
164
  getState: () => state,
123
165
  getSettings: () => settings,
124
- finishReady: (ctx) => exitPlanMode(ctx),
166
+ finishReady: (ctx) => {
167
+ exitPlanMode(ctx);
168
+ },
125
169
  });
126
170
  const planActions = createPlanActionController({
127
171
  loadInteractiveUi,
@@ -134,26 +178,20 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
134
178
  finalize: requestFinalPlan,
135
179
  implementHere: startImplementation,
136
180
  implementFresh: startFreshImplementation,
137
- exportPlan: (ctx, path, signal, isCurrent) => planExports.export(path, ctx, signal, isCurrent),
181
+ exportPlan: exportPlan,
138
182
  settings: showSettings,
139
183
  save: savePlanForLater,
140
184
  stay: updateUi,
141
185
  exitReady: (ctx) => {
142
- exitPlanMode(ctx);
143
- 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
+ }
144
189
  },
145
190
  clearSaved: (ctx) => {
146
- exitPlanMode(ctx);
147
- ctx.ui.notify("Saved plan cleared.", "info");
191
+ if (exitPlanMode(ctx)) ctx.ui.notify("Saved plan cleared.", "info");
148
192
  },
149
193
  });
150
194
 
151
- pi.registerFlag("plan", {
152
- description: "Start in Codex-like Plan mode",
153
- type: "boolean",
154
- default: false,
155
- });
156
-
157
195
  pi.registerTool({
158
196
  name: PLAN_MODE_QUESTION_TOOL_NAME,
159
197
  label: "Plan question",
@@ -165,7 +203,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
165
203
  ],
166
204
  parameters: PLAN_MODE_QUESTION_PARAMS,
167
205
  async execute(_toolCallId, params: unknown, _signal, _onUpdate, ctx) {
168
- if (!state.enabled) {
206
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {
169
207
  return planModeQuestionCancelled(
170
208
  [],
171
209
  "plan_mode_inactive",
@@ -177,6 +215,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
177
215
  if (!parsed.ok) {
178
216
  return planModeQuestionCancelled([], "invalid_input", `Error: ${parsed.error}`);
179
217
  }
218
+ finalizationRequest.satisfy();
180
219
 
181
220
  if (!ctx.hasUI) {
182
221
  return planModeQuestionCancelled(
@@ -188,9 +227,12 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
188
227
 
189
228
  const sessionGeneration = menuGeneration;
190
229
  const questionWorkflowGeneration = workflowGeneration;
230
+ const questionOwner = workflowOwner;
191
231
  return answerPlanModeQuestions(parsed.questions, ctx, {
192
232
  isCurrent: () =>
193
- sessionGeneration === menuGeneration && questionWorkflowGeneration === workflowGeneration,
233
+ sessionGeneration === menuGeneration &&
234
+ questionWorkflowGeneration === workflowGeneration &&
235
+ workflowMutex.isOwner(questionOwner),
194
236
  isEnabled: () => state.enabled,
195
237
  });
196
238
  },
@@ -208,7 +250,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
208
250
  parameters: PLAN_MODE_COMPLETE_PARAMS,
209
251
  renderResult: renderPlanModeCompletion,
210
252
  async execute(_toolCallId, params: unknown, _signal, _onUpdate, ctx) {
211
- if (!state.enabled) {
253
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {
212
254
  throw new Error("plan_mode_complete is only available while Plan mode is active");
213
255
  }
214
256
  const parsed = normalizePlanModeCompletion(params);
@@ -233,8 +275,12 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
233
275
  ctx.ui.notify("Plan mode is already active.", "info");
234
276
  return;
235
277
  }
236
- enterPlanMode(ctx);
237
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
278
+ if (enterPlanMode(ctx)) {
279
+ ctx.ui.notify(
280
+ "Plan mode enabled. I will explore and plan, but not modify files.",
281
+ "info",
282
+ );
283
+ }
238
284
  return;
239
285
  }
240
286
  if (command === "show") {
@@ -260,12 +306,12 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
260
306
  const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
261
307
  if (exportMatch) {
262
308
  const lifecycle = captureMenuLifecycle();
263
- await planExports.export(exportMatch[1], ctx, lifecycle.signal, lifecycle.isCurrent);
309
+ await exportPlan(ctx, exportMatch[1], lifecycle.signal, lifecycle.isCurrent);
264
310
  return;
265
311
  }
266
312
  if (command === "exit" || command === "off") {
267
- ctx.ui.notify(planModeDisableNotification(), "info");
268
- exitPlanMode(ctx);
313
+ const notification = planModeDisableNotification();
314
+ if (exitPlanMode(ctx)) ctx.ui.notify(notification, "info");
269
315
  return;
270
316
  }
271
317
  if (command === "tools") {
@@ -341,16 +387,21 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
341
387
  generation: number,
342
388
  ctx: ExtensionContext | undefined,
343
389
  showWarnings: boolean,
390
+ applyWatchedVisibility = false,
344
391
  ) => {
345
392
  const loadedSettings = await readPlanModeRuntimeSettings();
346
393
  if (generation !== menuGeneration || menuController.signal.aborted) {
347
394
  return undefined;
348
395
  }
349
- if (loadedSettings.kind === "loaded") {
350
- settings = loadedSettings.settings;
351
- } else {
352
- 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);
353
403
  }
404
+ settings = nextSettings;
354
405
  applyPlanModeShortcut(configuredPlanModeToggleShortcut(settings));
355
406
  if (!ctx || !showWarnings) return loadedSettings;
356
407
  if (loadedSettings.kind === "invalid") {
@@ -378,7 +429,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
378
429
  }
379
430
  settingsReloadTimer = setTimeout(() => {
380
431
  settingsReloadTimer = undefined;
381
- void applyPlanModeSettings(generation, undefined, false);
432
+ void applyPlanModeSettings(generation, currentSessionContext, false, true);
382
433
  }, 75);
383
434
  };
384
435
 
@@ -405,37 +456,66 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
405
456
 
406
457
  pi.on("session_start", async (event, ctx) => {
407
458
  const generation = ++menuGeneration;
459
+ const previousToolVisibility = configuredPlanModeToolVisibility(settings);
460
+ finalizationRequest.reset();
461
+ currentSession = ctx.sessionManager;
462
+ currentSessionContext = ctx;
463
+ workflowOwner = undefined;
464
+ workflowMutex.bindSession(ctx.sessionManager);
465
+ captureToolBaseline();
408
466
  refreshStateBeforeFirstAgentStart = event.reason === "new";
409
467
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
410
468
  menuController = new AbortController();
411
469
  readyPresentationIntent = undefined;
412
470
  latestCommandContext = undefined;
471
+ workflowAllowedToolNames = undefined;
413
472
  implementationRetention.reset();
414
473
  settings = { thinkingLevel: "inherit" };
415
- restoreState(ctx);
416
- implementationRetention.restore(state.activeImplementation);
474
+ const branch = ctx.sessionManager.getBranch();
475
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
476
+ restoreModeContractTracking(branch, restoredState);
477
+ state = { enabled: false, awaitingAction: false };
417
478
  await applyPlanModeSettings(generation, ctx, true);
418
479
  if (generation !== menuGeneration || menuController.signal.aborted) return;
419
480
  startPlanModeSettingsWatch(generation);
420
- const persistFlagActivation = pi.getFlag("plan") === true && !state.enabled;
421
- if (persistFlagActivation) {
422
- state = state.savedPlan
423
- ? {
424
- ...state,
425
- enabled: true,
426
- latestPlan: state.savedPlan.plan,
427
- latestPlanSource: state.savedPlan.source,
428
- awaitingAction: true,
429
- savedPlan: undefined,
430
- activeImplementation: undefined,
431
- }
432
- : { ...state, enabled: true, activeImplementation: undefined };
481
+ if (restoredState.enabled) {
482
+ if (!installRestoredState(restoredState, ctx, previousToolVisibility)) return;
483
+ } else {
484
+ reconcileInactiveHelperVisibility(previousToolVisibility, ctx);
485
+ if (!installRestoredState(restoredState, ctx)) return;
433
486
  }
434
- if (state.enabled) {
435
- activatePlanModeTools();
436
- applyPlanThinkingLevel();
437
- } else deactivatePlanModeQuestionTool();
438
- if (persistFlagActivation) persistState();
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;
517
+ implementationRetention.restore(state.activeImplementation);
518
+ startPlanModeSettingsWatch(menuGeneration);
439
519
  updateUi(ctx);
440
520
  });
441
521
 
@@ -453,6 +533,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
453
533
  });
454
534
 
455
535
  pi.on("session_shutdown", async (_event, ctx) => {
536
+ const shutdownSession = ctx.sessionManager;
537
+ finalizationRequest.reset();
456
538
  menuGeneration += 1;
457
539
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
458
540
  readyPresentationIntent = undefined;
@@ -460,39 +542,65 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
460
542
  refreshStateBeforeFirstAgentStart = false;
461
543
  implementationRetention.reset();
462
544
  await awaitPlanModeSettingsWrites(dependencies.settingsPath);
545
+ if (currentSession !== undefined && currentSession !== shutdownSession) {
546
+ workflowMutex.unbindSession(shutdownSession);
547
+ return;
548
+ }
463
549
  captureManualThinkingLevel();
464
550
  persistState();
465
- if (state.enabled) {
466
- restoreTools();
467
- restoreThinkingLevel();
468
- }
551
+ if (state.enabled) restoreThinkingLevel();
469
552
  stopPlanModeSettingsWatch();
470
553
  clearUi(ctx);
554
+ releaseWorkflowOwner();
555
+ workflowMutex.unbindSession(ctx.sessionManager);
556
+ if (currentSession === ctx.sessionManager) {
557
+ currentSession = undefined;
558
+ currentSessionContext = undefined;
559
+ }
471
560
  });
472
561
 
473
562
  pi.on("tool_call", async (event) => {
474
- if (!state.enabled) return;
475
- 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)) {
476
580
  return {
477
581
  block: true,
478
582
  reason:
479
- "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}'.`,
480
586
  };
481
587
  }
482
- const calledTool = toolByName(event.toolName);
483
- if (calledTool && classifyPlanModeTool(calledTool) === "blocked") {
588
+ if (requiredHelper) return;
589
+
590
+ const allowedToolNames = new Set(planModePolicyToolNames());
591
+ if (!allowedToolNames.has(event.toolName)) {
484
592
  return {
485
593
  block: true,
486
- 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.`,
487
595
  };
488
596
  }
489
- if (!calledTool && BLOCKED_BUILTIN_TOOLS.has(event.toolName)) {
597
+ const calledTool = toolByName(event.toolName);
598
+ if (!calledTool || classifyPlanModeTool(calledTool) === "blocked") {
490
599
  return {
491
600
  block: true,
492
- 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.`,
493
602
  };
494
603
  }
495
- // Built-in-compatible overrides retain the canonical name but replace its source metadata.
496
604
  if (event.toolName !== "bash") return;
497
605
 
498
606
  const blocked = findBlockedCommandSegment(readCommand(event.input), settings.safeSubcommands);
@@ -504,27 +612,40 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
504
612
  }
505
613
  });
506
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
+
507
625
  pi.on("context", async (event, ctx) => {
508
626
  const result = implementationRetention.transformContext(event.messages, state);
509
627
  if (result.clearActiveImplementationId) {
510
628
  clearActiveImplementation(result.clearActiveImplementationId, ctx);
511
629
  }
512
- 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 };
513
635
  });
514
636
 
515
- pi.on("before_agent_start", (event, ctx) => {
637
+ pi.on("before_agent_start", (_event, ctx) => {
516
638
  if (refreshStateBeforeFirstAgentStart) {
517
639
  refreshStateBeforeFirstAgentStart = false;
518
- restoreState(ctx);
519
640
  implementationRetention.reset();
641
+ const branch = ctx.sessionManager.getBranch();
642
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
643
+ restoreModeContractTracking(branch, restoredState);
644
+ if (!installRestoredState(restoredState, ctx)) return;
520
645
  implementationRetention.restore(state.activeImplementation);
521
- if (state.enabled) {
522
- activatePlanModeTools();
523
- applyPlanThinkingLevel();
524
- } else deactivatePlanModeQuestionTool();
525
646
  updateUi(ctx);
526
647
  }
527
- if (!state.enabled) return;
648
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
528
649
  if (state.latestPlan || state.awaitingAction) {
529
650
  readyPresentationIntent = undefined;
530
651
  state = {
@@ -536,18 +657,15 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
536
657
  persistState();
537
658
  updateUi(ctx);
538
659
  }
539
- applyPlanModeTools();
540
- return {
541
- systemPrompt: `${event.systemPrompt}\n\n${buildPlanModePrompt()}`,
542
- };
543
660
  });
544
661
 
545
662
  pi.on("agent_end", async (event, ctx) => {
546
- if (!state.enabled) return;
663
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
547
664
 
548
665
  const text = latestAssistantText(event.messages);
549
666
  const parsedPlan = parseProposedPlan(text);
550
667
  if (parsedPlan.kind !== "valid") {
668
+ finalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));
551
669
  if (parsedPlan.kind !== "absent") {
552
670
  ctx.ui.notify(invalidPlanMessage(parsedPlan.kind), "warning");
553
671
  }
@@ -558,12 +676,31 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
558
676
  acceptCompletedPlan(parsedPlan.plan, "legacy_proposed_plan", ctx);
559
677
  });
560
678
 
561
- onAgentSettled(pi, async (_event, ctx) => {
679
+ pi.on("agent_settled", async (_event, ctx) => {
562
680
  const settledImplementationId = implementationRetention.implementationSettled(
563
681
  state.activeImplementation,
564
682
  );
565
683
  if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);
566
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
+
567
704
  const intent = readyPresentationIntent;
568
705
  if (!intent || !readyPresentationIsCurrent(intent)) return;
569
706
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
@@ -588,43 +725,77 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
588
725
  }
589
726
  });
590
727
 
591
- function enterPlanMode(ctx: ExtensionContext) {
592
- workflowGeneration += 1;
593
- if (!state.enabled) previousTools = withoutRequiredPlanModeTools(safeGetActiveTools());
594
- state = {
595
- ...state,
596
- enabled: true,
597
- awaitingAction: false,
598
- savedPlan: undefined,
599
- activeImplementation: undefined,
600
- };
601
- activatePlanModeTools();
602
- applyPlanThinkingLevel();
603
- persistState();
604
- updateUi(ctx);
728
+ function enterPlanMode(
729
+ ctx: ExtensionContext,
730
+ candidate: Pick<PlanModeState, "selectedToolNames" | "selectedToolKeys"> = state,
731
+ ) {
732
+ if (!state.enabled && !allowModeTransition(ctx, "start Plan mode")) return false;
733
+ bindWorkflowSessionIfNeeded(ctx);
734
+ if (state.enabled) return workflowMutex.isOwner(workflowOwner);
735
+ const owner = workflowMutex.acquire();
736
+ if (!owner) return reportWorkflowBusy(ctx);
737
+ workflowOwner = owner;
738
+
739
+ const previousState = state;
740
+ const previousHelperVisibility = helperVisibility.snapshot();
741
+ try {
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;
756
+ state = {
757
+ ...state,
758
+ enabled: true,
759
+ awaitingAction: false,
760
+ savedPlan: undefined,
761
+ activeImplementation: undefined,
762
+ selectedToolNames: candidate.selectedToolNames,
763
+ selectedToolKeys: candidate.selectedToolKeys,
764
+ };
765
+ workflowAllowedToolNames = computePlanModePolicyToolNames();
766
+ applyPlanThinkingLevel();
767
+ persistState();
768
+ updateUi(ctx);
769
+ return true;
770
+ } catch (error: unknown) {
771
+ rollbackNewActivation(previousState, ctx, undefined, previousHelperVisibility);
772
+ throw error;
773
+ }
605
774
  }
606
775
 
607
776
  function enterPlanModeWithPrompt(prompt: string, ctx: ExtensionContext) {
608
777
  const previousState = state;
778
+ const previousOwner = workflowOwner;
779
+ const previousHelperVisibility = helperVisibility.snapshot();
609
780
  const wasEnabled = state.enabled;
610
- enterPlanMode(ctx);
781
+ if (!enterPlanMode(ctx)) return;
611
782
  if (!wasEnabled) {
612
783
  ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
613
784
  }
614
785
  if (sendPlanModeUserMessage(prompt, ctx)) return;
615
- if (!previousState.enabled) {
616
- restoreTools();
617
- restoreThinkingLevel();
618
- }
619
- state = previousState;
620
- persistState();
621
- updateUi(ctx);
786
+ if (wasEnabled) return;
787
+ rollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility);
622
788
  }
623
789
 
624
790
  function exitPlanMode(ctx: ExtensionContext) {
625
- workflowGeneration += 1;
791
+ if (!allowModeTransition(ctx, "leave or clear Plan mode")) return false;
626
792
  const wasEnabled = state.enabled;
793
+ if ((wasEnabled || modeContractsRelevant) && !publishModeContract("normal", ctx)) {
794
+ return false;
795
+ }
796
+ advanceWorkflowGeneration();
627
797
  readyPresentationIntent = undefined;
798
+ workflowAllowedToolNames = undefined;
628
799
  state = {
629
800
  ...state,
630
801
  enabled: false,
@@ -636,12 +807,39 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
636
807
  manualThinkingLevel: undefined,
637
808
  };
638
809
  if (wasEnabled) {
639
- restoreTools();
640
810
  restoreThinkingLevel();
641
811
  state = { ...state, manualThinkingLevel: undefined };
642
812
  }
643
813
  persistState();
644
814
  updateUi(ctx);
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
+ }
645
843
  }
646
844
 
647
845
  function sendPlanModeUserMessage(message: string, ctx: ExtensionContext) {
@@ -650,7 +848,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
650
848
  else pi.sendUserMessage(message, { deliverAs: "followUp" });
651
849
  return true;
652
850
  } catch (error: unknown) {
653
- const detail = error instanceof Error ? error.message : String(error);
851
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
654
852
  ctx.ui.notify(`Unable to send Plan-mode message: ${detail}`, "error");
655
853
  return false;
656
854
  }
@@ -664,6 +862,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
664
862
  updateUi(ctx);
665
863
  return;
666
864
  }
865
+ finalizationRequest.satisfy();
667
866
  if (
668
867
  state.enabled &&
669
868
  state.awaitingAction &&
@@ -690,6 +889,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
690
889
  function completedPlanIsCurrent(intent: ReadyPresentationIntent) {
691
890
  return (
692
891
  state.enabled &&
892
+ workflowMutex.isOwner(workflowOwner) &&
693
893
  state.awaitingAction &&
694
894
  state.latestPlan === intent.plan &&
695
895
  state.latestPlanSource === intent.source
@@ -702,13 +902,14 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
702
902
 
703
903
  function togglePlanMode(ctx: ExtensionContext) {
704
904
  if (state.enabled) {
705
- ctx.ui.notify(planModeDisableNotification(), "info");
706
- exitPlanMode(ctx);
905
+ const notification = planModeDisableNotification();
906
+ if (exitPlanMode(ctx)) ctx.ui.notify(notification, "info");
707
907
  return;
708
908
  }
709
909
  if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined)) return;
710
- enterPlanMode(ctx);
711
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
910
+ if (enterPlanMode(ctx)) {
911
+ ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
912
+ }
712
913
  }
713
914
 
714
915
  function planModeDisableNotification() {
@@ -726,10 +927,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
726
927
  ctx.ui.notify("Plan mode is not active. Use /plan first.", "warning");
727
928
  return;
728
929
  }
729
- sendPlanModeUserMessage(
730
- "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.",
731
- ctx,
732
- );
930
+ finalizationRequest.request(workflowGeneration);
931
+ if (!sendPlanModeUserMessage(FINALIZE_PLAN_PROMPT, ctx)) finalizationRequest.reset();
733
932
  }
734
933
 
735
934
  function savePlanForLater(ctx: ExtensionContext) {
@@ -741,9 +940,12 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
741
940
  return;
742
941
  }
743
942
  const source = state.latestPlanSource ?? "legacy_proposed_plan";
943
+ if (!allowModeTransition(ctx, "save the plan and leave Plan mode")) return;
744
944
 
745
- workflowGeneration += 1;
945
+ if (!publishModeContract("normal", ctx)) return;
946
+ advanceWorkflowGeneration();
746
947
  readyPresentationIntent = undefined;
948
+ workflowAllowedToolNames = undefined;
747
949
  state = {
748
950
  ...state,
749
951
  enabled: false,
@@ -754,11 +956,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
754
956
  activeImplementation: undefined,
755
957
  manualThinkingLevel: undefined,
756
958
  };
757
- restoreTools();
758
959
  restoreThinkingLevel();
759
960
  state = { ...state, manualThinkingLevel: undefined };
760
961
  persistState();
761
962
  updateUi(ctx);
963
+ releaseWorkflowOwner();
762
964
  ctx.ui.notify("Plan saved for later. Plan mode disabled.", "info");
763
965
  }
764
966
 
@@ -773,6 +975,12 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
773
975
 
774
976
  async function startImplementation(ctx: ExtensionContext) {
775
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;
776
984
  if (savedPlan) {
777
985
  const sessionGeneration = menuGeneration;
778
986
  const planWorkflowGeneration = workflowGeneration;
@@ -783,19 +991,22 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
783
991
  !state.enabled &&
784
992
  state.savedPlan === savedPlan;
785
993
  if (!(await preflightSavedPlanImplementation(ctx, isCurrent))) return;
994
+ if (!allowModeTransition(ctx, "start plan implementation")) return;
786
995
  }
787
996
  const plan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
788
997
  const source =
789
998
  (state.enabled ? state.latestPlanSource : savedPlan?.source) ?? "legacy_proposed_plan";
790
- if (!plan) {
791
- ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
792
- return;
793
- }
999
+ if (!plan) return;
794
1000
 
795
- workflowGeneration += 1;
796
1001
  const previousState = state;
1002
+ const previousIntent = readyPresentationIntent;
797
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";
798
1008
  readyPresentationIntent = undefined;
1009
+ workflowAllowedToolNames = undefined;
799
1010
  state = {
800
1011
  ...state,
801
1012
  enabled: false,
@@ -803,46 +1014,69 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
803
1014
  latestPlanSource: undefined,
804
1015
  awaitingAction: false,
805
1016
  savedPlan: undefined,
806
- activeImplementation: {
807
- id: randomUUID(),
808
- plan,
809
- source,
810
- startedAt: Date.now(),
811
- retention: configuredImplementationPlanRetention(settings),
812
- },
1017
+ activeImplementation: usesConversationHistory
1018
+ ? undefined
1019
+ : {
1020
+ id: randomUUID(),
1021
+ plan,
1022
+ source,
1023
+ startedAt: Date.now(),
1024
+ retention,
1025
+ },
813
1026
  manualThinkingLevel: undefined,
814
1027
  };
815
1028
  if (wasEnabled) {
816
- restoreTools();
817
1029
  restoreThinkingLevel();
818
1030
  state = { ...state, manualThinkingLevel: undefined };
819
1031
  }
820
1032
  persistState();
821
1033
  updateUi(ctx);
822
1034
 
823
- 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);
824
1041
  if (!sent) {
825
- if (savedPlan) {
826
- state = previousState;
827
- } else {
828
- enterPlanMode(ctx);
829
- state = previousState;
1042
+ state = previousState;
1043
+ readyPresentationIntent = previousIntent;
1044
+ if (wasEnabled) {
1045
+ publishModeContract("plan", ctx);
1046
+ workflowAllowedToolNames = computePlanModePolicyToolNames();
830
1047
  applyPlanThinkingLevel();
831
1048
  }
832
1049
  persistState();
833
1050
  updateUi(ctx);
1051
+ return;
834
1052
  }
1053
+ if (wasEnabled) releaseWorkflowOwner();
835
1054
  }
836
1055
 
837
1056
  function clearActiveImplementation(id: string, ctx: ExtensionContext) {
838
1057
  if (state.activeImplementation?.id !== id) return false;
839
- workflowGeneration += 1;
1058
+ advanceWorkflowGeneration();
840
1059
  state = { ...state, activeImplementation: undefined };
841
1060
  persistState();
842
1061
  updateUi(ctx);
843
1062
  return true;
844
1063
  }
845
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
+
846
1080
  async function showLaunchMenu(ctx: ExtensionContext, initialScreen: "main" | "tools" = "main") {
847
1081
  const lifecycle = captureMenuLifecycle();
848
1082
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
@@ -850,38 +1084,55 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
850
1084
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
851
1085
  const tools = selectableTools();
852
1086
  await ui.showPlanLaunchMenu(ctx, {
853
- 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.",
854
1090
  initialScreen,
855
1091
  getSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),
856
- toolSummary: (selectedNames) =>
857
- `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
+ },
858
1103
  tools: tools.map((tool) => {
859
1104
  const selectable = canSelectToolInPlanMode(tool);
860
- const policy = toolPolicyLabel(tool);
1105
+ const active = toolIsActive(tool.name);
1106
+ const policy = active ? toolPolicyLabel(tool) : "not active in this Pi session";
861
1107
  const description = tool.description ?? "No description available";
862
1108
  return {
863
1109
  name: tool.name,
864
1110
  description: `${policy} · ${description}`,
865
1111
  searchText: [policy, description].join(" "),
866
- disabled: !selectable,
867
- 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",
868
1118
  };
869
1119
  }),
870
1120
  ...lifecycle,
871
1121
  start: (signal) => {
872
1122
  if (signal.aborted || !lifecycle.isCurrent()) return;
873
- enterPlanMode(ctx);
874
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1123
+ if (enterPlanMode(ctx)) {
1124
+ ctx.ui.notify(
1125
+ "Plan mode enabled. I will explore and plan, but not modify files.",
1126
+ "info",
1127
+ );
1128
+ }
875
1129
  },
876
1130
  startWithTools: (names, signal) => {
877
1131
  if (signal.aborted || !lifecycle.isCurrent()) return;
878
- state = {
879
- ...state,
880
- selectedToolNames: filterAvailableSelectedToolNames(names, tools),
881
- selectedToolKeys: undefined,
882
- };
883
- enterPlanMode(ctx);
884
- ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
1132
+ const selectedToolNames = filterAvailableSelectedToolNames(names, activePlanPolicyTools());
1133
+ if (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: undefined })) {
1134
+ ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
1135
+ }
885
1136
  },
886
1137
  settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),
887
1138
  });
@@ -905,12 +1156,15 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
905
1156
  exportPlan: (path, signal) => planExports.export(path, ctx, signal, lifecycle.isCurrent),
906
1157
  settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),
907
1158
  startNew: () => {
908
- enterPlanMode(ctx);
909
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1159
+ if (enterPlanMode(ctx)) {
1160
+ ctx.ui.notify(
1161
+ "Plan mode enabled. I will explore and plan, but not modify files.",
1162
+ "info",
1163
+ );
1164
+ }
910
1165
  },
911
1166
  clear: () => {
912
- exitPlanMode(ctx);
913
- ctx.ui.notify("Active implementation plan cleared.", "info");
1167
+ if (exitPlanMode(ctx)) ctx.ui.notify("Active implementation plan cleared.", "info");
914
1168
  },
915
1169
  });
916
1170
  }
@@ -925,9 +1179,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
925
1179
  if (!isCurrent() || signal.aborted) return false;
926
1180
  const result = await ui.showPlanModeSettings(ctx, {
927
1181
  tools: selectableTools(),
1182
+ activeToolNames: activeToolBaseline,
928
1183
  signal,
929
1184
  isCurrent,
930
1185
  settingsPath: dependencies.settingsPath,
1186
+ updateSettings: (patch, options) => updateSettingsWithRuntime(patch, options, ctx, isCurrent),
931
1187
  onSaved: (saved) => {
932
1188
  if (!isCurrent()) return;
933
1189
  settings = saved;
@@ -940,45 +1196,188 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
940
1196
  return result.kind === "closed" && "reason" in result && result.reason === "close";
941
1197
  }
942
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
+
943
1276
  function captureMenuLifecycle() {
944
1277
  const sessionGeneration = menuGeneration;
945
1278
  const planWorkflowGeneration = workflowGeneration;
1279
+ const owner = workflowOwner;
946
1280
  const controller = menuController;
947
1281
  return {
948
1282
  signal: controller.signal,
949
1283
  isCurrent: () =>
950
1284
  sessionGeneration === menuGeneration &&
951
1285
  planWorkflowGeneration === workflowGeneration &&
952
- !controller.signal.aborted,
1286
+ !controller.signal.aborted &&
1287
+ (!state.enabled || workflowMutex.isOwner(owner)),
953
1288
  };
954
1289
  }
955
1290
 
956
- function activatePlanModeTools() {
957
- previousTools ??= withoutRequiredPlanModeTools(safeGetActiveTools());
958
- applyPlanModeTools();
1291
+ function captureToolBaseline() {
1292
+ activeToolBaseline = withRequiredPlanModeTools(safeGetActiveTools());
959
1293
  }
960
1294
 
961
- function applyPlanModeTools() {
962
- 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
+ }
963
1337
  }
964
1338
 
965
- function planModeToolNames() {
966
- const tools = selectableTools();
967
- if (
968
- tools.length === 0 &&
969
- state.selectedToolNames === undefined &&
970
- state.selectedToolKeys === undefined &&
971
- settings.defaultPlanTools === undefined
972
- ) {
973
- 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;
974
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);
1368
+ }
1369
+ }
1370
+
1371
+ function planModePolicyToolNames() {
1372
+ return workflowAllowedToolNames ?? computePlanModePolicyToolNames();
1373
+ }
975
1374
 
1375
+ function computePlanModePolicyToolNames() {
1376
+ const tools = activePlanPolicyTools();
976
1377
  const selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
977
- return withRequiredPlanModeTools(
978
- tools
979
- .filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool))
980
- .map((tool) => tool.name),
981
- );
1378
+ return tools
1379
+ .filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool))
1380
+ .map((tool) => tool.name);
982
1381
  }
983
1382
 
984
1383
  function toolSelectionSnapshot() {
@@ -998,6 +1397,15 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
998
1397
  .sort(compareTools);
999
1398
  }
1000
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
+
1001
1409
  function safeGetAllTools() {
1002
1410
  try {
1003
1411
  return pi.getAllTools();
@@ -1006,16 +1414,10 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1006
1414
  }
1007
1415
  }
1008
1416
 
1009
- function restoreTools() {
1010
- const restoredTools = previousTools ?? DEFAULT_TOOLS;
1011
- pi.setActiveTools(withoutRequiredPlanModeTools(restoredTools));
1012
- previousTools = undefined;
1013
- }
1014
-
1015
1417
  function applyPlanThinkingLevel() {
1016
1418
  if (state.manualThinkingLevel) {
1017
1419
  if (pi.getThinkingLevel() !== state.manualThinkingLevel) {
1018
- setPlanThinkingLevel(pi, state.manualThinkingLevel);
1420
+ pi.setThinkingLevel(state.manualThinkingLevel);
1019
1421
  }
1020
1422
  return;
1021
1423
  }
@@ -1030,7 +1432,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1030
1432
  }
1031
1433
  const current = pi.getThinkingLevel();
1032
1434
  if (!state.appliedThinkingLevel) state.previousThinkingLevel = current;
1033
- if (current !== configured) setPlanThinkingLevel(pi, configured);
1435
+ if (current !== configured) pi.setThinkingLevel(configured);
1034
1436
  state.appliedThinkingLevel = pi.getThinkingLevel();
1035
1437
  }
1036
1438
 
@@ -1054,19 +1456,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1054
1456
  previousThinkingLevel &&
1055
1457
  pi.getThinkingLevel() === appliedThinkingLevel
1056
1458
  ) {
1057
- setPlanThinkingLevel(pi, previousThinkingLevel);
1459
+ pi.setThinkingLevel(previousThinkingLevel);
1058
1460
  }
1059
1461
  state = { ...state, appliedThinkingLevel: undefined, previousThinkingLevel: undefined };
1060
1462
  }
1061
1463
 
1062
- function deactivatePlanModeQuestionTool() {
1063
- const activeTools = safeGetActiveTools();
1064
- const filteredTools = withoutRequiredPlanModeTools(activeTools);
1065
- if (filteredTools.length !== activeTools.length) {
1066
- pi.setActiveTools(filteredTools);
1067
- }
1068
- }
1069
-
1070
1464
  function safeGetActiveTools() {
1071
1465
  try {
1072
1466
  return pi.getActiveTools();
@@ -1075,8 +1469,145 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1075
1469
  }
1076
1470
  }
1077
1471
 
1078
- function restoreState(ctx: ExtensionContext) {
1079
- state = restorePlanModeState(ctx.sessionManager.getBranch(), STATE_ENTRY_TYPE);
1472
+ function installRestoredState(
1473
+ candidate: PlanModeState,
1474
+ ctx: ExtensionContext,
1475
+ previousToolVisibility?: PlanModeToolVisibility,
1476
+ ) {
1477
+ const previousState = state;
1478
+ const previousWorkflowAllowedToolNames = workflowAllowedToolNames;
1479
+ const previousOwner = workflowOwner;
1480
+ const previousHelperVisibility = helperVisibility.snapshot();
1481
+ const wasEnabled = state.enabled;
1482
+ if (candidate.enabled && !workflowMutex.isOwner(workflowOwner)) {
1483
+ const owner = workflowMutex.acquire();
1484
+ if (!owner) {
1485
+ state = { enabled: false, awaitingAction: false };
1486
+ workflowAllowedToolNames = undefined;
1487
+ reportRestoredWorkflowBusy(ctx);
1488
+ return false;
1489
+ }
1490
+ workflowOwner = owner;
1491
+ }
1492
+
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
+ }
1515
+ if (wasEnabled && !candidate.enabled) {
1516
+ readyPresentationIntent = undefined;
1517
+ restoreThinkingLevel();
1518
+ }
1519
+ state = candidate;
1520
+ workflowAllowedToolNames = state.enabled ? computePlanModePolicyToolNames() : undefined;
1521
+ if (state.enabled) applyPlanThinkingLevel();
1522
+ else if (wasEnabled) releaseWorkflowOwner();
1523
+ return true;
1524
+ } catch (error: unknown) {
1525
+ try {
1526
+ if (!wasEnabled && state.enabled) restoreThinkingLevel();
1527
+ } finally {
1528
+ state = previousState;
1529
+ workflowAllowedToolNames = previousWorkflowAllowedToolNames;
1530
+ helperVisibility.restore(previousHelperVisibility);
1531
+ if (workflowOwner !== previousOwner) {
1532
+ workflowMutex.release(workflowOwner);
1533
+ workflowOwner = previousOwner;
1534
+ }
1535
+ }
1536
+ throw error;
1537
+ }
1538
+ }
1539
+
1540
+ function rollbackNewActivation(
1541
+ previousState: PlanModeState,
1542
+ ctx: ExtensionContext,
1543
+ previousOwner?: WorkflowMutexOwner,
1544
+ previousHelperVisibility?: PlanModeHelperVisibilitySnapshot,
1545
+ ) {
1546
+ const activatedOwner = workflowOwner;
1547
+ readyPresentationIntent = undefined;
1548
+ try {
1549
+ if (state.enabled) {
1550
+ publishModeContract("normal", ctx);
1551
+ restoreThinkingLevel();
1552
+ }
1553
+ } finally {
1554
+ state = previousState;
1555
+ workflowAllowedToolNames = undefined;
1556
+ try {
1557
+ if (previousHelperVisibility) helperVisibility.restore(previousHelperVisibility);
1558
+ persistState();
1559
+ updateUi(ctx);
1560
+ } finally {
1561
+ if (activatedOwner !== previousOwner) {
1562
+ workflowMutex.release(activatedOwner);
1563
+ workflowOwner = previousOwner;
1564
+ }
1565
+ }
1566
+ }
1567
+ }
1568
+
1569
+ function bindWorkflowSessionIfNeeded(ctx: ExtensionContext) {
1570
+ if (currentSession === ctx.sessionManager) return;
1571
+ currentSession = ctx.sessionManager;
1572
+ workflowOwner = undefined;
1573
+ workflowMutex.bindSession(ctx.sessionManager);
1574
+ }
1575
+
1576
+ function releaseWorkflowOwner() {
1577
+ const owner = workflowOwner;
1578
+ workflowMutex.release(owner);
1579
+ if (!workflowMutex.isOwner(owner)) workflowOwner = undefined;
1580
+ }
1581
+
1582
+ function reportWorkflowBusy(ctx: ExtensionContext) {
1583
+ const message = "Another workflow is active in this session. End it before starting Plan mode.";
1584
+ if (!ctx.hasUI) throw new Error(message);
1585
+ ctx.ui.notify(message, "warning");
1586
+ return false;
1587
+ }
1588
+
1589
+ function reportRestoredWorkflowBusy(ctx: ExtensionContext) {
1590
+ if (!ctx.hasUI) return;
1591
+ ctx.ui.notify(
1592
+ "Plan mode was not restored because another workflow is active in this session. Reload or start Plan mode after it ends.",
1593
+ "warning",
1594
+ );
1595
+ }
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;
1080
1611
  }
1081
1612
 
1082
1613
  function updateUi(ctx: ExtensionContext) {
@@ -1096,13 +1627,23 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1096
1627
  }
1097
1628
 
1098
1629
  function formatToolSummary() {
1099
- const names = planModeToolNames();
1100
- 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.`;
1101
1632
  }
1102
1633
 
1103
1634
  function toolByName(toolName: string) {
1104
1635
  return safeGetAllTools().find((candidate) => candidate.name === toolName);
1105
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
+ }
1106
1647
  }
1107
1648
 
1108
1649
  export { completePlanArguments } from "./command.js";
@@ -1113,8 +1654,13 @@ export {
1113
1654
  stripProposedPlanBlocks,
1114
1655
  stripProposedPlanBlocksFromMessage,
1115
1656
  } from "./message-transform.js";
1657
+ export {
1658
+ createModeContractMessage,
1659
+ modeContractContent,
1660
+ reconcileModeContract,
1661
+ } from "./mode-contract.js";
1116
1662
  export { buildPlanModePrompt } from "./prompt.js";
1117
1663
  export { normalizePlanModeQuestionParams } from "./question-tool.js";
1118
- export { withoutPlanModeQuestionTool, withRequiredPlanModeTools } from "./required-tools.js";
1664
+ export { withRequiredPlanModeTools } from "./required-tools.js";
1119
1665
  export { normalizePlanModeSettings, readPlanModeSettings } from "./settings.js";
1120
1666
  export { canSelectToolInPlanMode, classifyPlanModeTool, isSafeCommand } from "./tool-policy.js";