@narumitw/pi-plan-mode 0.38.0 → 0.40.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
@@ -18,8 +18,8 @@ Pi core intentionally does not ship a built-in plan mode; this package provides
18
18
  - Adds required `plan_mode_question` and `plan_mode_complete` tools for structured questions and completion.
19
19
  - Presents the complete plan and prompts you to implement, stay in Plan mode, or exit and discard it.
20
20
  - Keeps legacy `<proposed_plan>` responses compatible without advertising XML as the primary workflow.
21
- - Shows Plan mode state in Pi's statusline as `plan active` or `plan ready`; `@narumitw/pi-statusline` adds the default `📝` icon unless configured otherwise.
22
- - Persists Plan mode state in the Pi session so resume restores the mode.
21
+ - 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.
22
+ - Persists Plan mode and active implementation state in the Pi session so resume and compaction retain the exact accepted plan.
23
23
 
24
24
  ## 📦 Install
25
25
 
@@ -57,12 +57,14 @@ Use `/plan` to enter Plan mode before writing your planning prompt. Use `/plan <
57
57
  Plan mode and immediately submit `<prompt>` as the first Plan-mode user message. Use `/plan tools`
58
58
  to choose which tools are active while Plan mode is enabled; the standard bounded multi-select shows
59
59
  10 rows at a time, supports viewport paging, descriptions, and explicit unavailable rows for blocked
60
- tools. The `plan_mode_question` tool keeps its one-off question/choice dialog because it is a
60
+ tools. In TUI mode, type to fuzzy-search tool names, descriptions, policy, and source metadata; clear
61
+ the query to restore the stable tool cursor. RPC keeps the complete unfiltered tool list. The
62
+ `plan_mode_question` tool keeps its one-off question/choice dialog because it is a
61
63
  model-requested planning interaction, not command-menu navigation. `/plan show` displays the stored
62
- plan without starting a model turn, `/plan finalize`
63
- explicitly asks the agent to complete the plan or ask one remaining material question, and
64
- `/plan implement` hands a stored plan to a normal implementation turn. `show` and `implement` fail
65
- closed when no plan is stored; `finalize` requires active Plan mode.
64
+ plan without starting a model turn, including the accepted plan while implementation is active.
65
+ `/plan finalize` explicitly asks the agent to complete the plan or ask one remaining material
66
+ question, and `/plan implement` hands a stored plan to a normal implementation turn. `show` and
67
+ `implement` fail closed when no applicable plan is stored; `finalize` requires active Plan mode.
66
68
 
67
69
  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.
68
70
 
@@ -82,14 +84,17 @@ A complete Plan mode answer should appear only after the agent has resolved disc
82
84
 
83
85
  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.
84
86
 
85
- 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 Stay 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. Exit/off discards the plan and removes its completion result from later non-Plan model context. Without interactive UI, the plan remains visible in the tool result and stored as `plan ready`; use `/plan show`, `/plan implement`, or `/plan exit` directly.
87
+ 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
+
89
+ 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.
86
90
 
87
91
  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:
88
92
 
89
93
  - `plan active`: Plan mode is enabled and still gathering context or drafting a plan.
90
94
  - `plan ready`: A completed plan is stored until you implement it, continue planning, or exit Plan mode.
95
+ - `plan implementing`: The exact accepted plan remains active until you clear or supersede it.
91
96
 
92
- You can also exit directly. Direct exit discards the latest proposed plan instead of treating it as an implementation request:
97
+ 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:
93
98
 
94
99
  ```text
95
100
  /plan exit
@@ -182,7 +187,7 @@ This extension maps Codex's `ModeKind::Plan` behavior onto Pi's extension API:
182
187
  - The agent should use `plan_mode_question` for important non-discoverable preferences or tradeoffs before finalizing.
183
188
  - The agent completes with a standalone `plan_mode_complete` tool call instead of relying on semantic prose detection.
184
189
  - `update_plan` checklist use is blocked while Plan mode is active.
185
- - 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 plain exit/off discards the stored plan.
190
+ - 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.
186
191
  - 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.
187
192
  - Unlike native Codex, this extension uses a terminating Pi tool plus an `agent_settled` ready flow; Pi cannot provide sandbox-level enforcement.
188
193
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-plan-mode",
3
- "version": "0.38.0",
3
+ "version": "0.40.0",
4
4
  "description": "Pi extension that adds a Codex-like read-only /plan collaboration mode.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,9 +32,9 @@
32
32
  "@earendil-works/pi-tui": "*"
33
33
  },
34
34
  "devDependencies": {
35
- "@biomejs/biome": "2.5.5",
36
- "@earendil-works/pi-coding-agent": "0.82.1",
37
- "@earendil-works/pi-tui": "0.82.1",
35
+ "@biomejs/biome": "2.5.6",
36
+ "@earendil-works/pi-coding-agent": "0.83.0",
37
+ "@earendil-works/pi-tui": "0.83.0",
38
38
  "typescript": "7.0.2"
39
39
  },
40
40
  "repository": {
@@ -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 ActiveImplementationMenuOptions {
5
+ statusText: string;
6
+ signal: AbortSignal;
7
+ isCurrent(): boolean;
8
+ show(): void;
9
+ startNew(): void;
10
+ clear(): void;
11
+ }
12
+
13
+ export async function showActiveImplementationMenu(
14
+ ctx: ExtensionContext,
15
+ options: ActiveImplementationMenuOptions,
16
+ ) {
17
+ type Action = "show" | "start-new" | "clear";
18
+ const menu = defineMenu<undefined, "active", Action, ExtensionContext>({
19
+ start: "active",
20
+ screens: {
21
+ active: () => ({
22
+ kind: "actions",
23
+ title: "Active implementation plan",
24
+ lines: [options.statusText],
25
+ items: [
26
+ { id: "show", label: "Show active implementation plan", action: "show" },
27
+ { id: "start-new", label: "Start a new plan", action: "start-new" },
28
+ { id: "clear", label: "Clear active implementation plan", action: "clear" },
29
+ ],
30
+ hint: "close",
31
+ }),
32
+ },
33
+ actions: {
34
+ show: async () => {
35
+ options.show();
36
+ return { kind: "close" };
37
+ },
38
+ "start-new": async () => {
39
+ options.startNew();
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
+ }
package/src/command.ts ADDED
@@ -0,0 +1,23 @@
1
+ export interface CommandArgumentCompletion {
2
+ value: string;
3
+ label: string;
4
+ description?: string;
5
+ }
6
+
7
+ const PLAN_COMMAND_COMPLETIONS: readonly CommandArgumentCompletion[] = [
8
+ { value: "show", label: "show", description: "Show the ready or active plan" },
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" },
13
+ { value: "tools", label: "tools", description: "Select tools allowed in Plan mode" },
14
+ ];
15
+
16
+ export function completePlanArguments(argumentPrefix: string): CommandArgumentCompletion[] | null {
17
+ const prefix = argumentPrefix.trimStart().toLowerCase();
18
+ if (prefix === "") return [...PLAN_COMMAND_COMPLETIONS];
19
+ if (/\s/.test(prefix)) return null;
20
+
21
+ const matches = PLAN_COMMAND_COMPLETIONS.filter((item) => item.value.startsWith(prefix));
22
+ return matches.length > 0 ? [...matches] : null;
23
+ }
@@ -0,0 +1,24 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { PlanModeFixedThinkingLevel } from "./settings.js";
3
+
4
+ type AgentSettledHandler = (event: unknown, ctx: ExtensionContext) => unknown;
5
+
6
+ export function onAgentSettled(pi: ExtensionAPI, handler: AgentSettledHandler) {
7
+ (
8
+ pi as unknown as {
9
+ on(event: "agent_settled", callback: AgentSettledHandler): void;
10
+ }
11
+ ).on("agent_settled", handler);
12
+ }
13
+
14
+ export function setPlanThinkingLevel(pi: ExtensionAPI, level: PlanModeFixedThinkingLevel) {
15
+ (pi.setThinkingLevel as unknown as (level: PlanModeFixedThinkingLevel) => void)(level);
16
+ }
17
+
18
+ export function isStaleExtensionContextError(error: unknown) {
19
+ return (
20
+ error instanceof Error &&
21
+ (error.message.includes("This extension ctx is stale after session replacement or reload") ||
22
+ error.message.includes("Extension context is no longer active"))
23
+ );
24
+ }
@@ -1,6 +1,8 @@
1
1
  import { PLAN_MODE_COMPLETE_TOOL_NAME } from "./completion-tool.js";
2
+ import type { ActiveImplementationPlan } from "./state.js";
2
3
 
3
4
  const PLAN_CONTEXT_MESSAGE_TYPE = "plan-mode-context";
5
+ export const PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE = "plan-mode-implementation-context";
4
6
  const PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
5
7
  const PLAN_IMPLEMENTATION_HANDOFF_PREFIX =
6
8
  "Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:";
@@ -46,6 +48,16 @@ export function extractProposedPlan(text: string) {
46
48
  return result.kind === "valid" ? result.plan : undefined;
47
49
  }
48
50
 
51
+ export function invalidPlanMessage(kind: "empty" | "multiple" | "malformed" | "unclosed") {
52
+ const detail = {
53
+ empty: "the block is empty",
54
+ multiple: "more than one plan block was produced",
55
+ malformed: "the tags must be on their own lines",
56
+ unclosed: "the closing tag is missing",
57
+ }[kind];
58
+ return `Proposed plan is not ready: ${detail}. Continue Plan mode and produce one complete non-empty <proposed_plan> block.`;
59
+ }
60
+
49
61
  export function latestAssistantText(messages: unknown) {
50
62
  if (!Array.isArray(messages)) return "";
51
63
  for (const entry of [...messages].reverse()) {
@@ -61,6 +73,45 @@ export function messageContainsLegacyPlanModeContextArtifact(message: unknown) {
61
73
  return unwrapSessionMessage(message).customType === PLAN_CONTEXT_MESSAGE_TYPE;
62
74
  }
63
75
 
76
+ export function messageContainsPlanModeImplementationContextArtifact(message: unknown) {
77
+ return unwrapSessionMessage(message).customType === PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE;
78
+ }
79
+
80
+ export function injectActiveImplementationContext(
81
+ messages: unknown[],
82
+ activeImplementation: ActiveImplementationPlan,
83
+ ) {
84
+ let foundCurrentHandoff = false;
85
+ const messagesWithoutStaleContext = messages.filter((message) => {
86
+ if (messageContainsPlanModeImplementationContextArtifact(message)) return false;
87
+ if (!messageContainsPlanModeImplementationHandoff(message)) return true;
88
+ if (
89
+ !foundCurrentHandoff &&
90
+ messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)
91
+ ) {
92
+ foundCurrentHandoff = true;
93
+ return true;
94
+ }
95
+ return false;
96
+ });
97
+ if (foundCurrentHandoff) return messagesWithoutStaleContext;
98
+
99
+ let insertionIndex = 0;
100
+ while (isSummaryMessage(messagesWithoutStaleContext[insertionIndex])) insertionIndex += 1;
101
+ const contextMessage = {
102
+ role: "custom" as const,
103
+ customType: PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE,
104
+ content: `[ACTIVE IMPLEMENTATION PLAN]\n\nThe user approved the exact implementation plan below. Continue following it until the user explicitly clears or supersedes it. The exact plan is the remainder of this message:\n\n${activeImplementation.plan}`,
105
+ display: false,
106
+ timestamp: activeImplementation.startedAt,
107
+ };
108
+ return [
109
+ ...messagesWithoutStaleContext.slice(0, insertionIndex),
110
+ contextMessage,
111
+ ...messagesWithoutStaleContext.slice(insertionIndex),
112
+ ];
113
+ }
114
+
64
115
  export function messageContainsInactivePlanModeArtifact(message: unknown) {
65
116
  const candidate = unwrapSessionMessage(message);
66
117
  return (
@@ -77,6 +128,20 @@ export function messageContainsPlanModeImplementationHandoff(message: unknown) {
77
128
  );
78
129
  }
79
130
 
131
+ function messageContainsExactPlanModeImplementationHandoff(message: unknown, plan: string) {
132
+ const candidate = unwrapSessionMessage(message);
133
+ if (candidate.role !== "user") return false;
134
+ return (
135
+ contentText(candidate.content).trim() ===
136
+ `${PLAN_IMPLEMENTATION_HANDOFF_PREFIX}\n\n${plan}`.trim()
137
+ );
138
+ }
139
+
140
+ function isSummaryMessage(message: unknown) {
141
+ const role = unwrapSessionMessage(message)?.role;
142
+ return role === "compactionSummary" || role === "branchSummary";
143
+ }
144
+
80
145
  export function stripProposedPlanBlocksFromMessage<T>(message: T): T {
81
146
  return replaceAssistantContent(message, stripProposedPlanBlocksFromContent);
82
147
  }
@@ -115,8 +180,8 @@ function replaceAssistantContent<T>(message: T, transform: (content: unknown) =>
115
180
  }
116
181
 
117
182
  function unwrapSessionMessage(message: unknown) {
118
- const entry = message as { message?: unknown };
119
- return (entry.message ?? message) as {
183
+ const entry = message as { message?: unknown } | null | undefined;
184
+ return (entry?.message ?? message ?? {}) as {
120
185
  role?: string;
121
186
  customType?: string;
122
187
  toolName?: string;
package/src/plan-mode.ts CHANGED
@@ -1,5 +1,8 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import type { ExtensionAPI, ExtensionContext, ToolInfo } from "@earendil-works/pi-coding-agent";
2
3
  import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
4
+ import { showActiveImplementationMenu } from "./active-implementation-menu.js";
5
+ import { completePlanArguments } from "./command.js";
3
6
  import {
4
7
  normalizePlanModeCompletion,
5
8
  PLAN_MODE_COMPLETE_PARAMS,
@@ -8,27 +11,39 @@ import {
8
11
  renderPlanModeCompletion,
9
12
  } from "./completion-tool.js";
10
13
  import {
14
+ isStaleExtensionContextError,
15
+ onAgentSettled,
16
+ setPlanThinkingLevel,
17
+ } from "./extension-runtime.js";
18
+ import {
19
+ injectActiveImplementationContext,
20
+ invalidPlanMessage,
11
21
  isEmptyAssistantMessage,
12
22
  latestAssistantText,
13
23
  messageContainsInactivePlanModeArtifact,
14
24
  messageContainsLegacyPlanModeContextArtifact,
25
+ messageContainsPlanModeImplementationContextArtifact,
15
26
  messageContainsPlanModeImplementationHandoff,
16
27
  parseProposedPlan,
17
28
  stripPlanModeCompletionCallsFromMessage,
18
29
  stripProposedPlanBlocksFromMessage,
19
30
  } from "./message-transform.js";
31
+ import {
32
+ clearPlanModeUi,
33
+ planModeStatusText as formatPlanModeStatusText,
34
+ updatePlanModeUi,
35
+ } from "./presentation.js";
20
36
  import { buildPlanModePrompt } from "./prompt.js";
21
37
  import {
22
- askPlanModeQuestions,
38
+ answerPlanModeQuestions,
23
39
  normalizePlanModeQuestionParams,
24
40
  PLAN_MODE_QUESTION_PARAMS,
25
41
  PLAN_MODE_QUESTION_TOOL_NAME,
26
- planModeQuestionAnswered,
27
42
  planModeQuestionCancelled,
28
43
  } from "./question-tool.js";
44
+ import { withoutRequiredPlanModeTools, withRequiredPlanModeTools } from "./required-tools.js";
29
45
  import {
30
46
  configuredThinkingLevel,
31
- type PlanModeFixedThinkingLevel,
32
47
  type PlanModeSettings,
33
48
  readPlanModeSettings,
34
49
  } from "./settings.js";
@@ -42,57 +57,31 @@ import {
42
57
  readCommand,
43
58
  SAFE_BUILTIN_PLAN_TOOLS,
44
59
  } from "./tool-policy.js";
60
+ import { compareTools, toolNameFromLegacyKey, toolPolicyLabel, unique } from "./tool-selection.js";
45
61
 
46
62
  const STATE_ENTRY_TYPE = "plan-mode-state";
47
- const STATUS_KEY = "plan-mode";
48
- const PLAN_WIDGET_KEY = "plan-mode-plan";
49
63
  const PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
50
64
  const BLOCKED_BUILTIN_TOOLS = new Set(["edit", "write"]);
51
65
  const DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
52
66
  const TOOL_SELECTOR_VIEWPORT_SIZE = 10;
53
67
 
54
- type AgentSettledHandler = (event: unknown, ctx: ExtensionContext) => unknown;
55
-
56
- function onAgentSettled(pi: ExtensionAPI, handler: AgentSettledHandler) {
57
- (
58
- pi as unknown as {
59
- on(event: "agent_settled", callback: AgentSettledHandler): void;
60
- }
61
- ).on("agent_settled", handler);
62
- }
63
-
64
- function setPlanThinkingLevel(pi: ExtensionAPI, level: PlanModeFixedThinkingLevel) {
65
- (pi.setThinkingLevel as unknown as (level: PlanModeFixedThinkingLevel) => void)(level);
66
- }
67
-
68
- interface CommandArgumentCompletion {
69
- value: string;
70
- label: string;
71
- description?: string;
72
- }
73
-
74
68
  interface ReadyPresentationIntent {
75
69
  nonce: number;
76
70
  plan: string;
77
71
  source: PlanCompletionSource;
78
72
  }
79
73
 
80
- const PLAN_COMMAND_COMPLETIONS: readonly CommandArgumentCompletion[] = [
81
- { value: "show", label: "show", description: "Show the completed plan" },
82
- { value: "finalize", label: "finalize", description: "Request a completed plan" },
83
- { value: "implement", label: "implement", description: "Implement the completed plan" },
84
- { value: "exit", label: "exit", description: "Leave Plan mode" },
85
- { value: "off", label: "off", description: "Leave Plan mode" },
86
- { value: "tools", label: "tools", description: "Select tools allowed in Plan mode" },
87
- ];
88
-
89
- export default function planMode(pi: ExtensionAPI) {
74
+ export default function planMode(
75
+ pi: ExtensionAPI,
76
+ dependencies: { readSettings?(): ReturnType<typeof readPlanModeSettings> } = {},
77
+ ) {
90
78
  let state: PlanModeState = { enabled: false, awaitingAction: false };
91
79
  let settings: PlanModeSettings = { thinkingLevel: "inherit" };
92
80
  let previousTools: string[] | undefined;
93
81
  let readyPresentationIntent: ReadyPresentationIntent | undefined;
94
82
  let nextReadyPresentationNonce = 0;
95
83
  let menuGeneration = 0;
84
+ let workflowGeneration = 0;
96
85
  let menuController = new AbortController();
97
86
 
98
87
  pi.registerFlag("plan", {
@@ -133,16 +122,13 @@ export default function planMode(pi: ExtensionAPI) {
133
122
  );
134
123
  }
135
124
 
136
- const answers = await askPlanModeQuestions(parsed.questions, ctx);
137
- if (!answers) {
138
- return planModeQuestionCancelled(
139
- parsed.questions,
140
- "cancelled",
141
- "User cancelled the Plan-mode question prompt.",
142
- );
143
- }
144
-
145
- return planModeQuestionAnswered(parsed.questions, answers);
125
+ const sessionGeneration = menuGeneration;
126
+ const questionWorkflowGeneration = workflowGeneration;
127
+ return answerPlanModeQuestions(parsed.questions, ctx, {
128
+ isCurrent: () =>
129
+ sessionGeneration === menuGeneration && questionWorkflowGeneration === workflowGeneration,
130
+ isEnabled: () => state.enabled,
131
+ });
146
132
  },
147
133
  });
148
134
 
@@ -192,8 +178,14 @@ export default function planMode(pi: ExtensionAPI) {
192
178
  return;
193
179
  }
194
180
  if (command === "exit" || command === "off") {
181
+ const hadActiveImplementation = state.activeImplementation !== undefined;
195
182
  exitPlanMode(ctx);
196
- ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
183
+ ctx.ui.notify(
184
+ hadActiveImplementation
185
+ ? "Active implementation plan cleared."
186
+ : "Plan mode disabled. Proposed plan discarded.",
187
+ "info",
188
+ );
197
189
  return;
198
190
  }
199
191
  if (command === "tools") {
@@ -206,6 +198,10 @@ export default function planMode(pi: ExtensionAPI) {
206
198
  return;
207
199
  }
208
200
  if (!state.enabled) {
201
+ if (state.activeImplementation && ctx.hasUI) {
202
+ await showActivePlanMenu(ctx);
203
+ return;
204
+ }
209
205
  enterPlanMode(ctx);
210
206
  ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
211
207
  return;
@@ -215,23 +211,28 @@ export default function planMode(pi: ExtensionAPI) {
215
211
  });
216
212
 
217
213
  pi.on("session_start", async (_event, ctx) => {
218
- menuGeneration += 1;
214
+ const generation = ++menuGeneration;
219
215
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
220
216
  menuController = new AbortController();
221
217
  readyPresentationIntent = undefined;
222
218
  settings = { thinkingLevel: "inherit" };
223
- const loadedSettings = await readPlanModeSettings();
219
+ restoreState(ctx);
220
+ const loadedSettings = await (dependencies.readSettings?.() ?? readPlanModeSettings());
221
+ if (generation !== menuGeneration || menuController.signal.aborted) return;
224
222
  if (loadedSettings.kind === "loaded") settings = loadedSettings.settings;
225
223
  else if (loadedSettings.kind === "invalid") {
226
224
  ctx.ui.notify(`pi-plan-mode settings ignored: ${loadedSettings.reason}`, "warning");
227
225
  }
228
226
  if (loadedSettings.notice) ctx.ui.notify(loadedSettings.notice, "warning");
229
- restoreState(ctx);
230
- if (pi.getFlag("plan") === true) state.enabled = true;
227
+ const persistFlagActivation = pi.getFlag("plan") === true && !state.enabled;
228
+ if (persistFlagActivation) {
229
+ state = { ...state, enabled: true, activeImplementation: undefined };
230
+ }
231
231
  if (state.enabled) {
232
232
  activatePlanModeTools();
233
233
  applyPlanThinkingLevel();
234
234
  } else deactivatePlanModeQuestionTool();
235
+ if (persistFlagActivation) persistState();
235
236
  updateUi(ctx);
236
237
  });
237
238
 
@@ -304,23 +305,32 @@ export default function planMode(pi: ExtensionAPI) {
304
305
  });
305
306
 
306
307
  pi.on("context", async (event) => {
307
- const messagesWithoutLegacyPlanContext = event.messages.filter(
308
- (message: unknown) => !messageContainsLegacyPlanModeContextArtifact(message),
308
+ const messagesWithoutPlanContext = event.messages.filter(
309
+ (message: unknown) =>
310
+ !messageContainsLegacyPlanModeContextArtifact(message) &&
311
+ !messageContainsPlanModeImplementationContextArtifact(message),
309
312
  );
310
313
  if (state.enabled) {
311
314
  return {
312
- messages: messagesWithoutLegacyPlanContext.filter(
315
+ messages: messagesWithoutPlanContext.filter(
313
316
  (message: unknown) => !messageContainsPlanModeImplementationHandoff(message),
314
317
  ),
315
318
  };
316
319
  }
317
- return {
318
- messages: messagesWithoutLegacyPlanContext
319
- .filter((message: unknown) => !messageContainsInactivePlanModeArtifact(message))
320
- .map(stripProposedPlanBlocksFromMessage)
321
- .map(stripPlanModeCompletionCallsFromMessage)
322
- .filter((message: unknown) => !isEmptyAssistantMessage(message)),
323
- };
320
+ const inactiveMessages = state.activeImplementation
321
+ ? messagesWithoutPlanContext
322
+ : messagesWithoutPlanContext.filter(
323
+ (message: unknown) => !messageContainsPlanModeImplementationHandoff(message),
324
+ );
325
+ const messages = inactiveMessages
326
+ .filter((message: unknown) => !messageContainsInactivePlanModeArtifact(message))
327
+ .map(stripProposedPlanBlocksFromMessage)
328
+ .map(stripPlanModeCompletionCallsFromMessage)
329
+ .filter((message: unknown) => !isEmptyAssistantMessage(message));
330
+ const contextualMessages = state.activeImplementation
331
+ ? injectActiveImplementationContext(messages, state.activeImplementation)
332
+ : messages;
333
+ return { messages: contextualMessages as typeof event.messages };
324
334
  });
325
335
 
326
336
  pi.on("before_agent_start", (event, ctx) => {
@@ -384,8 +394,14 @@ export default function planMode(pi: ExtensionAPI) {
384
394
  });
385
395
 
386
396
  function enterPlanMode(ctx: ExtensionContext) {
397
+ workflowGeneration += 1;
387
398
  if (!state.enabled) previousTools = withoutRequiredPlanModeTools(safeGetActiveTools());
388
- state = { ...state, enabled: true, awaitingAction: false };
399
+ state = {
400
+ ...state,
401
+ enabled: true,
402
+ awaitingAction: false,
403
+ activeImplementation: undefined,
404
+ };
389
405
  activatePlanModeTools();
390
406
  applyPlanThinkingLevel();
391
407
  persistState();
@@ -393,15 +409,24 @@ export default function planMode(pi: ExtensionAPI) {
393
409
  }
394
410
 
395
411
  function enterPlanModeWithPrompt(prompt: string, ctx: ExtensionContext) {
412
+ const previousState = state;
396
413
  const wasEnabled = state.enabled;
397
414
  enterPlanMode(ctx);
398
415
  if (!wasEnabled) {
399
416
  ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
400
417
  }
401
- if (!sendPlanModeUserMessage(prompt, ctx) && !wasEnabled) exitPlanMode(ctx);
418
+ if (sendPlanModeUserMessage(prompt, ctx)) return;
419
+ if (!previousState.enabled) {
420
+ restoreTools();
421
+ restoreThinkingLevel();
422
+ }
423
+ state = previousState;
424
+ persistState();
425
+ updateUi(ctx);
402
426
  }
403
427
 
404
428
  function exitPlanMode(ctx: ExtensionContext) {
429
+ workflowGeneration += 1;
405
430
  const wasEnabled = state.enabled;
406
431
  readyPresentationIntent = undefined;
407
432
  state = {
@@ -410,6 +435,7 @@ export default function planMode(pi: ExtensionAPI) {
410
435
  latestPlan: undefined,
411
436
  latestPlanSource: undefined,
412
437
  awaitingAction: false,
438
+ activeImplementation: undefined,
413
439
  manualThinkingLevel: undefined,
414
440
  };
415
441
  if (wasEnabled) {
@@ -434,23 +460,30 @@ export default function planMode(pi: ExtensionAPI) {
434
460
  }
435
461
 
436
462
  function acceptCompletedPlan(plan: string, source: PlanCompletionSource, ctx: ExtensionContext) {
463
+ const normalized = normalizePlanModeCompletion({ plan });
464
+ if (!normalized.ok) {
465
+ ctx.ui.notify(`Proposed plan is not ready: ${normalized.error}.`, "warning");
466
+ persistState();
467
+ updateUi(ctx);
468
+ return;
469
+ }
437
470
  if (
438
471
  state.enabled &&
439
472
  state.awaitingAction &&
440
- state.latestPlan === plan &&
473
+ state.latestPlan === normalized.plan &&
441
474
  state.latestPlanSource === source
442
475
  ) {
443
476
  return;
444
477
  }
445
478
  state = {
446
479
  ...state,
447
- latestPlan: plan,
480
+ latestPlan: normalized.plan,
448
481
  latestPlanSource: source,
449
482
  awaitingAction: true,
450
483
  };
451
484
  readyPresentationIntent = {
452
485
  nonce: ++nextReadyPresentationNonce,
453
- plan,
486
+ plan: normalized.plan,
454
487
  source,
455
488
  };
456
489
  persistState();
@@ -471,8 +504,10 @@ export default function planMode(pi: ExtensionAPI) {
471
504
  }
472
505
 
473
506
  function showStoredPlan(ctx: ExtensionContext) {
474
- const plan = state.latestPlan?.trim();
475
- if (!state.enabled || !plan) {
507
+ const readyPlan = state.enabled ? state.latestPlan?.trim() : undefined;
508
+ const activePlan = state.activeImplementation?.plan.trim();
509
+ const plan = readyPlan ?? activePlan;
510
+ if (!plan) {
476
511
  ctx.ui.notify(
477
512
  "No completed plan is available. Use /plan finalize when planning is complete.",
478
513
  "info",
@@ -483,7 +518,7 @@ export default function planMode(pi: ExtensionAPI) {
483
518
  pi.sendMessage(
484
519
  {
485
520
  customType: PROPOSED_PLAN_MESSAGE_TYPE,
486
- content: `**Proposed Plan**\n\n${plan}`,
521
+ content: `**${readyPlan ? "Proposed Plan" : "Active Implementation Plan"}**\n\n${plan}`,
487
522
  display: true,
488
523
  },
489
524
  { triggerTurn: false },
@@ -507,14 +542,37 @@ export default function planMode(pi: ExtensionAPI) {
507
542
 
508
543
  function startImplementation(ctx: ExtensionContext) {
509
544
  const plan = state.latestPlan?.trim();
510
- const source = state.latestPlanSource;
511
- exitPlanMode(ctx);
512
-
545
+ const source = state.latestPlanSource ?? "legacy_proposed_plan";
513
546
  if (!plan) {
514
547
  ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
515
548
  return;
516
549
  }
517
550
 
551
+ workflowGeneration += 1;
552
+ const wasEnabled = state.enabled;
553
+ readyPresentationIntent = undefined;
554
+ state = {
555
+ ...state,
556
+ enabled: false,
557
+ latestPlan: undefined,
558
+ latestPlanSource: undefined,
559
+ awaitingAction: false,
560
+ activeImplementation: {
561
+ id: randomUUID(),
562
+ plan,
563
+ source,
564
+ startedAt: Date.now(),
565
+ },
566
+ manualThinkingLevel: undefined,
567
+ };
568
+ if (wasEnabled) {
569
+ restoreTools();
570
+ restoreThinkingLevel();
571
+ state = { ...state, manualThinkingLevel: undefined };
572
+ }
573
+ persistState();
574
+ updateUi(ctx);
575
+
518
576
  const sent = sendPlanModeUserMessage(
519
577
  `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:\n\n${plan}`,
520
578
  ctx,
@@ -527,12 +585,34 @@ export default function planMode(pi: ExtensionAPI) {
527
585
  }
528
586
  }
529
587
 
588
+ async function showActivePlanMenu(ctx: ExtensionContext) {
589
+ if (!ctx.hasUI) {
590
+ ctx.ui.notify(planStatusText(), "info");
591
+ return;
592
+ }
593
+ const lifecycle = captureMenuLifecycle();
594
+ await showActiveImplementationMenu(ctx, {
595
+ statusText: planStatusText(),
596
+ signal: lifecycle.signal,
597
+ isCurrent: lifecycle.isCurrent,
598
+ show: () => showStoredPlan(ctx),
599
+ startNew: () => {
600
+ enterPlanMode(ctx);
601
+ ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
602
+ },
603
+ clear: () => {
604
+ exitPlanMode(ctx);
605
+ ctx.ui.notify("Active implementation plan cleared.", "info");
606
+ },
607
+ });
608
+ }
609
+
530
610
  async function showPlanMenu(ctx: ExtensionContext) {
531
611
  if (!ctx.hasUI) {
532
612
  ctx.ui.notify(planStatusText(), "info");
533
613
  return;
534
614
  }
535
- const generation = menuGeneration;
615
+ const lifecycle = captureMenuLifecycle();
536
616
  type Action = "show" | "finalize" | "implement" | "tools" | "stay" | "exit";
537
617
  const menu = defineMenu<undefined, "main", Action, ExtensionContext>({
538
618
  start: "main",
@@ -588,13 +668,12 @@ export default function planMode(pi: ExtensionAPI) {
588
668
  });
589
669
  await runMenu(ctx, menu, {
590
670
  getState: () => undefined,
591
- signal: menuController.signal,
592
- isCurrent: () => generation === menuGeneration && !menuController.signal.aborted,
671
+ ...lifecycle,
593
672
  });
594
673
  }
595
674
 
596
675
  async function showPlanReadyMenu(ctx: ExtensionContext) {
597
- const generation = menuGeneration;
676
+ const lifecycle = captureMenuLifecycle();
598
677
  type Action = "implement" | "stay" | "exit";
599
678
  const menu = defineMenu<undefined, "ready", Action, ExtensionContext>({
600
679
  start: "ready",
@@ -625,8 +704,7 @@ export default function planMode(pi: ExtensionAPI) {
625
704
  });
626
705
  await runMenu(ctx, menu, {
627
706
  getState: () => undefined,
628
- signal: menuController.signal,
629
- isCurrent: () => generation === menuGeneration && !menuController.signal.aborted,
707
+ ...lifecycle,
630
708
  });
631
709
  }
632
710
 
@@ -635,7 +713,7 @@ export default function planMode(pi: ExtensionAPI) {
635
713
  ctx.ui.notify(formatToolSummary(), "info");
636
714
  return;
637
715
  }
638
- const generation = menuGeneration;
716
+ const lifecycle = captureMenuLifecycle();
639
717
  const tools = selectableTools();
640
718
  const toolById = new Map(tools.map((tool, index) => [`${index}:${tool.name}`, tool]));
641
719
  const menu = defineMenu<undefined, "tools", "toggle", ExtensionContext>({
@@ -647,6 +725,7 @@ export default function planMode(pi: ExtensionAPI) {
647
725
  kind: "multiSelect",
648
726
  title: "Plan-mode tools",
649
727
  lines: ["Non-built-in tools run at user risk."],
728
+ enableSearch: true,
650
729
  viewportSize: TOOL_SELECTOR_VIEWPORT_SIZE,
651
730
  items: tools.map((tool, index) => {
652
731
  const selectable = canSelectToolInPlanMode(tool);
@@ -654,6 +733,7 @@ export default function planMode(pi: ExtensionAPI) {
654
733
  id: `${index}:${tool.name}`,
655
734
  label: tool.name,
656
735
  description: `${toolPolicyLabel(tool)} · ${tool.description}`,
736
+ searchText: [toolPolicyLabel(tool), tool.description].filter(Boolean).join(" "),
657
737
  selected: selectedNames.has(tool.name),
658
738
  disabled: !selectable,
659
739
  disabledReason: selectable ? undefined : "Blocked by Plan-mode policy",
@@ -685,14 +765,25 @@ export default function planMode(pi: ExtensionAPI) {
685
765
  });
686
766
  await runMenu(ctx, menu, {
687
767
  getState: () => undefined,
688
- signal: menuController.signal,
689
- isCurrent: () => generation === menuGeneration && !menuController.signal.aborted,
768
+ ...lifecycle,
690
769
  });
770
+ if (!lifecycle.isCurrent()) return;
691
771
  applyPlanModeTools();
692
- if (generation === menuGeneration) {
693
- persistState();
694
- updateUi(ctx);
695
- }
772
+ persistState();
773
+ updateUi(ctx);
774
+ }
775
+
776
+ function captureMenuLifecycle() {
777
+ const sessionGeneration = menuGeneration;
778
+ const planWorkflowGeneration = workflowGeneration;
779
+ const controller = menuController;
780
+ return {
781
+ signal: controller.signal,
782
+ isCurrent: () =>
783
+ sessionGeneration === menuGeneration &&
784
+ planWorkflowGeneration === workflowGeneration &&
785
+ !controller.signal.aborted,
786
+ };
696
787
  }
697
788
 
698
789
  function activatePlanModeTools() {
@@ -851,39 +942,15 @@ export default function planMode(pi: ExtensionAPI) {
851
942
  }
852
943
 
853
944
  function updateUi(ctx: ExtensionContext) {
854
- ctx.ui.setStatus(STATUS_KEY, formatStatus());
855
- if (state.enabled && state.latestPlan) {
856
- ctx.ui.setWidget(PLAN_WIDGET_KEY, [
857
- "Proposed plan ready",
858
- "Use /plan to implement, revise, or exit Plan mode.",
859
- ]);
860
- } else if (state.enabled) {
861
- ctx.ui.setWidget(PLAN_WIDGET_KEY, [
862
- "Plan mode: planning",
863
- formatToolSummary(),
864
- "Finish with plan_mode_complete when decision-ready.",
865
- ]);
866
- } else {
867
- ctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);
868
- }
869
- }
870
-
871
- function formatStatus() {
872
- if (!state.enabled) return undefined;
873
- if (state.awaitingAction || state.latestPlan) return "plan ready";
874
- return "plan active";
945
+ updatePlanModeUi(ctx, state, formatToolSummary);
875
946
  }
876
947
 
877
948
  function clearUi(ctx: ExtensionContext) {
878
- ctx.ui.setStatus(STATUS_KEY, undefined);
879
- ctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);
949
+ clearPlanModeUi(ctx);
880
950
  }
881
951
 
882
952
  function planStatusText() {
883
- if (!state.enabled) return "Plan mode is off.";
884
- if (state.latestPlan)
885
- return `Plan mode is active and a proposed plan is ready. ${formatToolSummary()}`;
886
- return `Plan mode is active. ${formatToolSummary()} Explore, ask, and finish with plan_mode_complete when decision-ready.`;
953
+ return formatPlanModeStatusText(state, formatToolSummary);
887
954
  }
888
955
 
889
956
  function formatToolSummary() {
@@ -896,84 +963,7 @@ export default function planMode(pi: ExtensionAPI) {
896
963
  }
897
964
  }
898
965
 
899
- export function completePlanArguments(argumentPrefix: string): CommandArgumentCompletion[] | null {
900
- const prefix = argumentPrefix.trimStart().toLowerCase();
901
- if (prefix === "") return [...PLAN_COMMAND_COMPLETIONS];
902
- if (/\s/.test(prefix)) return null;
903
-
904
- const matches = PLAN_COMMAND_COMPLETIONS.filter((item) => item.value.startsWith(prefix));
905
- return matches.length > 0 ? [...matches] : null;
906
- }
907
-
908
- function toolNameFromLegacyKey(key: string, tools: ToolInfo[]) {
909
- const directName = tools.find((tool) => tool.name === key)?.name;
910
- if (directName) return directName;
911
- const [name] = key.split("\u001f");
912
- return tools.find((tool) => tool.name === name) ? name : undefined;
913
- }
914
-
915
- function compareTools(left: ToolInfo, right: ToolInfo) {
916
- const leftBuiltin = isBuiltinTool(left);
917
- const rightBuiltin = isBuiltinTool(right);
918
- if (leftBuiltin !== rightBuiltin) return leftBuiltin ? -1 : 1;
919
- return left.name.localeCompare(right.name);
920
- }
921
-
922
- function toolPolicyLabel(tool: ToolInfo) {
923
- const policy = classifyPlanModeTool(tool);
924
- if (policy === "read-only") return "built-in read-only";
925
- if (policy === "limited") return "built-in limited";
926
- if (policy === "blocked") return "built-in blocked";
927
- return `user opt-in: ${toolSourceLabel(tool)}`;
928
- }
929
-
930
- function toolSourceLabel(tool: ToolInfo) {
931
- const sourceInfo = tool.sourceInfo;
932
- const source = `${sourceInfo.scope}/${sourceInfo.source}`;
933
- return sourceInfo.path ? `${source} ${sourceInfo.path}` : source;
934
- }
935
-
936
- function unique(values: string[]) {
937
- return Array.from(new Set(values));
938
- }
939
-
940
- function isStaleExtensionContextError(error: unknown) {
941
- return (
942
- error instanceof Error &&
943
- (error.message.includes("This extension ctx is stale after session replacement or reload") ||
944
- error.message.includes("Extension context is no longer active"))
945
- );
946
- }
947
-
948
- export function withRequiredPlanModeTools(toolNames: string[]) {
949
- return unique([
950
- ...withoutRequiredPlanModeTools(toolNames),
951
- PLAN_MODE_QUESTION_TOOL_NAME,
952
- PLAN_MODE_COMPLETE_TOOL_NAME,
953
- ]);
954
- }
955
-
956
- export function withoutPlanModeQuestionTool(toolNames: string[]) {
957
- return toolNames.filter((toolName) => toolName !== PLAN_MODE_QUESTION_TOOL_NAME);
958
- }
959
-
960
- function withoutRequiredPlanModeTools(toolNames: string[]) {
961
- return toolNames.filter(
962
- (toolName) =>
963
- toolName !== PLAN_MODE_QUESTION_TOOL_NAME && toolName !== PLAN_MODE_COMPLETE_TOOL_NAME,
964
- );
965
- }
966
-
967
- function invalidPlanMessage(kind: "empty" | "multiple" | "malformed" | "unclosed") {
968
- const detail = {
969
- empty: "the block is empty",
970
- multiple: "more than one plan block was produced",
971
- malformed: "the tags must be on their own lines",
972
- unclosed: "the closing tag is missing",
973
- }[kind];
974
- return `Proposed plan is not ready: ${detail}. Continue Plan mode and produce one complete non-empty <proposed_plan> block.`;
975
- }
976
-
966
+ export { completePlanArguments } from "./command.js";
977
967
  export {
978
968
  extractProposedPlan,
979
969
  latestAssistantText,
@@ -983,5 +973,6 @@ export {
983
973
  } from "./message-transform.js";
984
974
  export { buildPlanModePrompt } from "./prompt.js";
985
975
  export { normalizePlanModeQuestionParams } from "./question-tool.js";
976
+ export { withoutPlanModeQuestionTool, withRequiredPlanModeTools } from "./required-tools.js";
986
977
  export { normalizePlanModeSettings, readPlanModeSettings } from "./settings.js";
987
978
  export { canSelectToolInPlanMode, classifyPlanModeTool, isSafeCommand } from "./tool-policy.js";
@@ -0,0 +1,57 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { PlanModeState } from "./state.js";
3
+
4
+ const STATUS_KEY = "plan-mode";
5
+ const PLAN_WIDGET_KEY = "plan-mode-plan";
6
+
7
+ export function updatePlanModeUi(
8
+ ctx: ExtensionContext,
9
+ state: PlanModeState,
10
+ toolSummary: () => string,
11
+ ) {
12
+ ctx.ui.setStatus(STATUS_KEY, formatStatus(state));
13
+ if (state.enabled && state.latestPlan) {
14
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, [
15
+ "Proposed plan ready",
16
+ "Use /plan to implement, revise, or exit Plan mode.",
17
+ ]);
18
+ } else if (state.enabled) {
19
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, [
20
+ "Plan mode: planning",
21
+ toolSummary(),
22
+ "Finish with plan_mode_complete when decision-ready.",
23
+ ]);
24
+ } else if (state.activeImplementation) {
25
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, [
26
+ "Implementation plan active",
27
+ "Use /plan to show, replace, or clear it.",
28
+ ]);
29
+ } else {
30
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);
31
+ }
32
+ }
33
+
34
+ export function clearPlanModeUi(ctx: ExtensionContext) {
35
+ ctx.ui.setStatus(STATUS_KEY, undefined);
36
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);
37
+ }
38
+
39
+ export function planModeStatusText(state: PlanModeState, toolSummary: () => string) {
40
+ if (state.enabled) {
41
+ if (state.latestPlan) {
42
+ return `Plan mode is active and a proposed plan is ready. ${toolSummary()}`;
43
+ }
44
+ return `Plan mode is active. ${toolSummary()} Explore, ask, and finish with plan_mode_complete when decision-ready.`;
45
+ }
46
+ if (state.activeImplementation) return "An implementation plan is active.";
47
+ return "Plan mode is off.";
48
+ }
49
+
50
+ function formatStatus(state: PlanModeState) {
51
+ if (state.enabled) {
52
+ if (state.awaitingAction || state.latestPlan) return "plan ready";
53
+ return "plan active";
54
+ }
55
+ if (state.activeImplementation) return "plan implementing";
56
+ return undefined;
57
+ }
@@ -148,9 +148,44 @@ export function normalizePlanModeQuestionParams(
148
148
  return { ok: true, questions };
149
149
  }
150
150
 
151
+ export async function answerPlanModeQuestions(
152
+ questions: PlanModeQuestion[],
153
+ ctx: ExtensionContext,
154
+ lifecycle: { isCurrent(): boolean; isEnabled(): boolean },
155
+ ) {
156
+ const answers = await askPlanModeQuestions(
157
+ questions,
158
+ ctx,
159
+ () => lifecycle.isCurrent() && lifecycle.isEnabled(),
160
+ );
161
+ if (!lifecycle.isCurrent()) {
162
+ return planModeQuestionCancelled(
163
+ questions,
164
+ "cancelled",
165
+ "Plan-mode question cancelled because the session changed.",
166
+ );
167
+ }
168
+ if (!lifecycle.isEnabled()) {
169
+ return planModeQuestionCancelled(
170
+ questions,
171
+ "plan_mode_inactive",
172
+ "Plan-mode question cancelled because Plan mode is no longer active.",
173
+ );
174
+ }
175
+ if (!answers) {
176
+ return planModeQuestionCancelled(
177
+ questions,
178
+ "cancelled",
179
+ "User cancelled the Plan-mode question prompt.",
180
+ );
181
+ }
182
+ return planModeQuestionAnswered(questions, answers);
183
+ }
184
+
151
185
  export async function askPlanModeQuestions(
152
186
  questions: PlanModeQuestion[],
153
187
  ctx: ExtensionContext,
188
+ shouldContinue: () => boolean = () => true,
154
189
  ): Promise<PlanModeQuestionAnswer[] | undefined> {
155
190
  const answers: PlanModeQuestionAnswer[] = [];
156
191
  for (const question of questions) {
@@ -160,10 +195,10 @@ export async function askPlanModeQuestions(
160
195
  ...choices,
161
196
  otherChoice,
162
197
  ]);
163
- if (!choice) return undefined;
198
+ if (!shouldContinue() || !choice) return undefined;
164
199
  if (choice === otherChoice) {
165
200
  const customAnswer = (await ctx.ui.editor(question.question, ""))?.trim();
166
- if (!customAnswer) return undefined;
201
+ if (!shouldContinue() || !customAnswer) return undefined;
167
202
  answers.push({
168
203
  id: question.id,
169
204
  header: question.header,
@@ -0,0 +1,22 @@
1
+ import { PLAN_MODE_COMPLETE_TOOL_NAME } from "./completion-tool.js";
2
+ import { PLAN_MODE_QUESTION_TOOL_NAME } from "./question-tool.js";
3
+ import { unique } from "./tool-selection.js";
4
+
5
+ export function withRequiredPlanModeTools(toolNames: string[]) {
6
+ return unique([
7
+ ...withoutRequiredPlanModeTools(toolNames),
8
+ PLAN_MODE_QUESTION_TOOL_NAME,
9
+ PLAN_MODE_COMPLETE_TOOL_NAME,
10
+ ]);
11
+ }
12
+
13
+ export function withoutPlanModeQuestionTool(toolNames: string[]) {
14
+ return toolNames.filter((toolName) => toolName !== PLAN_MODE_QUESTION_TOOL_NAME);
15
+ }
16
+
17
+ export function withoutRequiredPlanModeTools(toolNames: string[]) {
18
+ return toolNames.filter(
19
+ (toolName) =>
20
+ toolName !== PLAN_MODE_QUESTION_TOOL_NAME && toolName !== PLAN_MODE_COMPLETE_TOOL_NAME,
21
+ );
22
+ }
package/src/state.ts CHANGED
@@ -7,11 +7,19 @@ import { PLAN_MODE_THINKING_LEVELS, type PlanModeFixedThinkingLevel } from "./se
7
7
 
8
8
  export type PlanCompletionSource = typeof PLAN_MODE_COMPLETE_TOOL_NAME | "legacy_proposed_plan";
9
9
 
10
+ export interface ActiveImplementationPlan {
11
+ id: string;
12
+ plan: string;
13
+ source: PlanCompletionSource;
14
+ startedAt: number;
15
+ }
16
+
10
17
  export interface PlanModeState {
11
18
  enabled: boolean;
12
19
  latestPlan?: string;
13
20
  latestPlanSource?: PlanCompletionSource;
14
21
  awaitingAction: boolean;
22
+ activeImplementation?: ActiveImplementationPlan;
15
23
  selectedToolNames?: string[];
16
24
  selectedToolKeys?: string[];
17
25
  previousThinkingLevel?: PlanModeFixedThinkingLevel;
@@ -45,12 +53,13 @@ export function restorePlanModeState(entries: unknown[], stateEntryType: string)
45
53
 
46
54
  const enabled = entry.data.enabled === true;
47
55
  const persistedSource = enabled ? planCompletionSource(entry.data.latestPlanSource) : undefined;
48
- const persistedPlan = enabled
49
- ? normalizePersistedPlan(entry.data.latestPlan, persistedSource)
50
- : undefined;
56
+ const persistedPlan = enabled ? normalizePersistedPlan(entry.data.latestPlan) : undefined;
51
57
  const recoveredPlan =
52
58
  enabled && !persistedPlan ? latestCompletionPlan(branch.slice(stateEntryIndex + 1)) : undefined;
53
59
  const latestPlan = persistedPlan ?? recoveredPlan;
60
+ const activeImplementation = enabled
61
+ ? undefined
62
+ : normalizeActiveImplementation(entry.data.activeImplementation);
54
63
  return {
55
64
  enabled,
56
65
  latestPlan,
@@ -59,6 +68,7 @@ export function restorePlanModeState(entries: unknown[], stateEntryType: string)
59
68
  (recoveredPlan ? PLAN_MODE_COMPLETE_TOOL_NAME : undefined))
60
69
  : undefined,
61
70
  awaitingAction: enabled && latestPlan !== undefined,
71
+ activeImplementation,
62
72
  selectedToolNames: stringArray(entry.data.selectedToolNames),
63
73
  selectedToolKeys: stringArray(entry.data.selectedToolKeys),
64
74
  previousThinkingLevel: enabled
@@ -69,13 +79,27 @@ export function restorePlanModeState(entries: unknown[], stateEntryType: string)
69
79
  };
70
80
  }
71
81
 
72
- function normalizePersistedPlan(value: unknown, source: PlanCompletionSource | undefined) {
73
- if (typeof value !== "string") return undefined;
74
- if (source === PLAN_MODE_COMPLETE_TOOL_NAME) {
75
- const normalized = normalizePlanModeCompletion({ plan: value });
76
- return normalized.ok ? normalized.plan : undefined;
77
- }
78
- return value.trim() || undefined;
82
+ function normalizeActiveImplementation(value: unknown): ActiveImplementationPlan | undefined {
83
+ if (!isRecord(value)) return undefined;
84
+ const id =
85
+ typeof value.id === "string" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value.id)
86
+ ? value.id
87
+ : undefined;
88
+ const source = planCompletionSource(value.source);
89
+ const normalized = normalizePlanModeCompletion({ plan: value.plan });
90
+ const startedAt =
91
+ typeof value.startedAt === "number" &&
92
+ Number.isSafeInteger(value.startedAt) &&
93
+ value.startedAt >= 0
94
+ ? value.startedAt
95
+ : undefined;
96
+ if (!id || !source || !normalized.ok || startedAt === undefined) return undefined;
97
+ return { id, plan: normalized.plan, source, startedAt };
98
+ }
99
+
100
+ function normalizePersistedPlan(value: unknown) {
101
+ const normalized = normalizePlanModeCompletion({ plan: value });
102
+ return normalized.ok ? normalized.plan : undefined;
79
103
  }
80
104
 
81
105
  function latestCompletionPlan(entries: SessionEntry[]) {
@@ -0,0 +1,34 @@
1
+ import type { ToolInfo } from "@earendil-works/pi-coding-agent";
2
+ import { classifyPlanModeTool, isBuiltinTool } from "./tool-policy.js";
3
+
4
+ export function toolNameFromLegacyKey(key: string, tools: ToolInfo[]) {
5
+ const directName = tools.find((tool) => tool.name === key)?.name;
6
+ if (directName) return directName;
7
+ const [name] = key.split("\u001f");
8
+ return tools.find((tool) => tool.name === name) ? name : undefined;
9
+ }
10
+
11
+ export function compareTools(left: ToolInfo, right: ToolInfo) {
12
+ const leftBuiltin = isBuiltinTool(left);
13
+ const rightBuiltin = isBuiltinTool(right);
14
+ if (leftBuiltin !== rightBuiltin) return leftBuiltin ? -1 : 1;
15
+ return left.name.localeCompare(right.name);
16
+ }
17
+
18
+ export function toolPolicyLabel(tool: ToolInfo) {
19
+ const policy = classifyPlanModeTool(tool);
20
+ if (policy === "read-only") return "built-in read-only";
21
+ if (policy === "limited") return "built-in limited";
22
+ if (policy === "blocked") return "built-in blocked";
23
+ return `user opt-in: ${toolSourceLabel(tool)}`;
24
+ }
25
+
26
+ function toolSourceLabel(tool: ToolInfo) {
27
+ const sourceInfo = tool.sourceInfo;
28
+ const source = `${sourceInfo.scope}/${sourceInfo.source}`;
29
+ return sourceInfo.path ? `${source} ${sourceInfo.path}` : source;
30
+ }
31
+
32
+ export function unique(values: string[]) {
33
+ return Array.from(new Set(values));
34
+ }