@narumitw/pi-plan-mode 0.47.1 → 0.48.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
@@ -1,6 +1,9 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import type { ExtensionAPI, ExtensionContext, ToolInfo } from "@earendil-works/pi-coding-agent";
3
- import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionCommandContext,
5
+ ExtensionContext,
6
+ } from "@earendil-works/pi-coding-agent";
4
7
  import { showActiveImplementationMenu } from "./active-implementation-menu.js";
5
8
  import { completePlanArguments } from "./command.js";
6
9
  import {
@@ -16,20 +19,17 @@ import {
16
19
  setPlanThinkingLevel,
17
20
  } from "./extension-runtime.js";
18
21
  import {
19
- injectActiveImplementationContext,
20
- invalidPlanMessage,
21
- isEmptyAssistantMessage,
22
- latestAssistantText,
23
- messageContainsInactivePlanModeArtifact,
24
- messageContainsLegacyPlanModeContextArtifact,
25
- messageContainsPlanModeImplementationContextArtifact,
26
- messageContainsPlanModeImplementationHandoff,
27
- parseProposedPlan,
28
- stripPlanModeCompletionCallsFromMessage,
29
- stripProposedPlanBlocksFromMessage,
30
- } from "./message-transform.js";
31
- import { showPlanModeMenu, showReadyPlanMenu } from "./plan-action-menus.js";
32
- import { exportStoredPlan } from "./plan-export.js";
22
+ formatImplementationHandoff,
23
+ startFreshImplementationFromState,
24
+ } from "./fresh-implementation.js";
25
+ import {
26
+ createImplementationRetentionCoordinator,
27
+ implementationRetentionPreview,
28
+ } from "./implementation-retention.js";
29
+ import { invalidPlanMessage, latestAssistantText, parseProposedPlan } from "./message-transform.js";
30
+ import { createPlanActionController } from "./plan-action-controller.js";
31
+ import { createPlanExportController } from "./plan-export-controller.js";
32
+ import { showPlanLaunchMenu } from "./plan-launch-menu.js";
33
33
  import {
34
34
  clearPlanModeUi,
35
35
  planModeStatusText as formatPlanModeStatusText,
@@ -45,51 +45,87 @@ import {
45
45
  planModeQuestionCancelled,
46
46
  } from "./question-tool.js";
47
47
  import { withoutRequiredPlanModeTools, withRequiredPlanModeTools } from "./required-tools.js";
48
- import { showSavedPlanMenu } from "./saved-plan-menu.js";
49
48
  import {
50
49
  preflightSavedPlanImplementation,
51
50
  savedPlanBlocksNewWorkflow,
52
51
  } from "./saved-plan-preflight.js";
53
52
  import {
53
+ awaitPlanModeSettingsWrites,
54
+ configuredImplementationPlanRetention,
54
55
  configuredThinkingLevel,
55
56
  type PlanModeSettings,
56
57
  readPlanModeSettings,
57
58
  } from "./settings.js";
59
+ import { showPlanModeSettings } from "./settings-menu.js";
58
60
  import { type PlanCompletionSource, type PlanModeState, restorePlanModeState } from "./state.js";
59
61
  import {
60
62
  canSelectToolInPlanMode,
61
63
  classifyPlanModeTool,
62
64
  findBlockedCommandSegment,
63
- isBuiltinTool,
64
65
  readCommand,
65
- SAFE_BUILTIN_PLAN_TOOLS,
66
66
  } from "./tool-policy.js";
67
- import { compareTools, toolNameFromLegacyKey, toolPolicyLabel, unique } from "./tool-selection.js";
67
+ import {
68
+ compareTools,
69
+ filterAvailableSelectedToolNames,
70
+ snapshotPlanModeSelectedNames,
71
+ snapshotPlanModeToolNames,
72
+ toolPolicyLabel,
73
+ } from "./tool-selection.js";
68
74
 
69
75
  const STATE_ENTRY_TYPE = "plan-mode-state";
70
76
  const PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
71
77
  const BLOCKED_BUILTIN_TOOLS = new Set(["edit", "write"]);
72
78
  const DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
73
- const TOOL_SELECTOR_VIEWPORT_SIZE = 10;
74
-
75
79
  interface ReadyPresentationIntent {
76
80
  nonce: number;
77
81
  plan: string;
78
82
  source: PlanCompletionSource;
79
83
  }
80
-
81
- export default function planMode(
82
- pi: ExtensionAPI,
83
- dependencies: { readSettings?(): ReturnType<typeof readPlanModeSettings> } = {},
84
- ) {
84
+ interface PlanModeDependencies {
85
+ readSettings?(): ReturnType<typeof readPlanModeSettings>;
86
+ settingsPath?: string;
87
+ }
88
+ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDependencies = {}) {
85
89
  let state: PlanModeState = { enabled: false, awaitingAction: false };
86
90
  let settings: PlanModeSettings = { thinkingLevel: "inherit" };
87
91
  let previousTools: string[] | undefined;
88
92
  let readyPresentationIntent: ReadyPresentationIntent | undefined;
93
+ let latestCommandContext: ExtensionCommandContext | undefined;
89
94
  let nextReadyPresentationNonce = 0;
90
95
  let menuGeneration = 0;
91
96
  let workflowGeneration = 0;
97
+ let refreshStateBeforeFirstAgentStart = false;
92
98
  let menuController = new AbortController();
99
+ const implementationRetention = createImplementationRetentionCoordinator();
100
+ const persistState = () => pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, state);
101
+ const planExports = createPlanExportController({
102
+ getState: () => state,
103
+ getSettings: () => settings,
104
+ finishReady: (ctx) => exitPlanMode(ctx),
105
+ });
106
+ const planActions = createPlanActionController({
107
+ getState: () => state,
108
+ captureLifecycle: captureMenuLifecycle,
109
+ statusText: planStatusText,
110
+ implementationOutcome,
111
+ getExportDestination: (ctx) => planExports.getDestination(ctx),
112
+ show: (ctx) => showStoredPlan(pi, ctx, state),
113
+ finalize: requestFinalPlan,
114
+ implementHere: startImplementation,
115
+ implementFresh: startFreshImplementation,
116
+ exportPlan: (ctx, path, signal, isCurrent) => planExports.export(path, ctx, signal, isCurrent),
117
+ settings: showSettings,
118
+ save: savePlanForLater,
119
+ stay: updateUi,
120
+ exitReady: (ctx) => {
121
+ exitPlanMode(ctx);
122
+ ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
123
+ },
124
+ clearSaved: (ctx) => {
125
+ exitPlanMode(ctx);
126
+ ctx.ui.notify("Saved plan cleared.", "info");
127
+ },
128
+ });
93
129
 
94
130
  pi.registerFlag("plan", {
95
131
  description: "Start in Codex-like Plan mode",
@@ -166,8 +202,20 @@ export default function planMode(
166
202
  description: "Enter or manage Codex-like Plan mode",
167
203
  getArgumentCompletions: completePlanArguments,
168
204
  handler: async (args, ctx) => {
205
+ latestCommandContext = ctx;
169
206
  const prompt = args.trim();
170
207
  const command = prompt.toLowerCase();
208
+ if (command === "start") {
209
+ if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))
210
+ return;
211
+ if (state.enabled) {
212
+ ctx.ui.notify("Plan mode is already active.", "info");
213
+ return;
214
+ }
215
+ enterPlanMode(ctx);
216
+ ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
217
+ return;
218
+ }
171
219
  if (command === "show") {
172
220
  showStoredPlan(pi, ctx, state);
173
221
  return;
@@ -191,12 +239,7 @@ export default function planMode(
191
239
  const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
192
240
  if (exportMatch) {
193
241
  const lifecycle = captureMenuLifecycle();
194
- await exportStoredPlan(
195
- state,
196
- exportMatch[1],
197
- ctx,
198
- exportOwner(ctx, lifecycle.signal, lifecycle.isCurrent),
199
- );
242
+ await planExports.export(exportMatch[1], ctx, lifecycle.signal, lifecycle.isCurrent);
200
243
  return;
201
244
  }
202
245
  if (command === "exit" || command === "off") {
@@ -214,8 +257,17 @@ export default function planMode(
214
257
  if (command === "tools") {
215
258
  if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))
216
259
  return;
217
- if (!state.enabled) enterPlanMode(ctx);
218
- await showToolSelector(ctx);
260
+ if (state.enabled) {
261
+ const message =
262
+ "Plan-mode tools are locked while Planning is active. Exit Plan mode and choose tools before starting again.";
263
+ if (!ctx.hasUI) throw new Error(message);
264
+ ctx.ui.notify(message, "warning");
265
+ return;
266
+ }
267
+ if (!ctx.hasUI) {
268
+ throw new Error("/plan tools requires TUI or RPC mode and is unavailable here.");
269
+ }
270
+ await showLaunchMenu(ctx, "tools");
219
271
  return;
220
272
  }
221
273
  if (prompt) {
@@ -224,30 +276,38 @@ export default function planMode(
224
276
  enterPlanModeWithPrompt(prompt, ctx);
225
277
  return;
226
278
  }
279
+ if (!ctx.hasUI) {
280
+ throw new Error(
281
+ "The interactive /plan menu is unavailable in print and JSON modes. Use /plan start or /plan <prompt>.",
282
+ );
283
+ }
227
284
  if (!state.enabled) {
228
285
  if (state.activeImplementation && ctx.hasUI) {
229
286
  await showActivePlanMenu(ctx);
230
287
  return;
231
288
  }
232
289
  if (state.savedPlan) {
233
- await showSavedPlanActions(ctx);
290
+ await planActions.showSaved(ctx);
234
291
  return;
235
292
  }
236
- enterPlanMode(ctx);
237
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
293
+ await showLaunchMenu(ctx);
238
294
  return;
239
295
  }
240
- await showPlanMenu(ctx);
296
+ await planActions.showCurrent(ctx);
241
297
  },
242
298
  });
243
299
 
244
- pi.on("session_start", async (_event, ctx) => {
300
+ pi.on("session_start", async (event, ctx) => {
245
301
  const generation = ++menuGeneration;
302
+ refreshStateBeforeFirstAgentStart = event.reason === "new";
246
303
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
247
304
  menuController = new AbortController();
248
305
  readyPresentationIntent = undefined;
306
+ latestCommandContext = undefined;
307
+ implementationRetention.reset();
249
308
  settings = { thinkingLevel: "inherit" };
250
309
  restoreState(ctx);
310
+ implementationRetention.restore(state.activeImplementation);
251
311
  const loadedSettings = await (dependencies.readSettings?.() ?? readPlanModeSettings());
252
312
  if (generation !== menuGeneration || menuController.signal.aborted) return;
253
313
  if (loadedSettings.kind === "loaded") settings = loadedSettings.settings;
@@ -290,10 +350,14 @@ export default function planMode(
290
350
  }
291
351
  });
292
352
 
293
- pi.on("session_shutdown", (_event, ctx) => {
353
+ pi.on("session_shutdown", async (_event, ctx) => {
294
354
  menuGeneration += 1;
295
355
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
296
356
  readyPresentationIntent = undefined;
357
+ latestCommandContext = undefined;
358
+ refreshStateBeforeFirstAgentStart = false;
359
+ implementationRetention.reset();
360
+ await awaitPlanModeSettingsWrites(dependencies.settingsPath);
297
361
  captureManualThinkingLevel();
298
362
  persistState();
299
363
  if (state.enabled) {
@@ -337,36 +401,26 @@ export default function planMode(
337
401
  }
338
402
  });
339
403
 
340
- pi.on("context", async (event) => {
341
- const messagesWithoutPlanContext = event.messages.filter(
342
- (message: unknown) =>
343
- !messageContainsLegacyPlanModeContextArtifact(message) &&
344
- !messageContainsPlanModeImplementationContextArtifact(message),
345
- );
346
- if (state.enabled) {
347
- return {
348
- messages: messagesWithoutPlanContext.filter(
349
- (message: unknown) => !messageContainsPlanModeImplementationHandoff(message),
350
- ),
351
- };
404
+ pi.on("context", async (event, ctx) => {
405
+ const result = implementationRetention.transformContext(event.messages, state);
406
+ if (result.clearActiveImplementationId) {
407
+ clearActiveImplementation(result.clearActiveImplementationId, ctx);
352
408
  }
353
- const inactiveMessages = state.activeImplementation
354
- ? messagesWithoutPlanContext
355
- : messagesWithoutPlanContext.filter(
356
- (message: unknown) => !messageContainsPlanModeImplementationHandoff(message),
357
- );
358
- const messages = inactiveMessages
359
- .filter((message: unknown) => !messageContainsInactivePlanModeArtifact(message))
360
- .map(stripProposedPlanBlocksFromMessage)
361
- .map(stripPlanModeCompletionCallsFromMessage)
362
- .filter((message: unknown) => !isEmptyAssistantMessage(message));
363
- const contextualMessages = state.activeImplementation
364
- ? injectActiveImplementationContext(messages, state.activeImplementation)
365
- : messages;
366
- return { messages: contextualMessages as typeof event.messages };
409
+ return { messages: result.messages as typeof event.messages };
367
410
  });
368
411
 
369
412
  pi.on("before_agent_start", (event, ctx) => {
413
+ if (refreshStateBeforeFirstAgentStart) {
414
+ refreshStateBeforeFirstAgentStart = false;
415
+ restoreState(ctx);
416
+ implementationRetention.reset();
417
+ implementationRetention.restore(state.activeImplementation);
418
+ if (state.enabled) {
419
+ activatePlanModeTools();
420
+ applyPlanThinkingLevel();
421
+ } else deactivatePlanModeQuestionTool();
422
+ updateUi(ctx);
423
+ }
370
424
  if (!state.enabled) return;
371
425
  if (state.latestPlan || state.awaitingAction) {
372
426
  readyPresentationIntent = undefined;
@@ -402,6 +456,11 @@ export default function planMode(
402
456
  });
403
457
 
404
458
  onAgentSettled(pi, async (_event, ctx) => {
459
+ const settledImplementationId = implementationRetention.implementationSettled(
460
+ state.activeImplementation,
461
+ );
462
+ if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);
463
+
405
464
  const intent = readyPresentationIntent;
406
465
  if (!intent || !readyPresentationIsCurrent(intent)) return;
407
466
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
@@ -419,7 +478,7 @@ export default function planMode(
419
478
  );
420
479
  }
421
480
  if (ctx.hasUI && completedPlanIsCurrent(intent)) {
422
- await showPlanReadyMenu(ctx);
481
+ await planActions.showReady(latestCommandContext ?? ctx);
423
482
  }
424
483
  } catch (error: unknown) {
425
484
  if (!isStaleExtensionContextError(error)) throw error;
@@ -579,6 +638,15 @@ export default function planMode(
579
638
  ctx.ui.notify("Plan saved for later. Plan mode disabled.", "info");
580
639
  }
581
640
 
641
+ async function startFreshImplementation(ctx: ExtensionContext, menuIsCurrent: () => boolean) {
642
+ await startFreshImplementationFromState(ctx, {
643
+ getState: () => state,
644
+ menuIsCurrent,
645
+ retention: configuredImplementationPlanRetention(settings),
646
+ stateEntryType: STATE_ENTRY_TYPE,
647
+ });
648
+ }
649
+
582
650
  async function startImplementation(ctx: ExtensionContext) {
583
651
  const savedPlan = state.enabled ? undefined : state.savedPlan;
584
652
  if (savedPlan) {
@@ -616,6 +684,7 @@ export default function planMode(
616
684
  plan,
617
685
  source,
618
686
  startedAt: Date.now(),
687
+ retention: configuredImplementationPlanRetention(settings),
619
688
  },
620
689
  manualThinkingLevel: undefined,
621
690
  };
@@ -627,10 +696,7 @@ export default function planMode(
627
696
  persistState();
628
697
  updateUi(ctx);
629
698
 
630
- const sent = sendPlanModeUserMessage(
631
- `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:\n\n${plan}`,
632
- ctx,
633
- );
699
+ const sent = sendPlanModeUserMessage(formatImplementationHandoff(plan), ctx);
634
700
  if (!sent) {
635
701
  if (savedPlan) {
636
702
  state = previousState;
@@ -644,6 +710,56 @@ export default function planMode(
644
710
  }
645
711
  }
646
712
 
713
+ function clearActiveImplementation(id: string, ctx: ExtensionContext) {
714
+ if (state.activeImplementation?.id !== id) return false;
715
+ workflowGeneration += 1;
716
+ state = { ...state, activeImplementation: undefined };
717
+ persistState();
718
+ updateUi(ctx);
719
+ return true;
720
+ }
721
+
722
+ async function showLaunchMenu(ctx: ExtensionContext, initialScreen: "main" | "tools" = "main") {
723
+ const lifecycle = captureMenuLifecycle();
724
+ const tools = selectableTools();
725
+ await showPlanLaunchMenu(ctx, {
726
+ statusText: "Status: Off — normal tools are active.",
727
+ initialScreen,
728
+ getSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),
729
+ toolSummary: (selectedNames) =>
730
+ `When started: ${snapshotPlanModeToolNames(tools, selectedNames, toolSelectionSnapshot()).join(", ")}`,
731
+ tools: tools.map((tool) => {
732
+ const selectable = canSelectToolInPlanMode(tool);
733
+ const policy = toolPolicyLabel(tool);
734
+ const description = tool.description ?? "No description available";
735
+ return {
736
+ name: tool.name,
737
+ description: `${policy} · ${description}`,
738
+ searchText: [policy, description].join(" "),
739
+ disabled: !selectable,
740
+ disabledReason: selectable ? undefined : "Blocked by Plan-mode policy",
741
+ };
742
+ }),
743
+ ...lifecycle,
744
+ start: (signal) => {
745
+ if (signal.aborted || !lifecycle.isCurrent()) return;
746
+ enterPlanMode(ctx);
747
+ ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
748
+ },
749
+ startWithTools: (names, signal) => {
750
+ if (signal.aborted || !lifecycle.isCurrent()) return;
751
+ state = {
752
+ ...state,
753
+ selectedToolNames: filterAvailableSelectedToolNames(names, tools),
754
+ selectedToolKeys: undefined,
755
+ };
756
+ enterPlanMode(ctx);
757
+ ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
758
+ },
759
+ settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),
760
+ });
761
+ }
762
+
647
763
  async function showActivePlanMenu(ctx: ExtensionContext) {
648
764
  if (!ctx.hasUI) {
649
765
  ctx.ui.notify(planStatusText(), "info");
@@ -652,11 +768,12 @@ export default function planMode(
652
768
  const lifecycle = captureMenuLifecycle();
653
769
  await showActiveImplementationMenu(ctx, {
654
770
  statusText: planStatusText(),
771
+ getExportDestination: () => planExports.getDestination(ctx),
655
772
  signal: lifecycle.signal,
656
773
  isCurrent: lifecycle.isCurrent,
657
774
  show: () => showStoredPlan(pi, ctx, state),
658
- exportPlan: (path, signal) =>
659
- exportStoredPlan(state, path, ctx, exportOwner(ctx, signal, lifecycle.isCurrent)),
775
+ exportPlan: (path, signal) => planExports.export(path, ctx, signal, lifecycle.isCurrent),
776
+ settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),
660
777
  startNew: () => {
661
778
  enterPlanMode(ctx);
662
779
  ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
@@ -668,131 +785,24 @@ export default function planMode(
668
785
  });
669
786
  }
670
787
 
671
- async function showSavedPlanActions(ctx: ExtensionContext) {
672
- const lifecycle = captureMenuLifecycle();
673
- await showSavedPlanMenu(ctx, {
674
- statusText: planStatusText(),
675
- signal: lifecycle.signal,
676
- isCurrent: lifecycle.isCurrent,
677
- show: () => showStoredPlan(pi, ctx, state),
678
- implement: () => startImplementation(ctx),
679
- exportPlan: (path, signal) =>
680
- exportStoredPlan(state, path, ctx, exportOwner(ctx, signal, lifecycle.isCurrent)),
681
- clear: () => {
682
- exitPlanMode(ctx);
683
- ctx.ui.notify("Saved plan cleared.", "info");
684
- },
685
- });
686
- }
687
-
688
- async function showPlanMenu(ctx: ExtensionContext) {
689
- if (!ctx.hasUI) {
690
- ctx.ui.notify(planStatusText(), "info");
691
- return;
692
- }
693
- const lifecycle = captureMenuLifecycle();
694
- await showPlanModeMenu(ctx, {
695
- statusText: planStatusText(),
696
- hasReadyPlan: state.latestPlan !== undefined,
697
- ...lifecycle,
698
- show: () => showStoredPlan(pi, ctx, state),
699
- finalize: () => requestFinalPlan(ctx),
700
- implement: () => startImplementation(ctx),
701
- exportPlan: (path, signal) =>
702
- exportStoredPlan(state, path, ctx, exportOwner(ctx, signal, lifecycle.isCurrent)),
703
- save: () => savePlanForLater(ctx),
704
- tools: () => showToolSelector(ctx),
705
- stay: () => updateUi(ctx),
706
- exit: () => {
707
- exitPlanMode(ctx);
708
- ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
709
- },
710
- });
711
- }
712
-
713
- async function showPlanReadyMenu(ctx: ExtensionContext) {
714
- const lifecycle = captureMenuLifecycle();
715
- await showReadyPlanMenu(ctx, {
716
- ...lifecycle,
717
- implement: () => startImplementation(ctx),
718
- exportPlan: (path, signal) =>
719
- exportStoredPlan(state, path, ctx, exportOwner(ctx, signal, lifecycle.isCurrent)),
720
- save: () => savePlanForLater(ctx),
721
- stay: () => undefined,
722
- exit: () => {
723
- exitPlanMode(ctx);
724
- ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
725
- },
726
- });
727
- }
728
-
729
- async function showToolSelector(ctx: ExtensionContext) {
730
- if (!ctx.hasUI) {
731
- ctx.ui.notify(formatToolSummary(), "info");
732
- return;
733
- }
734
- const lifecycle = captureMenuLifecycle();
735
- const tools = selectableTools();
736
- const toolById = new Map(tools.map((tool, index) => [`${index}:${tool.name}`, tool]));
737
- const menu = defineMenu<undefined, "tools", "toggle", ExtensionContext>({
738
- start: "tools",
739
- screens: {
740
- tools: () => {
741
- const selectedNames = planModeSelectedNames(tools);
742
- return {
743
- kind: "multiSelect",
744
- title: "Plan-mode tools",
745
- lines: ["Non-built-in tools run at user risk."],
746
- enableSearch: true,
747
- viewportSize: TOOL_SELECTOR_VIEWPORT_SIZE,
748
- items: tools.map((tool, index) => {
749
- const selectable = canSelectToolInPlanMode(tool);
750
- return {
751
- id: `${index}:${tool.name}`,
752
- label: tool.name,
753
- description: `${toolPolicyLabel(tool)} · ${tool.description}`,
754
- searchText: [toolPolicyLabel(tool), tool.description].filter(Boolean).join(" "),
755
- selected: selectedNames.has(tool.name),
756
- disabled: !selectable,
757
- disabledReason: selectable ? undefined : "Blocked by Plan-mode policy",
758
- };
759
- }),
760
- action: "toggle",
761
- hint: "close",
762
- doneLabel: "Done",
763
- };
764
- },
765
- },
766
- actions: {
767
- toggle: async ({ itemId, selected }) => {
768
- const tool = toolById.get(itemId);
769
- if (!tool || !canSelectToolInPlanMode(tool)) return { kind: "rejected" };
770
- const names = planModeSelectedNames(tools);
771
- if (selected) names.add(tool.name);
772
- else names.delete(tool.name);
773
- state = {
774
- ...state,
775
- selectedToolNames: filterAvailableSelectedNames(Array.from(names), tools),
776
- };
777
- applyPlanModeTools();
778
- persistState();
779
- updateUi(ctx);
780
- return { kind: "stay" };
781
- },
788
+ async function showSettings(
789
+ ctx: ExtensionContext,
790
+ signal: AbortSignal,
791
+ isCurrent: () => boolean,
792
+ ) {
793
+ const result = await showPlanModeSettings(ctx, {
794
+ tools: selectableTools(),
795
+ signal,
796
+ isCurrent,
797
+ settingsPath: dependencies.settingsPath,
798
+ onSaved: (saved) => {
799
+ if (isCurrent()) settings = saved;
782
800
  },
801
+ ...(dependencies.readSettings
802
+ ? { readSettings: async () => dependencies.readSettings?.() ?? { kind: "missing" } }
803
+ : {}),
783
804
  });
784
- await runMenu(ctx, menu, {
785
- getState: () => undefined,
786
- ...lifecycle,
787
- });
788
- if (!lifecycle.isCurrent()) return;
789
- applyPlanModeTools();
790
- persistState();
791
- updateUi(ctx);
792
- }
793
-
794
- function exportOwner(ctx: ExtensionContext, signal: AbortSignal, isCurrent: () => boolean) {
795
- return { signal, isCurrent, getState: () => state, finishReady: () => exitPlanMode(ctx) };
805
+ return result.kind === "closed" && "reason" in result && result.reason === "close";
796
806
  }
797
807
 
798
808
  function captureMenuLifecycle() {
@@ -828,7 +838,7 @@ export default function planMode(
828
838
  return ["read", "bash", PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME];
829
839
  }
830
840
 
831
- const selectedNames = planModeSelectedNames(tools);
841
+ const selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
832
842
  return withRequiredPlanModeTools(
833
843
  tools
834
844
  .filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool))
@@ -836,37 +846,12 @@ export default function planMode(
836
846
  );
837
847
  }
838
848
 
839
- function planModeSelectedNames(tools: ToolInfo[]) {
840
- const selectedToolNames = state.selectedToolNames ?? migrateSelectedToolKeys(tools);
841
- if (selectedToolNames === undefined) return new Set(defaultPlanModeToolNames(tools));
842
-
843
- state = {
844
- ...state,
845
- selectedToolNames: filterAvailableSelectedNames(selectedToolNames, tools),
846
- selectedToolKeys: undefined,
849
+ function toolSelectionSnapshot() {
850
+ return {
851
+ selectedToolNames: state.selectedToolNames,
852
+ selectedToolKeys: state.selectedToolKeys,
853
+ defaultPlanTools: settings.defaultPlanTools,
847
854
  };
848
- return new Set(state.selectedToolNames);
849
- }
850
-
851
- function defaultPlanModeToolNames(tools: ToolInfo[]) {
852
- if (settings.defaultPlanTools !== undefined) {
853
- return filterAvailableSelectedNames(settings.defaultPlanTools, tools);
854
- }
855
- return tools
856
- .filter((tool) => isBuiltinTool(tool) && SAFE_BUILTIN_PLAN_TOOLS.has(tool.name))
857
- .map((tool) => tool.name);
858
- }
859
-
860
- function migrateSelectedToolKeys(tools: ToolInfo[]) {
861
- if (state.selectedToolKeys === undefined) return undefined;
862
- return state.selectedToolKeys
863
- .map((key) => toolNameFromLegacyKey(key, tools))
864
- .filter((name): name is string => name !== undefined);
865
- }
866
-
867
- function filterAvailableSelectedNames(names: string[], tools: ToolInfo[]) {
868
- const availableNames = new Set(tools.filter(canSelectToolInPlanMode).map((tool) => tool.name));
869
- return unique(names.filter((name) => availableNames.has(name)));
870
855
  }
871
856
 
872
857
  function selectableTools() {
@@ -955,10 +940,6 @@ export default function planMode(
955
940
  }
956
941
  }
957
942
 
958
- function persistState() {
959
- pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, state);
960
- }
961
-
962
943
  function restoreState(ctx: ExtensionContext) {
963
944
  state = restorePlanModeState(ctx.sessionManager.getBranch(), STATE_ENTRY_TYPE);
964
945
  }
@@ -975,6 +956,10 @@ export default function planMode(
975
956
  return formatPlanModeStatusText(state, formatToolSummary);
976
957
  }
977
958
 
959
+ function implementationOutcome() {
960
+ return implementationRetentionPreview(configuredImplementationPlanRetention(settings));
961
+ }
962
+
978
963
  function formatToolSummary() {
979
964
  const names = planModeToolNames();
980
965
  return `Tools: ${names.length > 0 ? names.join(", ") : "none"}`;