@narumitw/pi-plan-mode 0.42.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
@@ -12,14 +12,13 @@ Pi core intentionally does not ship a built-in plan mode; this package provides
12
12
  - Adds `--plan` to start a session in Plan mode.
13
13
  - Enables built-in read-only tools by default while Plan mode is active.
14
14
  - Disables extension and custom tools by default, with a `/plan tools` selector for explicit user-risk opt-in.
15
- - Optionally limits `subagent` and `subagent_spawn` launches to named planning roles while Plan mode is active.
16
15
  - Blocks `update_plan`, mutating built-in tools, and unsafe `bash` forms such as writes, substitutions, background jobs, dependency installs, and mutating Git commands.
17
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.
18
17
  - Adds required `plan_mode_question` and `plan_mode_complete` tools for structured questions and completion.
19
- - 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.
20
19
  - 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`, `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.
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.
23
22
 
24
23
  ## 📦 Install
25
24
 
@@ -50,6 +49,7 @@ pi -e ./extensions/pi-plan-mode
50
49
  /plan show
51
50
  /plan finalize
52
51
  /plan implement
52
+ /plan save
53
53
  /plan exit
54
54
  ```
55
55
 
@@ -63,7 +63,8 @@ the query to restore the stable tool cursor. RPC keeps the complete unfiltered t
63
63
  model-requested planning interaction, not command-menu navigation. `/plan show` displays the stored
64
64
  plan without starting a model turn, including the accepted plan while implementation is active.
65
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
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
67
68
  `implement` fail closed when no applicable plan is stored; `finalize` requires active Plan mode.
68
69
 
69
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.
@@ -84,17 +85,24 @@ A complete Plan mode answer should appear only after the agent has resolved disc
84
85
 
85
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.
86
87
 
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
+ 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.
88
89
 
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.
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.
90
97
 
91
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:
92
99
 
93
100
  - `plan active`: Plan mode is enabled and still gathering context or drafting a plan.
94
- - `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.
95
103
  - `plan implementing`: The exact accepted plan remains active until you clear or supersede it.
96
104
 
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:
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:
98
106
 
99
107
  ```text
100
108
  /plan exit
@@ -107,8 +115,7 @@ Create `$PI_CODING_AGENT_DIR/pi-plan-mode.json` (normally `~/.pi/agent/pi-plan-m
107
115
  ```json
108
116
  {
109
117
  "thinkingLevel": "inherit",
110
- "defaultPlanTools": ["read", "bash", "grep", "find", "ls", "subagent"],
111
- "allowedPlanSubagents": ["plan-scout", "plan-researcher", "plan-reviewer"],
118
+ "defaultPlanTools": ["read", "bash", "grep", "find", "ls"],
112
119
  "safeSubcommands": {
113
120
  "git": ["status", "log", "rev-parse", "blame"],
114
121
  "gh": ["pr view", "pr list", "issue view", "issue list"]
@@ -120,20 +127,10 @@ Create `$PI_CODING_AGENT_DIR/pi-plan-mode.json` (normally `~/.pi/agent/pi-plan-m
120
127
 
121
128
  `defaultPlanTools` defines the initial tool selection when a session has no stored `/plan tools` selection. Omit it to keep the available safe built-ins as the default. An explicit empty array is valid and enables only the required `plan_mode_question` and `plan_mode_complete` tools.
122
129
 
123
- Tool names must be non-empty strings; duplicates are removed in first-seen order. Unknown, unavailable, and Plan-mode-blocked names are ignored when tools are activated. A tool registered after Plan mode is already active is not added automatically; re-enter Plan mode or reopen `/plan tools` to reapply the selection. Non-built-in tools named in this global setting are an explicit user-risk opt-in, just like selecting them with `/plan tools`. Pi resolves tools by name, so if an extension overrides a built-in name, the effective extension tool is selected instead. An effective tool named `bash` remains subject to the limited-shell policy regardless of its source metadata.
130
+ Tool names must be non-empty strings; duplicates are removed in first-seen order. Unknown, unavailable, and Plan-mode-blocked names are ignored when tools are activated. A tool registered after Plan mode is already active is not added automatically; re-enter Plan mode or reopen `/plan tools` to reapply the selection. Non-built-in tools named in this global setting are an explicit user-risk opt-in, just like selecting them with `/plan tools`. Plan mode does not interpret their arguments or actions: enabling one trusts the whole effective tool. Pi resolves tools by name, so if an extension overrides a built-in name, the effective extension tool is selected instead. An effective tool named `bash` remains subject to the limited-shell policy regardless of its source metadata.
124
131
 
125
132
  A selection made with `/plan tools` is stored in that Pi session and takes precedence over `defaultPlanTools` when the session resumes. The global setting remains the baseline for fresh sessions and sessions without an explicit selection.
126
133
 
127
- ### Allowed Plan subagents
128
-
129
- `allowedPlanSubagents` is an optional, exact, case-sensitive allowlist of role names for subagent launches while Plan mode is active. It does not activate delegation tools by itself: add `subagent` or `subagent_spawn` to `defaultPlanTools`, or select the tool through `/plan tools`. The same role policy applies whichever activation path is used.
130
-
131
- When configured, Plan mode checks every role in blocking `subagent` single, parallel, chain, and fan-in calls (`agent`, `tasks[].agent`, `chain[].agent`, and `aggregator.agent`) and the top-level `agent` in `subagent_spawn`. A call containing any disallowed role is rejected as a whole before the launch tool executes. Covered calls whose role fields cannot be verified are also rejected so a malformed launch cannot bypass the policy.
132
-
133
- Omit `allowedPlanSubagents` to preserve the unrestricted role behavior for explicitly enabled delegation tools. Set it to `[]` to reject every covered launch in Plan mode. Names must be non-empty strings; duplicates are removed in first-seen order. A wrong type or an empty, whitespace-only, or non-string entry invalidates the settings file and triggers the normal warning/default fallback. Settings reload on `session_start`; removing the property removes the role restriction. Non-Plan sessions are never restricted. If no extension has registered the covered tool names, the setting is inert, so `pi-plan-mode` and `pi-subagents` remain independently installable.
134
-
135
- This is a name check, not capability enforcement or a sandbox. `pi-plan-mode` does not inspect an allowed role's effective tools, permissions, or source. User or project definitions can change or override the meaning of an allowed name, so keep every allowed role independently read-only and retain normal project-agent trust and confirmation controls. The policy does not resolve retained agent IDs used by `subagent_send`; enabling follow-up lifecycle tools remains a separate user-risk decision.
136
-
137
134
  ### Safe shell subcommands
138
135
 
139
136
  `safeSubcommands` adds reviewed command validators to limited `bash`; it is not a raw shell allowlist. Only the following exact values are accepted:
@@ -187,7 +184,7 @@ This extension maps Codex's `ModeKind::Plan` behavior onto Pi's extension API:
187
184
  - The agent should use `plan_mode_question` for important non-discoverable preferences or tradeoffs before finalizing.
188
185
  - The agent completes with a standalone `plan_mode_complete` tool call instead of relying on semantic prose detection.
189
186
  - `update_plan` checklist use is blocked while Plan mode is active.
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.
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.
191
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.
192
189
  - Unlike native Codex, this extension uses a terminating Pi tool plus an `agent_settled` ready flow; Pi cannot provide sandbox-level enforcement.
193
190
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-plan-mode",
3
- "version": "0.42.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,13 +44,17 @@ 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,
48
55
  readPlanModeSettings,
49
56
  } from "./settings.js";
50
57
  import { type PlanCompletionSource, type PlanModeState, restorePlanModeState } from "./state.js";
51
- import { enforcePlanSubagentAllowlist } from "./subagent-policy.js";
52
58
  import {
53
59
  canSelectToolInPlanMode,
54
60
  classifyPlanModeTool,
@@ -170,30 +176,39 @@ export default function planMode(
170
176
  return;
171
177
  }
172
178
  if (command === "implement") {
173
- if (!state.enabled || !state.latestPlan?.trim()) {
179
+ if (!(state.enabled && state.latestPlan?.trim()) && !state.savedPlan?.plan.trim()) {
174
180
  ctx.ui.notify("No completed plan is available to implement.", "warning");
175
181
  return;
176
182
  }
177
- startImplementation(ctx);
183
+ await startImplementation(ctx);
184
+ return;
185
+ }
186
+ if (command === "save") {
187
+ savePlanForLater(ctx);
178
188
  return;
179
189
  }
180
190
  if (command === "exit" || command === "off") {
181
- 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.";
182
198
  exitPlanMode(ctx);
183
- ctx.ui.notify(
184
- hadActiveImplementation
185
- ? "Active implementation plan cleared."
186
- : "Plan mode disabled. Proposed plan discarded.",
187
- "info",
188
- );
199
+ ctx.ui.notify(notification, "info");
189
200
  return;
190
201
  }
191
202
  if (command === "tools") {
203
+ if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))
204
+ return;
192
205
  if (!state.enabled) enterPlanMode(ctx);
193
206
  await showToolSelector(ctx);
194
207
  return;
195
208
  }
196
209
  if (prompt) {
210
+ if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))
211
+ return;
197
212
  enterPlanModeWithPrompt(prompt, ctx);
198
213
  return;
199
214
  }
@@ -202,6 +217,10 @@ export default function planMode(
202
217
  await showActivePlanMenu(ctx);
203
218
  return;
204
219
  }
220
+ if (state.savedPlan) {
221
+ await showSavedPlanActions(ctx);
222
+ return;
223
+ }
205
224
  enterPlanMode(ctx);
206
225
  ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
207
226
  return;
@@ -226,7 +245,17 @@ export default function planMode(
226
245
  if (loadedSettings.notice) ctx.ui.notify(loadedSettings.notice, "warning");
227
246
  const persistFlagActivation = pi.getFlag("plan") === true && !state.enabled;
228
247
  if (persistFlagActivation) {
229
- 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 };
230
259
  }
231
260
  if (state.enabled) {
232
261
  activatePlanModeTools();
@@ -271,14 +300,6 @@ export default function planMode(
271
300
  "Plan mode blocks update_plan because it tracks execution progress rather than conversational planning.",
272
301
  };
273
302
  }
274
- if (settings.allowedPlanSubagents !== undefined) {
275
- const blocked = enforcePlanSubagentAllowlist(
276
- event.toolName,
277
- event.input,
278
- settings.allowedPlanSubagents,
279
- );
280
- if (blocked) return blocked;
281
- }
282
303
  const calledTool = toolByName(event.toolName);
283
304
  if (calledTool && classifyPlanModeTool(calledTool) === "blocked") {
284
305
  return {
@@ -400,6 +421,7 @@ export default function planMode(
400
421
  ...state,
401
422
  enabled: true,
402
423
  awaitingAction: false,
424
+ savedPlan: undefined,
403
425
  activeImplementation: undefined,
404
426
  };
405
427
  activatePlanModeTools();
@@ -435,6 +457,7 @@ export default function planMode(
435
457
  latestPlan: undefined,
436
458
  latestPlanSource: undefined,
437
459
  awaitingAction: false,
460
+ savedPlan: undefined,
438
461
  activeImplementation: undefined,
439
462
  manualThinkingLevel: undefined,
440
463
  };
@@ -505,8 +528,12 @@ export default function planMode(
505
528
 
506
529
  function showStoredPlan(ctx: ExtensionContext) {
507
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
+ }
508
535
  const activePlan = state.activeImplementation?.plan.trim();
509
- const plan = readyPlan ?? activePlan;
536
+ const plan = readyPlan ?? savedPlan ?? activePlan;
510
537
  if (!plan) {
511
538
  ctx.ui.notify(
512
539
  "No completed plan is available. Use /plan finalize when planning is complete.",
@@ -514,19 +541,12 @@ export default function planMode(
514
541
  );
515
542
  return;
516
543
  }
517
- try {
518
- pi.sendMessage(
519
- {
520
- customType: PROPOSED_PLAN_MESSAGE_TYPE,
521
- content: `**${readyPlan ? "Proposed Plan" : "Active Implementation Plan"}**\n\n${plan}`,
522
- display: true,
523
- },
524
- { triggerTurn: false },
525
- );
526
- } catch (error: unknown) {
527
- const detail = error instanceof Error ? error.message : String(error);
528
- ctx.ui.notify(`Unable to show completed plan: ${detail}`, "error");
529
- }
544
+ const title = readyPlan
545
+ ? "Proposed Plan"
546
+ : savedPlan
547
+ ? "Saved Plan"
548
+ : "Active Implementation Plan";
549
+ showPlanModePlan(pi, ctx, title, plan);
530
550
  }
531
551
 
532
552
  function requestFinalPlan(ctx: ExtensionContext) {
@@ -540,15 +560,59 @@ export default function planMode(
540
560
  );
541
561
  }
542
562
 
543
- function startImplementation(ctx: ExtensionContext) {
544
- 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
+ }
545
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";
546
609
  if (!plan) {
547
610
  ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
548
611
  return;
549
612
  }
550
613
 
551
614
  workflowGeneration += 1;
615
+ const previousState = state;
552
616
  const wasEnabled = state.enabled;
553
617
  readyPresentationIntent = undefined;
554
618
  state = {
@@ -557,6 +621,7 @@ export default function planMode(
557
621
  latestPlan: undefined,
558
622
  latestPlanSource: undefined,
559
623
  awaitingAction: false,
624
+ savedPlan: undefined,
560
625
  activeImplementation: {
561
626
  id: randomUUID(),
562
627
  plan,
@@ -578,8 +643,13 @@ export default function planMode(
578
643
  ctx,
579
644
  );
580
645
  if (!sent) {
581
- enterPlanMode(ctx);
582
- 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
+ }
583
653
  persistState();
584
654
  updateUi(ctx);
585
655
  }
@@ -607,104 +677,55 @@ export default function planMode(
607
677
  });
608
678
  }
609
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
+
610
695
  async function showPlanMenu(ctx: ExtensionContext) {
611
696
  if (!ctx.hasUI) {
612
697
  ctx.ui.notify(planStatusText(), "info");
613
698
  return;
614
699
  }
615
700
  const lifecycle = captureMenuLifecycle();
616
- type Action = "show" | "finalize" | "implement" | "tools" | "stay" | "exit";
617
- const menu = defineMenu<undefined, "main", Action, ExtensionContext>({
618
- start: "main",
619
- screens: {
620
- main: () => ({
621
- kind: "actions",
622
- title: "Plan mode",
623
- lines: [planStatusText()],
624
- items: state.latestPlan
625
- ? [
626
- { id: "show", label: "Show latest proposed plan", action: "show" },
627
- { id: "implement", label: "Implement this plan", action: "implement" },
628
- { id: "tools", label: "Configure Plan-mode tools", action: "tools" },
629
- { id: "stay", label: "Stay in Plan mode", action: "stay" },
630
- { id: "exit", label: "Exit Plan mode", action: "exit" },
631
- ]
632
- : [
633
- { id: "finalize", label: "Request final plan", action: "finalize" },
634
- { id: "tools", label: "Configure Plan-mode tools", action: "tools" },
635
- { id: "stay", label: "Stay in Plan mode", action: "stay" },
636
- { id: "exit", label: "Exit Plan mode", action: "exit" },
637
- ],
638
- hint: "close",
639
- }),
640
- },
641
- actions: {
642
- show: async () => {
643
- showStoredPlan(ctx);
644
- return { kind: "close" };
645
- },
646
- finalize: async () => {
647
- requestFinalPlan(ctx);
648
- return { kind: "close" };
649
- },
650
- implement: async () => {
651
- startImplementation(ctx);
652
- return { kind: "close" };
653
- },
654
- tools: async () => {
655
- await showToolSelector(ctx);
656
- return { kind: "stay" };
657
- },
658
- stay: async () => {
659
- updateUi(ctx);
660
- return { kind: "close" };
661
- },
662
- exit: async () => {
663
- exitPlanMode(ctx);
664
- ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
665
- return { kind: "close" };
666
- },
667
- },
668
- });
669
- await runMenu(ctx, menu, {
670
- getState: () => undefined,
701
+ await showPlanModeMenu(ctx, {
702
+ statusText: planStatusText(),
703
+ hasReadyPlan: state.latestPlan !== undefined,
671
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
+ },
672
715
  });
673
716
  }
674
717
 
675
718
  async function showPlanReadyMenu(ctx: ExtensionContext) {
676
719
  const lifecycle = captureMenuLifecycle();
677
- type Action = "implement" | "stay" | "exit";
678
- const menu = defineMenu<undefined, "ready", Action, ExtensionContext>({
679
- start: "ready",
680
- screens: {
681
- ready: () => ({
682
- kind: "actions",
683
- title: "Proposed plan ready. What next?",
684
- items: [
685
- { id: "implement", label: "Implement this plan", action: "implement" },
686
- { id: "stay", label: "Stay in Plan mode", action: "stay" },
687
- { id: "exit", label: "Exit Plan mode", action: "exit" },
688
- ],
689
- hint: "close",
690
- }),
691
- },
692
- actions: {
693
- implement: async () => {
694
- startImplementation(ctx);
695
- return { kind: "close" };
696
- },
697
- stay: async () => ({ kind: "close" }),
698
- exit: async () => {
699
- exitPlanMode(ctx);
700
- ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
701
- return { kind: "close" };
702
- },
703
- },
704
- });
705
- await runMenu(ctx, menu, {
706
- getState: () => undefined,
720
+ await showReadyPlanMenu(ctx, {
707
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
+ },
708
729
  });
709
730
  }
710
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/settings.ts CHANGED
@@ -27,7 +27,6 @@ export type PlanModeFixedThinkingLevel = Exclude<PlanModeThinkingLevel, "inherit
27
27
  export interface PlanModeSettings {
28
28
  thinkingLevel: PlanModeThinkingLevel;
29
29
  defaultPlanTools?: string[];
30
- allowedPlanSubagents?: string[];
31
30
  safeSubcommands?: SafeSubcommands;
32
31
  }
33
32
  export type PlanModeSettingsLoadResult =
@@ -51,11 +50,6 @@ export function normalizePlanModeSettings(value: unknown): PlanModeSettings | un
51
50
  if (!defaultPlanTools) return undefined;
52
51
  settings.defaultPlanTools = defaultPlanTools;
53
52
  }
54
- if (Object.hasOwn(value, "allowedPlanSubagents")) {
55
- const allowedPlanSubagents = normalizeToolNames(Reflect.get(value, "allowedPlanSubagents"));
56
- if (!allowedPlanSubagents) return undefined;
57
- settings.allowedPlanSubagents = allowedPlanSubagents;
58
- }
59
53
  if (Object.hasOwn(value, "safeSubcommands")) {
60
54
  const safeSubcommands = normalizeSafeSubcommands(Reflect.get(value, "safeSubcommands"));
61
55
  if (!safeSubcommands) return undefined;
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 =
@@ -1,98 +0,0 @@
1
- export interface PlanSubagentPolicyBlock {
2
- block: true;
3
- reason: string;
4
- }
5
-
6
- const COVERED_SUBAGENT_TOOLS = new Set(["subagent", "subagent_spawn"]);
7
-
8
- export function enforcePlanSubagentAllowlist(
9
- toolName: string,
10
- input: unknown,
11
- allowedRoleNames: readonly string[],
12
- ): PlanSubagentPolicyBlock | undefined {
13
- if (!COVERED_SUBAGENT_TOOLS.has(toolName)) return undefined;
14
-
15
- const requestedRoleNames =
16
- toolName === "subagent_spawn" ? readSpawnRoleNames(input) : readBlockingRoleNames(input);
17
- const allowedNames = unique(allowedRoleNames);
18
- if (!requestedRoleNames) {
19
- return {
20
- block: true,
21
- reason: `Plan mode could not verify subagent roles for tool '${toolName}'. ${formatAllowedRoles(allowedNames)}`,
22
- };
23
- }
24
-
25
- const allowed = new Set(allowedNames);
26
- const disallowedNames = unique(requestedRoleNames).filter((name) => !allowed.has(name));
27
- if (disallowedNames.length === 0) return undefined;
28
-
29
- return {
30
- block: true,
31
- reason: `Plan mode blocks subagent role(s): ${disallowedNames.join(", ")}. ${formatAllowedRoles(allowedNames)}`,
32
- };
33
- }
34
-
35
- function readSpawnRoleNames(input: unknown) {
36
- if (!isRecord(input)) return undefined;
37
- const agent = readRoleName(input.agent);
38
- return agent ? [agent] : undefined;
39
- }
40
-
41
- function readBlockingRoleNames(input: unknown) {
42
- if (!isRecord(input)) return undefined;
43
- const roleNames: string[] = [];
44
- let hasRoleField = false;
45
-
46
- if (Object.hasOwn(input, "agent")) {
47
- hasRoleField = true;
48
- const agent = readRoleName(input.agent);
49
- if (!agent) return undefined;
50
- roleNames.push(agent);
51
- }
52
- for (const field of ["tasks", "chain"] as const) {
53
- if (!Object.hasOwn(input, field)) continue;
54
- hasRoleField = true;
55
- const agents = readRoleArray(input[field]);
56
- if (!agents) return undefined;
57
- roleNames.push(...agents);
58
- }
59
- if (Object.hasOwn(input, "aggregator")) {
60
- hasRoleField = true;
61
- if (!isRecord(input.aggregator)) return undefined;
62
- const agent = readRoleName(input.aggregator.agent);
63
- if (!agent) return undefined;
64
- roleNames.push(agent);
65
- }
66
-
67
- return hasRoleField && roleNames.length > 0 ? roleNames : undefined;
68
- }
69
-
70
- function readRoleArray(value: unknown) {
71
- if (!Array.isArray(value) || value.length === 0) return undefined;
72
- const roleNames: string[] = [];
73
- for (const item of value) {
74
- if (!isRecord(item)) return undefined;
75
- const agent = readRoleName(item.agent);
76
- if (!agent) return undefined;
77
- roleNames.push(agent);
78
- }
79
- return roleNames;
80
- }
81
-
82
- function readRoleName(value: unknown) {
83
- return typeof value === "string" && value.trim().length > 0 ? value : undefined;
84
- }
85
-
86
- function isRecord(value: unknown): value is Record<string, unknown> {
87
- return typeof value === "object" && value !== null && !Array.isArray(value);
88
- }
89
-
90
- function formatAllowedRoles(allowedRoleNames: readonly string[]) {
91
- return allowedRoleNames.length > 0
92
- ? `Allowed Plan subagents: ${allowedRoleNames.join(", ")}.`
93
- : "No subagent roles are allowed in Plan mode.";
94
- }
95
-
96
- function unique(values: readonly string[]) {
97
- return Array.from(new Set(values));
98
- }