@narumitw/pi-plan-mode 0.43.0 → 0.44.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/README.md CHANGED
@@ -15,10 +15,10 @@ Pi core intentionally does not ship a built-in plan mode; this package provides
15
15
  - Blocks `update_plan`, mutating built-in tools, and unsafe `bash` forms such as writes, substitutions, background jobs, dependency installs, and mutating Git commands.
16
16
  - Injects Codex-like Plan mode instructions: explore first, ask decision questions for high-impact ambiguity, do not mutate files, and finalize only when decision-complete.
17
17
  - Adds required `plan_mode_question` and `plan_mode_complete` tools for structured questions and completion.
18
- - Presents the complete plan and prompts you to implement, stay in Plan mode, or exit and discard it.
18
+ - Presents the complete plan and prompts you to implement, save it for later, stay in Plan mode, or exit and discard it.
19
19
  - Keeps legacy `<proposed_plan>` responses compatible without advertising XML as the primary workflow.
20
- - Shows Plan mode state in Pi's statusline as `plan active`, `plan ready`, or `plan implementing`; `@narumitw/pi-statusline` adds the default `📝` icon unless configured otherwise.
21
- - Persists Plan mode and active implementation state in the Pi session so resume and compaction retain the exact accepted plan.
20
+ - Shows Plan mode state in Pi's statusline as `plan active`, `plan ready`, `plan saved`, or `plan implementing`; `@narumitw/pi-statusline` adds the default `📝` icon unless configured otherwise.
21
+ - Persists Plan mode, one session-local saved plan, and active implementation state so resume and compaction retain the exact accepted plan.
22
22
 
23
23
  ## 📦 Install
24
24
 
@@ -49,6 +49,7 @@ pi -e ./extensions/pi-plan-mode
49
49
  /plan show
50
50
  /plan finalize
51
51
  /plan implement
52
+ /plan save
52
53
  /plan exit
53
54
  ```
54
55
 
@@ -62,7 +63,8 @@ the query to restore the stable tool cursor. RPC keeps the complete unfiltered t
62
63
  model-requested planning interaction, not command-menu navigation. `/plan show` displays the stored
63
64
  plan without starting a model turn, including the accepted plan while implementation is active.
64
65
  `/plan finalize` explicitly asks the agent to complete the plan or ask one remaining material
65
- question, and `/plan implement` hands a stored plan to a normal implementation turn. `show` and
66
+ question, `/plan save` stores a completed ready plan for later and leaves Plan mode, and `/plan
67
+ implement` hands a ready or saved plan to a normal implementation turn. `show`, `save`, and
66
68
  `implement` fail closed when no applicable plan is stored; `finalize` requires active Plan mode.
67
69
 
68
70
  When Plan mode is active, ask the agent to design the change. The agent may inspect files and run read-only commands, but it should not edit files or execute the implementation. It should explore first, then use structured questions when your preference or a tradeoff materially changes the plan.
@@ -83,17 +85,24 @@ A complete Plan mode answer should appear only after the agent has resolved disc
83
85
 
84
86
  Legacy sessions and models may still submit one non-empty `<proposed_plan>` block with tags on their own lines. That compatibility path remains accepted, but it is not the primary workflow. Empty, malformed, unclosed, or multiple legacy blocks keep Plan mode active and produce a warning.
85
87
 
86
- After completion, `/plan` opens the ready actions when interactive UI is available. Choosing implementation—or running `/plan implement`—disables Plan mode, restores full tool access, and starts an implementation turn with the stored plan. The exact accepted plan then remains active across later turns, session resume, and manual or automatic compaction without depending on the compaction summary. Plan mode avoids a duplicate context block while the original implementation handoff remains available and injects one hidden canonical copy after that handoff is compacted away. This can consume up to the existing 50,000-character plan limit in model context when reinjection is needed.
88
+ After completion, `/plan` opens the ready actions when interactive UI is available. Choosing implementation—or running `/plan implement`—disables Plan mode, restores full tool access, and starts an implementation turn with the stored plan. Choosing **Save for later**—or running `/plan save`—instead stores one plan in the current Pi session, restores normal tools and thinking, and leaves Plan mode without starting a model turn.
87
89
 
88
- While implementation is active, `/plan show` displays the accepted plan. Interactive `/plan` offers Show, Start a new plan, and Clear; `/plan exit` and `/plan off` are the direct clear routes. Starting a new Plan-mode workflow or implementing a replacement plan supersedes the previous active plan. The extension deliberately does not infer completion from assistant prose or agent settlement, so clear the active plan when the implementation no longer applies. Choosing Stay before implementation keeps the plan ready. Revision feedback starts another Plan-mode turn and clears the previous implementable plan until an updated completion arrives. For clarification-only follow-ups, the agent answers and resubmits the complete unchanged plan so it remains implementable. Before implementation, exit/off discards the ready plan and removes its completion result from later non-Plan model context. Without interactive UI, use `/plan show`, `/plan implement`, or `/plan exit` directly.
90
+ A saved plan appears as `plan saved` and remains available after reload, resume, branch-local fork, and compaction in that session. It does not expire automatically, cross into a new session, or participate in ordinary model context. Open `/plan` to Show, Implement, or Clear it; `/plan show`, `/plan implement`, and `/plan exit`/`off` provide the same direct routes in TUI and RPC. Implementation checks the selected model and authentication before consuming the saved plan. Starting another workflow with `/plan <prompt>` or `/plan tools` is blocked until the saved plan is implemented or cleared, so the single saved slot is never silently overwritten. Resuming that session with `--plan` moves the saved plan back to ready Plan mode. Cancellation or failed implementation preflight leaves it unchanged.
91
+
92
+ Text print and JSON modes can save a ready plan with `/plan save` and clear it with `/plan exit` or `/plan off`. They reject saved-plan display and implementation before changing state because Pi provides neither printable custom-message output nor acknowledged extension-triggered turns in those modes; resume the session in TUI or RPC to show or implement it.
93
+
94
+ Once implemented, the exact accepted plan remains active across later turns, session resume, and manual or automatic compaction without depending on the compaction summary. Plan mode avoids a duplicate context block while the original implementation handoff remains available and injects one hidden canonical copy after that handoff is compacted away. This can consume up to the existing 50,000-character plan limit in model context when reinjection is needed.
95
+
96
+ While implementation is active, `/plan show` displays the accepted plan. Interactive `/plan` offers Show, Start a new plan, and Clear; `/plan exit` and `/plan off` are the direct clear routes. Starting a new Plan-mode workflow or implementing a replacement plan supersedes the previous active plan. The extension deliberately does not infer completion from assistant prose or agent settlement, so clear the active plan when the implementation no longer applies. Choosing Stay before implementation keeps the plan ready. Revision feedback starts another Plan-mode turn and clears the previous implementable plan until an updated completion arrives. For clarification-only follow-ups, the agent answers and resubmits the complete unchanged plan so it remains implementable. Before saving or implementation, exit/off discards the ready plan and removes its completion result from later non-Plan model context.
89
97
 
90
98
  While Plan mode is enabled, the extension also publishes a compact status for Pi statuslines. With `@narumitw/pi-statusline`, this appears in the extension status area:
91
99
 
92
100
  - `plan active`: Plan mode is enabled and still gathering context or drafting a plan.
93
- - `plan ready`: A completed plan is stored until you implement it, continue planning, or exit Plan mode.
101
+ - `plan ready`: A completed plan is stored until you implement it, save it, continue planning, or exit Plan mode.
102
+ - `plan saved`: One completed plan is stored outside model context in the current session until you implement or clear it.
94
103
  - `plan implementing`: The exact accepted plan remains active until you clear or supersede it.
95
104
 
96
- You can also exit directly. Before implementation, direct exit discards the latest proposed plan instead of treating it as an implementation request. During implementation, it removes both the original implementation handoff and the extension's canonical active-plan block from later model calls; an earlier Pi-generated compaction summary may still describe prior work:
105
+ You can also exit directly. Before implementation, direct exit discards the latest proposed plan; while a plan is saved, it clears that saved plan. During implementation, it removes both the original implementation handoff and the extension's canonical active-plan block from later model calls; an earlier Pi-generated compaction summary may still describe prior work:
97
106
 
98
107
  ```text
99
108
  /plan exit
@@ -175,7 +184,7 @@ This extension maps Codex's `ModeKind::Plan` behavior onto Pi's extension API:
175
184
  - The agent should use `plan_mode_question` for important non-discoverable preferences or tradeoffs before finalizing.
176
185
  - The agent completes with a standalone `plan_mode_complete` tool call instead of relying on semantic prose detection.
177
186
  - `update_plan` checklist use is blocked while Plan mode is active.
178
- - The implementation boundary is explicit: Plan mode restores tools before starting implementation, choosing implementation immediately triggers a normal agent turn with full tool access, and the accepted plan remains active across compaction until exit/off or a replacement workflow clears it.
187
+ - The implementation boundary is explicit: Plan mode restores tools before saving or starting implementation, saving keeps the plan outside ordinary model context, choosing implementation immediately triggers a normal agent turn with full tool access, and the accepted plan remains active across compaction until exit/off or a replacement workflow clears it.
179
188
  - Pi extension safety is approximated with tool classification and fail-closed filtering for every effective tool named `bash`; other non-built-in tools remain user-selected at user risk because Pi does not expose standardized tool mutability metadata.
180
189
  - Unlike native Codex, this extension uses a terminating Pi tool plus an `agent_settled` ready flow; Pi cannot provide sandbox-level enforcement.
181
190
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-plan-mode",
3
- "version": "0.43.0",
3
+ "version": "0.44.0",
4
4
  "description": "Pi extension that adds a Codex-like read-only /plan collaboration mode.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/command.ts CHANGED
@@ -5,11 +5,12 @@ export interface CommandArgumentCompletion {
5
5
  }
6
6
 
7
7
  const PLAN_COMMAND_COMPLETIONS: readonly CommandArgumentCompletion[] = [
8
- { value: "show", label: "show", description: "Show the ready or active plan" },
8
+ { value: "show", label: "show", description: "Show the ready, saved, or active plan" },
9
9
  { value: "finalize", label: "finalize", description: "Request a completed plan" },
10
- { value: "implement", label: "implement", description: "Implement the completed plan" },
11
- { value: "exit", label: "exit", description: "Leave Plan mode or clear the active plan" },
12
- { value: "off", label: "off", description: "Leave Plan mode or clear the active plan" },
10
+ { value: "implement", label: "implement", description: "Implement the completed or saved plan" },
11
+ { value: "save", label: "save", description: "Save the completed plan for later" },
12
+ { value: "exit", label: "exit", description: "Leave Plan mode or clear a saved/active plan" },
13
+ { value: "off", label: "off", description: "Leave Plan mode or clear a saved/active plan" },
13
14
  { value: "tools", label: "tools", description: "Select tools allowed in Plan mode" },
14
15
  ];
15
16
 
@@ -0,0 +1,134 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
3
+
4
+ interface MenuLifecycle {
5
+ signal: AbortSignal;
6
+ isCurrent(): boolean;
7
+ }
8
+
9
+ interface PlanMenuOptions extends MenuLifecycle {
10
+ statusText: string;
11
+ hasReadyPlan: boolean;
12
+ show(): void;
13
+ finalize(): void;
14
+ implement(): void | Promise<void>;
15
+ save(): void;
16
+ tools(): Promise<void>;
17
+ stay(): void;
18
+ exit(): void;
19
+ }
20
+
21
+ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuOptions) {
22
+ type Action = "show" | "finalize" | "implement" | "save" | "tools" | "stay" | "exit";
23
+ const menu = defineMenu<undefined, "main", Action, ExtensionContext>({
24
+ start: "main",
25
+ screens: {
26
+ main: () => ({
27
+ kind: "actions",
28
+ title: "Plan mode",
29
+ lines: [options.statusText],
30
+ items: options.hasReadyPlan
31
+ ? [
32
+ { id: "show", label: "Show latest proposed plan", action: "show" },
33
+ { id: "implement", label: "Implement this plan", action: "implement" },
34
+ { id: "save", label: "Save for later", action: "save" },
35
+ { id: "tools", label: "Configure Plan-mode tools", action: "tools" },
36
+ { id: "stay", label: "Stay in Plan mode", action: "stay" },
37
+ { id: "exit", label: "Exit Plan mode", action: "exit" },
38
+ ]
39
+ : [
40
+ { id: "finalize", label: "Request final plan", action: "finalize" },
41
+ { id: "tools", label: "Configure Plan-mode tools", action: "tools" },
42
+ { id: "stay", label: "Stay in Plan mode", action: "stay" },
43
+ { id: "exit", label: "Exit Plan mode", action: "exit" },
44
+ ],
45
+ hint: "close",
46
+ }),
47
+ },
48
+ actions: {
49
+ show: async () => {
50
+ options.show();
51
+ return { kind: "close" };
52
+ },
53
+ finalize: async () => {
54
+ options.finalize();
55
+ return { kind: "close" };
56
+ },
57
+ implement: async () => {
58
+ await options.implement();
59
+ return { kind: "close" };
60
+ },
61
+ save: async () => {
62
+ options.save();
63
+ return { kind: "close" };
64
+ },
65
+ tools: async () => {
66
+ await options.tools();
67
+ return { kind: "stay" };
68
+ },
69
+ stay: async () => {
70
+ options.stay();
71
+ return { kind: "close" };
72
+ },
73
+ exit: async () => {
74
+ options.exit();
75
+ return { kind: "close" };
76
+ },
77
+ },
78
+ });
79
+ await runMenu(ctx, menu, {
80
+ getState: () => undefined,
81
+ signal: options.signal,
82
+ isCurrent: options.isCurrent,
83
+ });
84
+ }
85
+
86
+ interface ReadyPlanMenuOptions extends MenuLifecycle {
87
+ implement(): void | Promise<void>;
88
+ save(): void;
89
+ stay(): void;
90
+ exit(): void;
91
+ }
92
+
93
+ export async function showReadyPlanMenu(ctx: ExtensionContext, options: ReadyPlanMenuOptions) {
94
+ type Action = "implement" | "save" | "stay" | "exit";
95
+ const menu = defineMenu<undefined, "ready", Action, ExtensionContext>({
96
+ start: "ready",
97
+ screens: {
98
+ ready: () => ({
99
+ kind: "actions",
100
+ title: "Proposed plan ready. What next?",
101
+ items: [
102
+ { id: "implement", label: "Implement this plan", action: "implement" },
103
+ { id: "save", label: "Save for later", action: "save" },
104
+ { id: "stay", label: "Stay in Plan mode", action: "stay" },
105
+ { id: "exit", label: "Exit Plan mode", action: "exit" },
106
+ ],
107
+ hint: "close",
108
+ }),
109
+ },
110
+ actions: {
111
+ implement: async () => {
112
+ await options.implement();
113
+ return { kind: "close" };
114
+ },
115
+ save: async () => {
116
+ options.save();
117
+ return { kind: "close" };
118
+ },
119
+ stay: async () => {
120
+ options.stay();
121
+ return { kind: "close" };
122
+ },
123
+ exit: async () => {
124
+ options.exit();
125
+ return { kind: "close" };
126
+ },
127
+ },
128
+ });
129
+ await runMenu(ctx, menu, {
130
+ getState: () => undefined,
131
+ signal: options.signal,
132
+ isCurrent: options.isCurrent,
133
+ });
134
+ }
package/src/plan-mode.ts CHANGED
@@ -28,9 +28,11 @@ import {
28
28
  stripPlanModeCompletionCallsFromMessage,
29
29
  stripProposedPlanBlocksFromMessage,
30
30
  } from "./message-transform.js";
31
+ import { showPlanModeMenu, showReadyPlanMenu } from "./plan-action-menus.js";
31
32
  import {
32
33
  clearPlanModeUi,
33
34
  planModeStatusText as formatPlanModeStatusText,
35
+ showPlanModePlan,
34
36
  updatePlanModeUi,
35
37
  } from "./presentation.js";
36
38
  import { buildPlanModePrompt } from "./prompt.js";
@@ -42,6 +44,11 @@ import {
42
44
  planModeQuestionCancelled,
43
45
  } from "./question-tool.js";
44
46
  import { withoutRequiredPlanModeTools, withRequiredPlanModeTools } from "./required-tools.js";
47
+ import { showSavedPlanMenu } from "./saved-plan-menu.js";
48
+ import {
49
+ preflightSavedPlanImplementation,
50
+ savedPlanBlocksNewWorkflow,
51
+ } from "./saved-plan-preflight.js";
45
52
  import {
46
53
  configuredThinkingLevel,
47
54
  type PlanModeSettings,
@@ -169,30 +176,39 @@ export default function planMode(
169
176
  return;
170
177
  }
171
178
  if (command === "implement") {
172
- if (!state.enabled || !state.latestPlan?.trim()) {
179
+ if (!(state.enabled && state.latestPlan?.trim()) && !state.savedPlan?.plan.trim()) {
173
180
  ctx.ui.notify("No completed plan is available to implement.", "warning");
174
181
  return;
175
182
  }
176
- startImplementation(ctx);
183
+ await startImplementation(ctx);
184
+ return;
185
+ }
186
+ if (command === "save") {
187
+ savePlanForLater(ctx);
177
188
  return;
178
189
  }
179
190
  if (command === "exit" || command === "off") {
180
- const hadActiveImplementation = state.activeImplementation !== undefined;
191
+ const notification = state.activeImplementation
192
+ ? "Active implementation plan cleared."
193
+ : state.savedPlan
194
+ ? "Saved plan cleared."
195
+ : state.latestPlan
196
+ ? "Plan mode disabled. Proposed plan discarded."
197
+ : "Plan mode disabled.";
181
198
  exitPlanMode(ctx);
182
- ctx.ui.notify(
183
- hadActiveImplementation
184
- ? "Active implementation plan cleared."
185
- : "Plan mode disabled. Proposed plan discarded.",
186
- "info",
187
- );
199
+ ctx.ui.notify(notification, "info");
188
200
  return;
189
201
  }
190
202
  if (command === "tools") {
203
+ if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))
204
+ return;
191
205
  if (!state.enabled) enterPlanMode(ctx);
192
206
  await showToolSelector(ctx);
193
207
  return;
194
208
  }
195
209
  if (prompt) {
210
+ if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))
211
+ return;
196
212
  enterPlanModeWithPrompt(prompt, ctx);
197
213
  return;
198
214
  }
@@ -201,6 +217,10 @@ export default function planMode(
201
217
  await showActivePlanMenu(ctx);
202
218
  return;
203
219
  }
220
+ if (state.savedPlan) {
221
+ await showSavedPlanActions(ctx);
222
+ return;
223
+ }
204
224
  enterPlanMode(ctx);
205
225
  ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
206
226
  return;
@@ -225,7 +245,17 @@ export default function planMode(
225
245
  if (loadedSettings.notice) ctx.ui.notify(loadedSettings.notice, "warning");
226
246
  const persistFlagActivation = pi.getFlag("plan") === true && !state.enabled;
227
247
  if (persistFlagActivation) {
228
- state = { ...state, enabled: true, activeImplementation: undefined };
248
+ state = state.savedPlan
249
+ ? {
250
+ ...state,
251
+ enabled: true,
252
+ latestPlan: state.savedPlan.plan,
253
+ latestPlanSource: state.savedPlan.source,
254
+ awaitingAction: true,
255
+ savedPlan: undefined,
256
+ activeImplementation: undefined,
257
+ }
258
+ : { ...state, enabled: true, activeImplementation: undefined };
229
259
  }
230
260
  if (state.enabled) {
231
261
  activatePlanModeTools();
@@ -391,6 +421,7 @@ export default function planMode(
391
421
  ...state,
392
422
  enabled: true,
393
423
  awaitingAction: false,
424
+ savedPlan: undefined,
394
425
  activeImplementation: undefined,
395
426
  };
396
427
  activatePlanModeTools();
@@ -426,6 +457,7 @@ export default function planMode(
426
457
  latestPlan: undefined,
427
458
  latestPlanSource: undefined,
428
459
  awaitingAction: false,
460
+ savedPlan: undefined,
429
461
  activeImplementation: undefined,
430
462
  manualThinkingLevel: undefined,
431
463
  };
@@ -496,8 +528,12 @@ export default function planMode(
496
528
 
497
529
  function showStoredPlan(ctx: ExtensionContext) {
498
530
  const readyPlan = state.enabled ? state.latestPlan?.trim() : undefined;
531
+ const savedPlan = state.savedPlan?.plan.trim();
532
+ if (savedPlan && (ctx.mode === "print" || ctx.mode === "json")) {
533
+ throw new Error("Saved plan display is unavailable in print/JSON mode. Use TUI or RPC.");
534
+ }
499
535
  const activePlan = state.activeImplementation?.plan.trim();
500
- const plan = readyPlan ?? activePlan;
536
+ const plan = readyPlan ?? savedPlan ?? activePlan;
501
537
  if (!plan) {
502
538
  ctx.ui.notify(
503
539
  "No completed plan is available. Use /plan finalize when planning is complete.",
@@ -505,19 +541,12 @@ export default function planMode(
505
541
  );
506
542
  return;
507
543
  }
508
- try {
509
- pi.sendMessage(
510
- {
511
- customType: PROPOSED_PLAN_MESSAGE_TYPE,
512
- content: `**${readyPlan ? "Proposed Plan" : "Active Implementation Plan"}**\n\n${plan}`,
513
- display: true,
514
- },
515
- { triggerTurn: false },
516
- );
517
- } catch (error: unknown) {
518
- const detail = error instanceof Error ? error.message : String(error);
519
- ctx.ui.notify(`Unable to show completed plan: ${detail}`, "error");
520
- }
544
+ const title = readyPlan
545
+ ? "Proposed Plan"
546
+ : savedPlan
547
+ ? "Saved Plan"
548
+ : "Active Implementation Plan";
549
+ showPlanModePlan(pi, ctx, title, plan);
521
550
  }
522
551
 
523
552
  function requestFinalPlan(ctx: ExtensionContext) {
@@ -531,15 +560,59 @@ export default function planMode(
531
560
  );
532
561
  }
533
562
 
534
- function startImplementation(ctx: ExtensionContext) {
535
- const plan = state.latestPlan?.trim();
563
+ function savePlanForLater(ctx: ExtensionContext) {
564
+ const plan = state.enabled ? state.latestPlan?.trim() : undefined;
565
+ if (!plan) {
566
+ const message = "No completed plan is available to save.";
567
+ if (!ctx.hasUI) throw new Error(message);
568
+ ctx.ui.notify(message, "warning");
569
+ return;
570
+ }
536
571
  const source = state.latestPlanSource ?? "legacy_proposed_plan";
572
+
573
+ workflowGeneration += 1;
574
+ readyPresentationIntent = undefined;
575
+ state = {
576
+ ...state,
577
+ enabled: false,
578
+ latestPlan: undefined,
579
+ latestPlanSource: undefined,
580
+ awaitingAction: false,
581
+ savedPlan: { plan, source },
582
+ activeImplementation: undefined,
583
+ manualThinkingLevel: undefined,
584
+ };
585
+ restoreTools();
586
+ restoreThinkingLevel();
587
+ state = { ...state, manualThinkingLevel: undefined };
588
+ persistState();
589
+ updateUi(ctx);
590
+ ctx.ui.notify("Plan saved for later. Plan mode disabled.", "info");
591
+ }
592
+
593
+ async function startImplementation(ctx: ExtensionContext) {
594
+ const savedPlan = state.enabled ? undefined : state.savedPlan;
595
+ if (savedPlan) {
596
+ const sessionGeneration = menuGeneration;
597
+ const planWorkflowGeneration = workflowGeneration;
598
+ const isCurrent = () =>
599
+ sessionGeneration === menuGeneration &&
600
+ planWorkflowGeneration === workflowGeneration &&
601
+ !menuController.signal.aborted &&
602
+ !state.enabled &&
603
+ state.savedPlan === savedPlan;
604
+ if (!(await preflightSavedPlanImplementation(ctx, isCurrent))) return;
605
+ }
606
+ const plan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
607
+ const source =
608
+ (state.enabled ? state.latestPlanSource : savedPlan?.source) ?? "legacy_proposed_plan";
537
609
  if (!plan) {
538
610
  ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
539
611
  return;
540
612
  }
541
613
 
542
614
  workflowGeneration += 1;
615
+ const previousState = state;
543
616
  const wasEnabled = state.enabled;
544
617
  readyPresentationIntent = undefined;
545
618
  state = {
@@ -548,6 +621,7 @@ export default function planMode(
548
621
  latestPlan: undefined,
549
622
  latestPlanSource: undefined,
550
623
  awaitingAction: false,
624
+ savedPlan: undefined,
551
625
  activeImplementation: {
552
626
  id: randomUUID(),
553
627
  plan,
@@ -569,8 +643,13 @@ export default function planMode(
569
643
  ctx,
570
644
  );
571
645
  if (!sent) {
572
- enterPlanMode(ctx);
573
- state = { ...state, latestPlan: plan, latestPlanSource: source, awaitingAction: true };
646
+ if (savedPlan) {
647
+ state = previousState;
648
+ } else {
649
+ enterPlanMode(ctx);
650
+ state = previousState;
651
+ applyPlanThinkingLevel();
652
+ }
574
653
  persistState();
575
654
  updateUi(ctx);
576
655
  }
@@ -598,104 +677,55 @@ export default function planMode(
598
677
  });
599
678
  }
600
679
 
680
+ async function showSavedPlanActions(ctx: ExtensionContext) {
681
+ const lifecycle = captureMenuLifecycle();
682
+ await showSavedPlanMenu(ctx, {
683
+ statusText: planStatusText(),
684
+ signal: lifecycle.signal,
685
+ isCurrent: lifecycle.isCurrent,
686
+ show: () => showStoredPlan(ctx),
687
+ implement: () => startImplementation(ctx),
688
+ clear: () => {
689
+ exitPlanMode(ctx);
690
+ ctx.ui.notify("Saved plan cleared.", "info");
691
+ },
692
+ });
693
+ }
694
+
601
695
  async function showPlanMenu(ctx: ExtensionContext) {
602
696
  if (!ctx.hasUI) {
603
697
  ctx.ui.notify(planStatusText(), "info");
604
698
  return;
605
699
  }
606
700
  const lifecycle = captureMenuLifecycle();
607
- type Action = "show" | "finalize" | "implement" | "tools" | "stay" | "exit";
608
- const menu = defineMenu<undefined, "main", Action, ExtensionContext>({
609
- start: "main",
610
- screens: {
611
- main: () => ({
612
- kind: "actions",
613
- title: "Plan mode",
614
- lines: [planStatusText()],
615
- items: state.latestPlan
616
- ? [
617
- { id: "show", label: "Show latest proposed plan", action: "show" },
618
- { id: "implement", label: "Implement this plan", action: "implement" },
619
- { id: "tools", label: "Configure Plan-mode tools", action: "tools" },
620
- { id: "stay", label: "Stay in Plan mode", action: "stay" },
621
- { id: "exit", label: "Exit Plan mode", action: "exit" },
622
- ]
623
- : [
624
- { id: "finalize", label: "Request final plan", action: "finalize" },
625
- { id: "tools", label: "Configure Plan-mode tools", action: "tools" },
626
- { id: "stay", label: "Stay in Plan mode", action: "stay" },
627
- { id: "exit", label: "Exit Plan mode", action: "exit" },
628
- ],
629
- hint: "close",
630
- }),
631
- },
632
- actions: {
633
- show: async () => {
634
- showStoredPlan(ctx);
635
- return { kind: "close" };
636
- },
637
- finalize: async () => {
638
- requestFinalPlan(ctx);
639
- return { kind: "close" };
640
- },
641
- implement: async () => {
642
- startImplementation(ctx);
643
- return { kind: "close" };
644
- },
645
- tools: async () => {
646
- await showToolSelector(ctx);
647
- return { kind: "stay" };
648
- },
649
- stay: async () => {
650
- updateUi(ctx);
651
- return { kind: "close" };
652
- },
653
- exit: async () => {
654
- exitPlanMode(ctx);
655
- ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
656
- return { kind: "close" };
657
- },
658
- },
659
- });
660
- await runMenu(ctx, menu, {
661
- getState: () => undefined,
701
+ await showPlanModeMenu(ctx, {
702
+ statusText: planStatusText(),
703
+ hasReadyPlan: state.latestPlan !== undefined,
662
704
  ...lifecycle,
705
+ show: () => showStoredPlan(ctx),
706
+ finalize: () => requestFinalPlan(ctx),
707
+ implement: () => startImplementation(ctx),
708
+ save: () => savePlanForLater(ctx),
709
+ tools: () => showToolSelector(ctx),
710
+ stay: () => updateUi(ctx),
711
+ exit: () => {
712
+ exitPlanMode(ctx);
713
+ ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
714
+ },
663
715
  });
664
716
  }
665
717
 
666
718
  async function showPlanReadyMenu(ctx: ExtensionContext) {
667
719
  const lifecycle = captureMenuLifecycle();
668
- type Action = "implement" | "stay" | "exit";
669
- const menu = defineMenu<undefined, "ready", Action, ExtensionContext>({
670
- start: "ready",
671
- screens: {
672
- ready: () => ({
673
- kind: "actions",
674
- title: "Proposed plan ready. What next?",
675
- items: [
676
- { id: "implement", label: "Implement this plan", action: "implement" },
677
- { id: "stay", label: "Stay in Plan mode", action: "stay" },
678
- { id: "exit", label: "Exit Plan mode", action: "exit" },
679
- ],
680
- hint: "close",
681
- }),
682
- },
683
- actions: {
684
- implement: async () => {
685
- startImplementation(ctx);
686
- return { kind: "close" };
687
- },
688
- stay: async () => ({ kind: "close" }),
689
- exit: async () => {
690
- exitPlanMode(ctx);
691
- ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
692
- return { kind: "close" };
693
- },
694
- },
695
- });
696
- await runMenu(ctx, menu, {
697
- getState: () => undefined,
720
+ await showReadyPlanMenu(ctx, {
698
721
  ...lifecycle,
722
+ implement: () => startImplementation(ctx),
723
+ save: () => savePlanForLater(ctx),
724
+ stay: () => undefined,
725
+ exit: () => {
726
+ exitPlanMode(ctx);
727
+ ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
728
+ },
699
729
  });
700
730
  }
701
731
 
@@ -1,4 +1,4 @@
1
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { PlanModeState } from "./state.js";
3
3
 
4
4
  const STATUS_KEY = "plan-mode";
@@ -13,7 +13,7 @@ export function updatePlanModeUi(
13
13
  if (state.enabled && state.latestPlan) {
14
14
  ctx.ui.setWidget(PLAN_WIDGET_KEY, [
15
15
  "Proposed plan ready",
16
- "Use /plan to implement, revise, or exit Plan mode.",
16
+ "Use /plan to implement, save, revise, or exit Plan mode.",
17
17
  ]);
18
18
  } else if (state.enabled) {
19
19
  ctx.ui.setWidget(PLAN_WIDGET_KEY, [
@@ -21,6 +21,11 @@ export function updatePlanModeUi(
21
21
  toolSummary(),
22
22
  "Finish with plan_mode_complete when decision-ready.",
23
23
  ]);
24
+ } else if (state.savedPlan) {
25
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, [
26
+ "Plan saved for later",
27
+ "Use /plan to show, implement, or clear it.",
28
+ ]);
24
29
  } else if (state.activeImplementation) {
25
30
  ctx.ui.setWidget(PLAN_WIDGET_KEY, [
26
31
  "Implementation plan active",
@@ -36,6 +41,27 @@ export function clearPlanModeUi(ctx: ExtensionContext) {
36
41
  ctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);
37
42
  }
38
43
 
44
+ export function showPlanModePlan(
45
+ pi: ExtensionAPI,
46
+ ctx: ExtensionContext,
47
+ title: string,
48
+ plan: string,
49
+ ) {
50
+ try {
51
+ pi.sendMessage(
52
+ {
53
+ customType: "proposed-plan",
54
+ content: `**${title}**\n\n${plan}`,
55
+ display: true,
56
+ },
57
+ { triggerTurn: false },
58
+ );
59
+ } catch (error: unknown) {
60
+ const detail = error instanceof Error ? error.message : String(error);
61
+ ctx.ui.notify(`Unable to show completed plan: ${detail}`, "error");
62
+ }
63
+ }
64
+
39
65
  export function planModeStatusText(state: PlanModeState, toolSummary: () => string) {
40
66
  if (state.enabled) {
41
67
  if (state.latestPlan) {
@@ -43,6 +69,7 @@ export function planModeStatusText(state: PlanModeState, toolSummary: () => stri
43
69
  }
44
70
  return `Plan mode is active. ${toolSummary()} Explore, ask, and finish with plan_mode_complete when decision-ready.`;
45
71
  }
72
+ if (state.savedPlan) return "A plan is saved for later.";
46
73
  if (state.activeImplementation) return "An implementation plan is active.";
47
74
  return "Plan mode is off.";
48
75
  }
@@ -52,6 +79,7 @@ function formatStatus(state: PlanModeState) {
52
79
  if (state.awaitingAction || state.latestPlan) return "plan ready";
53
80
  return "plan active";
54
81
  }
82
+ if (state.savedPlan) return "plan saved";
55
83
  if (state.activeImplementation) return "plan implementing";
56
84
  return undefined;
57
85
  }
@@ -0,0 +1,53 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
3
+
4
+ interface SavedPlanMenuOptions {
5
+ statusText: string;
6
+ signal: AbortSignal;
7
+ isCurrent(): boolean;
8
+ show(): void;
9
+ implement(): void | Promise<void>;
10
+ clear(): void;
11
+ }
12
+
13
+ export async function showSavedPlanMenu(ctx: ExtensionContext, options: SavedPlanMenuOptions) {
14
+ if (!ctx.hasUI) {
15
+ throw new Error(`${options.statusText} Use /plan show, /plan implement, or /plan exit.`);
16
+ }
17
+ type Action = "show" | "implement" | "clear";
18
+ const menu = defineMenu<undefined, "saved", Action, ExtensionContext>({
19
+ start: "saved",
20
+ screens: {
21
+ saved: () => ({
22
+ kind: "actions",
23
+ title: "Saved plan",
24
+ lines: [options.statusText],
25
+ items: [
26
+ { id: "show", label: "Show saved plan", action: "show" },
27
+ { id: "implement", label: "Implement saved plan", action: "implement" },
28
+ { id: "clear", label: "Clear saved plan", action: "clear" },
29
+ ],
30
+ hint: "close",
31
+ }),
32
+ },
33
+ actions: {
34
+ show: async () => {
35
+ options.show();
36
+ return { kind: "close" };
37
+ },
38
+ implement: async () => {
39
+ await options.implement();
40
+ return { kind: "close" };
41
+ },
42
+ clear: async () => {
43
+ options.clear();
44
+ return { kind: "close" };
45
+ },
46
+ },
47
+ });
48
+ await runMenu(ctx, menu, {
49
+ getState: () => undefined,
50
+ signal: options.signal,
51
+ isCurrent: options.isCurrent,
52
+ });
53
+ }
@@ -0,0 +1,39 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ export function savedPlanBlocksNewWorkflow(ctx: ExtensionContext, hasSavedPlan: boolean) {
4
+ if (!hasSavedPlan) return false;
5
+ const message =
6
+ "A plan is saved for later. Implement or clear it before starting another Plan-mode workflow.";
7
+ if (!ctx.hasUI) throw new Error(message);
8
+ ctx.ui.notify(message, "warning");
9
+ return true;
10
+ }
11
+
12
+ export async function preflightSavedPlanImplementation(
13
+ ctx: ExtensionContext,
14
+ isCurrent: () => boolean,
15
+ ) {
16
+ if (ctx.mode === "print" || ctx.mode === "json") {
17
+ throw new Error("Saved plan implementation is unavailable in print/JSON mode. Use TUI or RPC.");
18
+ }
19
+ const model = ctx.model;
20
+ if (!model) {
21
+ ctx.ui.notify("Unable to implement saved plan: no model is selected.", "warning");
22
+ return false;
23
+ }
24
+ let auth: Awaited<ReturnType<ExtensionContext["modelRegistry"]["getApiKeyAndHeaders"]>>;
25
+ try {
26
+ auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
27
+ } catch (error: unknown) {
28
+ if (!isCurrent()) return false;
29
+ const detail = error instanceof Error ? error.message : String(error);
30
+ ctx.ui.notify(`Unable to implement saved plan: ${detail}`, "error");
31
+ return false;
32
+ }
33
+ if (!isCurrent()) return false;
34
+ if (!auth.ok) {
35
+ ctx.ui.notify(`Unable to implement saved plan: ${auth.error}`, "warning");
36
+ return false;
37
+ }
38
+ return true;
39
+ }
package/src/state.ts CHANGED
@@ -14,11 +14,17 @@ export interface ActiveImplementationPlan {
14
14
  startedAt: number;
15
15
  }
16
16
 
17
+ export interface SavedPlan {
18
+ plan: string;
19
+ source: PlanCompletionSource;
20
+ }
21
+
17
22
  export interface PlanModeState {
18
23
  enabled: boolean;
19
24
  latestPlan?: string;
20
25
  latestPlanSource?: PlanCompletionSource;
21
26
  awaitingAction: boolean;
27
+ savedPlan?: SavedPlan;
22
28
  activeImplementation?: ActiveImplementationPlan;
23
29
  selectedToolNames?: string[];
24
30
  selectedToolKeys?: string[];
@@ -60,6 +66,8 @@ export function restorePlanModeState(entries: unknown[], stateEntryType: string)
60
66
  const activeImplementation = enabled
61
67
  ? undefined
62
68
  : normalizeActiveImplementation(entry.data.activeImplementation);
69
+ const savedPlan =
70
+ enabled || activeImplementation ? undefined : normalizeSavedPlan(entry.data.savedPlan);
63
71
  return {
64
72
  enabled,
65
73
  latestPlan,
@@ -68,6 +76,7 @@ export function restorePlanModeState(entries: unknown[], stateEntryType: string)
68
76
  (recoveredPlan ? PLAN_MODE_COMPLETE_TOOL_NAME : undefined))
69
77
  : undefined,
70
78
  awaitingAction: enabled && latestPlan !== undefined,
79
+ savedPlan,
71
80
  activeImplementation,
72
81
  selectedToolNames: stringArray(entry.data.selectedToolNames),
73
82
  selectedToolKeys: stringArray(entry.data.selectedToolKeys),
@@ -79,6 +88,14 @@ export function restorePlanModeState(entries: unknown[], stateEntryType: string)
79
88
  };
80
89
  }
81
90
 
91
+ function normalizeSavedPlan(value: unknown): SavedPlan | undefined {
92
+ if (!isRecord(value)) return undefined;
93
+ const source = planCompletionSource(value.source);
94
+ const normalized = normalizePlanModeCompletion({ plan: value.plan });
95
+ if (!source || !normalized.ok) return undefined;
96
+ return { plan: normalized.plan, source };
97
+ }
98
+
82
99
  function normalizeActiveImplementation(value: unknown): ActiveImplementationPlan | undefined {
83
100
  if (!isRecord(value)) return undefined;
84
101
  const id =