@narumitw/pi-plan-mode 0.47.1 → 0.49.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,7 +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";
4
- import { showActiveImplementationMenu } from "./active-implementation-menu.js";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionCommandContext,
5
+ ExtensionContext,
6
+ } from "@earendil-works/pi-coding-agent";
5
7
  import { completePlanArguments } from "./command.js";
6
8
  import {
7
9
  normalizePlanModeCompletion,
@@ -16,20 +18,16 @@ import {
16
18
  setPlanThinkingLevel,
17
19
  } from "./extension-runtime.js";
18
20
  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";
21
+ formatImplementationHandoff,
22
+ startFreshImplementationFromState,
23
+ } from "./fresh-implementation.js";
24
+ import {
25
+ createImplementationRetentionCoordinator,
26
+ implementationRetentionPreview,
27
+ } from "./implementation-retention.js";
28
+ import { invalidPlanMessage, latestAssistantText, parseProposedPlan } from "./message-transform.js";
29
+ import { createPlanActionController } from "./plan-action-controller.js";
30
+ import { createPlanExportController } from "./plan-export-controller.js";
33
31
  import {
34
32
  clearPlanModeUi,
35
33
  planModeStatusText as formatPlanModeStatusText,
@@ -45,12 +43,13 @@ import {
45
43
  planModeQuestionCancelled,
46
44
  } from "./question-tool.js";
47
45
  import { withoutRequiredPlanModeTools, withRequiredPlanModeTools } from "./required-tools.js";
48
- import { showSavedPlanMenu } from "./saved-plan-menu.js";
49
46
  import {
50
47
  preflightSavedPlanImplementation,
51
48
  savedPlanBlocksNewWorkflow,
52
49
  } from "./saved-plan-preflight.js";
53
50
  import {
51
+ awaitPlanModeSettingsWrites,
52
+ configuredImplementationPlanRetention,
54
53
  configuredThinkingLevel,
55
54
  type PlanModeSettings,
56
55
  readPlanModeSettings,
@@ -60,36 +59,85 @@ import {
60
59
  canSelectToolInPlanMode,
61
60
  classifyPlanModeTool,
62
61
  findBlockedCommandSegment,
63
- isBuiltinTool,
64
62
  readCommand,
65
- SAFE_BUILTIN_PLAN_TOOLS,
66
63
  } from "./tool-policy.js";
67
- import { compareTools, toolNameFromLegacyKey, toolPolicyLabel, unique } from "./tool-selection.js";
64
+ import {
65
+ compareTools,
66
+ filterAvailableSelectedToolNames,
67
+ snapshotPlanModeSelectedNames,
68
+ snapshotPlanModeToolNames,
69
+ toolPolicyLabel,
70
+ } from "./tool-selection.js";
68
71
 
69
72
  const STATE_ENTRY_TYPE = "plan-mode-state";
70
73
  const PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
71
74
  const BLOCKED_BUILTIN_TOOLS = new Set(["edit", "write"]);
72
75
  const DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
73
- const TOOL_SELECTOR_VIEWPORT_SIZE = 10;
74
-
75
76
  interface ReadyPresentationIntent {
76
77
  nonce: number;
77
78
  plan: string;
78
79
  source: PlanCompletionSource;
79
80
  }
81
+ type InteractiveUi = typeof import("./interactive-ui.js");
80
82
 
81
- export default function planMode(
82
- pi: ExtensionAPI,
83
- dependencies: { readSettings?(): ReturnType<typeof readPlanModeSettings> } = {},
84
- ) {
83
+ interface PlanModeDependencies {
84
+ readSettings?(): ReturnType<typeof readPlanModeSettings>;
85
+ settingsPath?: string;
86
+ loadInteractiveUi?(): Promise<InteractiveUi>;
87
+ }
88
+ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDependencies = {}) {
89
+ let interactiveUiPromise: Promise<InteractiveUi> | undefined;
90
+ const loadInteractiveUi = () => {
91
+ if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
92
+ if (!interactiveUiPromise) {
93
+ interactiveUiPromise = import("./interactive-ui.js").catch((error) => {
94
+ interactiveUiPromise = undefined;
95
+ throw error;
96
+ });
97
+ }
98
+ return interactiveUiPromise;
99
+ };
85
100
  let state: PlanModeState = { enabled: false, awaitingAction: false };
86
101
  let settings: PlanModeSettings = { thinkingLevel: "inherit" };
87
102
  let previousTools: string[] | undefined;
88
103
  let readyPresentationIntent: ReadyPresentationIntent | undefined;
104
+ let latestCommandContext: ExtensionCommandContext | undefined;
89
105
  let nextReadyPresentationNonce = 0;
90
106
  let menuGeneration = 0;
91
107
  let workflowGeneration = 0;
108
+ let refreshStateBeforeFirstAgentStart = false;
92
109
  let menuController = new AbortController();
110
+ const implementationRetention = createImplementationRetentionCoordinator();
111
+ const persistState = () => pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, state);
112
+ const planExports = createPlanExportController({
113
+ getState: () => state,
114
+ getSettings: () => settings,
115
+ finishReady: (ctx) => exitPlanMode(ctx),
116
+ });
117
+ const planActions = createPlanActionController({
118
+ loadInteractiveUi,
119
+ getState: () => state,
120
+ captureLifecycle: captureMenuLifecycle,
121
+ statusText: planStatusText,
122
+ implementationOutcome,
123
+ getExportDestination: (ctx) => planExports.getDestination(ctx),
124
+ show: (ctx) => showStoredPlan(pi, ctx, state),
125
+ finalize: requestFinalPlan,
126
+ implementHere: startImplementation,
127
+ implementFresh: startFreshImplementation,
128
+ exportPlan: (ctx, path, signal, isCurrent) => planExports.export(path, ctx, signal, isCurrent),
129
+ settings: showSettings,
130
+ save: savePlanForLater,
131
+ stay: updateUi,
132
+ exitReady: (ctx) => {
133
+ exitPlanMode(ctx);
134
+ ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
135
+ },
136
+ clearSaved: (ctx) => {
137
+ exitPlanMode(ctx);
138
+ ctx.ui.notify("Saved plan cleared.", "info");
139
+ },
140
+ });
93
141
 
94
142
  pi.registerFlag("plan", {
95
143
  description: "Start in Codex-like Plan mode",
@@ -166,8 +214,20 @@ export default function planMode(
166
214
  description: "Enter or manage Codex-like Plan mode",
167
215
  getArgumentCompletions: completePlanArguments,
168
216
  handler: async (args, ctx) => {
217
+ latestCommandContext = ctx;
169
218
  const prompt = args.trim();
170
219
  const command = prompt.toLowerCase();
220
+ if (command === "start") {
221
+ if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))
222
+ return;
223
+ if (state.enabled) {
224
+ ctx.ui.notify("Plan mode is already active.", "info");
225
+ return;
226
+ }
227
+ enterPlanMode(ctx);
228
+ ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
229
+ return;
230
+ }
171
231
  if (command === "show") {
172
232
  showStoredPlan(pi, ctx, state);
173
233
  return;
@@ -191,12 +251,7 @@ export default function planMode(
191
251
  const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
192
252
  if (exportMatch) {
193
253
  const lifecycle = captureMenuLifecycle();
194
- await exportStoredPlan(
195
- state,
196
- exportMatch[1],
197
- ctx,
198
- exportOwner(ctx, lifecycle.signal, lifecycle.isCurrent),
199
- );
254
+ await planExports.export(exportMatch[1], ctx, lifecycle.signal, lifecycle.isCurrent);
200
255
  return;
201
256
  }
202
257
  if (command === "exit" || command === "off") {
@@ -214,8 +269,17 @@ export default function planMode(
214
269
  if (command === "tools") {
215
270
  if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))
216
271
  return;
217
- if (!state.enabled) enterPlanMode(ctx);
218
- await showToolSelector(ctx);
272
+ if (state.enabled) {
273
+ const message =
274
+ "Plan-mode tools are locked while Planning is active. Exit Plan mode and choose tools before starting again.";
275
+ if (!ctx.hasUI) throw new Error(message);
276
+ ctx.ui.notify(message, "warning");
277
+ return;
278
+ }
279
+ if (!ctx.hasUI) {
280
+ throw new Error("/plan tools requires TUI or RPC mode and is unavailable here.");
281
+ }
282
+ await showLaunchMenu(ctx, "tools");
219
283
  return;
220
284
  }
221
285
  if (prompt) {
@@ -224,30 +288,38 @@ export default function planMode(
224
288
  enterPlanModeWithPrompt(prompt, ctx);
225
289
  return;
226
290
  }
291
+ if (!ctx.hasUI) {
292
+ throw new Error(
293
+ "The interactive /plan menu is unavailable in print and JSON modes. Use /plan start or /plan <prompt>.",
294
+ );
295
+ }
227
296
  if (!state.enabled) {
228
297
  if (state.activeImplementation && ctx.hasUI) {
229
298
  await showActivePlanMenu(ctx);
230
299
  return;
231
300
  }
232
301
  if (state.savedPlan) {
233
- await showSavedPlanActions(ctx);
302
+ await planActions.showSaved(ctx);
234
303
  return;
235
304
  }
236
- enterPlanMode(ctx);
237
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
305
+ await showLaunchMenu(ctx);
238
306
  return;
239
307
  }
240
- await showPlanMenu(ctx);
308
+ await planActions.showCurrent(ctx);
241
309
  },
242
310
  });
243
311
 
244
- pi.on("session_start", async (_event, ctx) => {
312
+ pi.on("session_start", async (event, ctx) => {
245
313
  const generation = ++menuGeneration;
314
+ refreshStateBeforeFirstAgentStart = event.reason === "new";
246
315
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
247
316
  menuController = new AbortController();
248
317
  readyPresentationIntent = undefined;
318
+ latestCommandContext = undefined;
319
+ implementationRetention.reset();
249
320
  settings = { thinkingLevel: "inherit" };
250
321
  restoreState(ctx);
322
+ implementationRetention.restore(state.activeImplementation);
251
323
  const loadedSettings = await (dependencies.readSettings?.() ?? readPlanModeSettings());
252
324
  if (generation !== menuGeneration || menuController.signal.aborted) return;
253
325
  if (loadedSettings.kind === "loaded") settings = loadedSettings.settings;
@@ -290,10 +362,14 @@ export default function planMode(
290
362
  }
291
363
  });
292
364
 
293
- pi.on("session_shutdown", (_event, ctx) => {
365
+ pi.on("session_shutdown", async (_event, ctx) => {
294
366
  menuGeneration += 1;
295
367
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
296
368
  readyPresentationIntent = undefined;
369
+ latestCommandContext = undefined;
370
+ refreshStateBeforeFirstAgentStart = false;
371
+ implementationRetention.reset();
372
+ await awaitPlanModeSettingsWrites(dependencies.settingsPath);
297
373
  captureManualThinkingLevel();
298
374
  persistState();
299
375
  if (state.enabled) {
@@ -337,36 +413,26 @@ export default function planMode(
337
413
  }
338
414
  });
339
415
 
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
- };
416
+ pi.on("context", async (event, ctx) => {
417
+ const result = implementationRetention.transformContext(event.messages, state);
418
+ if (result.clearActiveImplementationId) {
419
+ clearActiveImplementation(result.clearActiveImplementationId, ctx);
352
420
  }
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 };
421
+ return { messages: result.messages as typeof event.messages };
367
422
  });
368
423
 
369
424
  pi.on("before_agent_start", (event, ctx) => {
425
+ if (refreshStateBeforeFirstAgentStart) {
426
+ refreshStateBeforeFirstAgentStart = false;
427
+ restoreState(ctx);
428
+ implementationRetention.reset();
429
+ implementationRetention.restore(state.activeImplementation);
430
+ if (state.enabled) {
431
+ activatePlanModeTools();
432
+ applyPlanThinkingLevel();
433
+ } else deactivatePlanModeQuestionTool();
434
+ updateUi(ctx);
435
+ }
370
436
  if (!state.enabled) return;
371
437
  if (state.latestPlan || state.awaitingAction) {
372
438
  readyPresentationIntent = undefined;
@@ -402,6 +468,11 @@ export default function planMode(
402
468
  });
403
469
 
404
470
  onAgentSettled(pi, async (_event, ctx) => {
471
+ const settledImplementationId = implementationRetention.implementationSettled(
472
+ state.activeImplementation,
473
+ );
474
+ if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);
475
+
405
476
  const intent = readyPresentationIntent;
406
477
  if (!intent || !readyPresentationIsCurrent(intent)) return;
407
478
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
@@ -419,7 +490,7 @@ export default function planMode(
419
490
  );
420
491
  }
421
492
  if (ctx.hasUI && completedPlanIsCurrent(intent)) {
422
- await showPlanReadyMenu(ctx);
493
+ await planActions.showReady(latestCommandContext ?? ctx);
423
494
  }
424
495
  } catch (error: unknown) {
425
496
  if (!isStaleExtensionContextError(error)) throw error;
@@ -579,6 +650,15 @@ export default function planMode(
579
650
  ctx.ui.notify("Plan saved for later. Plan mode disabled.", "info");
580
651
  }
581
652
 
653
+ async function startFreshImplementation(ctx: ExtensionContext, menuIsCurrent: () => boolean) {
654
+ await startFreshImplementationFromState(ctx, {
655
+ getState: () => state,
656
+ menuIsCurrent,
657
+ retention: configuredImplementationPlanRetention(settings),
658
+ stateEntryType: STATE_ENTRY_TYPE,
659
+ });
660
+ }
661
+
582
662
  async function startImplementation(ctx: ExtensionContext) {
583
663
  const savedPlan = state.enabled ? undefined : state.savedPlan;
584
664
  if (savedPlan) {
@@ -616,6 +696,7 @@ export default function planMode(
616
696
  plan,
617
697
  source,
618
698
  startedAt: Date.now(),
699
+ retention: configuredImplementationPlanRetention(settings),
619
700
  },
620
701
  manualThinkingLevel: undefined,
621
702
  };
@@ -627,10 +708,7 @@ export default function planMode(
627
708
  persistState();
628
709
  updateUi(ctx);
629
710
 
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
- );
711
+ const sent = sendPlanModeUserMessage(formatImplementationHandoff(plan), ctx);
634
712
  if (!sent) {
635
713
  if (savedPlan) {
636
714
  state = previousState;
@@ -644,155 +722,108 @@ export default function planMode(
644
722
  }
645
723
  }
646
724
 
647
- async function showActivePlanMenu(ctx: ExtensionContext) {
648
- if (!ctx.hasUI) {
649
- ctx.ui.notify(planStatusText(), "info");
650
- return;
651
- }
725
+ function clearActiveImplementation(id: string, ctx: ExtensionContext) {
726
+ if (state.activeImplementation?.id !== id) return false;
727
+ workflowGeneration += 1;
728
+ state = { ...state, activeImplementation: undefined };
729
+ persistState();
730
+ updateUi(ctx);
731
+ return true;
732
+ }
733
+
734
+ async function showLaunchMenu(ctx: ExtensionContext, initialScreen: "main" | "tools" = "main") {
652
735
  const lifecycle = captureMenuLifecycle();
653
- await showActiveImplementationMenu(ctx, {
654
- statusText: planStatusText(),
655
- signal: lifecycle.signal,
656
- isCurrent: lifecycle.isCurrent,
657
- show: () => showStoredPlan(pi, ctx, state),
658
- exportPlan: (path, signal) =>
659
- exportStoredPlan(state, path, ctx, exportOwner(ctx, signal, lifecycle.isCurrent)),
660
- startNew: () => {
736
+ if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
737
+ const ui = await loadInteractiveUi();
738
+ if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
739
+ const tools = selectableTools();
740
+ await ui.showPlanLaunchMenu(ctx, {
741
+ statusText: "Status: Off — normal tools are active.",
742
+ initialScreen,
743
+ getSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),
744
+ toolSummary: (selectedNames) =>
745
+ `When started: ${snapshotPlanModeToolNames(tools, selectedNames, toolSelectionSnapshot()).join(", ")}`,
746
+ tools: tools.map((tool) => {
747
+ const selectable = canSelectToolInPlanMode(tool);
748
+ const policy = toolPolicyLabel(tool);
749
+ const description = tool.description ?? "No description available";
750
+ return {
751
+ name: tool.name,
752
+ description: `${policy} · ${description}`,
753
+ searchText: [policy, description].join(" "),
754
+ disabled: !selectable,
755
+ disabledReason: selectable ? undefined : "Blocked by Plan-mode policy",
756
+ };
757
+ }),
758
+ ...lifecycle,
759
+ start: (signal) => {
760
+ if (signal.aborted || !lifecycle.isCurrent()) return;
661
761
  enterPlanMode(ctx);
662
762
  ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
663
763
  },
664
- clear: () => {
665
- exitPlanMode(ctx);
666
- ctx.ui.notify("Active implementation plan cleared.", "info");
667
- },
668
- });
669
- }
670
-
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");
764
+ startWithTools: (names, signal) => {
765
+ if (signal.aborted || !lifecycle.isCurrent()) return;
766
+ state = {
767
+ ...state,
768
+ selectedToolNames: filterAvailableSelectedToolNames(names, tools),
769
+ selectedToolKeys: undefined,
770
+ };
771
+ enterPlanMode(ctx);
772
+ ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
684
773
  },
774
+ settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),
685
775
  });
686
776
  }
687
777
 
688
- async function showPlanMenu(ctx: ExtensionContext) {
778
+ async function showActivePlanMenu(ctx: ExtensionContext) {
689
779
  if (!ctx.hasUI) {
690
780
  ctx.ui.notify(planStatusText(), "info");
691
781
  return;
692
782
  }
693
783
  const lifecycle = captureMenuLifecycle();
694
- await showPlanModeMenu(ctx, {
784
+ if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
785
+ const ui = await loadInteractiveUi();
786
+ if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
787
+ await ui.showActiveImplementationMenu(ctx, {
695
788
  statusText: planStatusText(),
696
- hasReadyPlan: state.latestPlan !== undefined,
697
- ...lifecycle,
789
+ getExportDestination: () => planExports.getDestination(ctx),
790
+ signal: lifecycle.signal,
791
+ isCurrent: lifecycle.isCurrent,
698
792
  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");
793
+ exportPlan: (path, signal) => planExports.export(path, ctx, signal, lifecycle.isCurrent),
794
+ settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),
795
+ startNew: () => {
796
+ enterPlanMode(ctx);
797
+ ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
709
798
  },
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: () => {
799
+ clear: () => {
723
800
  exitPlanMode(ctx);
724
- ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
801
+ ctx.ui.notify("Active implementation plan cleared.", "info");
725
802
  },
726
803
  });
727
804
  }
728
805
 
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
- },
806
+ async function showSettings(
807
+ ctx: ExtensionContext,
808
+ signal: AbortSignal,
809
+ isCurrent: () => boolean,
810
+ ) {
811
+ if (!isCurrent() || signal.aborted) return false;
812
+ const ui = await loadInteractiveUi();
813
+ if (!isCurrent() || signal.aborted) return false;
814
+ const result = await ui.showPlanModeSettings(ctx, {
815
+ tools: selectableTools(),
816
+ signal,
817
+ isCurrent,
818
+ settingsPath: dependencies.settingsPath,
819
+ onSaved: (saved) => {
820
+ if (isCurrent()) settings = saved;
782
821
  },
822
+ ...(dependencies.readSettings
823
+ ? { readSettings: async () => dependencies.readSettings?.() ?? { kind: "missing" } }
824
+ : {}),
783
825
  });
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) };
826
+ return result.kind === "closed" && "reason" in result && result.reason === "close";
796
827
  }
797
828
 
798
829
  function captureMenuLifecycle() {
@@ -828,7 +859,7 @@ export default function planMode(
828
859
  return ["read", "bash", PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME];
829
860
  }
830
861
 
831
- const selectedNames = planModeSelectedNames(tools);
862
+ const selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
832
863
  return withRequiredPlanModeTools(
833
864
  tools
834
865
  .filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool))
@@ -836,37 +867,12 @@ export default function planMode(
836
867
  );
837
868
  }
838
869
 
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,
870
+ function toolSelectionSnapshot() {
871
+ return {
872
+ selectedToolNames: state.selectedToolNames,
873
+ selectedToolKeys: state.selectedToolKeys,
874
+ defaultPlanTools: settings.defaultPlanTools,
847
875
  };
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
876
  }
871
877
 
872
878
  function selectableTools() {
@@ -955,10 +961,6 @@ export default function planMode(
955
961
  }
956
962
  }
957
963
 
958
- function persistState() {
959
- pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, state);
960
- }
961
-
962
964
  function restoreState(ctx: ExtensionContext) {
963
965
  state = restorePlanModeState(ctx.sessionManager.getBranch(), STATE_ENTRY_TYPE);
964
966
  }
@@ -975,6 +977,10 @@ export default function planMode(
975
977
  return formatPlanModeStatusText(state, formatToolSummary);
976
978
  }
977
979
 
980
+ function implementationOutcome() {
981
+ return implementationRetentionPreview(configuredImplementationPlanRetention(settings));
982
+ }
983
+
978
984
  function formatToolSummary() {
979
985
  const names = planModeToolNames();
980
986
  return `Tools: ${names.length > 0 ? names.join(", ") : "none"}`;