@narumitw/pi-plan-mode 0.59.5 → 0.59.6

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/CHANGELOG.md ADDED
@@ -0,0 +1,215 @@
1
+ # @narumitw/pi-plan-mode
2
+
3
+ ## 0.59.6
4
+
5
+ ### Patch Changes
6
+
7
+ - 6c76ef1: Report inline Plan questions, Notes template editing, and Progress settings as waiting for user input on supported Pi hosts and terminals. Add optional consumer-owned blocked metadata to Kit custom interactions and questionnaires without marking loaders or changing RPC and print behavior. Settle host-disposed interactions and drain their work without interrupting native reset or restoring stale editor drafts.
8
+ - e484010: Include the existing package-root CHANGELOG.md in extension tarballs so Pi can show native update notices. Keep Changesets version headings and Pi's first-observation and collapseChangelog behavior unchanged.
9
+ - Updated dependencies [54f2700]
10
+ - Updated dependencies [6c76ef1]
11
+ - @narumitw/pi-tui-kit@0.69.0
12
+
13
+ ## 0.59.5
14
+
15
+ ### Patch Changes
16
+
17
+ - 9d3e0d7: Prevent passive UI timers from keeping Node alive while preserving status expiry, settings reloads, paste handling, and cleanup.
18
+ - Updated dependencies [9d3e0d7]
19
+ - @narumitw/pi-tui-kit@0.68.1
20
+
21
+ ## 0.59.4
22
+
23
+ ### Patch Changes
24
+
25
+ - 9f80b89: Reuse published Kit interaction ownership for native Progress and Subagents settings while preserving ordered saves, rollback, and durable-save recovery after the screen closes.
26
+
27
+ Share passive widget framing in Subagents, Tool, Plan Mode, and Cache Hit Monitor. Keep domain rendering and lifecycle ownership local, bound narrow and invalid widths, and retain lazy loading of Kit menus and other interactive APIs.
28
+ - Updated dependencies [077137a]
29
+ - Updated dependencies [9f80b89]
30
+ - Updated dependencies [efc474c]
31
+ - @narumitw/pi-tui-kit@0.66.0
32
+
33
+ ## 0.59.3
34
+
35
+ ### Patch Changes
36
+
37
+ - fed7bfb: Handle Pi custom-message run starts without consuming queued file quotes, clearing ready plans, or applying user-prompt Goal ownership logic.
38
+
39
+ ## 0.59.2
40
+
41
+ ### Patch Changes
42
+
43
+ - 2708319: Require Pi TUI Kit's published questionnaire custom-editor fix so existing lockfiles cannot retain a Kit release that bypasses the configured editor factory or mishandles editor submissions and key-release cycles.
44
+
45
+ ## 0.59.1
46
+
47
+ ### Patch Changes
48
+
49
+ - 000bd50: Use Pi's publicly configured custom editor factory for TUI questionnaire answers and notes. Custom editors own editing and submission keys, while Ctrl+C remains hard cancellation and the main prompt editor stays untouched. Preserve raw expanded drafts, fragmented paste safety, default-editor and non-TUI behavior, and release questionnaire-owned editor instances when the interaction ends.
50
+
51
+ Honor custom editor submission values without replacing intentional normalization with the original draft, and retain editor-owned key-release cycles across answer and note transitions.
52
+ - Updated dependencies [000bd50]
53
+ - @narumitw/pi-tui-kit@0.65.2
54
+
55
+ ## 0.59.0
56
+
57
+ ### Minor Changes
58
+
59
+ - 51d8c21: Restrict `safeSubcommands` trust to individual parsed Bash and PowerShell segments. A matching prefix no longer exempts trailing commands or bypasses the shell parser: every segment must pass its own policy, and unsupported syntax such as redirects and multiline input remains blocked.
60
+
61
+ This is a compatibility change from full-command trust. Simple configured commands and trusted arguments remain supported, but chains require each additional segment to be independently permitted. Run workflows requiring parser-unsupported syntax outside Plan mode after review. The settings schema is unchanged, and explicitly trusted commands and their arguments can still mutate data or execute code; this setting is not a read-only guarantee or sandbox.
62
+
63
+ ## 0.58.4
64
+
65
+ ### Patch Changes
66
+
67
+ - 9621cda: Distinguish inactive Pi tools from Plan-policy blocks in Settings and the pre-start picker, and explain how to enable built-in search tools through Pi settings without changing tool activation or execution policy.
68
+ - dbc6e8e: Allow explicit selection of native MCP and orchestration tools in Plan Mode. Honor registered callable exposure without direct activation while preserving automatic core defaults, frozen workflow policies, and per-call nested safety checks.
69
+ - acb3aaf: Allow case-insensitive inspection flags such as `rg -i` and `grep -i` in the Plan mode shell policy.
70
+
71
+ ## 0.58.3
72
+
73
+ ### Patch Changes
74
+
75
+ - 26e8801: Make Plan-mode shortcut changes explicitly take effect after `/reload` or restarting Pi. Keep startup shortcut registrations stable, remove ineffective live rebinding, and show the configured and startup-loaded values with reload guidance in Settings. Other settings retain their existing reload behavior.
76
+ - Updated dependencies [e6db042]
77
+ - @narumitw/pi-tui-kit@0.65.1
78
+
79
+ ## 0.58.2
80
+
81
+ ### Patch Changes
82
+
83
+ - 8abd5b7: Keep generated extension runtime graphs inside Pi's Jiti-loaded TypeScript path to avoid duplicate peer-runtime evaluation during startup. Add measured generated runtimes for Context Management, Herdr, and TypeSafe Search.
84
+
85
+ ## 0.58.1
86
+
87
+ ### Patch Changes
88
+
89
+ - 67a3049: Adapt provider, transcript, usage, deferred-tool, and telemetry behavior to Pi's current runtime contracts, including accurate cache-warming accounting and exclusion from ordinary generation traces.
90
+
91
+ ## 0.58.0
92
+
93
+ ### Minor Changes
94
+
95
+ - b745330: Add persistent fresh implementation model and thinking defaults with a same-as-plan fallback.
96
+ - 0ef037d: Add one-shot model and thinking selection before fresh ready-plan implementation.
97
+
98
+ ### Patch Changes
99
+
100
+ - 7c9a062: Defer automatic ready-plan fresh session handoffs until lifecycle dispatch and prompt cleanup finish.
101
+ - Updated dependencies [4485b49]
102
+ - Updated dependencies [6b1e009]
103
+ - @narumitw/pi-tui-kit@0.62.0
104
+
105
+ ## 0.57.1
106
+
107
+ ### Patch Changes
108
+
109
+ - 31b3dde: Remove the implementation model and thinking selectors, restoring Plan implementation handoffs to the current model and normal thinking behavior.
110
+
111
+ ## 0.57.0
112
+
113
+ ### Minor Changes
114
+
115
+ - e2af16b: Add optional implementation model and thinking defaults plus per-menu implementation options for same-session and fresh-session handoffs. Apply choices only at implementation start without changing Pi defaults or automatically restoring the planner's model after a run ends.
116
+
117
+ ### Patch Changes
118
+
119
+ - Updated dependencies [317f7bd]
120
+ - @narumitw/pi-tui-kit@0.61.0
121
+
122
+ ## 0.56.0
123
+
124
+ ### Minor Changes
125
+
126
+ - e230348: Allow narrowly validated local `hostname`, `tasklist`, `Get-Process`, and `Get-Service` inspections in Plan mode by default.
127
+ - 708cc2e: Let users add arbitrary `safeSubcommands` entries and treat every configured command-subcommand prefix as fully trusted for Plan-mode Bash and PowerShell calls.
128
+
129
+ ## 0.55.3
130
+
131
+ ### Patch Changes
132
+
133
+ - 14068d2: Allow reviewed Git inspections to use current-working-directory `git -C <path>` forms, and report actionable reasons when Plan mode denies an unavailable, inactive, frozen, blocked, or unselected tool.
134
+
135
+ ## 0.55.2
136
+
137
+ ### Patch Changes
138
+
139
+ - Updated dependencies [40182e5]
140
+ - @narumitw/pi-tui-kit@0.59.0
141
+
142
+ ## 0.55.1
143
+
144
+ ### Patch Changes
145
+
146
+ - b99b3db: Resolve explicitly selected tools registered before the first Plan request without mutating Pi's active tool schemas.
147
+
148
+ ## 0.55.0
149
+
150
+ ### Minor Changes
151
+
152
+ - b59cdbc: Remove the `toolVisibility` setting and keep Plan helper schemas stable from startup.
153
+ Retired settings keys are ignored and preserved, while globally visible helper metadata now distinguishes `/plan` from ordinary planning workflows.
154
+
155
+ ## 0.54.0
156
+
157
+ ### Minor Changes
158
+
159
+ - ab467e0: Allow Pi's active native PowerShell tool to run reviewed read-only file, directory, Git, and GitHub inspections in Plan mode while blocking mutation and unsupported dynamic syntax.
160
+
161
+ ## 0.53.1
162
+
163
+ ### Patch Changes
164
+
165
+ - 02878f5: Add an editor-style divider above the Plan mode widget.
166
+ - 3346683: Publish generated lazy chunks at the JavaScript paths referenced by each extension runtime so deferred menus and implementations load correctly through Pi's Jiti loader.
167
+ - Updated dependencies [b9eba3a]
168
+ - @narumitw/pi-tui-kit@0.58.0
169
+
170
+ ## 0.53.0
171
+
172
+ ### Minor Changes
173
+
174
+ - c194597: Make conversation-history-only implementation the default, use Codex-style kickoff prompts without active-plan injection, and clarify Plan reinjection controls.
175
+ - e74ee84: Add configurable Plan helper visibility and default to revealing the helper tools on the first successful Plan activation.
176
+ - 67eb77b: Remove the `--plan` startup flag. Start Plan mode after launch with `/plan start` or begin with a prompt through `/plan <prompt>`.
177
+ - da265a0: Keep Plan and Normal requests on one append-only conversation with stable tool schemas, versioned mode contracts, and a runtime Plan tool allowlist that no longer activates inactive tools.
178
+
179
+ ### Patch Changes
180
+
181
+ - df584db: Keep unused resumed sessions free of mode contracts and reject `/tree` navigation to internal transition markers.
182
+ - 5be9aa2: Prevent active agent runs from mixing Plan and Normal tool contracts, and retry explicit structured finalization once after settlement when the model responds with prose only.
183
+
184
+ ## 0.52.0
185
+
186
+ ### Minor Changes
187
+
188
+ - 85d13c8: Coordinate Plan-mode activation through Workflow Mutex Protocol v1 so cooperating agent workflows cannot start in the same Pi session.
189
+
190
+ ## 0.51.1
191
+
192
+ ### Patch Changes
193
+
194
+ - 8540d0f: Simplify single-question TUI questionnaires with a plain header and immediate answer submission while retaining tabbed Review for multiple questions.
195
+ - 5785cb4: Reuse Pi TUI Kit's questionnaire runner while preserving Plan mode answer and lifecycle behavior.
196
+ - Updated dependencies [8540d0f]
197
+ - @narumitw/pi-tui-kit@0.57.1
198
+
199
+ ## 0.51.0
200
+
201
+ ### Minor Changes
202
+
203
+ - 416da47: Add tabbed TUI Plan questions with answer notes and final review.
204
+
205
+ ## 0.50.1
206
+
207
+ ### Patch Changes
208
+
209
+ - 30bc076: Load each extension from a generated TypeScript runtime to reduce Jiti package startup work while preserving existing first-use boundaries.
210
+
211
+ ## 0.50.0
212
+
213
+ ### Minor Changes
214
+
215
+ - 160f2fc: Add an optional `toggleShortcut` setting and a **Plan mode shortcut** Settings row so the global Plan-mode keybinding can be chosen, and keep it disabled while the setting is omitted. Reload the settings file automatically when it changes and rebind the configured shortcut immediately after a Settings save.
package/README.md CHANGED
@@ -176,6 +176,7 @@ While that editor is active, it controls Escape and submission keys; Ctrl+C stil
176
176
  The editor's submitted value is retained, including any whitespace normalization it intentionally applies.
177
177
  Without a custom editor, existing editing and cancellation behavior is unchanged.
178
178
  The TUI rejects either field above 4,000 characters instead of truncating it.
179
+ On Pi 1.5 or later, the inline question prompt reports `question` waiting status to supported terminals until it closes. Older hosts keep the same question UI without this terminal status.
179
180
  RPC keeps the existing sequential `select` and `editor` dialogs because Pi RPC cannot render custom TUI components.
180
181
  If you cancel or no interactive UI is available, the agent should ask a concise plain-text question or proceed only with a clearly stated low-risk assumption instead of prematurely producing a final plan.
181
182
 
@@ -1022,6 +1022,7 @@ async function askPlanModeQuestions(questions, ctx, shouldContinue = () => true)
1022
1022
  }))
1023
1023
  }));
1024
1024
  const result = await runQuestionnaire(ctx, {
1025
+ blocked: { kind: "question", message: "Answer Plan mode questions" },
1025
1026
  questions: runnerQuestions,
1026
1027
  allowNotes: true,
1027
1028
  maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,
@@ -1876,4 +1877,4 @@ export {
1876
1877
  defaultPlanModeToolNames,
1877
1878
  snapshotPlanModeSelectedNames
1878
1879
  };
1879
- //# sourceMappingURL=chunk-MJV6WNHK.ts.map
1880
+ //# sourceMappingURL=chunk-W7D6N2MI.ts.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/completion-tool.ts", "../../src/message-transform.ts", "../../src/implementation-models.ts", "../../src/settings.ts", "../../src/implementation-retention.ts", "../../src/plan-export.ts", "../../src/question-tool.ts", "../../src/tool-availability.ts", "../../src/tool-policy.ts", "../../src/tool-selection.ts"],
4
- "sourcesContent": ["import { getMarkdownTheme } from \"@earendil-works/pi-coding-agent\";\nimport { Markdown } from \"@earendil-works/pi-tui\";\n\nexport const PLAN_MODE_COMPLETE_TOOL_NAME = \"plan_mode_complete\";\nexport const PLAN_MODE_COMPLETE_VERSION = 1;\nexport const PLAN_MODE_MAX_CHARS = 50_000;\n\nexport type PlanModeCompletionDetails = {\n version: typeof PLAN_MODE_COMPLETE_VERSION;\n source: typeof PLAN_MODE_COMPLETE_TOOL_NAME;\n plan: string;\n};\n\nexport const PLAN_MODE_COMPLETE_PARAMS = {\n type: \"object\",\n additionalProperties: false,\n required: [\"plan\"],\n properties: {\n plan: {\n type: \"string\",\n minLength: 1,\n maxLength: PLAN_MODE_MAX_CHARS,\n description: \"The complete decision-ready implementation plan in Markdown.\",\n },\n },\n} as const;\n\ntype NormalizePlanModeCompletionResult = { ok: true; plan: string } | { ok: false; error: string };\n\nexport function normalizePlanModeCompletion(input: unknown): NormalizePlanModeCompletionResult {\n if (!isRecord(input) || typeof input.plan !== \"string\") {\n return { ok: false, error: \"plan must be a string\" };\n }\n const plan = input.plan.trim();\n if (!plan) return { ok: false, error: \"plan must not be empty\" };\n if (plan.length > PLAN_MODE_MAX_CHARS) {\n return {\n ok: false,\n error: `plan must not exceed ${PLAN_MODE_MAX_CHARS} characters`,\n };\n }\n return { ok: true, plan };\n}\n\nexport function planFromCompletionDetails(value: unknown) {\n if (!isRecord(value)) return undefined;\n if (value.version !== PLAN_MODE_COMPLETE_VERSION || value.source !== PLAN_MODE_COMPLETE_TOOL_NAME) {\n return undefined;\n }\n const normalized = normalizePlanModeCompletion({ plan: value.plan });\n return normalized.ok ? normalized.plan : undefined;\n}\n\nexport function planModeCompleted(plan: string) {\n return {\n content: [{ type: \"text\" as const, text: `**Proposed Plan**\\n\\n${plan}` }],\n details: {\n version: PLAN_MODE_COMPLETE_VERSION,\n source: PLAN_MODE_COMPLETE_TOOL_NAME,\n plan,\n } satisfies PlanModeCompletionDetails,\n terminate: true,\n };\n}\n\ntype PlanModeCompletionRenderResult = {\n content: Array<{ type: string; text?: string }>;\n details?: unknown;\n};\n\nexport function planModeCompletionMarkdown(result: PlanModeCompletionRenderResult) {\n const content = result.content\n .filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n .map((block) => block.text)\n .join(\"\\n\")\n .trim();\n if (content) return content;\n const plan = planFromCompletionDetails(result.details);\n return plan ? `**Proposed Plan**\\n\\n${plan}` : \"\";\n}\n\nexport function renderPlanModeCompletion(result: PlanModeCompletionRenderResult) {\n return new Markdown(planModeCompletionMarkdown(result), 0, 0, getMarkdownTheme());\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "import { PLAN_MODE_COMPLETE_TOOL_NAME } from \"./completion-tool.js\";\nimport type { ActiveImplementationPlan } from \"./state.js\";\n\nconst PLAN_CONTEXT_MESSAGE_TYPE = \"plan-mode-context\";\nexport const PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE = \"plan-mode-implementation-context\";\nconst PROPOSED_PLAN_MESSAGE_TYPE = \"proposed-plan\";\nconst PLAN_IMPLEMENTATION_HANDOFF_PREFIX =\n \"Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:\";\nexport const PLAN_HISTORY_IMPLEMENTATION_PROMPT = \"Implement the plan.\";\nconst PROPOSED_PLAN_PATTERN = /^<proposed_plan>[\\t ]*\\r?\\n([\\s\\S]*?)\\r?\\n<\\/proposed_plan>[\\t ]*$/gm;\nconst PROPOSED_PLAN_BLOCK_PATTERN = /^<proposed_plan>[\\t ]*\\r?\\n[\\s\\S]*?\\r?\\n<\\/proposed_plan>[\\t ]*$/gm;\n\nexport type ProposedPlanParseResult =\n | { kind: \"absent\" }\n | { kind: \"valid\"; plan: string }\n | { kind: \"empty\" }\n | { kind: \"multiple\" }\n | { kind: \"malformed\" }\n | { kind: \"unclosed\" };\n\ntype SessionMessage = {\n role?: string;\n content?: unknown;\n stopReason?: string;\n};\n\ntype TextBlock = {\n type?: string;\n text?: string;\n};\n\nexport function parseProposedPlan(text: string): ProposedPlanParseResult {\n const openingCount = text.match(/<proposed_plan>/gi)?.length ?? 0;\n const closingCount = text.match(/<\\/proposed_plan>/gi)?.length ?? 0;\n if (openingCount === 0 && closingCount === 0) return { kind: \"absent\" };\n if (openingCount > 1 || closingCount > 1) return { kind: \"multiple\" };\n if (openingCount === 1 && closingCount === 0) return { kind: \"unclosed\" };\n if (openingCount !== 1 || closingCount !== 1) return { kind: \"malformed\" };\n\n const matches = Array.from(text.matchAll(PROPOSED_PLAN_PATTERN));\n if (matches.length !== 1) return { kind: \"malformed\" };\n const plan = matches[0]?.[1]?.trim() ?? \"\";\n return plan ? { kind: \"valid\", plan } : { kind: \"empty\" };\n}\n\nexport function extractProposedPlan(text: string) {\n const result = parseProposedPlan(text);\n return result.kind === \"valid\" ? result.plan : undefined;\n}\n\nexport function invalidPlanMessage(kind: \"empty\" | \"multiple\" | \"malformed\" | \"unclosed\") {\n const detail = {\n empty: \"the block is empty\",\n multiple: \"more than one plan block was produced\",\n malformed: \"the tags must be on their own lines\",\n unclosed: \"the closing tag is missing\",\n }[kind];\n return `Proposed plan is not ready: ${detail}. Continue Plan mode and produce one complete non-empty <proposed_plan> block.`;\n}\n\nexport function latestAssistantText(messages: unknown) {\n if (!Array.isArray(messages)) return \"\";\n for (const entry of [...messages].reverse()) {\n const message = (entry as { message?: SessionMessage })?.message ?? (entry as SessionMessage);\n if (message?.role !== \"assistant\") continue;\n const text = messageText(message);\n if (text) return text;\n }\n return \"\";\n}\n\nexport function latestAssistantStopReason(messages: unknown) {\n if (!Array.isArray(messages)) return undefined;\n for (const entry of [...messages].reverse()) {\n const message = (entry as { message?: SessionMessage })?.message ?? (entry as SessionMessage);\n if (message?.role === \"assistant\") return message.stopReason;\n }\n return undefined;\n}\n\nexport function messageTextContent(message: unknown) {\n return messageText((message as { message?: SessionMessage })?.message ?? (message as SessionMessage));\n}\n\nexport function messageContainsLegacyPlanModeContextArtifact(message: unknown) {\n return unwrapSessionMessage(message).customType === PLAN_CONTEXT_MESSAGE_TYPE;\n}\n\nexport function messageContainsPlanModeImplementationContextArtifact(message: unknown) {\n return unwrapSessionMessage(message).customType === PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE;\n}\n\nexport function injectActiveImplementationContext(messages: unknown[], activeImplementation: ActiveImplementationPlan) {\n let foundCurrentContext = false;\n let foundCurrentHandoff = false;\n const expectedContext = activeImplementationContextContent(activeImplementation);\n const messagesWithoutStaleContext = messages.filter((message) => {\n if (messageContainsPlanModeImplementationContextArtifact(message)) {\n const candidate = unwrapSessionMessage(message);\n if (!foundCurrentContext && candidate.content === expectedContext) {\n foundCurrentContext = true;\n return true;\n }\n return false;\n }\n if (!messageContainsPlanModeImplementationHandoff(message)) return true;\n if (!foundCurrentHandoff && messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)) {\n foundCurrentHandoff = true;\n return true;\n }\n return false;\n });\n if (foundCurrentHandoff || foundCurrentContext) return messagesWithoutStaleContext;\n\n let insertionIndex = 0;\n while (isSummaryMessage(messagesWithoutStaleContext[insertionIndex])) insertionIndex += 1;\n const contextMessage = {\n role: \"custom\" as const,\n customType: PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE,\n content: expectedContext,\n display: false,\n timestamp: activeImplementation.startedAt,\n };\n return [\n ...messagesWithoutStaleContext.slice(0, insertionIndex),\n contextMessage,\n ...messagesWithoutStaleContext.slice(insertionIndex),\n ];\n}\n\nfunction activeImplementationContextContent(activeImplementation: ActiveImplementationPlan) {\n return `[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}`;\n}\n\nexport function messageContainsInactivePlanModeArtifact(message: unknown) {\n const candidate = unwrapSessionMessage(message);\n return (\n candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE ||\n (candidate.role === \"toolResult\" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME)\n );\n}\n\ninterface HistoryImplementationArtifact {\n messageIndex: number;\n kind: \"completion\" | \"legacy\" | \"presentation\";\n toolCallId?: string;\n toolCallMessageIndex?: number;\n}\n\n// The kickoff text is intentionally generic, so only trust a plan artifact in the same\n// uninterrupted user/summary segment and require a complete tool-call/result pair.\nexport function findHistoryImplementationArtifact(messages: unknown[]): HistoryImplementationArtifact | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const candidate = unwrapSessionMessage(messages[index]);\n if (candidate.role !== \"user\" || contentText(candidate.content).trim() !== PLAN_HISTORY_IMPLEMENTATION_PROMPT) {\n continue;\n }\n const artifact = findHistoryImplementationArtifactBeforeKickoff(messages, index);\n if (artifact) return artifact;\n }\n return undefined;\n}\n\nfunction findHistoryImplementationArtifactBeforeKickoff(\n messages: unknown[],\n kickoffIndex: number,\n): HistoryImplementationArtifact | undefined {\n for (let index = kickoffIndex - 1; index >= 0; index -= 1) {\n const candidate = unwrapSessionMessage(messages[index]);\n if (candidate.role === \"user\" || isSummaryMessage(messages[index])) return undefined;\n if (candidate.role === \"toolResult\" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME) {\n const toolCallId = candidate.toolCallId;\n const toolCallMessageIndex = toolCallId\n ? findPlanModeCompletionCallMessageIndex(messages, index, toolCallId)\n : undefined;\n if (toolCallId && toolCallMessageIndex !== undefined) {\n return {\n messageIndex: index,\n kind: \"completion\",\n toolCallId,\n toolCallMessageIndex,\n };\n }\n continue;\n }\n if (candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE) {\n return { messageIndex: index, kind: \"presentation\" };\n }\n if (candidate.role === \"assistant\" && contentText(candidate.content).match(PROPOSED_PLAN_BLOCK_PATTERN)) {\n return { messageIndex: index, kind: \"legacy\" };\n }\n }\n return undefined;\n}\n\nfunction findPlanModeCompletionCallMessageIndex(messages: unknown[], endIndex: number, toolCallId: string) {\n for (let index = endIndex - 1; index >= 0; index -= 1) {\n const candidate = unwrapSessionMessage(messages[index]);\n if (candidate.role === \"user\" || isSummaryMessage(messages[index])) return undefined;\n if (!Array.isArray(candidate.content)) continue;\n if (\n candidate.content.some((block) => {\n const toolCall = block as { type?: string; id?: string; name?: string };\n return (\n toolCall.type === \"toolCall\" && toolCall.id === toolCallId && toolCall.name === PLAN_MODE_COMPLETE_TOOL_NAME\n );\n })\n ) {\n return index;\n }\n }\n return undefined;\n}\n\nexport function messageContainsPlanModeImplementationHandoff(message: unknown) {\n const candidate = unwrapSessionMessage(message);\n return (\n candidate.role === \"user\" &&\n contentText(candidate.content).trimStart().startsWith(PLAN_IMPLEMENTATION_HANDOFF_PREFIX)\n );\n}\n\nexport function messageContainsExactPlanModeImplementationHandoff(message: unknown, plan: string) {\n const candidate = unwrapSessionMessage(message);\n if (candidate.role !== \"user\") return false;\n return contentText(candidate.content).trim() === `${PLAN_IMPLEMENTATION_HANDOFF_PREFIX}\\n\\n${plan}`.trim();\n}\n\nfunction isSummaryMessage(message: unknown) {\n const role = unwrapSessionMessage(message)?.role;\n return role === \"compactionSummary\" || role === \"branchSummary\";\n}\n\nexport function stripProposedPlanBlocksFromMessage<T>(message: T): T {\n return replaceAssistantContent(message, stripProposedPlanBlocksFromContent);\n}\n\nexport function stripPlanModeCompletionCallsFromMessage<T>(message: T, preservedToolCallId?: string): T {\n return replaceAssistantContent(message, (content) => {\n if (!Array.isArray(content)) return content;\n const nextContent = content.filter((block) => {\n const candidate = block as { type?: string; id?: string; name?: string };\n return !(\n candidate.type === \"toolCall\" &&\n candidate.name === PLAN_MODE_COMPLETE_TOOL_NAME &&\n (!preservedToolCallId || candidate.id !== preservedToolCallId)\n );\n });\n return nextContent.length === content.length ? content : nextContent;\n });\n}\n\nexport function isEmptyAssistantMessage(message: unknown) {\n const candidate = unwrapSessionMessage(message);\n return candidate.role === \"assistant\" && Array.isArray(candidate.content) && candidate.content.length === 0;\n}\n\nfunction replaceAssistantContent<T>(message: T, transform: (content: unknown) => unknown): T {\n const candidate = unwrapSessionMessage(message);\n if (candidate.role !== \"assistant\") return message;\n\n const content = transform(candidate.content);\n if (content === candidate.content) return message;\n\n if (isSessionMessageEntry(message)) {\n return { ...message, message: { ...candidate, content } };\n }\n return { ...candidate, content } as T;\n}\n\nfunction unwrapSessionMessage(message: unknown) {\n const entry = message as { message?: unknown } | null | undefined;\n return (entry?.message ?? message ?? {}) as {\n role?: string;\n customType?: string;\n toolName?: string;\n toolCallId?: string;\n content?: unknown;\n };\n}\n\nfunction isSessionMessageEntry<T>(message: T): message is T & { message: SessionMessage } {\n return typeof message === \"object\" && message !== null && \"message\" in message;\n}\n\nfunction stripProposedPlanBlocksFromContent(content: unknown) {\n if (typeof content === \"string\") return stripProposedPlanBlocks(content);\n if (!Array.isArray(content)) return content;\n\n let changed = false;\n const nextContent = content.map((block) => {\n const textBlock = block as TextBlock;\n if (textBlock.type !== \"text\" || typeof textBlock.text !== \"string\") return block;\n\n const text = stripProposedPlanBlocks(textBlock.text);\n if (text === textBlock.text) return block;\n\n changed = true;\n return { ...textBlock, text };\n });\n return changed ? nextContent : content;\n}\n\nexport function stripProposedPlanBlocks(text: string) {\n return text.replace(PROPOSED_PLAN_BLOCK_PATTERN, \"\");\n}\n\nfunction messageText(message: SessionMessage) {\n return contentText(message.content);\n}\n\nfunction contentText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .map((block) => {\n const textBlock = block as TextBlock;\n return textBlock.type === \"text\" && typeof textBlock.text === \"string\" ? textBlock.text : \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\n\nexport const MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH = 512;\n\nexport interface ImplementationModelOverride {\n provider: string;\n modelId: string;\n}\n\nexport interface AvailableImplementationModel {\n provider: string;\n id: string;\n name?: string;\n}\n\nexport function isPendingImplementationModelIdentifier(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.trim().length > 0 &&\n value.length <= MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH\n );\n}\n\nexport function snapshotAvailableImplementationModels(ctx: ExtensionContext): AvailableImplementationModel[] {\n const getAvailable = ctx.modelRegistry.getAvailable;\n const availableModels = typeof getAvailable === \"function\" ? getAvailable.call(ctx.modelRegistry) : [];\n const scopedModels = ctx.scopedModels ?? [];\n if (scopedModels.length === 0) return availableModels;\n return scopedModels.flatMap((entry) => {\n const availableModel = availableModels.find(\n (model) => model.provider === entry.model.provider && model.id === entry.model.id,\n );\n return availableModel ? [availableModel] : [];\n });\n}\n\nexport function findAvailableImplementationModel(\n models: readonly AvailableImplementationModel[],\n configured: ImplementationModelOverride | undefined,\n): AvailableImplementationModel | undefined {\n if (!configured) return undefined;\n return models.find((model) => model.provider === configured.provider && model.id === configured.modelId);\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { mkdir, open, rename, rm, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, join } from \"node:path\";\nimport { getAgentDir } from \"@earendil-works/pi-coding-agent\";\nimport type { KeyId } from \"@earendil-works/pi-tui\";\nimport { type ImplementationModelOverride, isPendingImplementationModelIdentifier } from \"./implementation-models.js\";\nimport type { SafeSubcommands } from \"./tool-policy.js\";\n\nexport const PLAN_MODE_SETTINGS_FILE = \"pi-plan-mode.json\";\nconst LEGACY_PLAN_MODE_SETTINGS_FILE = \"plan-mode.json\";\nconst MAX_SETTINGS_BYTES = 64 * 1024;\nexport const PLAN_MODE_THINKING_LEVELS = [\n \"inherit\",\n \"off\",\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n] as const;\nexport const IMPLEMENTATION_THINKING_LEVELS = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const IMPLEMENTATION_PLAN_RETENTIONS = [\"clear-on-start\", \"clear-after-first-run\", \"keep\"] as const;\nexport const DEFAULT_PLAN_EXPORT_PATH = \"PLAN.md\";\nconst MODIFIERS = new Set([\"ctrl\", \"shift\", \"alt\", \"super\"]);\nconst BASE_KEYS = new Set([\n ...\"abcdefghijklmnopqrstuvwxyz0123456789\",\n \"`\",\n \"-\",\n \"=\",\n \"[\",\n \"]\",\n \"\\\\\",\n \";\",\n \"'\",\n \",\",\n \".\",\n \"/\",\n \"!\",\n \"@\",\n \"#\",\n \"$\",\n \"%\",\n \"^\",\n \"&\",\n \"*\",\n \"(\",\n \")\",\n \"_\",\n \"+\",\n \"|\",\n \"~\",\n \"{\",\n \"}\",\n \":\",\n \"<\",\n \">\",\n \"?\",\n \"escape\",\n \"esc\",\n \"enter\",\n \"return\",\n \"tab\",\n \"space\",\n \"backspace\",\n \"delete\",\n \"insert\",\n \"clear\",\n \"home\",\n \"end\",\n \"pageup\",\n \"pagedown\",\n \"up\",\n \"down\",\n \"left\",\n \"right\",\n ...Array.from({ length: 12 }, (_unused, index) => `f${index + 1}`),\n]);\nconst MAX_PLAN_EXPORT_PATH_LENGTH = 4096;\n\nexport type PlanModeThinkingLevel = (typeof PLAN_MODE_THINKING_LEVELS)[number];\nexport type ImplementationPlanRetention = (typeof IMPLEMENTATION_PLAN_RETENTIONS)[number];\nexport type PlanModeFixedThinkingLevel = (typeof IMPLEMENTATION_THINKING_LEVELS)[number];\nexport interface PlanModeSettings {\n thinkingLevel: PlanModeThinkingLevel;\n defaultPlanTools?: string[];\n implementationPlanRetention?: ImplementationPlanRetention;\n defaultImplementationModel?: ImplementationModelOverride;\n defaultImplementationThinkingLevel?: PlanModeFixedThinkingLevel;\n defaultPlanExportPath?: string;\n safeSubcommands?: SafeSubcommands;\n toggleShortcut?: KeyId;\n}\nexport interface PlanModeSettingsPatch {\n thinkingLevel?: PlanModeThinkingLevel;\n defaultPlanTools?: readonly string[] | null;\n implementationPlanRetention?: ImplementationPlanRetention;\n defaultImplementationModel?: ImplementationModelOverride | null;\n defaultImplementationThinkingLevel?: PlanModeFixedThinkingLevel | null;\n defaultPlanExportPath?: string | null;\n toggleShortcut?: KeyId | null;\n}\nexport interface UpdatePlanModeSettingsOptions {\n settingsPath?: string;\n legacySettingsPath?: string;\n signal?: AbortSignal;\n beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;\n}\nexport type PlanModeSettingsLoadResult =\n | { kind: \"missing\"; notice?: string }\n | { kind: \"invalid\"; reason: string; notice?: string }\n | { kind: \"loaded\"; settings: PlanModeSettings; notice?: string };\n\ntype SettingsDocument = Record<string, unknown>;\ntype SettingsSnapshot = {\n result: PlanModeSettingsLoadResult;\n document?: SettingsDocument;\n};\n\nconst mutationQueues = new Map<string, Promise<void>>();\n\nexport function planModeSettingsPath() {\n return join(getAgentDir(), PLAN_MODE_SETTINGS_FILE);\n}\n\nfunction legacyPlanModeSettingsPath() {\n return join(getAgentDir(), LEGACY_PLAN_MODE_SETTINGS_FILE);\n}\n\nexport function normalizePlanModeSettings(value: unknown): PlanModeSettings | undefined {\n if (!isSettingsDocument(value)) return undefined;\n const thinkingLevel = Object.hasOwn(value, \"thinkingLevel\") ? Reflect.get(value, \"thinkingLevel\") : \"inherit\";\n if (!PLAN_MODE_THINKING_LEVELS.includes(thinkingLevel as PlanModeThinkingLevel)) {\n return undefined;\n }\n const settings: PlanModeSettings = {\n thinkingLevel: thinkingLevel as PlanModeThinkingLevel,\n };\n if (Object.hasOwn(value, \"defaultPlanTools\")) {\n const defaultPlanTools = normalizeToolNames(Reflect.get(value, \"defaultPlanTools\"));\n if (!defaultPlanTools) return undefined;\n settings.defaultPlanTools = defaultPlanTools;\n }\n if (Object.hasOwn(value, \"implementationPlanRetention\")) {\n const implementationPlanRetention = Reflect.get(value, \"implementationPlanRetention\");\n if (!IMPLEMENTATION_PLAN_RETENTIONS.includes(implementationPlanRetention as ImplementationPlanRetention)) {\n return undefined;\n }\n settings.implementationPlanRetention = implementationPlanRetention as ImplementationPlanRetention;\n }\n if (Object.hasOwn(value, \"defaultImplementationModel\")) {\n const defaultImplementationModel = normalizeImplementationModel(Reflect.get(value, \"defaultImplementationModel\"));\n if (!defaultImplementationModel) return undefined;\n settings.defaultImplementationModel = defaultImplementationModel;\n }\n if (Object.hasOwn(value, \"defaultImplementationThinkingLevel\")) {\n const defaultImplementationThinkingLevel = Reflect.get(value, \"defaultImplementationThinkingLevel\");\n if (!IMPLEMENTATION_THINKING_LEVELS.includes(defaultImplementationThinkingLevel as PlanModeFixedThinkingLevel)) {\n return undefined;\n }\n settings.defaultImplementationThinkingLevel = defaultImplementationThinkingLevel as PlanModeFixedThinkingLevel;\n }\n if (Object.hasOwn(value, \"defaultPlanExportPath\")) {\n const defaultPlanExportPath = normalizePlanExportPath(Reflect.get(value, \"defaultPlanExportPath\"));\n if (!defaultPlanExportPath) return undefined;\n settings.defaultPlanExportPath = defaultPlanExportPath;\n }\n if (Object.hasOwn(value, \"toggleShortcut\")) {\n const toggleShortcut = normalizeKeyId(Reflect.get(value, \"toggleShortcut\"));\n if (!toggleShortcut) return undefined;\n settings.toggleShortcut = toggleShortcut;\n }\n if (Object.hasOwn(value, \"safeSubcommands\")) {\n const safeSubcommands = normalizeSafeSubcommands(Reflect.get(value, \"safeSubcommands\"));\n if (!safeSubcommands) return undefined;\n settings.safeSubcommands = safeSubcommands;\n }\n return settings;\n}\n\nfunction normalizeImplementationModel(value: unknown): ImplementationModelOverride | undefined {\n if (!isSettingsDocument(value) || Object.keys(value).some((key) => key !== \"provider\" && key !== \"modelId\")) {\n return undefined;\n }\n const provider = typeof value.provider === \"string\" ? value.provider.trim() : value.provider;\n const modelId = typeof value.modelId === \"string\" ? value.modelId.trim() : value.modelId;\n if (!isPendingImplementationModelIdentifier(provider) || !isPendingImplementationModelIdentifier(modelId)) {\n return undefined;\n }\n return { provider, modelId };\n}\n\nfunction normalizeToolNames(value: unknown) {\n if (\n !Array.isArray(value) ||\n !value.every((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n ) {\n return undefined;\n }\n return Array.from(new Set(value));\n}\n\nfunction normalizePlanExportPath(value: unknown) {\n if (typeof value !== \"string\") return undefined;\n const normalized = value.trim();\n if (\n !normalized ||\n normalized.length > MAX_PLAN_EXPORT_PATH_LENGTH ||\n !/[^@\\s]/u.test(normalized) ||\n [...normalized].some((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n })\n ) {\n return undefined;\n }\n return normalized;\n}\n\nexport function normalizeKeyId(value: unknown): KeyId | undefined {\n if (typeof value !== \"string\") return undefined;\n const normalized = value.trim().toLowerCase();\n const base = [...BASE_KEYS]\n .sort((left, right) => right.length - left.length)\n .find((candidate) => normalized === candidate || normalized.endsWith(`+${candidate}`));\n if (!base) return undefined;\n const prefix = normalized.slice(0, normalized.length - base.length);\n if (!prefix) return base as KeyId;\n if (/^f(?:[1-9]|1[0-2])$/.test(base) || !prefix.endsWith(\"+\")) return undefined;\n const modifiers = prefix.slice(0, -1).split(\"+\");\n if (\n modifiers.length === 0 ||\n modifiers.some((modifier) => !MODIFIERS.has(modifier)) ||\n new Set(modifiers).size !== modifiers.length\n ) {\n return undefined;\n }\n return normalized as KeyId;\n}\n\nfunction normalizeSafeSubcommands(value: unknown): SafeSubcommands | undefined {\n if (!isSettingsDocument(value)) return undefined;\n const entries: [string, string[]][] = [];\n for (const [command, subcommands] of Object.entries(value)) {\n const normalizedCommand = command.trim();\n if (\n !normalizedCommand ||\n !Array.isArray(subcommands) ||\n !subcommands.every((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n ) {\n return undefined;\n }\n const normalizedSubcommands = Array.from(new Set(subcommands.map((subcommand) => subcommand.trim())));\n const existing = entries.find(([existingCommand]) => existingCommand === normalizedCommand);\n if (existing) existing[1] = Array.from(new Set([...existing[1], ...normalizedSubcommands]));\n else entries.push([normalizedCommand, normalizedSubcommands]);\n }\n return Object.fromEntries(entries);\n}\n\nexport async function readPlanModeSettings(settingsPath?: string): Promise<PlanModeSettingsLoadResult> {\n if (settingsPath) {\n await awaitPlanModeSettingsWrites(settingsPath);\n return (await readSettingsSnapshot(settingsPath)).result;\n }\n const canonicalPath = planModeSettingsPath();\n await awaitPlanModeSettingsWrites(canonicalPath);\n const canonical = await readSettingsSnapshot(canonicalPath);\n const legacyPath = legacyPlanModeSettingsPath();\n if (canonical.result.kind !== \"missing\") {\n return (await pathExists(legacyPath))\n ? {\n ...canonical.result,\n notice: `${LEGACY_PLAN_MODE_SETTINGS_FILE} ignored because ${PLAN_MODE_SETTINGS_FILE} takes precedence.`,\n }\n : canonical.result;\n }\n\n const legacy = await readSettingsSnapshot(legacyPath);\n const raced = await readSettingsSnapshot(canonicalPath);\n if (raced.result.kind !== \"missing\") return raced.result;\n return legacy.result.kind === \"loaded\"\n ? {\n ...legacy.result,\n notice: `Using legacy ${LEGACY_PLAN_MODE_SETTINGS_FILE}; rename it to ${PLAN_MODE_SETTINGS_FILE}. The legacy file was not modified.`,\n }\n : legacy.result;\n}\n\nexport function updatePlanModeSettings(\n patch: PlanModeSettingsPatch,\n options: UpdatePlanModeSettingsOptions = {},\n): Promise<PlanModeSettings> {\n const settingsPath = options.settingsPath ?? planModeSettingsPath();\n const legacySettingsPath =\n options.legacySettingsPath ?? (options.settingsPath ? undefined : legacyPlanModeSettingsPath());\n return enqueueMutation(settingsPath, async () => {\n options.signal?.throwIfAborted();\n const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);\n const updated: SettingsDocument = { ...current };\n if (patch.thinkingLevel !== undefined) updated.thinkingLevel = patch.thinkingLevel;\n if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;\n else if (patch.defaultPlanTools !== undefined) {\n updated.defaultPlanTools = [...patch.defaultPlanTools];\n }\n if (patch.implementationPlanRetention !== undefined) {\n updated.implementationPlanRetention = patch.implementationPlanRetention;\n }\n if (patch.defaultImplementationModel === null) delete updated.defaultImplementationModel;\n else if (patch.defaultImplementationModel !== undefined) {\n const model = normalizeImplementationModel(patch.defaultImplementationModel);\n if (!model) throw invalidSettingsError(settingsPath, \"invalid implementation model\");\n updated.defaultImplementationModel = model;\n }\n if (patch.defaultImplementationThinkingLevel === null) {\n delete updated.defaultImplementationThinkingLevel;\n } else if (patch.defaultImplementationThinkingLevel !== undefined) {\n updated.defaultImplementationThinkingLevel = patch.defaultImplementationThinkingLevel;\n }\n if (patch.defaultPlanExportPath === null) delete updated.defaultPlanExportPath;\n else if (patch.defaultPlanExportPath !== undefined) {\n updated.defaultPlanExportPath = patch.defaultPlanExportPath;\n }\n if (patch.toggleShortcut === null) delete updated.toggleShortcut;\n else if (patch.toggleShortcut !== undefined) {\n updated.toggleShortcut = patch.toggleShortcut;\n }\n const settings = normalizePlanModeSettings(updated);\n if (!settings) throw invalidSettingsError(settingsPath, \"invalid settings shape\");\n await publishSettings(settingsPath, updated, options.signal, options.beforeRename);\n return settings;\n });\n}\n\nexport async function awaitPlanModeSettingsWrites(settingsPath = planModeSettingsPath()): Promise<void> {\n await mutationQueues.get(settingsPath);\n}\n\nfunction enqueueMutation<T>(settingsPath: string, mutation: () => Promise<T>): Promise<T> {\n const previous = mutationQueues.get(settingsPath) ?? Promise.resolve();\n const result = previous.then(mutation, mutation);\n const settled = result.then(\n () => undefined,\n () => undefined,\n );\n mutationQueues.set(settingsPath, settled);\n void settled.finally(() => {\n if (mutationQueues.get(settingsPath) === settled) mutationQueues.delete(settingsPath);\n });\n return result;\n}\n\nasync function readSettingsDocumentForUpdate(\n settingsPath: string,\n legacySettingsPath: string | undefined,\n): Promise<SettingsDocument> {\n const canonical = await readSettingsSnapshot(settingsPath);\n if (canonical.result.kind === \"loaded\") return canonical.document ?? {};\n if (canonical.result.kind === \"invalid\") {\n throw invalidSettingsError(settingsPath, canonical.result.reason);\n }\n if (!legacySettingsPath) return {};\n\n const legacy = await readSettingsSnapshot(legacySettingsPath);\n const raced = await readSettingsSnapshot(settingsPath);\n if (raced.result.kind === \"loaded\") return raced.document ?? {};\n if (raced.result.kind === \"invalid\") {\n throw invalidSettingsError(settingsPath, raced.result.reason);\n }\n if (legacy.result.kind === \"invalid\") {\n throw invalidSettingsError(legacySettingsPath, legacy.result.reason);\n }\n return legacy.document ?? {};\n}\n\nasync function readSettingsSnapshot(settingsPath: string): Promise<SettingsSnapshot> {\n let contents: string;\n try {\n contents = await readSettingsContents(settingsPath);\n } catch (error: unknown) {\n if (isNodeError(error) && error.code === \"ENOENT\") return { result: { kind: \"missing\" } };\n return { result: { kind: \"invalid\", reason: safeReadError(error) } };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(contents) as unknown;\n } catch {\n return { result: { kind: \"invalid\", reason: \"invalid JSON\" } };\n }\n const settings = normalizePlanModeSettings(parsed);\n if (!settings || !isSettingsDocument(parsed)) {\n return { result: { kind: \"invalid\", reason: \"invalid settings shape\" } };\n }\n return { document: parsed, result: { kind: \"loaded\", settings } };\n}\n\nasync function readSettingsContents(settingsPath: string): Promise<string> {\n const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0);\n const handle = await open(settingsPath, flags);\n try {\n const stats = await handle.stat();\n if (!stats.isFile()) throw new Error(\"settings path is not a regular file\");\n if (stats.size > MAX_SETTINGS_BYTES) {\n throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);\n }\n const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);\n let offset = 0;\n while (offset < buffer.byteLength) {\n const { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n if (offset > MAX_SETTINGS_BYTES) {\n throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);\n }\n try {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, offset));\n } catch {\n throw new Error(\"settings file is not valid UTF-8\");\n }\n } finally {\n await handle.close();\n }\n}\n\nasync function publishSettings(\n settingsPath: string,\n document: SettingsDocument,\n signal?: AbortSignal,\n beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>,\n): Promise<void> {\n signal?.throwIfAborted();\n const contents = `${JSON.stringify(document, null, 2)}\\n`;\n if (Buffer.byteLength(contents, \"utf8\") > MAX_SETTINGS_BYTES) {\n throw new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);\n }\n const directory = dirname(settingsPath);\n await mkdir(directory, { recursive: true });\n signal?.throwIfAborted();\n const temporaryPath = join(directory, `.${basename(settingsPath)}.${process.pid}.${randomUUID()}.tmp`);\n try {\n await writeFile(temporaryPath, contents, {\n encoding: \"utf8\",\n flag: \"wx\",\n mode: 0o600,\n signal,\n });\n await beforeRename?.(temporaryPath, settingsPath);\n signal?.throwIfAborted();\n await rename(temporaryPath, settingsPath);\n } finally {\n await rm(temporaryPath, { force: true }).catch(() => undefined);\n }\n}\n\nfunction isSettingsDocument(value: unknown): value is SettingsDocument {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nasync function pathExists(path: string) {\n try {\n const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n await handle.close();\n return true;\n } catch (error: unknown) {\n return !(isNodeError(error) && error.code === \"ENOENT\");\n }\n}\n\nfunction invalidSettingsError(settingsPath: string, reason: string) {\n return new Error(`pi-plan-mode settings at ${settingsPath} are invalid: ${reason}`);\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n\nfunction safeReadError(error: unknown) {\n if (isNodeError(error) && error.code === \"ELOOP\") return \"settings path is not a regular file\";\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function configuredThinkingLevel(settings: PlanModeSettings): PlanModeFixedThinkingLevel | undefined {\n return settings.thinkingLevel === \"inherit\" ? undefined : settings.thinkingLevel;\n}\n\nexport function configuredImplementationPlanRetention(settings: PlanModeSettings): ImplementationPlanRetention {\n return settings.implementationPlanRetention ?? \"clear-on-start\";\n}\n\nexport function configuredImplementationModel(settings: PlanModeSettings): ImplementationModelOverride | undefined {\n return settings.defaultImplementationModel;\n}\n\nexport function configuredImplementationThinkingLevel(\n settings: PlanModeSettings,\n): PlanModeFixedThinkingLevel | undefined {\n return settings.defaultImplementationThinkingLevel;\n}\n\nexport function configuredPlanExportPath(settings: PlanModeSettings) {\n return settings.defaultPlanExportPath ?? DEFAULT_PLAN_EXPORT_PATH;\n}\n\nexport function configuredPlanModeToggleShortcut(settings: PlanModeSettings): KeyId | undefined {\n return settings.toggleShortcut;\n}\n", "import {\n findHistoryImplementationArtifact,\n injectActiveImplementationContext,\n isEmptyAssistantMessage,\n messageContainsExactPlanModeImplementationHandoff,\n messageContainsInactivePlanModeArtifact,\n messageContainsLegacyPlanModeContextArtifact,\n messageContainsPlanModeImplementationContextArtifact,\n messageContainsPlanModeImplementationHandoff,\n stripPlanModeCompletionCallsFromMessage,\n stripProposedPlanBlocksFromMessage,\n} from \"./message-transform.js\";\nimport type { ImplementationPlanRetention } from \"./settings.js\";\nimport type { ActiveImplementationPlan, PlanModeState } from \"./state.js\";\n\nexport function retentionLabel(retention: ImplementationPlanRetention) {\n return {\n \"clear-on-start\": \"Off \u2014 conversation history only\",\n \"clear-after-first-run\": \"Through first implementation run\",\n keep: \"Until manually cleared\",\n }[retention];\n}\n\nexport function implementationRetentionPreview(retention: ImplementationPlanRetention) {\n return {\n \"clear-on-start\": \"Plan reinjection: Off; use conversation history only.\",\n \"clear-after-first-run\": \"Plan reinjection: Through the first implementation run.\",\n keep: \"Plan reinjection: Until /plan exit.\",\n }[retention];\n}\n\nexport interface ImplementationContextResult {\n messages: unknown[];\n clearActiveImplementationId?: string;\n}\n\nexport interface ImplementationRetentionCoordinator {\n restore(activeImplementation: ActiveImplementationPlan | undefined): void;\n transformContext(messages: unknown[], state: PlanModeState): ImplementationContextResult;\n implementationSettled(activeImplementation: ActiveImplementationPlan | undefined): string | undefined;\n reset(): void;\n}\n\nexport function createImplementationRetentionCoordinator(): ImplementationRetentionCoordinator {\n let implementationWithDeliveredContext: string | undefined;\n let restoredImplementationAwaitingContext: string | undefined;\n\n return {\n restore(activeImplementation) {\n restoredImplementationAwaitingContext =\n activeImplementation && activeImplementation.retention !== \"keep\" ? activeImplementation.id : undefined;\n },\n transformContext(messages, state) {\n const messagesWithoutLegacyContext = messages.filter(\n (message) => !messageContainsLegacyPlanModeContextArtifact(message),\n );\n if (state.enabled) {\n return {\n messages: messagesWithoutLegacyContext.filter(\n (message) =>\n !messageContainsPlanModeImplementationContextArtifact(message) &&\n !messageContainsPlanModeImplementationHandoff(message),\n ),\n };\n }\n\n const activeImplementation = state.activeImplementation;\n const inactiveMessages = activeImplementation\n ? messagesWithoutLegacyContext\n : messagesWithoutLegacyContext.filter(\n (message) =>\n !messageContainsPlanModeImplementationContextArtifact(message) &&\n !messageContainsPlanModeImplementationHandoff(message),\n );\n const historyArtifact = activeImplementation ? undefined : findHistoryImplementationArtifact(inactiveMessages);\n const historyArtifactMessage = historyArtifact ? inactiveMessages[historyArtifact.messageIndex] : undefined;\n const historyToolCallMessage =\n historyArtifact?.toolCallMessageIndex !== undefined\n ? inactiveMessages[historyArtifact.toolCallMessageIndex]\n : undefined;\n const filteredMessages = inactiveMessages\n .filter((message) => message === historyArtifactMessage || !messageContainsInactivePlanModeArtifact(message))\n .map((message) =>\n message === historyArtifactMessage && historyArtifact?.kind === \"legacy\"\n ? message\n : stripProposedPlanBlocksFromMessage(message),\n )\n .map((message) =>\n stripPlanModeCompletionCallsFromMessage(\n message,\n message === historyToolCallMessage ? historyArtifact?.toolCallId : undefined,\n ),\n )\n .filter((message) => !isEmptyAssistantMessage(message));\n if (!activeImplementation) return { messages: filteredMessages };\n\n const contextualMessages = injectActiveImplementationContext(filteredMessages, activeImplementation);\n // A busy /plan implement queues its handoff behind an older run. Do not arm cleanup\n // until that exact handoff reaches context; a restored session has no older run to drain.\n const deliveredCurrentHandoff =\n restoredImplementationAwaitingContext === activeImplementation.id ||\n filteredMessages.some((message) =>\n messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan),\n );\n if (!deliveredCurrentHandoff) return { messages: contextualMessages };\n restoredImplementationAwaitingContext = undefined;\n\n if (activeImplementation.retention === \"clear-after-first-run\") {\n implementationWithDeliveredContext = activeImplementation.id;\n }\n return {\n messages: contextualMessages,\n clearActiveImplementationId:\n activeImplementation.retention === \"clear-on-start\" ? activeImplementation.id : undefined,\n };\n },\n implementationSettled(activeImplementation) {\n if (\n activeImplementation?.retention !== \"clear-after-first-run\" ||\n implementationWithDeliveredContext !== activeImplementation.id\n ) {\n return undefined;\n }\n implementationWithDeliveredContext = undefined;\n return activeImplementation.id;\n },\n reset() {\n implementationWithDeliveredContext = undefined;\n restoredImplementationAwaitingContext = undefined;\n },\n };\n}\n", "import { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport { type ExtensionContext, withFileMutationQueue } from \"@earendil-works/pi-coding-agent\";\nimport { DEFAULT_PLAN_EXPORT_PATH } from \"./settings.js\";\nimport type { PlanModeState } from \"./state.js\";\n\nexport { DEFAULT_PLAN_EXPORT_PATH };\n\nexport interface PlanExportResult {\n path: string;\n}\n\nexport interface PlanExportDestination {\n configuredPath: string;\n resolvedPath: string;\n}\n\nexport interface PlanExportLifecycle {\n signal: AbortSignal;\n isCurrent(): boolean;\n getState?(): PlanModeState;\n finishReady?(): void;\n}\n\nexport async function exportStoredPlan(\n state: PlanModeState,\n requestedPath: string | undefined,\n ctx: ExtensionContext,\n lifecycle?: PlanExportLifecycle,\n defaultPath = DEFAULT_PLAN_EXPORT_PATH,\n) {\n const plan =\n (state.enabled ? state.latestPlan : undefined)?.trim() ??\n state.savedPlan?.plan.trim() ??\n state.activeImplementation?.plan.trim();\n if (!plan) {\n const error = new Error(\"No completed plan is available to export. Use /plan finalize when planning is complete.\");\n if (!ctx.hasUI) throw error;\n ctx.ui.notify(error.message, \"warning\");\n return false;\n }\n\n const isCurrent = () =>\n !lifecycle || (lifecycle.isCurrent() && (!lifecycle.getState || lifecycle.getState() === state));\n let result: PlanExportResult;\n try {\n result = await exportPlanToFile(plan, requestedPath, ctx.cwd, lifecycle?.signal, isCurrent, defaultPath);\n } catch (error: unknown) {\n if (lifecycle?.signal.aborted || !isCurrent()) return false;\n if (!ctx.hasUI) throw error;\n const detail = error instanceof Error ? error.message : String(error);\n ctx.ui.notify(safeNotification(`Unable to export plan: ${detail}`), \"error\");\n return false;\n }\n\n if (!isCurrent()) return false;\n const finishedReady = state.enabled && Boolean(state.latestPlan?.trim()) && lifecycle?.finishReady !== undefined;\n if (finishedReady) lifecycle.finishReady?.();\n const detail = finishedReady ? \" Plan mode disabled.\" : \"\";\n ctx.ui.notify(safeNotification(`Plan exported to ${result.path}.${detail}`), \"info\");\n return true;\n}\n\nexport async function exportPlanToFile(\n plan: string,\n requestedPath: string | undefined,\n cwd: string,\n signal?: AbortSignal,\n isCurrent: () => boolean = () => true,\n defaultPath = DEFAULT_PLAN_EXPORT_PATH,\n): Promise<PlanExportResult> {\n const path = resolvePlanExportPath(requestedPath, cwd, defaultPath);\n await withFileMutationQueue(path, async () => {\n throwIfCancelled(signal, isCurrent);\n await mkdir(dirname(path), { recursive: true });\n throwIfCancelled(signal, isCurrent);\n try {\n await writeFile(path, `${plan}\\n`, { encoding: \"utf8\", flag: \"wx\" });\n } catch (error: unknown) {\n if (isNodeError(error) && error.code === \"EEXIST\") {\n throw new Error(`Plan export target already exists: ${path}. Choose another path or remove it first.`);\n }\n throw error;\n }\n });\n return { path };\n}\n\nexport function planExportDestination(defaultPath: string, cwd: string): PlanExportDestination {\n return {\n configuredPath: safeNotification(defaultPath),\n resolvedPath: safeNotification(resolvePlanExportPath(undefined, cwd, defaultPath)),\n };\n}\n\nexport function resolvePlanExportPath(\n requestedPath: string | undefined,\n cwd: string,\n defaultPath = DEFAULT_PLAN_EXPORT_PATH,\n) {\n const rawPath = requestedPath?.trim() || defaultPath;\n const normalizedPath = rawPath.startsWith(\"@\") ? rawPath.slice(1) : rawPath;\n if (!normalizedPath.trim()) throw new Error(\"Plan export path must not be empty.\");\n if (normalizedPath.includes(\"\\0\")) {\n throw new Error(\"Plan export path must not contain NUL bytes.\");\n }\n return resolve(cwd, normalizedPath);\n}\n\nfunction safeNotification(value: string) {\n let sanitized = \"\";\n for (const character of stripVTControlCharacters(value)) {\n const codePoint = character.codePointAt(0);\n sanitized +=\n codePoint !== undefined && codePoint > 0x1f && !(codePoint >= 0x7f && codePoint <= 0x9f) ? character : \" \";\n }\n return sanitized;\n}\n\nfunction throwIfCancelled(signal: AbortSignal | undefined, isCurrent: () => boolean) {\n if (!signal?.aborted && isCurrent()) return;\n throw signal?.reason instanceof Error ? signal.reason : new DOMException(\"Plan export cancelled\", \"AbortError\");\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport type { QuestionnaireAnswer, QuestionnaireQuestion, RunQuestionnaireResult } from \"@narumitw/pi-tui-kit\";\n\nexport const PLAN_MODE_QUESTION_TOOL_NAME = \"plan_mode_question\";\nexport const MAX_PLAN_MODE_RESPONSE_LENGTH = 4_000;\n\nexport type PlanModeQuestionOption = {\n label: string;\n description?: string;\n};\n\nexport type PlanModeQuestion = {\n id: string;\n header: string;\n question: string;\n options: PlanModeQuestionOption[];\n};\n\nexport type PlanModeQuestionAnswer = {\n id: string;\n header: string;\n question: string;\n answer: string;\n wasCustom: boolean;\n optionIndex?: number;\n note?: string;\n};\n\ntype PlanModeQuestionReason = \"cancelled\" | \"ui_unavailable\" | \"plan_mode_inactive\" | \"invalid_input\";\n\ntype PlanModeQuestionDetails = {\n cancelled: boolean;\n reason?: PlanModeQuestionReason;\n questions: PlanModeQuestion[];\n answers?: PlanModeQuestionAnswer[];\n};\n\nexport const PLAN_MODE_QUESTION_PARAMS = {\n type: \"object\",\n additionalProperties: false,\n required: [\"questions\"],\n properties: {\n questions: {\n type: \"array\",\n minItems: 1,\n maxItems: 3,\n description: \"Questions to show the user. Prefer 1 and do not exceed 3.\",\n items: {\n type: \"object\",\n additionalProperties: false,\n required: [\"id\", \"header\", \"question\", \"options\"],\n properties: {\n id: {\n type: \"string\",\n description: \"Stable identifier for mapping answers (snake_case).\",\n },\n header: {\n type: \"string\",\n description: \"Short header label shown in the UI (12 or fewer chars).\",\n },\n question: { type: \"string\", description: \"Single-sentence prompt shown to the user.\" },\n options: {\n type: \"array\",\n minItems: 2,\n maxItems: 4,\n description:\n \"Provide 2-4 mutually exclusive choices. Put the recommended option first when there is a clear default.\",\n items: {\n type: \"object\",\n additionalProperties: false,\n required: [\"label\", \"description\"],\n properties: {\n label: { type: \"string\", description: \"User-facing label (1-5 words).\" },\n description: {\n type: \"string\",\n description: \"One short sentence explaining impact/tradeoff if selected.\",\n },\n },\n },\n },\n },\n },\n },\n },\n} as const;\n\ntype NormalizePlanModeQuestionParamsResult = { ok: true; questions: PlanModeQuestion[] } | { ok: false; error: string };\n\nexport function normalizePlanModeQuestionParams(input: unknown): NormalizePlanModeQuestionParamsResult {\n if (!isRecord(input) || !Array.isArray(input.questions)) {\n return { ok: false, error: \"questions must be an array\" };\n }\n if (input.questions.length < 1 || input.questions.length > 3) {\n return { ok: false, error: \"questions must contain 1-3 items\" };\n }\n\n const questions: PlanModeQuestion[] = [];\n for (const [questionIndex, rawQuestion] of input.questions.entries()) {\n if (!isRecord(rawQuestion)) {\n return { ok: false, error: `question ${questionIndex + 1} must be an object` };\n }\n const id = stringField(rawQuestion.id);\n const header = stringField(rawQuestion.header);\n const question = stringField(rawQuestion.question);\n if (!id || !header || !question) {\n return {\n ok: false,\n error: `question ${questionIndex + 1} requires non-empty id, header, and question`,\n };\n }\n if (!Array.isArray(rawQuestion.options)) {\n return { ok: false, error: `question ${questionIndex + 1} options must be an array` };\n }\n if (rawQuestion.options.length < 2 || rawQuestion.options.length > 4) {\n return { ok: false, error: `question ${questionIndex + 1} options must contain 2-4 items` };\n }\n const options: PlanModeQuestionOption[] = [];\n for (const [optionIndex, rawOption] of rawQuestion.options.entries()) {\n if (!isRecord(rawOption)) {\n return {\n ok: false,\n error: `question ${questionIndex + 1} option ${optionIndex + 1} must be an object`,\n };\n }\n const label = stringField(rawOption.label);\n if (!label) {\n return {\n ok: false,\n error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a label`,\n };\n }\n const description = stringField(rawOption.description);\n if (!description) {\n return {\n ok: false,\n error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a description`,\n };\n }\n options.push({ label, description });\n }\n questions.push({ id, header, question, options });\n }\n return { ok: true, questions };\n}\n\nexport async function answerPlanModeQuestions(\n questions: PlanModeQuestion[],\n ctx: ExtensionContext,\n lifecycle: { isCurrent(): boolean; isEnabled(): boolean },\n) {\n const answers = await askPlanModeQuestions(questions, ctx, () => lifecycle.isCurrent() && lifecycle.isEnabled());\n if (!lifecycle.isCurrent()) {\n return planModeQuestionCancelled(\n questions,\n \"cancelled\",\n \"Plan-mode question cancelled because the session changed.\",\n );\n }\n if (!lifecycle.isEnabled()) {\n return planModeQuestionCancelled(\n questions,\n \"plan_mode_inactive\",\n \"Plan-mode question cancelled because Plan mode is no longer active.\",\n );\n }\n if (!answers) {\n return planModeQuestionCancelled(questions, \"cancelled\", \"User cancelled the Plan-mode question prompt.\");\n }\n return planModeQuestionAnswered(questions, answers);\n}\n\nexport async function askPlanModeQuestions(\n questions: PlanModeQuestion[],\n ctx: ExtensionContext,\n shouldContinue: () => boolean = () => true,\n): Promise<PlanModeQuestionAnswer[] | undefined> {\n const { runQuestionnaire, sanitizeTerminalText } = await import(\"@narumitw/pi-tui-kit\");\n if (!shouldContinue()) return undefined;\n const runnerQuestions: QuestionnaireQuestion<string>[] = questions.map((question, index) => ({\n id: String(index),\n header: displayText(question.header, `Question ${index + 1}`, sanitizeTerminalText),\n prompt: displayText(question.question, `Question ${index + 1}`, sanitizeTerminalText),\n options: question.options.map((option, optionIndex) => ({\n ...option,\n label: displayText(option.label, `Option ${optionIndex + 1}`, sanitizeTerminalText),\n })),\n }));\n const result = await runQuestionnaire(ctx, {\n questions: runnerQuestions,\n allowNotes: true,\n maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,\n signal: ctx.signal,\n isCurrent: shouldContinue,\n });\n if (!shouldContinue()) return undefined;\n return mapQuestionnaireResult(questions, result);\n}\n\nfunction mapQuestionnaireResult(\n questions: PlanModeQuestion[],\n result: RunQuestionnaireResult<string>,\n): PlanModeQuestionAnswer[] | undefined {\n if (result.kind !== \"submitted\") return undefined;\n if (result.answers.length !== questions.length) {\n throw new Error(\"Questionnaire returned an incomplete answer set\");\n }\n\n const answers = new Map<number, QuestionnaireAnswer<string>>();\n for (const answer of result.answers) {\n const index = Number(answer.questionId);\n if (!Number.isSafeInteger(index) || String(index) !== answer.questionId || !questions[index]) {\n throw new Error(\"Questionnaire returned an answer for an unknown question\");\n }\n if (answers.has(index)) throw new Error(\"Questionnaire returned duplicate answers\");\n if (answer.wasCustom) {\n if (answer.optionIndex !== undefined) {\n throw new Error(\"Questionnaire returned a custom answer with an option index\");\n }\n if (!answer.answer.trim()) return undefined;\n } else if (answer.optionIndex === undefined || !questions[index]?.options[answer.optionIndex - 1]) {\n throw new Error(\"Questionnaire returned an invalid selected option\");\n }\n answers.set(index, answer);\n }\n\n return questions.map((question, index) => {\n const answer = answers.get(index);\n if (!answer) throw new Error(\"Questionnaire returned an incomplete answer set\");\n const answerText = answer.wasCustom\n ? answer.answer\n : (question.options[(answer.optionIndex ?? 0) - 1]?.label ?? answer.answer);\n return answerFor(question, answerText, {\n wasCustom: answer.wasCustom,\n optionIndex: answer.optionIndex,\n note: answer.note,\n });\n });\n}\n\nfunction displayText(value: string, fallback: string, sanitize: (value: string) => string): string {\n const sanitized = sanitize(value);\n return sanitized.trim() ? sanitized : fallback;\n}\n\nfunction answerFor(\n question: PlanModeQuestion,\n answer: string,\n options: { wasCustom: boolean; optionIndex?: number; note?: string },\n): PlanModeQuestionAnswer {\n const result: PlanModeQuestionAnswer = {\n id: question.id,\n header: question.header,\n question: question.question,\n answer,\n wasCustom: options.wasCustom,\n };\n if (options.optionIndex !== undefined) result.optionIndex = options.optionIndex;\n if (options.note !== undefined) result.note = options.note;\n return result;\n}\n\nexport function planModeQuestionAnswered(questions: PlanModeQuestion[], answers: PlanModeQuestionAnswer[]) {\n return {\n content: [{ type: \"text\" as const, text: formatPlanModeQuestionPayload({ cancelled: false, answers }) }],\n details: { cancelled: false, questions, answers } satisfies PlanModeQuestionDetails,\n };\n}\n\nexport function planModeQuestionCancelled(\n questions: PlanModeQuestion[],\n reason: PlanModeQuestionReason,\n message: string,\n) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: formatPlanModeQuestionPayload({ cancelled: true, reason, message }),\n },\n ],\n details: { cancelled: true, reason, questions } satisfies PlanModeQuestionDetails,\n };\n}\n\nfunction formatPlanModeQuestionPayload(payload: {\n cancelled: boolean;\n reason?: PlanModeQuestionReason;\n message?: string;\n answers?: PlanModeQuestionAnswer[];\n}) {\n return JSON.stringify(payload, null, 2);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction stringField(value: unknown) {\n return typeof value === \"string\" ? value.trim() : undefined;\n}\n", "import type { ToolInfo } from \"@earendil-works/pi-coding-agent\";\n\nexport type PlanModeToolAvailability = \"available\" | \"inactive\" | \"hidden\" | \"model-only\" | \"unsupported\";\n\n/** Pi's active set is model declaration, not the complete callable registry. */\nexport function planModeToolAvailability(\n tool: ToolInfo,\n activeNames: ReadonlySet<string>,\n route: \"selection\" | \"model\" | \"nested\" = \"selection\",\n): PlanModeToolAvailability {\n switch (tool.exposure) {\n case \"hidden\":\n return \"hidden\";\n case \"model-only\":\n if (route === \"nested\") return \"model-only\";\n return activeNames.has(tool.name) ? \"available\" : \"inactive\";\n case \"codemode\":\n case \"deferred\":\n if (route !== \"model\") return \"available\";\n return activeNames.has(tool.name) ? \"available\" : \"inactive\";\n case undefined: // Older Pi versions exposed only directly active tools.\n case \"direct\":\n return activeNames.has(tool.name) ? \"available\" : \"inactive\";\n default:\n return \"unsupported\";\n }\n}\n", "import { isAbsolute, normalize } from \"node:path\";\nimport type { ToolInfo } from \"@earendil-works/pi-coding-agent\";\n\nexport const BUILTIN_SAFE_GIT_SUBCOMMANDS = [\n \"status\",\n \"log\",\n \"diff\",\n \"show\",\n \"branch\",\n \"remote\",\n \"ls-files\",\n \"grep\",\n] as const;\nexport const CONFIGURABLE_SAFE_GIT_SUBCOMMANDS = [\n \"rev-parse\",\n \"blame\",\n \"describe\",\n \"merge-base\",\n \"ls-tree\",\n \"cat-file\",\n] as const;\nexport const SAFE_GIT_SUBCOMMANDS = [...BUILTIN_SAFE_GIT_SUBCOMMANDS, ...CONFIGURABLE_SAFE_GIT_SUBCOMMANDS] as const;\nexport const SAFE_GH_SUBCOMMAND_PATHS = [\"pr view\", \"pr list\", \"issue view\", \"issue list\"] as const;\n\nexport type BuiltinSafeGitSubcommand = (typeof BUILTIN_SAFE_GIT_SUBCOMMANDS)[number];\nexport type ConfigurableSafeGitSubcommand = (typeof CONFIGURABLE_SAFE_GIT_SUBCOMMANDS)[number];\nexport type SafeGitSubcommand = (typeof SAFE_GIT_SUBCOMMANDS)[number];\nexport type SafeGhSubcommandPath = (typeof SAFE_GH_SUBCOMMAND_PATHS)[number];\nexport interface SafeSubcommands {\n [command: string]: string[] | undefined;\n}\n\nexport const SAFE_BUILTIN_PLAN_TOOLS = new Set([\"read\", \"bash\", \"powershell\", \"grep\", \"find\", \"ls\"]);\nexport type PlanModeToolPolicy = \"read-only\" | \"limited\" | \"user-opt-in\" | \"blocked\";\n\nconst BLOCKED_BUILTIN_TOOLS = new Set([\"edit\", \"write\"]);\nconst MUTATING_COMMANDS = new Set([\n \"rm\",\n \"rmdir\",\n \"mv\",\n \"cp\",\n \"mkdir\",\n \"touch\",\n \"chmod\",\n \"chown\",\n \"chgrp\",\n \"ln\",\n \"tee\",\n \"truncate\",\n \"dd\",\n \"sudo\",\n \"su\",\n \"kill\",\n \"pkill\",\n \"killall\",\n \"reboot\",\n \"shutdown\",\n \"vim\",\n \"vi\",\n \"nano\",\n \"emacs\",\n \"code\",\n \"subl\",\n]);\nconst READ_ONLY_POWERSHELL_COMMANDS = new Set([\n \"format-list\",\n \"format-table\",\n \"get-childitem\",\n \"get-content\",\n \"get-item\",\n \"get-location\",\n \"measure-object\",\n \"out-string\",\n \"resolve-path\",\n \"select-string\",\n \"sort-object\",\n \"test-path\",\n \"write-output\",\n]);\nconst READ_ONLY_COMMANDS = new Set([\n \"cat\",\n \"head\",\n \"tail\",\n \"grep\",\n \"find\",\n \"ls\",\n \"pwd\",\n \"echo\",\n \"printf\",\n \"wc\",\n \"sort\",\n \"uniq\",\n \"diff\",\n \"file\",\n \"stat\",\n \"du\",\n \"df\",\n \"tree\",\n \"which\",\n \"whereis\",\n \"type\",\n \"printenv\",\n \"uname\",\n \"whoami\",\n \"id\",\n \"date\",\n \"uptime\",\n \"ps\",\n \"jq\",\n \"rg\",\n \"fd\",\n \"bat\",\n \"eza\",\n]);\n\n// `-i` edits in place for sed. For these inspection commands it is case-insensitive\n// search or inode output, which is how plan mode reads markdown and other text.\nconst INSPECTION_CASE_FLAG_COMMANDS = new Set([\"rg\", \"grep\", \"git\", \"diff\", \"fd\", \"ls\", \"sort\", \"find\", \"bat\", \"eza\"]);\n\nexport function isBuiltinTool(tool: ToolInfo) {\n const source = tool.sourceInfo;\n if (source?.source !== \"builtin\") return false;\n // Core tools own builtin:<name>; built-in extensions may own many tools or\n // expose model-only orchestration. Missing paths preserve legacy core policy.\n return !source.path || (source.path === `builtin:${tool.name}` && tool.exposure !== \"model-only\");\n}\n\nexport function classifyPlanModeTool(tool: ToolInfo): PlanModeToolPolicy {\n if (!tool.sourceInfo?.source) return \"blocked\";\n if (!isBuiltinTool(tool)) return \"user-opt-in\";\n if (BLOCKED_BUILTIN_TOOLS.has(tool.name)) return \"blocked\";\n if (tool.name === \"bash\" || tool.name === \"powershell\") return \"limited\";\n return SAFE_BUILTIN_PLAN_TOOLS.has(tool.name) ? \"read-only\" : \"blocked\";\n}\n\nexport function canSelectToolInPlanMode(tool: ToolInfo) {\n return classifyPlanModeTool(tool) !== \"blocked\";\n}\n\nexport function readCommand(input: unknown) {\n const command = input as { command?: unknown } | undefined;\n return typeof command?.command === \"string\" ? command.command : \"\";\n}\n\nexport function findBlockedCommandSegment(\n command: string,\n safeSubcommands: SafeSubcommands = {},\n workingDirectory?: string,\n platform: NodeJS.Platform = process.platform,\n): string | undefined {\n const segments = splitShellSegments(command);\n if (!segments || segments.length === 0) return command.trim() || \"(empty command)\";\n return segments.find((segment) => !isSafeSegment(segment, safeSubcommands, workingDirectory, platform));\n}\n\nexport function isSafeCommand(\n command: string,\n safeSubcommands: SafeSubcommands = {},\n workingDirectory?: string,\n platform: NodeJS.Platform = process.platform,\n) {\n return findBlockedCommandSegment(command, safeSubcommands, workingDirectory, platform) === undefined;\n}\n\nexport function findBlockedPowerShellCommandSegment(\n command: string,\n safeSubcommands: SafeSubcommands = {},\n workingDirectory?: string,\n): string | undefined {\n const segments = splitPowerShellSegments(command);\n if (!segments || segments.length === 0) return command.trim() || \"(empty command)\";\n return segments.find((segment) => !isSafePowerShellSegment(segment, safeSubcommands, workingDirectory));\n}\n\nexport function isSafePowerShellCommand(\n command: string,\n safeSubcommands: SafeSubcommands = {},\n workingDirectory?: string,\n) {\n return findBlockedPowerShellCommandSegment(command, safeSubcommands, workingDirectory) === undefined;\n}\n\nfunction matchesConfiguredSafeSubcommand(command: string, safeSubcommands: SafeSubcommands) {\n const candidate = command.trimStart();\n return Object.entries(safeSubcommands).some(([configuredCommand, subcommands]) =>\n subcommands?.some((subcommand) => {\n const prefix = `${configuredCommand.trim()} ${subcommand.trim()}`;\n if (!configuredCommand.trim() || !subcommand.trim() || !candidate.startsWith(prefix)) {\n return false;\n }\n const boundary = candidate[prefix.length];\n return boundary === undefined || /[\\s;&|<>()]/.test(boundary);\n }),\n );\n}\n\nfunction splitPowerShellSegments(command: string): string[] | undefined {\n const trimmed = command.trim();\n if (!trimmed || /[\\n\\r`\\u2018-\\u201e]/.test(trimmed)) return undefined;\n\n const segments: string[] = [];\n let quote: \"'\" | '\"' | undefined;\n let start = 0;\n for (let index = 0; index < trimmed.length; index += 1) {\n const character = trimmed[index];\n if (quote === \"'\") {\n if (character !== \"'\") continue;\n if (trimmed[index + 1] === \"'\") {\n index += 1;\n continue;\n }\n quote = undefined;\n continue;\n }\n if (quote === '\"') {\n if (character === \"$\" || character === \"`\") return undefined;\n if (character === '\"') quote = undefined;\n continue;\n }\n if (character === \"'\" || character === '\"') {\n quote = character;\n continue;\n }\n if ([\"$\", \"@\", \"#\", \"!\", \"?\", \"{\", \"}\", \"(\", \")\", \"[\", \"]\", \">\", \"<\"].includes(character)) {\n return undefined;\n }\n const next = trimmed[index + 1];\n if (character === \"&\" || (character === \"|\" && next === \"|\")) return undefined;\n const separatorLength = character === \";\" || character === \"|\" ? 1 : 0;\n if (separatorLength === 0) continue;\n const segment = trimmed.slice(start, index).trim();\n if (!segment) return undefined;\n segments.push(segment);\n index += separatorLength - 1;\n start = index + 1;\n }\n if (quote) return undefined;\n const finalSegment = trimmed.slice(start).trim();\n if (!finalSegment) return undefined;\n segments.push(finalSegment);\n return segments;\n}\n\nfunction isSafePowerShellSegment(segment: string, safeSubcommands: SafeSubcommands, workingDirectory?: string) {\n if (matchesConfiguredSafeSubcommand(segment, safeSubcommands)) return true;\n const tokens = powerShellWords(segment);\n if (!tokens || tokens.length === 0 || tokens.includes(\"--%\")) return false;\n const command = tokens[0]?.toLowerCase();\n if (!command) return false;\n const args = tokens.slice(1);\n if (READ_ONLY_POWERSHELL_COMMANDS.has(command)) return true;\n if (command === \"get-process\") return isSafeGetProcessArguments(args);\n if (command === \"get-service\") return isSafeGetServiceArguments(args);\n if (command !== \"git\" && command !== \"gh\") return false;\n return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);\n}\n\nfunction powerShellWords(segment: string): string[] | undefined {\n const words: string[] = [];\n let word = \"\";\n let hasWord = false;\n let quote: \"'\" | '\"' | undefined;\n for (let index = 0; index < segment.length; index += 1) {\n const character = segment[index];\n if (quote === \"'\") {\n if (character !== \"'\") {\n word += character;\n continue;\n }\n if (segment[index + 1] === \"'\") {\n word += \"'\";\n index += 1;\n continue;\n }\n quote = undefined;\n continue;\n }\n if (quote === '\"') {\n if (character === '\"') quote = undefined;\n else word += character;\n continue;\n }\n if (character === \"'\" || character === '\"') {\n quote = character;\n hasWord = true;\n } else if (/\\s/.test(character)) {\n if (hasWord) words.push(word);\n word = \"\";\n hasWord = false;\n } else {\n word += character;\n hasWord = true;\n }\n }\n if (quote) return undefined;\n if (hasWord) words.push(word);\n return words;\n}\n\nfunction splitShellSegments(command: string): string[] | undefined {\n const trimmed = command.trim();\n if (!trimmed || /[\\n\\r`]/.test(trimmed)) return undefined;\n\n const segments: string[] = [];\n let quote: \"'\" | '\"' | undefined;\n let escaped = false;\n let start = 0;\n for (let index = 0; index < trimmed.length; index += 1) {\n const character = trimmed[index];\n if (escaped) {\n escaped = false;\n continue;\n }\n if (character === \"\\\\\" && quote !== \"'\") {\n escaped = true;\n continue;\n }\n if (quote) {\n if (character === quote) quote = undefined;\n continue;\n }\n if (character === \"'\" || character === '\"') {\n quote = character;\n continue;\n }\n if (character === \">\" || character === \"<\" || character === \"(\" || character === \")\") {\n return undefined;\n }\n const next = trimmed[index + 1];\n if (character === \"&\" && next !== \"&\") return undefined;\n const separatorLength =\n character === \";\" || character === \"|\" ? (next === character ? 2 : 1) : character === \"&\" && next === \"&\" ? 2 : 0;\n if (separatorLength === 0) continue;\n const segment = trimmed.slice(start, index).trim();\n if (!segment) return undefined;\n segments.push(segment);\n index += separatorLength - 1;\n start = index + 1;\n }\n if (quote || escaped) return undefined;\n const finalSegment = trimmed.slice(start).trim();\n if (!finalSegment) return undefined;\n segments.push(finalSegment);\n return segments;\n}\n\nfunction isSafeSegment(\n segment: string,\n safeSubcommands: SafeSubcommands,\n workingDirectory: string | undefined,\n platform: NodeJS.Platform,\n) {\n if (matchesConfiguredSafeSubcommand(segment, safeSubcommands)) return true;\n if (hasShellExpansion(segment) || /(^|\\s)[A-Za-z_][A-Za-z0-9_]*=/.test(segment)) {\n return false;\n }\n const tokens = shellWords(segment);\n if (!tokens || tokens.length === 0) return false;\n const command = tokens[0]?.toLowerCase();\n if (!command || MUTATING_COMMANDS.has(command)) return false;\n const args = tokens.slice(1);\n if (!hasSafeArguments(command, args)) return false;\n if (command === \"hostname\") return args.length === 0;\n if (command === \"tasklist\") return platform === \"win32\" && isSafeTasklistArguments(args);\n if (READ_ONLY_COMMANDS.has(command)) return true;\n return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);\n}\n\nfunction hasShellExpansion(segment: string) {\n let quote: \"'\" | '\"' | undefined;\n let escaped = false;\n for (const character of segment) {\n if (escaped) {\n escaped = false;\n continue;\n }\n if (character === \"\\\\\" && quote !== \"'\") {\n escaped = true;\n continue;\n }\n if (quote) {\n if (character === quote) quote = undefined;\n else if (character === \"$\" && quote === '\"') return true;\n continue;\n }\n if (character === \"'\" || character === '\"') {\n quote = character;\n continue;\n }\n if ([\"$\", \"*\", \"?\", \"[\", \"{\"].includes(character)) return true;\n }\n return false;\n}\n\nfunction shellWords(segment: string): string[] | undefined {\n const words: string[] = [];\n let word = \"\";\n let quote: \"'\" | '\"' | undefined;\n let escaped = false;\n for (const character of segment) {\n if (escaped) {\n word += character;\n escaped = false;\n continue;\n }\n if (character === \"\\\\\" && quote !== \"'\") {\n escaped = true;\n continue;\n }\n if (quote) {\n if (character === quote) quote = undefined;\n else word += character;\n continue;\n }\n if (character === \"'\" || character === '\"') quote = character;\n else if (/\\s/.test(character)) {\n if (word) words.push(word);\n word = \"\";\n } else word += character;\n }\n if (quote || escaped) return undefined;\n if (word) words.push(word);\n return words;\n}\n\nfunction hasSafeArguments(command: string, args: string[]) {\n const forbidden = new Set([\"--in-place\", \"--fix\", \"--write\", \"-delete\", \"--delete\"]);\n if (!INSPECTION_CASE_FLAG_COMMANDS.has(command)) forbidden.add(\"-i\");\n if (args.some((argument) => forbidden.has(argument))) return false;\n if (\n command === \"sed\" &&\n args.some(\n (argument) => argument.startsWith(\"--in-place=\") || (/^-[^-]+/.test(argument) && argument.slice(1).includes(\"i\")),\n )\n ) {\n return false;\n }\n if (\n command === \"find\" &&\n args.some((argument) =>\n [\"-exec\", \"-execdir\", \"-ok\", \"-okdir\", \"-fprint\", \"-fprint0\", \"-fprintf\", \"-fls\"].includes(argument),\n )\n ) {\n return false;\n }\n if (command === \"date\" && args.some((argument) => argument === \"-s\" || argument.startsWith(\"--set\"))) {\n return false;\n }\n if (\n (command === \"sort\" || command === \"tree\") &&\n args.some(\n (argument) =>\n argument === \"-o\" ||\n (argument.startsWith(\"-o\") && !argument.startsWith(\"--\")) ||\n argument.startsWith(\"--output\"),\n )\n ) {\n return false;\n }\n if (\n command === \"sort\" &&\n args.some(\n (argument) =>\n argument === \"-T\" ||\n (argument.startsWith(\"-T\") && argument.length > 2) ||\n argument.startsWith(\"--temporary-directory\") ||\n argument.startsWith(\"--compress-program\"),\n )\n ) {\n return false;\n }\n if (command === \"diff\" && args.some((argument) => argument === \"--output\" || argument.startsWith(\"--output=\"))) {\n return false;\n }\n if (command === \"uniq\" && args.filter((argument) => !argument.startsWith(\"-\")).length > 1) {\n return false;\n }\n if (\n command === \"fd\" &&\n args.some((argument) =>\n [\"-x\", \"-X\", \"--exec\", \"--exec-batch\"].some((flag) => argument === flag || argument.startsWith(`${flag}=`)),\n )\n ) {\n return false;\n }\n if (command === \"rg\" && args.some((argument) => argument === \"--pre\" || argument.startsWith(\"--pre=\"))) {\n return false;\n }\n if (command === \"bat\" && args.some((argument) => argument === \"--pager\" || argument.startsWith(\"--pager=\"))) {\n return false;\n }\n return true;\n}\n\ntype ArgumentValidator = (args: string[]) => boolean;\nconst allowReadOnlyArguments: ArgumentValidator = () => true;\nconst BUILTIN_GIT_VALIDATORS: Record<BuiltinSafeGitSubcommand, ArgumentValidator> = {\n status: allowReadOnlyArguments,\n log: allowReadOnlyArguments,\n diff: allowReadOnlyArguments,\n show: allowReadOnlyArguments,\n branch: isSafeGitBranchArguments,\n remote: isSafeGitRemoteArguments,\n \"ls-files\": allowReadOnlyArguments,\n grep: isSafeGitGrepArguments,\n};\nconst CONFIGURABLE_GIT_VALIDATORS: Record<ConfigurableSafeGitSubcommand, ArgumentValidator> = {\n \"rev-parse\": allowReadOnlyArguments,\n blame: allowReadOnlyArguments,\n describe: allowReadOnlyArguments,\n \"merge-base\": allowReadOnlyArguments,\n \"ls-tree\": allowReadOnlyArguments,\n \"cat-file\": isSafeGitCatFileArguments,\n};\nconst GH_VALIDATORS: Record<SafeGhSubcommandPath, ArgumentValidator> = {\n \"pr view\": isSafeGhReadArguments,\n \"pr list\": isSafeGhReadArguments,\n \"issue view\": isSafeGhReadArguments,\n \"issue list\": isSafeGhReadArguments,\n};\n\nfunction isSafeStructuredCommand(\n command: string,\n args: string[],\n safeSubcommands: SafeSubcommands,\n workingDirectory?: string,\n) {\n if (command === \"git\") return isSafeGitCommand(args, safeSubcommands, workingDirectory);\n if (command === \"gh\") return isSafeGhCommand(args, safeSubcommands);\n\n const subcommandIndex = args.findIndex((argument) => !argument.startsWith(\"-\"));\n const subcommand = args[subcommandIndex]?.toLowerCase();\n const subcommandArgs = subcommandIndex >= 0 ? args.slice(subcommandIndex + 1) : [];\n if (command === \"sed\") {\n const script = args.find((argument) => !argument.startsWith(\"-\"));\n return (\n Boolean(script) &&\n (args.includes(\"-n\") || args.some((argument) => /^-[^-]*n[^-]*$/.test(argument))) &&\n /^\\d+(,\\d+)?p$/.test(script ?? \"\")\n );\n }\n if ([\"node\", \"python\", \"python3\", \"tsc\", \"biome\", \"ruff\", \"ty\"].includes(command)) {\n if (args.includes(\"--version\")) return true;\n return (\n command === \"tsc\" &&\n args.includes(\"--noEmit\") &&\n !args.some(\n (argument) =>\n argument === \"--incremental\" ||\n argument.startsWith(\"--incremental=\") ||\n argument === \"--tsBuildInfoFile\" ||\n argument.startsWith(\"--tsBuildInfoFile=\") ||\n argument === \"--generateTrace\" ||\n argument.startsWith(\"--generateTrace=\"),\n )\n );\n }\n if (command === \"npm\") {\n if (subcommand === \"audit\" && subcommandArgs.includes(\"fix\")) return false;\n if ([\"list\", \"ls\", \"view\", \"info\", \"search\", \"outdated\", \"audit\", \"test\"].includes(subcommand ?? \"\")) {\n return true;\n }\n return subcommand === \"run\" && [\"test\", \"check\", \"typecheck\", \"lint\"].includes(args[1] ?? \"\");\n }\n if ([\"cargo\", \"go\", \"pytest\", \"vitest\", \"jest\"].includes(command)) {\n return [\"test\", \"check\"].includes(subcommand ?? \"\") || [\"pytest\", \"vitest\", \"jest\"].includes(command);\n }\n return false;\n}\n\nfunction isSafeTasklistArguments(args: string[]) {\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index]?.toLowerCase();\n if ([\"/v\", \"/nh\", \"/svc\"].includes(argument ?? \"\")) continue;\n if (argument === \"/fo\") {\n const format = args[index + 1]?.toLowerCase();\n if (!format || ![\"table\", \"list\", \"csv\"].includes(format)) return false;\n index += 1;\n continue;\n }\n if (argument === \"/fi\") {\n const filter = args[index + 1];\n if (!filter || filter.startsWith(\"/\")) return false;\n index += 1;\n continue;\n }\n if (argument === \"/m\") {\n const module = args[index + 1];\n if (module && !module.startsWith(\"/\")) index += 1;\n continue;\n }\n return false;\n }\n return true;\n}\n\nfunction isSafeGetProcessArguments(args: string[]) {\n return hasSafePowerShellQueryArguments(\n args,\n new Set([\"-module\", \"-fileversioninfo\", \"-includeusername\"]),\n new Set([\"-name\", \"-id\"]),\n );\n}\n\nfunction isSafeGetServiceArguments(args: string[]) {\n return hasSafePowerShellQueryArguments(\n args,\n new Set([\"-dependentservices\", \"-requiredservices\"]),\n new Set([\"-name\", \"-displayname\", \"-include\", \"-exclude\"]),\n );\n}\n\nfunction hasSafePowerShellQueryArguments(\n args: string[],\n switches: ReadonlySet<string>,\n valueOptions: ReadonlySet<string>,\n) {\n let positionalValues = 0;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n const normalized = argument?.toLowerCase();\n if (!argument || !normalized) return false;\n if (!argument.startsWith(\"-\")) {\n positionalValues += 1;\n if (positionalValues > 1) return false;\n continue;\n }\n if (switches.has(normalized)) continue;\n if (!valueOptions.has(normalized)) return false;\n const value = args[index + 1];\n if (!value || value.startsWith(\"-\")) return false;\n index += 1;\n }\n return true;\n}\n\nfunction isSafeGitCommand(args: string[], safeSubcommands: SafeSubcommands, workingDirectory?: string) {\n const subcommandIndex = parseGitGlobalOptions(args, workingDirectory);\n if (subcommandIndex === undefined) return false;\n const subcommand = args[subcommandIndex]?.toLowerCase();\n if (!subcommand || subcommand.startsWith(\"-\")) return false;\n const subcommandArgs = args.slice(subcommandIndex + 1);\n const builtinValidator = (BUILTIN_GIT_VALIDATORS as Record<string, ArgumentValidator>)[subcommand];\n const configuredValidator = (CONFIGURABLE_GIT_VALIDATORS as Record<string, ArgumentValidator>)[subcommand];\n const configured = safeSubcommands.git?.includes(subcommand as SafeGitSubcommand) === true;\n const validator = builtinValidator ?? (configured ? configuredValidator : undefined);\n return validator !== undefined && hasSafeGitArguments(subcommand, subcommandArgs) && validator(subcommandArgs);\n}\n\nfunction parseGitGlobalOptions(args: string[], workingDirectory?: string) {\n let index = 0;\n while (index < args.length) {\n const argument = args[index];\n if (argument === \"--no-pager\") {\n index += 1;\n continue;\n }\n if (argument !== \"-C\") break;\n const directory = args[index + 1];\n if (!directory || !isCurrentWorkingDirectory(directory, workingDirectory)) return undefined;\n index += 2;\n }\n return index;\n}\n\nfunction isCurrentWorkingDirectory(directory: string, workingDirectory?: string) {\n if (!workingDirectory || directory.split(/[\\\\/]+/u).includes(\"..\")) return false;\n if (normalize(directory) === \".\") return true;\n return isAbsolute(directory) && normalize(directory) === normalize(workingDirectory);\n}\n\nfunction hasSafeGitArguments(subcommand: string, args: string[]) {\n return !args.some(\n (argument) =>\n argument === \"--help\" ||\n argument === \"--show-signature\" ||\n argument.startsWith(\"--show-signature=\") ||\n argument.includes(\"%G\") ||\n argument === \"--output\" ||\n argument.startsWith(\"--output=\") ||\n argument === \"--ext-diff\" ||\n argument.startsWith(\"--ext-diff=\") ||\n argument === \"--textconv\" ||\n argument.startsWith(\"--textconv=\") ||\n argument === \"--paginate\" ||\n argument === \"--open-files-in-pager\" ||\n argument.startsWith(\"--open-files-in-pager=\") ||\n (subcommand === \"grep\" && (argument === \"-O\" || argument.startsWith(\"-O\"))),\n );\n}\n\nfunction isSafeGitCatFileArguments(args: string[]) {\n return !args.some(\n (argument) =>\n matchesLongOptionPrefix(argument, \"--filters\", \"--fi\") || matchesLongOptionPrefix(argument, \"--textconv\", \"--t\"),\n );\n}\n\nfunction isSafeGitGrepArguments(args: string[]) {\n return !args.some(\n (argument) =>\n matchesLongOptionPrefix(argument, \"--textconv\", \"--textc\") ||\n matchesLongOptionPrefix(argument, \"--open-files-in-pager\", \"--op\") ||\n matchesLongOptionPrefix(argument, \"--ext-grep\", \"--ext\"),\n );\n}\n\nfunction matchesLongOptionPrefix(argument: string, option: string, shortest: string) {\n const optionName = argument.split(\"=\", 1)[0] ?? \"\";\n return optionName.length >= shortest.length && option.startsWith(optionName);\n}\n\nfunction isSafeGitBranchArguments(args: string[]) {\n if (args.some((argument) => !argument.startsWith(\"-\"))) return false;\n return !args.some(\n (argument) =>\n /^-[^-]*[dDmMcCu]/.test(argument) ||\n matchesLongOptionPrefix(argument, \"--delete\", \"--del\") ||\n matchesLongOptionPrefix(argument, \"--move\", \"--mov\") ||\n matchesLongOptionPrefix(argument, \"--copy\", \"--cop\") ||\n matchesLongOptionPrefix(argument, \"--edit-description\", \"--e\") ||\n matchesLongOptionPrefix(argument, \"--unset-upstream\", \"--u\") ||\n matchesLongOptionPrefix(argument, \"--set-upstream-to\", \"--set-u\") ||\n matchesLongOptionPrefix(argument, \"--create-reflog\", \"--creat\"),\n );\n}\n\nfunction isSafeGitRemoteArguments(args: string[]) {\n const actionIndex = args.findIndex((argument) => !argument.startsWith(\"-\"));\n if (actionIndex < 0) return true;\n const action = args[actionIndex];\n if (action === \"get-url\") return true;\n if (action !== \"show\") return false;\n\n const showArgs = args.slice(actionIndex + 1);\n if (showArgs.includes(\"--\")) return false;\n const remotes = showArgs.filter((argument) => !argument.startsWith(\"-\"));\n return remotes.length === 0 || (remotes.length === 1 && showArgs.includes(\"-n\"));\n}\n\nfunction isSafeGhCommand(args: string[], safeSubcommands: SafeSubcommands) {\n const group = args[0]?.toLowerCase();\n const action = args[1]?.toLowerCase();\n if (!group || !action || group.startsWith(\"-\") || action.startsWith(\"-\")) return false;\n const path = `${group} ${action}` as SafeGhSubcommandPath;\n if (!safeSubcommands.gh?.includes(path)) return false;\n const validator = (GH_VALIDATORS as Record<string, ArgumentValidator>)[path];\n return validator?.(args.slice(2)) ?? false;\n}\n\nfunction isSafeGhReadArguments(args: string[]) {\n return !args.some(isUnsafeGhReadArgument) && hasGhJsonOutput(args);\n}\n\nfunction isUnsafeGhReadArgument(argument: string) {\n return (\n argument.startsWith(\"-w\") ||\n argument === \"--web\" ||\n argument.startsWith(\"--web=\") ||\n argument === \"--browser\" ||\n argument.startsWith(\"--browser=\") ||\n argument === \"--paginate\" ||\n argument === \"--pager\" ||\n argument.startsWith(\"--pager=\") ||\n argument === \"--output\" ||\n argument.startsWith(\"--output=\")\n );\n}\n\nfunction hasGhJsonOutput(args: string[]) {\n let hasJson = false;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--json\") {\n const value = args[index + 1];\n if (!value || value.startsWith(\"-\")) return false;\n hasJson = true;\n index += 1;\n } else if (argument.startsWith(\"--json=\")) {\n if (argument === \"--json=\") return false;\n hasJson = true;\n }\n }\n return hasJson;\n}\n", "import type { ToolInfo } from \"@earendil-works/pi-coding-agent\";\nimport { planModeToolAvailability } from \"./tool-availability.js\";\nimport {\n canSelectToolInPlanMode,\n classifyPlanModeTool,\n isBuiltinTool,\n SAFE_BUILTIN_PLAN_TOOLS,\n} from \"./tool-policy.js\";\n\nexport function toolNameFromLegacyKey(key: string, tools: ToolInfo[]) {\n const directName = tools.find((tool) => tool.name === key)?.name;\n if (directName) return directName;\n const [name] = key.split(\"\\u001f\");\n return tools.find((tool) => tool.name === name) ? name : undefined;\n}\n\nexport function compareTools(left: ToolInfo, right: ToolInfo) {\n const leftBuiltin = isBuiltinTool(left);\n const rightBuiltin = isBuiltinTool(right);\n if (leftBuiltin !== rightBuiltin) return leftBuiltin ? -1 : 1;\n return left.name.localeCompare(right.name);\n}\n\nexport function toolPolicyLabel(tool: ToolInfo) {\n const policy = classifyPlanModeTool(tool);\n if (policy === \"read-only\") return \"built-in read-only\";\n if (policy === \"limited\") return \"built-in limited\";\n if (policy === \"blocked\") return tool.sourceInfo?.source ? \"built-in blocked\" : \"policy metadata unavailable\";\n return `user opt-in: ${toolSourceLabel(tool)}`;\n}\n\nexport function planModeToolSelection(tool: ToolInfo, activeNames: ReadonlySet<string>, retained: boolean) {\n const availability = planModeToolAvailability(tool, activeNames);\n const policyBlocked = !canSelectToolInPlanMode(tool);\n let unavailable: string | undefined;\n switch (availability) {\n case \"inactive\":\n unavailable = \"Not active in Pi; Plan mode will not activate it\";\n if (!policyBlocked && isBuiltinTool(tool) && [\"grep\", \"find\", \"ls\"].includes(tool.name)) {\n // ExtensionContext does not expose host-owned Pi settings; plain names also work before Pi 0.99.\n unavailable += `; on Pi with defaultTools support, use a full list including \"${tool.name}\" in this session's Pi settings (preserve existing/default tools), then restart Pi`;\n }\n if (retained) unavailable += \"; retained and resolved before the first request\";\n break;\n case \"hidden\":\n unavailable = \"Hidden in Pi; retained selection cannot enable it\";\n break;\n case \"unsupported\":\n unavailable = \"Unsupported tool exposure; Plan mode cannot enable it\";\n break;\n }\n const policy =\n (policyBlocked ? undefined : unavailable) ??\n [\n toolPolicyLabel(tool),\n ...(tool.exposure === \"codemode\" || tool.exposure === \"deferred\" ? [\"callable via other tools\"] : []),\n ...(tool.exposure === \"model-only\" ? [\"model calls only\"] : []),\n ].join(\" \u00B7 \");\n const description = tool.description ?? \"No description available\";\n const disabledReason = policyBlocked ? \"Blocked by Plan-mode policy\" : unavailable;\n const label = policyBlocked\n ? `${tool.name} \u2014 blocked by Plan policy`\n : availability === \"inactive\"\n ? `${tool.name} \u2014 inactive in Pi`\n : tool.name;\n return {\n label,\n description: `${policy} \u00B7 ${description}`,\n searchText: `${policy} ${description}`,\n disabled: disabledReason !== undefined,\n disabledReason,\n };\n}\n\nfunction toolSourceLabel(tool: ToolInfo) {\n const sourceInfo = tool.sourceInfo;\n const source = `${sourceInfo.scope}/${sourceInfo.source}`;\n return sourceInfo.path ? `${source} ${sourceInfo.path}` : source;\n}\n\nexport function unique(values: string[]) {\n return Array.from(new Set(values));\n}\n\nexport function filterAvailableSelectedToolNames(\n names: string[],\n tools: ToolInfo[],\n activeNames: ReadonlySet<string> = new Set(tools.map((tool) => tool.name)),\n) {\n const availableNames = new Set(\n tools\n .filter((tool) => canSelectToolInPlanMode(tool) && planModeToolAvailability(tool, activeNames) === \"available\")\n .map((tool) => tool.name),\n );\n return unique(names.filter((name) => availableNames.has(name)));\n}\n\nexport function defaultPlanModeToolNames(tools: ToolInfo[], configuredNames: string[] | undefined) {\n if (configuredNames !== undefined) return unique(configuredNames);\n return tools.filter((tool) => isBuiltinTool(tool) && SAFE_BUILTIN_PLAN_TOOLS.has(tool.name)).map((tool) => tool.name);\n}\n\ninterface PlanModeToolSelectionSnapshot {\n selectedToolNames?: string[];\n selectedToolKeys?: string[];\n defaultPlanTools?: string[];\n}\n\nexport function snapshotPlanModeSelectedNames(tools: ToolInfo[], selection: PlanModeToolSelectionSnapshot) {\n const selectedToolNames =\n selection.selectedToolNames ??\n selection.selectedToolKeys\n ?.map((key) => toolNameFromLegacyKey(key, tools))\n .filter((name): name is string => name !== undefined);\n return new Set(\n selectedToolNames === undefined\n ? defaultPlanModeToolNames(tools, selection.defaultPlanTools)\n : unique(selectedToolNames),\n );\n}\n"],
5
- "mappings": ";;;;AAAA,SAAS,wBAAwB;AACjC,SAAS,gBAAgB;AAElB,IAAM,+BAA+B;AACrC,IAAM,6BAA6B;AACnC,IAAM,sBAAsB;AAQ5B,IAAM,4BAA4B;AAAA,EACvC,MAAM;AAAA,EACN,sBAAsB;AAAA,EACtB,UAAU,CAAC,MAAM;AAAA,EACjB,YAAY;AAAA,IACV,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,WAAW;AAAA,MACX,WAAW;AAAA,MACX,aAAa;AAAA,IACf;AAAA,EACF;AACF;AAIO,SAAS,4BAA4B,OAAmD;AAC7F,MAAI,CAAC,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,UAAU;AACtD,WAA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OAAmB,WAA0C;AACzG,QAAM,oBACJ,UAAU,qBACV,UAAU,kBACN,IAAI,CAAC,QAAQ,sBAAsB,KAAK,KAAK,CAAC,EAC/C,OAAO,CAAC,SAAyB,SAAS,MAAS;AACxD,SAAO,IAAI;AAAA,IACT,sBAAsB,SAClB,yBAAyB,OAAO,UAAU,gBAAgB,IAC1D,OAAO,iBAAiB;AAAA,EAC9B;AACF;",
4
+ "sourcesContent": ["import { getMarkdownTheme } from \"@earendil-works/pi-coding-agent\";\nimport { Markdown } from \"@earendil-works/pi-tui\";\n\nexport const PLAN_MODE_COMPLETE_TOOL_NAME = \"plan_mode_complete\";\nexport const PLAN_MODE_COMPLETE_VERSION = 1;\nexport const PLAN_MODE_MAX_CHARS = 50_000;\n\nexport type PlanModeCompletionDetails = {\n version: typeof PLAN_MODE_COMPLETE_VERSION;\n source: typeof PLAN_MODE_COMPLETE_TOOL_NAME;\n plan: string;\n};\n\nexport const PLAN_MODE_COMPLETE_PARAMS = {\n type: \"object\",\n additionalProperties: false,\n required: [\"plan\"],\n properties: {\n plan: {\n type: \"string\",\n minLength: 1,\n maxLength: PLAN_MODE_MAX_CHARS,\n description: \"The complete decision-ready implementation plan in Markdown.\",\n },\n },\n} as const;\n\ntype NormalizePlanModeCompletionResult = { ok: true; plan: string } | { ok: false; error: string };\n\nexport function normalizePlanModeCompletion(input: unknown): NormalizePlanModeCompletionResult {\n if (!isRecord(input) || typeof input.plan !== \"string\") {\n return { ok: false, error: \"plan must be a string\" };\n }\n const plan = input.plan.trim();\n if (!plan) return { ok: false, error: \"plan must not be empty\" };\n if (plan.length > PLAN_MODE_MAX_CHARS) {\n return {\n ok: false,\n error: `plan must not exceed ${PLAN_MODE_MAX_CHARS} characters`,\n };\n }\n return { ok: true, plan };\n}\n\nexport function planFromCompletionDetails(value: unknown) {\n if (!isRecord(value)) return undefined;\n if (value.version !== PLAN_MODE_COMPLETE_VERSION || value.source !== PLAN_MODE_COMPLETE_TOOL_NAME) {\n return undefined;\n }\n const normalized = normalizePlanModeCompletion({ plan: value.plan });\n return normalized.ok ? normalized.plan : undefined;\n}\n\nexport function planModeCompleted(plan: string) {\n return {\n content: [{ type: \"text\" as const, text: `**Proposed Plan**\\n\\n${plan}` }],\n details: {\n version: PLAN_MODE_COMPLETE_VERSION,\n source: PLAN_MODE_COMPLETE_TOOL_NAME,\n plan,\n } satisfies PlanModeCompletionDetails,\n terminate: true,\n };\n}\n\ntype PlanModeCompletionRenderResult = {\n content: Array<{ type: string; text?: string }>;\n details?: unknown;\n};\n\nexport function planModeCompletionMarkdown(result: PlanModeCompletionRenderResult) {\n const content = result.content\n .filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n .map((block) => block.text)\n .join(\"\\n\")\n .trim();\n if (content) return content;\n const plan = planFromCompletionDetails(result.details);\n return plan ? `**Proposed Plan**\\n\\n${plan}` : \"\";\n}\n\nexport function renderPlanModeCompletion(result: PlanModeCompletionRenderResult) {\n return new Markdown(planModeCompletionMarkdown(result), 0, 0, getMarkdownTheme());\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "import { PLAN_MODE_COMPLETE_TOOL_NAME } from \"./completion-tool.js\";\nimport type { ActiveImplementationPlan } from \"./state.js\";\n\nconst PLAN_CONTEXT_MESSAGE_TYPE = \"plan-mode-context\";\nexport const PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE = \"plan-mode-implementation-context\";\nconst PROPOSED_PLAN_MESSAGE_TYPE = \"proposed-plan\";\nconst PLAN_IMPLEMENTATION_HANDOFF_PREFIX =\n \"Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:\";\nexport const PLAN_HISTORY_IMPLEMENTATION_PROMPT = \"Implement the plan.\";\nconst PROPOSED_PLAN_PATTERN = /^<proposed_plan>[\\t ]*\\r?\\n([\\s\\S]*?)\\r?\\n<\\/proposed_plan>[\\t ]*$/gm;\nconst PROPOSED_PLAN_BLOCK_PATTERN = /^<proposed_plan>[\\t ]*\\r?\\n[\\s\\S]*?\\r?\\n<\\/proposed_plan>[\\t ]*$/gm;\n\nexport type ProposedPlanParseResult =\n | { kind: \"absent\" }\n | { kind: \"valid\"; plan: string }\n | { kind: \"empty\" }\n | { kind: \"multiple\" }\n | { kind: \"malformed\" }\n | { kind: \"unclosed\" };\n\ntype SessionMessage = {\n role?: string;\n content?: unknown;\n stopReason?: string;\n};\n\ntype TextBlock = {\n type?: string;\n text?: string;\n};\n\nexport function parseProposedPlan(text: string): ProposedPlanParseResult {\n const openingCount = text.match(/<proposed_plan>/gi)?.length ?? 0;\n const closingCount = text.match(/<\\/proposed_plan>/gi)?.length ?? 0;\n if (openingCount === 0 && closingCount === 0) return { kind: \"absent\" };\n if (openingCount > 1 || closingCount > 1) return { kind: \"multiple\" };\n if (openingCount === 1 && closingCount === 0) return { kind: \"unclosed\" };\n if (openingCount !== 1 || closingCount !== 1) return { kind: \"malformed\" };\n\n const matches = Array.from(text.matchAll(PROPOSED_PLAN_PATTERN));\n if (matches.length !== 1) return { kind: \"malformed\" };\n const plan = matches[0]?.[1]?.trim() ?? \"\";\n return plan ? { kind: \"valid\", plan } : { kind: \"empty\" };\n}\n\nexport function extractProposedPlan(text: string) {\n const result = parseProposedPlan(text);\n return result.kind === \"valid\" ? result.plan : undefined;\n}\n\nexport function invalidPlanMessage(kind: \"empty\" | \"multiple\" | \"malformed\" | \"unclosed\") {\n const detail = {\n empty: \"the block is empty\",\n multiple: \"more than one plan block was produced\",\n malformed: \"the tags must be on their own lines\",\n unclosed: \"the closing tag is missing\",\n }[kind];\n return `Proposed plan is not ready: ${detail}. Continue Plan mode and produce one complete non-empty <proposed_plan> block.`;\n}\n\nexport function latestAssistantText(messages: unknown) {\n if (!Array.isArray(messages)) return \"\";\n for (const entry of [...messages].reverse()) {\n const message = (entry as { message?: SessionMessage })?.message ?? (entry as SessionMessage);\n if (message?.role !== \"assistant\") continue;\n const text = messageText(message);\n if (text) return text;\n }\n return \"\";\n}\n\nexport function latestAssistantStopReason(messages: unknown) {\n if (!Array.isArray(messages)) return undefined;\n for (const entry of [...messages].reverse()) {\n const message = (entry as { message?: SessionMessage })?.message ?? (entry as SessionMessage);\n if (message?.role === \"assistant\") return message.stopReason;\n }\n return undefined;\n}\n\nexport function messageTextContent(message: unknown) {\n return messageText((message as { message?: SessionMessage })?.message ?? (message as SessionMessage));\n}\n\nexport function messageContainsLegacyPlanModeContextArtifact(message: unknown) {\n return unwrapSessionMessage(message).customType === PLAN_CONTEXT_MESSAGE_TYPE;\n}\n\nexport function messageContainsPlanModeImplementationContextArtifact(message: unknown) {\n return unwrapSessionMessage(message).customType === PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE;\n}\n\nexport function injectActiveImplementationContext(messages: unknown[], activeImplementation: ActiveImplementationPlan) {\n let foundCurrentContext = false;\n let foundCurrentHandoff = false;\n const expectedContext = activeImplementationContextContent(activeImplementation);\n const messagesWithoutStaleContext = messages.filter((message) => {\n if (messageContainsPlanModeImplementationContextArtifact(message)) {\n const candidate = unwrapSessionMessage(message);\n if (!foundCurrentContext && candidate.content === expectedContext) {\n foundCurrentContext = true;\n return true;\n }\n return false;\n }\n if (!messageContainsPlanModeImplementationHandoff(message)) return true;\n if (!foundCurrentHandoff && messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)) {\n foundCurrentHandoff = true;\n return true;\n }\n return false;\n });\n if (foundCurrentHandoff || foundCurrentContext) return messagesWithoutStaleContext;\n\n let insertionIndex = 0;\n while (isSummaryMessage(messagesWithoutStaleContext[insertionIndex])) insertionIndex += 1;\n const contextMessage = {\n role: \"custom\" as const,\n customType: PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE,\n content: expectedContext,\n display: false,\n timestamp: activeImplementation.startedAt,\n };\n return [\n ...messagesWithoutStaleContext.slice(0, insertionIndex),\n contextMessage,\n ...messagesWithoutStaleContext.slice(insertionIndex),\n ];\n}\n\nfunction activeImplementationContextContent(activeImplementation: ActiveImplementationPlan) {\n return `[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}`;\n}\n\nexport function messageContainsInactivePlanModeArtifact(message: unknown) {\n const candidate = unwrapSessionMessage(message);\n return (\n candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE ||\n (candidate.role === \"toolResult\" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME)\n );\n}\n\ninterface HistoryImplementationArtifact {\n messageIndex: number;\n kind: \"completion\" | \"legacy\" | \"presentation\";\n toolCallId?: string;\n toolCallMessageIndex?: number;\n}\n\n// The kickoff text is intentionally generic, so only trust a plan artifact in the same\n// uninterrupted user/summary segment and require a complete tool-call/result pair.\nexport function findHistoryImplementationArtifact(messages: unknown[]): HistoryImplementationArtifact | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const candidate = unwrapSessionMessage(messages[index]);\n if (candidate.role !== \"user\" || contentText(candidate.content).trim() !== PLAN_HISTORY_IMPLEMENTATION_PROMPT) {\n continue;\n }\n const artifact = findHistoryImplementationArtifactBeforeKickoff(messages, index);\n if (artifact) return artifact;\n }\n return undefined;\n}\n\nfunction findHistoryImplementationArtifactBeforeKickoff(\n messages: unknown[],\n kickoffIndex: number,\n): HistoryImplementationArtifact | undefined {\n for (let index = kickoffIndex - 1; index >= 0; index -= 1) {\n const candidate = unwrapSessionMessage(messages[index]);\n if (candidate.role === \"user\" || isSummaryMessage(messages[index])) return undefined;\n if (candidate.role === \"toolResult\" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME) {\n const toolCallId = candidate.toolCallId;\n const toolCallMessageIndex = toolCallId\n ? findPlanModeCompletionCallMessageIndex(messages, index, toolCallId)\n : undefined;\n if (toolCallId && toolCallMessageIndex !== undefined) {\n return {\n messageIndex: index,\n kind: \"completion\",\n toolCallId,\n toolCallMessageIndex,\n };\n }\n continue;\n }\n if (candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE) {\n return { messageIndex: index, kind: \"presentation\" };\n }\n if (candidate.role === \"assistant\" && contentText(candidate.content).match(PROPOSED_PLAN_BLOCK_PATTERN)) {\n return { messageIndex: index, kind: \"legacy\" };\n }\n }\n return undefined;\n}\n\nfunction findPlanModeCompletionCallMessageIndex(messages: unknown[], endIndex: number, toolCallId: string) {\n for (let index = endIndex - 1; index >= 0; index -= 1) {\n const candidate = unwrapSessionMessage(messages[index]);\n if (candidate.role === \"user\" || isSummaryMessage(messages[index])) return undefined;\n if (!Array.isArray(candidate.content)) continue;\n if (\n candidate.content.some((block) => {\n const toolCall = block as { type?: string; id?: string; name?: string };\n return (\n toolCall.type === \"toolCall\" && toolCall.id === toolCallId && toolCall.name === PLAN_MODE_COMPLETE_TOOL_NAME\n );\n })\n ) {\n return index;\n }\n }\n return undefined;\n}\n\nexport function messageContainsPlanModeImplementationHandoff(message: unknown) {\n const candidate = unwrapSessionMessage(message);\n return (\n candidate.role === \"user\" &&\n contentText(candidate.content).trimStart().startsWith(PLAN_IMPLEMENTATION_HANDOFF_PREFIX)\n );\n}\n\nexport function messageContainsExactPlanModeImplementationHandoff(message: unknown, plan: string) {\n const candidate = unwrapSessionMessage(message);\n if (candidate.role !== \"user\") return false;\n return contentText(candidate.content).trim() === `${PLAN_IMPLEMENTATION_HANDOFF_PREFIX}\\n\\n${plan}`.trim();\n}\n\nfunction isSummaryMessage(message: unknown) {\n const role = unwrapSessionMessage(message)?.role;\n return role === \"compactionSummary\" || role === \"branchSummary\";\n}\n\nexport function stripProposedPlanBlocksFromMessage<T>(message: T): T {\n return replaceAssistantContent(message, stripProposedPlanBlocksFromContent);\n}\n\nexport function stripPlanModeCompletionCallsFromMessage<T>(message: T, preservedToolCallId?: string): T {\n return replaceAssistantContent(message, (content) => {\n if (!Array.isArray(content)) return content;\n const nextContent = content.filter((block) => {\n const candidate = block as { type?: string; id?: string; name?: string };\n return !(\n candidate.type === \"toolCall\" &&\n candidate.name === PLAN_MODE_COMPLETE_TOOL_NAME &&\n (!preservedToolCallId || candidate.id !== preservedToolCallId)\n );\n });\n return nextContent.length === content.length ? content : nextContent;\n });\n}\n\nexport function isEmptyAssistantMessage(message: unknown) {\n const candidate = unwrapSessionMessage(message);\n return candidate.role === \"assistant\" && Array.isArray(candidate.content) && candidate.content.length === 0;\n}\n\nfunction replaceAssistantContent<T>(message: T, transform: (content: unknown) => unknown): T {\n const candidate = unwrapSessionMessage(message);\n if (candidate.role !== \"assistant\") return message;\n\n const content = transform(candidate.content);\n if (content === candidate.content) return message;\n\n if (isSessionMessageEntry(message)) {\n return { ...message, message: { ...candidate, content } };\n }\n return { ...candidate, content } as T;\n}\n\nfunction unwrapSessionMessage(message: unknown) {\n const entry = message as { message?: unknown } | null | undefined;\n return (entry?.message ?? message ?? {}) as {\n role?: string;\n customType?: string;\n toolName?: string;\n toolCallId?: string;\n content?: unknown;\n };\n}\n\nfunction isSessionMessageEntry<T>(message: T): message is T & { message: SessionMessage } {\n return typeof message === \"object\" && message !== null && \"message\" in message;\n}\n\nfunction stripProposedPlanBlocksFromContent(content: unknown) {\n if (typeof content === \"string\") return stripProposedPlanBlocks(content);\n if (!Array.isArray(content)) return content;\n\n let changed = false;\n const nextContent = content.map((block) => {\n const textBlock = block as TextBlock;\n if (textBlock.type !== \"text\" || typeof textBlock.text !== \"string\") return block;\n\n const text = stripProposedPlanBlocks(textBlock.text);\n if (text === textBlock.text) return block;\n\n changed = true;\n return { ...textBlock, text };\n });\n return changed ? nextContent : content;\n}\n\nexport function stripProposedPlanBlocks(text: string) {\n return text.replace(PROPOSED_PLAN_BLOCK_PATTERN, \"\");\n}\n\nfunction messageText(message: SessionMessage) {\n return contentText(message.content);\n}\n\nfunction contentText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .map((block) => {\n const textBlock = block as TextBlock;\n return textBlock.type === \"text\" && typeof textBlock.text === \"string\" ? textBlock.text : \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\n\nexport const MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH = 512;\n\nexport interface ImplementationModelOverride {\n provider: string;\n modelId: string;\n}\n\nexport interface AvailableImplementationModel {\n provider: string;\n id: string;\n name?: string;\n}\n\nexport function isPendingImplementationModelIdentifier(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.trim().length > 0 &&\n value.length <= MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH\n );\n}\n\nexport function snapshotAvailableImplementationModels(ctx: ExtensionContext): AvailableImplementationModel[] {\n const getAvailable = ctx.modelRegistry.getAvailable;\n const availableModels = typeof getAvailable === \"function\" ? getAvailable.call(ctx.modelRegistry) : [];\n const scopedModels = ctx.scopedModels ?? [];\n if (scopedModels.length === 0) return availableModels;\n return scopedModels.flatMap((entry) => {\n const availableModel = availableModels.find(\n (model) => model.provider === entry.model.provider && model.id === entry.model.id,\n );\n return availableModel ? [availableModel] : [];\n });\n}\n\nexport function findAvailableImplementationModel(\n models: readonly AvailableImplementationModel[],\n configured: ImplementationModelOverride | undefined,\n): AvailableImplementationModel | undefined {\n if (!configured) return undefined;\n return models.find((model) => model.provider === configured.provider && model.id === configured.modelId);\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { mkdir, open, rename, rm, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, join } from \"node:path\";\nimport { getAgentDir } from \"@earendil-works/pi-coding-agent\";\nimport type { KeyId } from \"@earendil-works/pi-tui\";\nimport { type ImplementationModelOverride, isPendingImplementationModelIdentifier } from \"./implementation-models.js\";\nimport type { SafeSubcommands } from \"./tool-policy.js\";\n\nexport const PLAN_MODE_SETTINGS_FILE = \"pi-plan-mode.json\";\nconst LEGACY_PLAN_MODE_SETTINGS_FILE = \"plan-mode.json\";\nconst MAX_SETTINGS_BYTES = 64 * 1024;\nexport const PLAN_MODE_THINKING_LEVELS = [\n \"inherit\",\n \"off\",\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n] as const;\nexport const IMPLEMENTATION_THINKING_LEVELS = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const IMPLEMENTATION_PLAN_RETENTIONS = [\"clear-on-start\", \"clear-after-first-run\", \"keep\"] as const;\nexport const DEFAULT_PLAN_EXPORT_PATH = \"PLAN.md\";\nconst MODIFIERS = new Set([\"ctrl\", \"shift\", \"alt\", \"super\"]);\nconst BASE_KEYS = new Set([\n ...\"abcdefghijklmnopqrstuvwxyz0123456789\",\n \"`\",\n \"-\",\n \"=\",\n \"[\",\n \"]\",\n \"\\\\\",\n \";\",\n \"'\",\n \",\",\n \".\",\n \"/\",\n \"!\",\n \"@\",\n \"#\",\n \"$\",\n \"%\",\n \"^\",\n \"&\",\n \"*\",\n \"(\",\n \")\",\n \"_\",\n \"+\",\n \"|\",\n \"~\",\n \"{\",\n \"}\",\n \":\",\n \"<\",\n \">\",\n \"?\",\n \"escape\",\n \"esc\",\n \"enter\",\n \"return\",\n \"tab\",\n \"space\",\n \"backspace\",\n \"delete\",\n \"insert\",\n \"clear\",\n \"home\",\n \"end\",\n \"pageup\",\n \"pagedown\",\n \"up\",\n \"down\",\n \"left\",\n \"right\",\n ...Array.from({ length: 12 }, (_unused, index) => `f${index + 1}`),\n]);\nconst MAX_PLAN_EXPORT_PATH_LENGTH = 4096;\n\nexport type PlanModeThinkingLevel = (typeof PLAN_MODE_THINKING_LEVELS)[number];\nexport type ImplementationPlanRetention = (typeof IMPLEMENTATION_PLAN_RETENTIONS)[number];\nexport type PlanModeFixedThinkingLevel = (typeof IMPLEMENTATION_THINKING_LEVELS)[number];\nexport interface PlanModeSettings {\n thinkingLevel: PlanModeThinkingLevel;\n defaultPlanTools?: string[];\n implementationPlanRetention?: ImplementationPlanRetention;\n defaultImplementationModel?: ImplementationModelOverride;\n defaultImplementationThinkingLevel?: PlanModeFixedThinkingLevel;\n defaultPlanExportPath?: string;\n safeSubcommands?: SafeSubcommands;\n toggleShortcut?: KeyId;\n}\nexport interface PlanModeSettingsPatch {\n thinkingLevel?: PlanModeThinkingLevel;\n defaultPlanTools?: readonly string[] | null;\n implementationPlanRetention?: ImplementationPlanRetention;\n defaultImplementationModel?: ImplementationModelOverride | null;\n defaultImplementationThinkingLevel?: PlanModeFixedThinkingLevel | null;\n defaultPlanExportPath?: string | null;\n toggleShortcut?: KeyId | null;\n}\nexport interface UpdatePlanModeSettingsOptions {\n settingsPath?: string;\n legacySettingsPath?: string;\n signal?: AbortSignal;\n beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;\n}\nexport type PlanModeSettingsLoadResult =\n | { kind: \"missing\"; notice?: string }\n | { kind: \"invalid\"; reason: string; notice?: string }\n | { kind: \"loaded\"; settings: PlanModeSettings; notice?: string };\n\ntype SettingsDocument = Record<string, unknown>;\ntype SettingsSnapshot = {\n result: PlanModeSettingsLoadResult;\n document?: SettingsDocument;\n};\n\nconst mutationQueues = new Map<string, Promise<void>>();\n\nexport function planModeSettingsPath() {\n return join(getAgentDir(), PLAN_MODE_SETTINGS_FILE);\n}\n\nfunction legacyPlanModeSettingsPath() {\n return join(getAgentDir(), LEGACY_PLAN_MODE_SETTINGS_FILE);\n}\n\nexport function normalizePlanModeSettings(value: unknown): PlanModeSettings | undefined {\n if (!isSettingsDocument(value)) return undefined;\n const thinkingLevel = Object.hasOwn(value, \"thinkingLevel\") ? Reflect.get(value, \"thinkingLevel\") : \"inherit\";\n if (!PLAN_MODE_THINKING_LEVELS.includes(thinkingLevel as PlanModeThinkingLevel)) {\n return undefined;\n }\n const settings: PlanModeSettings = {\n thinkingLevel: thinkingLevel as PlanModeThinkingLevel,\n };\n if (Object.hasOwn(value, \"defaultPlanTools\")) {\n const defaultPlanTools = normalizeToolNames(Reflect.get(value, \"defaultPlanTools\"));\n if (!defaultPlanTools) return undefined;\n settings.defaultPlanTools = defaultPlanTools;\n }\n if (Object.hasOwn(value, \"implementationPlanRetention\")) {\n const implementationPlanRetention = Reflect.get(value, \"implementationPlanRetention\");\n if (!IMPLEMENTATION_PLAN_RETENTIONS.includes(implementationPlanRetention as ImplementationPlanRetention)) {\n return undefined;\n }\n settings.implementationPlanRetention = implementationPlanRetention as ImplementationPlanRetention;\n }\n if (Object.hasOwn(value, \"defaultImplementationModel\")) {\n const defaultImplementationModel = normalizeImplementationModel(Reflect.get(value, \"defaultImplementationModel\"));\n if (!defaultImplementationModel) return undefined;\n settings.defaultImplementationModel = defaultImplementationModel;\n }\n if (Object.hasOwn(value, \"defaultImplementationThinkingLevel\")) {\n const defaultImplementationThinkingLevel = Reflect.get(value, \"defaultImplementationThinkingLevel\");\n if (!IMPLEMENTATION_THINKING_LEVELS.includes(defaultImplementationThinkingLevel as PlanModeFixedThinkingLevel)) {\n return undefined;\n }\n settings.defaultImplementationThinkingLevel = defaultImplementationThinkingLevel as PlanModeFixedThinkingLevel;\n }\n if (Object.hasOwn(value, \"defaultPlanExportPath\")) {\n const defaultPlanExportPath = normalizePlanExportPath(Reflect.get(value, \"defaultPlanExportPath\"));\n if (!defaultPlanExportPath) return undefined;\n settings.defaultPlanExportPath = defaultPlanExportPath;\n }\n if (Object.hasOwn(value, \"toggleShortcut\")) {\n const toggleShortcut = normalizeKeyId(Reflect.get(value, \"toggleShortcut\"));\n if (!toggleShortcut) return undefined;\n settings.toggleShortcut = toggleShortcut;\n }\n if (Object.hasOwn(value, \"safeSubcommands\")) {\n const safeSubcommands = normalizeSafeSubcommands(Reflect.get(value, \"safeSubcommands\"));\n if (!safeSubcommands) return undefined;\n settings.safeSubcommands = safeSubcommands;\n }\n return settings;\n}\n\nfunction normalizeImplementationModel(value: unknown): ImplementationModelOverride | undefined {\n if (!isSettingsDocument(value) || Object.keys(value).some((key) => key !== \"provider\" && key !== \"modelId\")) {\n return undefined;\n }\n const provider = typeof value.provider === \"string\" ? value.provider.trim() : value.provider;\n const modelId = typeof value.modelId === \"string\" ? value.modelId.trim() : value.modelId;\n if (!isPendingImplementationModelIdentifier(provider) || !isPendingImplementationModelIdentifier(modelId)) {\n return undefined;\n }\n return { provider, modelId };\n}\n\nfunction normalizeToolNames(value: unknown) {\n if (\n !Array.isArray(value) ||\n !value.every((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n ) {\n return undefined;\n }\n return Array.from(new Set(value));\n}\n\nfunction normalizePlanExportPath(value: unknown) {\n if (typeof value !== \"string\") return undefined;\n const normalized = value.trim();\n if (\n !normalized ||\n normalized.length > MAX_PLAN_EXPORT_PATH_LENGTH ||\n !/[^@\\s]/u.test(normalized) ||\n [...normalized].some((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n })\n ) {\n return undefined;\n }\n return normalized;\n}\n\nexport function normalizeKeyId(value: unknown): KeyId | undefined {\n if (typeof value !== \"string\") return undefined;\n const normalized = value.trim().toLowerCase();\n const base = [...BASE_KEYS]\n .sort((left, right) => right.length - left.length)\n .find((candidate) => normalized === candidate || normalized.endsWith(`+${candidate}`));\n if (!base) return undefined;\n const prefix = normalized.slice(0, normalized.length - base.length);\n if (!prefix) return base as KeyId;\n if (/^f(?:[1-9]|1[0-2])$/.test(base) || !prefix.endsWith(\"+\")) return undefined;\n const modifiers = prefix.slice(0, -1).split(\"+\");\n if (\n modifiers.length === 0 ||\n modifiers.some((modifier) => !MODIFIERS.has(modifier)) ||\n new Set(modifiers).size !== modifiers.length\n ) {\n return undefined;\n }\n return normalized as KeyId;\n}\n\nfunction normalizeSafeSubcommands(value: unknown): SafeSubcommands | undefined {\n if (!isSettingsDocument(value)) return undefined;\n const entries: [string, string[]][] = [];\n for (const [command, subcommands] of Object.entries(value)) {\n const normalizedCommand = command.trim();\n if (\n !normalizedCommand ||\n !Array.isArray(subcommands) ||\n !subcommands.every((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n ) {\n return undefined;\n }\n const normalizedSubcommands = Array.from(new Set(subcommands.map((subcommand) => subcommand.trim())));\n const existing = entries.find(([existingCommand]) => existingCommand === normalizedCommand);\n if (existing) existing[1] = Array.from(new Set([...existing[1], ...normalizedSubcommands]));\n else entries.push([normalizedCommand, normalizedSubcommands]);\n }\n return Object.fromEntries(entries);\n}\n\nexport async function readPlanModeSettings(settingsPath?: string): Promise<PlanModeSettingsLoadResult> {\n if (settingsPath) {\n await awaitPlanModeSettingsWrites(settingsPath);\n return (await readSettingsSnapshot(settingsPath)).result;\n }\n const canonicalPath = planModeSettingsPath();\n await awaitPlanModeSettingsWrites(canonicalPath);\n const canonical = await readSettingsSnapshot(canonicalPath);\n const legacyPath = legacyPlanModeSettingsPath();\n if (canonical.result.kind !== \"missing\") {\n return (await pathExists(legacyPath))\n ? {\n ...canonical.result,\n notice: `${LEGACY_PLAN_MODE_SETTINGS_FILE} ignored because ${PLAN_MODE_SETTINGS_FILE} takes precedence.`,\n }\n : canonical.result;\n }\n\n const legacy = await readSettingsSnapshot(legacyPath);\n const raced = await readSettingsSnapshot(canonicalPath);\n if (raced.result.kind !== \"missing\") return raced.result;\n return legacy.result.kind === \"loaded\"\n ? {\n ...legacy.result,\n notice: `Using legacy ${LEGACY_PLAN_MODE_SETTINGS_FILE}; rename it to ${PLAN_MODE_SETTINGS_FILE}. The legacy file was not modified.`,\n }\n : legacy.result;\n}\n\nexport function updatePlanModeSettings(\n patch: PlanModeSettingsPatch,\n options: UpdatePlanModeSettingsOptions = {},\n): Promise<PlanModeSettings> {\n const settingsPath = options.settingsPath ?? planModeSettingsPath();\n const legacySettingsPath =\n options.legacySettingsPath ?? (options.settingsPath ? undefined : legacyPlanModeSettingsPath());\n return enqueueMutation(settingsPath, async () => {\n options.signal?.throwIfAborted();\n const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);\n const updated: SettingsDocument = { ...current };\n if (patch.thinkingLevel !== undefined) updated.thinkingLevel = patch.thinkingLevel;\n if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;\n else if (patch.defaultPlanTools !== undefined) {\n updated.defaultPlanTools = [...patch.defaultPlanTools];\n }\n if (patch.implementationPlanRetention !== undefined) {\n updated.implementationPlanRetention = patch.implementationPlanRetention;\n }\n if (patch.defaultImplementationModel === null) delete updated.defaultImplementationModel;\n else if (patch.defaultImplementationModel !== undefined) {\n const model = normalizeImplementationModel(patch.defaultImplementationModel);\n if (!model) throw invalidSettingsError(settingsPath, \"invalid implementation model\");\n updated.defaultImplementationModel = model;\n }\n if (patch.defaultImplementationThinkingLevel === null) {\n delete updated.defaultImplementationThinkingLevel;\n } else if (patch.defaultImplementationThinkingLevel !== undefined) {\n updated.defaultImplementationThinkingLevel = patch.defaultImplementationThinkingLevel;\n }\n if (patch.defaultPlanExportPath === null) delete updated.defaultPlanExportPath;\n else if (patch.defaultPlanExportPath !== undefined) {\n updated.defaultPlanExportPath = patch.defaultPlanExportPath;\n }\n if (patch.toggleShortcut === null) delete updated.toggleShortcut;\n else if (patch.toggleShortcut !== undefined) {\n updated.toggleShortcut = patch.toggleShortcut;\n }\n const settings = normalizePlanModeSettings(updated);\n if (!settings) throw invalidSettingsError(settingsPath, \"invalid settings shape\");\n await publishSettings(settingsPath, updated, options.signal, options.beforeRename);\n return settings;\n });\n}\n\nexport async function awaitPlanModeSettingsWrites(settingsPath = planModeSettingsPath()): Promise<void> {\n await mutationQueues.get(settingsPath);\n}\n\nfunction enqueueMutation<T>(settingsPath: string, mutation: () => Promise<T>): Promise<T> {\n const previous = mutationQueues.get(settingsPath) ?? Promise.resolve();\n const result = previous.then(mutation, mutation);\n const settled = result.then(\n () => undefined,\n () => undefined,\n );\n mutationQueues.set(settingsPath, settled);\n void settled.finally(() => {\n if (mutationQueues.get(settingsPath) === settled) mutationQueues.delete(settingsPath);\n });\n return result;\n}\n\nasync function readSettingsDocumentForUpdate(\n settingsPath: string,\n legacySettingsPath: string | undefined,\n): Promise<SettingsDocument> {\n const canonical = await readSettingsSnapshot(settingsPath);\n if (canonical.result.kind === \"loaded\") return canonical.document ?? {};\n if (canonical.result.kind === \"invalid\") {\n throw invalidSettingsError(settingsPath, canonical.result.reason);\n }\n if (!legacySettingsPath) return {};\n\n const legacy = await readSettingsSnapshot(legacySettingsPath);\n const raced = await readSettingsSnapshot(settingsPath);\n if (raced.result.kind === \"loaded\") return raced.document ?? {};\n if (raced.result.kind === \"invalid\") {\n throw invalidSettingsError(settingsPath, raced.result.reason);\n }\n if (legacy.result.kind === \"invalid\") {\n throw invalidSettingsError(legacySettingsPath, legacy.result.reason);\n }\n return legacy.document ?? {};\n}\n\nasync function readSettingsSnapshot(settingsPath: string): Promise<SettingsSnapshot> {\n let contents: string;\n try {\n contents = await readSettingsContents(settingsPath);\n } catch (error: unknown) {\n if (isNodeError(error) && error.code === \"ENOENT\") return { result: { kind: \"missing\" } };\n return { result: { kind: \"invalid\", reason: safeReadError(error) } };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(contents) as unknown;\n } catch {\n return { result: { kind: \"invalid\", reason: \"invalid JSON\" } };\n }\n const settings = normalizePlanModeSettings(parsed);\n if (!settings || !isSettingsDocument(parsed)) {\n return { result: { kind: \"invalid\", reason: \"invalid settings shape\" } };\n }\n return { document: parsed, result: { kind: \"loaded\", settings } };\n}\n\nasync function readSettingsContents(settingsPath: string): Promise<string> {\n const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0);\n const handle = await open(settingsPath, flags);\n try {\n const stats = await handle.stat();\n if (!stats.isFile()) throw new Error(\"settings path is not a regular file\");\n if (stats.size > MAX_SETTINGS_BYTES) {\n throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);\n }\n const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);\n let offset = 0;\n while (offset < buffer.byteLength) {\n const { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n if (offset > MAX_SETTINGS_BYTES) {\n throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);\n }\n try {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, offset));\n } catch {\n throw new Error(\"settings file is not valid UTF-8\");\n }\n } finally {\n await handle.close();\n }\n}\n\nasync function publishSettings(\n settingsPath: string,\n document: SettingsDocument,\n signal?: AbortSignal,\n beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>,\n): Promise<void> {\n signal?.throwIfAborted();\n const contents = `${JSON.stringify(document, null, 2)}\\n`;\n if (Buffer.byteLength(contents, \"utf8\") > MAX_SETTINGS_BYTES) {\n throw new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);\n }\n const directory = dirname(settingsPath);\n await mkdir(directory, { recursive: true });\n signal?.throwIfAborted();\n const temporaryPath = join(directory, `.${basename(settingsPath)}.${process.pid}.${randomUUID()}.tmp`);\n try {\n await writeFile(temporaryPath, contents, {\n encoding: \"utf8\",\n flag: \"wx\",\n mode: 0o600,\n signal,\n });\n await beforeRename?.(temporaryPath, settingsPath);\n signal?.throwIfAborted();\n await rename(temporaryPath, settingsPath);\n } finally {\n await rm(temporaryPath, { force: true }).catch(() => undefined);\n }\n}\n\nfunction isSettingsDocument(value: unknown): value is SettingsDocument {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nasync function pathExists(path: string) {\n try {\n const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n await handle.close();\n return true;\n } catch (error: unknown) {\n return !(isNodeError(error) && error.code === \"ENOENT\");\n }\n}\n\nfunction invalidSettingsError(settingsPath: string, reason: string) {\n return new Error(`pi-plan-mode settings at ${settingsPath} are invalid: ${reason}`);\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n\nfunction safeReadError(error: unknown) {\n if (isNodeError(error) && error.code === \"ELOOP\") return \"settings path is not a regular file\";\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function configuredThinkingLevel(settings: PlanModeSettings): PlanModeFixedThinkingLevel | undefined {\n return settings.thinkingLevel === \"inherit\" ? undefined : settings.thinkingLevel;\n}\n\nexport function configuredImplementationPlanRetention(settings: PlanModeSettings): ImplementationPlanRetention {\n return settings.implementationPlanRetention ?? \"clear-on-start\";\n}\n\nexport function configuredImplementationModel(settings: PlanModeSettings): ImplementationModelOverride | undefined {\n return settings.defaultImplementationModel;\n}\n\nexport function configuredImplementationThinkingLevel(\n settings: PlanModeSettings,\n): PlanModeFixedThinkingLevel | undefined {\n return settings.defaultImplementationThinkingLevel;\n}\n\nexport function configuredPlanExportPath(settings: PlanModeSettings) {\n return settings.defaultPlanExportPath ?? DEFAULT_PLAN_EXPORT_PATH;\n}\n\nexport function configuredPlanModeToggleShortcut(settings: PlanModeSettings): KeyId | undefined {\n return settings.toggleShortcut;\n}\n", "import {\n findHistoryImplementationArtifact,\n injectActiveImplementationContext,\n isEmptyAssistantMessage,\n messageContainsExactPlanModeImplementationHandoff,\n messageContainsInactivePlanModeArtifact,\n messageContainsLegacyPlanModeContextArtifact,\n messageContainsPlanModeImplementationContextArtifact,\n messageContainsPlanModeImplementationHandoff,\n stripPlanModeCompletionCallsFromMessage,\n stripProposedPlanBlocksFromMessage,\n} from \"./message-transform.js\";\nimport type { ImplementationPlanRetention } from \"./settings.js\";\nimport type { ActiveImplementationPlan, PlanModeState } from \"./state.js\";\n\nexport function retentionLabel(retention: ImplementationPlanRetention) {\n return {\n \"clear-on-start\": \"Off \u2014 conversation history only\",\n \"clear-after-first-run\": \"Through first implementation run\",\n keep: \"Until manually cleared\",\n }[retention];\n}\n\nexport function implementationRetentionPreview(retention: ImplementationPlanRetention) {\n return {\n \"clear-on-start\": \"Plan reinjection: Off; use conversation history only.\",\n \"clear-after-first-run\": \"Plan reinjection: Through the first implementation run.\",\n keep: \"Plan reinjection: Until /plan exit.\",\n }[retention];\n}\n\nexport interface ImplementationContextResult {\n messages: unknown[];\n clearActiveImplementationId?: string;\n}\n\nexport interface ImplementationRetentionCoordinator {\n restore(activeImplementation: ActiveImplementationPlan | undefined): void;\n transformContext(messages: unknown[], state: PlanModeState): ImplementationContextResult;\n implementationSettled(activeImplementation: ActiveImplementationPlan | undefined): string | undefined;\n reset(): void;\n}\n\nexport function createImplementationRetentionCoordinator(): ImplementationRetentionCoordinator {\n let implementationWithDeliveredContext: string | undefined;\n let restoredImplementationAwaitingContext: string | undefined;\n\n return {\n restore(activeImplementation) {\n restoredImplementationAwaitingContext =\n activeImplementation && activeImplementation.retention !== \"keep\" ? activeImplementation.id : undefined;\n },\n transformContext(messages, state) {\n const messagesWithoutLegacyContext = messages.filter(\n (message) => !messageContainsLegacyPlanModeContextArtifact(message),\n );\n if (state.enabled) {\n return {\n messages: messagesWithoutLegacyContext.filter(\n (message) =>\n !messageContainsPlanModeImplementationContextArtifact(message) &&\n !messageContainsPlanModeImplementationHandoff(message),\n ),\n };\n }\n\n const activeImplementation = state.activeImplementation;\n const inactiveMessages = activeImplementation\n ? messagesWithoutLegacyContext\n : messagesWithoutLegacyContext.filter(\n (message) =>\n !messageContainsPlanModeImplementationContextArtifact(message) &&\n !messageContainsPlanModeImplementationHandoff(message),\n );\n const historyArtifact = activeImplementation ? undefined : findHistoryImplementationArtifact(inactiveMessages);\n const historyArtifactMessage = historyArtifact ? inactiveMessages[historyArtifact.messageIndex] : undefined;\n const historyToolCallMessage =\n historyArtifact?.toolCallMessageIndex !== undefined\n ? inactiveMessages[historyArtifact.toolCallMessageIndex]\n : undefined;\n const filteredMessages = inactiveMessages\n .filter((message) => message === historyArtifactMessage || !messageContainsInactivePlanModeArtifact(message))\n .map((message) =>\n message === historyArtifactMessage && historyArtifact?.kind === \"legacy\"\n ? message\n : stripProposedPlanBlocksFromMessage(message),\n )\n .map((message) =>\n stripPlanModeCompletionCallsFromMessage(\n message,\n message === historyToolCallMessage ? historyArtifact?.toolCallId : undefined,\n ),\n )\n .filter((message) => !isEmptyAssistantMessage(message));\n if (!activeImplementation) return { messages: filteredMessages };\n\n const contextualMessages = injectActiveImplementationContext(filteredMessages, activeImplementation);\n // A busy /plan implement queues its handoff behind an older run. Do not arm cleanup\n // until that exact handoff reaches context; a restored session has no older run to drain.\n const deliveredCurrentHandoff =\n restoredImplementationAwaitingContext === activeImplementation.id ||\n filteredMessages.some((message) =>\n messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan),\n );\n if (!deliveredCurrentHandoff) return { messages: contextualMessages };\n restoredImplementationAwaitingContext = undefined;\n\n if (activeImplementation.retention === \"clear-after-first-run\") {\n implementationWithDeliveredContext = activeImplementation.id;\n }\n return {\n messages: contextualMessages,\n clearActiveImplementationId:\n activeImplementation.retention === \"clear-on-start\" ? activeImplementation.id : undefined,\n };\n },\n implementationSettled(activeImplementation) {\n if (\n activeImplementation?.retention !== \"clear-after-first-run\" ||\n implementationWithDeliveredContext !== activeImplementation.id\n ) {\n return undefined;\n }\n implementationWithDeliveredContext = undefined;\n return activeImplementation.id;\n },\n reset() {\n implementationWithDeliveredContext = undefined;\n restoredImplementationAwaitingContext = undefined;\n },\n };\n}\n", "import { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport { type ExtensionContext, withFileMutationQueue } from \"@earendil-works/pi-coding-agent\";\nimport { DEFAULT_PLAN_EXPORT_PATH } from \"./settings.js\";\nimport type { PlanModeState } from \"./state.js\";\n\nexport { DEFAULT_PLAN_EXPORT_PATH };\n\nexport interface PlanExportResult {\n path: string;\n}\n\nexport interface PlanExportDestination {\n configuredPath: string;\n resolvedPath: string;\n}\n\nexport interface PlanExportLifecycle {\n signal: AbortSignal;\n isCurrent(): boolean;\n getState?(): PlanModeState;\n finishReady?(): void;\n}\n\nexport async function exportStoredPlan(\n state: PlanModeState,\n requestedPath: string | undefined,\n ctx: ExtensionContext,\n lifecycle?: PlanExportLifecycle,\n defaultPath = DEFAULT_PLAN_EXPORT_PATH,\n) {\n const plan =\n (state.enabled ? state.latestPlan : undefined)?.trim() ??\n state.savedPlan?.plan.trim() ??\n state.activeImplementation?.plan.trim();\n if (!plan) {\n const error = new Error(\"No completed plan is available to export. Use /plan finalize when planning is complete.\");\n if (!ctx.hasUI) throw error;\n ctx.ui.notify(error.message, \"warning\");\n return false;\n }\n\n const isCurrent = () =>\n !lifecycle || (lifecycle.isCurrent() && (!lifecycle.getState || lifecycle.getState() === state));\n let result: PlanExportResult;\n try {\n result = await exportPlanToFile(plan, requestedPath, ctx.cwd, lifecycle?.signal, isCurrent, defaultPath);\n } catch (error: unknown) {\n if (lifecycle?.signal.aborted || !isCurrent()) return false;\n if (!ctx.hasUI) throw error;\n const detail = error instanceof Error ? error.message : String(error);\n ctx.ui.notify(safeNotification(`Unable to export plan: ${detail}`), \"error\");\n return false;\n }\n\n if (!isCurrent()) return false;\n const finishedReady = state.enabled && Boolean(state.latestPlan?.trim()) && lifecycle?.finishReady !== undefined;\n if (finishedReady) lifecycle.finishReady?.();\n const detail = finishedReady ? \" Plan mode disabled.\" : \"\";\n ctx.ui.notify(safeNotification(`Plan exported to ${result.path}.${detail}`), \"info\");\n return true;\n}\n\nexport async function exportPlanToFile(\n plan: string,\n requestedPath: string | undefined,\n cwd: string,\n signal?: AbortSignal,\n isCurrent: () => boolean = () => true,\n defaultPath = DEFAULT_PLAN_EXPORT_PATH,\n): Promise<PlanExportResult> {\n const path = resolvePlanExportPath(requestedPath, cwd, defaultPath);\n await withFileMutationQueue(path, async () => {\n throwIfCancelled(signal, isCurrent);\n await mkdir(dirname(path), { recursive: true });\n throwIfCancelled(signal, isCurrent);\n try {\n await writeFile(path, `${plan}\\n`, { encoding: \"utf8\", flag: \"wx\" });\n } catch (error: unknown) {\n if (isNodeError(error) && error.code === \"EEXIST\") {\n throw new Error(`Plan export target already exists: ${path}. Choose another path or remove it first.`);\n }\n throw error;\n }\n });\n return { path };\n}\n\nexport function planExportDestination(defaultPath: string, cwd: string): PlanExportDestination {\n return {\n configuredPath: safeNotification(defaultPath),\n resolvedPath: safeNotification(resolvePlanExportPath(undefined, cwd, defaultPath)),\n };\n}\n\nexport function resolvePlanExportPath(\n requestedPath: string | undefined,\n cwd: string,\n defaultPath = DEFAULT_PLAN_EXPORT_PATH,\n) {\n const rawPath = requestedPath?.trim() || defaultPath;\n const normalizedPath = rawPath.startsWith(\"@\") ? rawPath.slice(1) : rawPath;\n if (!normalizedPath.trim()) throw new Error(\"Plan export path must not be empty.\");\n if (normalizedPath.includes(\"\\0\")) {\n throw new Error(\"Plan export path must not contain NUL bytes.\");\n }\n return resolve(cwd, normalizedPath);\n}\n\nfunction safeNotification(value: string) {\n let sanitized = \"\";\n for (const character of stripVTControlCharacters(value)) {\n const codePoint = character.codePointAt(0);\n sanitized +=\n codePoint !== undefined && codePoint > 0x1f && !(codePoint >= 0x7f && codePoint <= 0x9f) ? character : \" \";\n }\n return sanitized;\n}\n\nfunction throwIfCancelled(signal: AbortSignal | undefined, isCurrent: () => boolean) {\n if (!signal?.aborted && isCurrent()) return;\n throw signal?.reason instanceof Error ? signal.reason : new DOMException(\"Plan export cancelled\", \"AbortError\");\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport type { QuestionnaireAnswer, QuestionnaireQuestion, RunQuestionnaireResult } from \"@narumitw/pi-tui-kit\";\n\nexport const PLAN_MODE_QUESTION_TOOL_NAME = \"plan_mode_question\";\nexport const MAX_PLAN_MODE_RESPONSE_LENGTH = 4_000;\n\nexport type PlanModeQuestionOption = {\n label: string;\n description?: string;\n};\n\nexport type PlanModeQuestion = {\n id: string;\n header: string;\n question: string;\n options: PlanModeQuestionOption[];\n};\n\nexport type PlanModeQuestionAnswer = {\n id: string;\n header: string;\n question: string;\n answer: string;\n wasCustom: boolean;\n optionIndex?: number;\n note?: string;\n};\n\ntype PlanModeQuestionReason = \"cancelled\" | \"ui_unavailable\" | \"plan_mode_inactive\" | \"invalid_input\";\n\ntype PlanModeQuestionDetails = {\n cancelled: boolean;\n reason?: PlanModeQuestionReason;\n questions: PlanModeQuestion[];\n answers?: PlanModeQuestionAnswer[];\n};\n\nexport const PLAN_MODE_QUESTION_PARAMS = {\n type: \"object\",\n additionalProperties: false,\n required: [\"questions\"],\n properties: {\n questions: {\n type: \"array\",\n minItems: 1,\n maxItems: 3,\n description: \"Questions to show the user. Prefer 1 and do not exceed 3.\",\n items: {\n type: \"object\",\n additionalProperties: false,\n required: [\"id\", \"header\", \"question\", \"options\"],\n properties: {\n id: {\n type: \"string\",\n description: \"Stable identifier for mapping answers (snake_case).\",\n },\n header: {\n type: \"string\",\n description: \"Short header label shown in the UI (12 or fewer chars).\",\n },\n question: { type: \"string\", description: \"Single-sentence prompt shown to the user.\" },\n options: {\n type: \"array\",\n minItems: 2,\n maxItems: 4,\n description:\n \"Provide 2-4 mutually exclusive choices. Put the recommended option first when there is a clear default.\",\n items: {\n type: \"object\",\n additionalProperties: false,\n required: [\"label\", \"description\"],\n properties: {\n label: { type: \"string\", description: \"User-facing label (1-5 words).\" },\n description: {\n type: \"string\",\n description: \"One short sentence explaining impact/tradeoff if selected.\",\n },\n },\n },\n },\n },\n },\n },\n },\n} as const;\n\ntype NormalizePlanModeQuestionParamsResult = { ok: true; questions: PlanModeQuestion[] } | { ok: false; error: string };\n\nexport function normalizePlanModeQuestionParams(input: unknown): NormalizePlanModeQuestionParamsResult {\n if (!isRecord(input) || !Array.isArray(input.questions)) {\n return { ok: false, error: \"questions must be an array\" };\n }\n if (input.questions.length < 1 || input.questions.length > 3) {\n return { ok: false, error: \"questions must contain 1-3 items\" };\n }\n\n const questions: PlanModeQuestion[] = [];\n for (const [questionIndex, rawQuestion] of input.questions.entries()) {\n if (!isRecord(rawQuestion)) {\n return { ok: false, error: `question ${questionIndex + 1} must be an object` };\n }\n const id = stringField(rawQuestion.id);\n const header = stringField(rawQuestion.header);\n const question = stringField(rawQuestion.question);\n if (!id || !header || !question) {\n return {\n ok: false,\n error: `question ${questionIndex + 1} requires non-empty id, header, and question`,\n };\n }\n if (!Array.isArray(rawQuestion.options)) {\n return { ok: false, error: `question ${questionIndex + 1} options must be an array` };\n }\n if (rawQuestion.options.length < 2 || rawQuestion.options.length > 4) {\n return { ok: false, error: `question ${questionIndex + 1} options must contain 2-4 items` };\n }\n const options: PlanModeQuestionOption[] = [];\n for (const [optionIndex, rawOption] of rawQuestion.options.entries()) {\n if (!isRecord(rawOption)) {\n return {\n ok: false,\n error: `question ${questionIndex + 1} option ${optionIndex + 1} must be an object`,\n };\n }\n const label = stringField(rawOption.label);\n if (!label) {\n return {\n ok: false,\n error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a label`,\n };\n }\n const description = stringField(rawOption.description);\n if (!description) {\n return {\n ok: false,\n error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a description`,\n };\n }\n options.push({ label, description });\n }\n questions.push({ id, header, question, options });\n }\n return { ok: true, questions };\n}\n\nexport async function answerPlanModeQuestions(\n questions: PlanModeQuestion[],\n ctx: ExtensionContext,\n lifecycle: { isCurrent(): boolean; isEnabled(): boolean },\n) {\n const answers = await askPlanModeQuestions(questions, ctx, () => lifecycle.isCurrent() && lifecycle.isEnabled());\n if (!lifecycle.isCurrent()) {\n return planModeQuestionCancelled(\n questions,\n \"cancelled\",\n \"Plan-mode question cancelled because the session changed.\",\n );\n }\n if (!lifecycle.isEnabled()) {\n return planModeQuestionCancelled(\n questions,\n \"plan_mode_inactive\",\n \"Plan-mode question cancelled because Plan mode is no longer active.\",\n );\n }\n if (!answers) {\n return planModeQuestionCancelled(questions, \"cancelled\", \"User cancelled the Plan-mode question prompt.\");\n }\n return planModeQuestionAnswered(questions, answers);\n}\n\nexport async function askPlanModeQuestions(\n questions: PlanModeQuestion[],\n ctx: ExtensionContext,\n shouldContinue: () => boolean = () => true,\n): Promise<PlanModeQuestionAnswer[] | undefined> {\n const { runQuestionnaire, sanitizeTerminalText } = await import(\"@narumitw/pi-tui-kit\");\n if (!shouldContinue()) return undefined;\n const runnerQuestions: QuestionnaireQuestion<string>[] = questions.map((question, index) => ({\n id: String(index),\n header: displayText(question.header, `Question ${index + 1}`, sanitizeTerminalText),\n prompt: displayText(question.question, `Question ${index + 1}`, sanitizeTerminalText),\n options: question.options.map((option, optionIndex) => ({\n ...option,\n label: displayText(option.label, `Option ${optionIndex + 1}`, sanitizeTerminalText),\n })),\n }));\n const result = await runQuestionnaire(ctx, {\n blocked: { kind: \"question\", message: \"Answer Plan mode questions\" },\n questions: runnerQuestions,\n allowNotes: true,\n maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,\n signal: ctx.signal,\n isCurrent: shouldContinue,\n });\n if (!shouldContinue()) return undefined;\n return mapQuestionnaireResult(questions, result);\n}\n\nfunction mapQuestionnaireResult(\n questions: PlanModeQuestion[],\n result: RunQuestionnaireResult<string>,\n): PlanModeQuestionAnswer[] | undefined {\n if (result.kind !== \"submitted\") return undefined;\n if (result.answers.length !== questions.length) {\n throw new Error(\"Questionnaire returned an incomplete answer set\");\n }\n\n const answers = new Map<number, QuestionnaireAnswer<string>>();\n for (const answer of result.answers) {\n const index = Number(answer.questionId);\n if (!Number.isSafeInteger(index) || String(index) !== answer.questionId || !questions[index]) {\n throw new Error(\"Questionnaire returned an answer for an unknown question\");\n }\n if (answers.has(index)) throw new Error(\"Questionnaire returned duplicate answers\");\n if (answer.wasCustom) {\n if (answer.optionIndex !== undefined) {\n throw new Error(\"Questionnaire returned a custom answer with an option index\");\n }\n if (!answer.answer.trim()) return undefined;\n } else if (answer.optionIndex === undefined || !questions[index]?.options[answer.optionIndex - 1]) {\n throw new Error(\"Questionnaire returned an invalid selected option\");\n }\n answers.set(index, answer);\n }\n\n return questions.map((question, index) => {\n const answer = answers.get(index);\n if (!answer) throw new Error(\"Questionnaire returned an incomplete answer set\");\n const answerText = answer.wasCustom\n ? answer.answer\n : (question.options[(answer.optionIndex ?? 0) - 1]?.label ?? answer.answer);\n return answerFor(question, answerText, {\n wasCustom: answer.wasCustom,\n optionIndex: answer.optionIndex,\n note: answer.note,\n });\n });\n}\n\nfunction displayText(value: string, fallback: string, sanitize: (value: string) => string): string {\n const sanitized = sanitize(value);\n return sanitized.trim() ? sanitized : fallback;\n}\n\nfunction answerFor(\n question: PlanModeQuestion,\n answer: string,\n options: { wasCustom: boolean; optionIndex?: number; note?: string },\n): PlanModeQuestionAnswer {\n const result: PlanModeQuestionAnswer = {\n id: question.id,\n header: question.header,\n question: question.question,\n answer,\n wasCustom: options.wasCustom,\n };\n if (options.optionIndex !== undefined) result.optionIndex = options.optionIndex;\n if (options.note !== undefined) result.note = options.note;\n return result;\n}\n\nexport function planModeQuestionAnswered(questions: PlanModeQuestion[], answers: PlanModeQuestionAnswer[]) {\n return {\n content: [{ type: \"text\" as const, text: formatPlanModeQuestionPayload({ cancelled: false, answers }) }],\n details: { cancelled: false, questions, answers } satisfies PlanModeQuestionDetails,\n };\n}\n\nexport function planModeQuestionCancelled(\n questions: PlanModeQuestion[],\n reason: PlanModeQuestionReason,\n message: string,\n) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: formatPlanModeQuestionPayload({ cancelled: true, reason, message }),\n },\n ],\n details: { cancelled: true, reason, questions } satisfies PlanModeQuestionDetails,\n };\n}\n\nfunction formatPlanModeQuestionPayload(payload: {\n cancelled: boolean;\n reason?: PlanModeQuestionReason;\n message?: string;\n answers?: PlanModeQuestionAnswer[];\n}) {\n return JSON.stringify(payload, null, 2);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction stringField(value: unknown) {\n return typeof value === \"string\" ? value.trim() : undefined;\n}\n", "import type { ToolInfo } from \"@earendil-works/pi-coding-agent\";\n\nexport type PlanModeToolAvailability = \"available\" | \"inactive\" | \"hidden\" | \"model-only\" | \"unsupported\";\n\n/** Pi's active set is model declaration, not the complete callable registry. */\nexport function planModeToolAvailability(\n tool: ToolInfo,\n activeNames: ReadonlySet<string>,\n route: \"selection\" | \"model\" | \"nested\" = \"selection\",\n): PlanModeToolAvailability {\n switch (tool.exposure) {\n case \"hidden\":\n return \"hidden\";\n case \"model-only\":\n if (route === \"nested\") return \"model-only\";\n return activeNames.has(tool.name) ? \"available\" : \"inactive\";\n case \"codemode\":\n case \"deferred\":\n if (route !== \"model\") return \"available\";\n return activeNames.has(tool.name) ? \"available\" : \"inactive\";\n case undefined: // Older Pi versions exposed only directly active tools.\n case \"direct\":\n return activeNames.has(tool.name) ? \"available\" : \"inactive\";\n default:\n return \"unsupported\";\n }\n}\n", "import { isAbsolute, normalize } from \"node:path\";\nimport type { ToolInfo } from \"@earendil-works/pi-coding-agent\";\n\nexport const BUILTIN_SAFE_GIT_SUBCOMMANDS = [\n \"status\",\n \"log\",\n \"diff\",\n \"show\",\n \"branch\",\n \"remote\",\n \"ls-files\",\n \"grep\",\n] as const;\nexport const CONFIGURABLE_SAFE_GIT_SUBCOMMANDS = [\n \"rev-parse\",\n \"blame\",\n \"describe\",\n \"merge-base\",\n \"ls-tree\",\n \"cat-file\",\n] as const;\nexport const SAFE_GIT_SUBCOMMANDS = [...BUILTIN_SAFE_GIT_SUBCOMMANDS, ...CONFIGURABLE_SAFE_GIT_SUBCOMMANDS] as const;\nexport const SAFE_GH_SUBCOMMAND_PATHS = [\"pr view\", \"pr list\", \"issue view\", \"issue list\"] as const;\n\nexport type BuiltinSafeGitSubcommand = (typeof BUILTIN_SAFE_GIT_SUBCOMMANDS)[number];\nexport type ConfigurableSafeGitSubcommand = (typeof CONFIGURABLE_SAFE_GIT_SUBCOMMANDS)[number];\nexport type SafeGitSubcommand = (typeof SAFE_GIT_SUBCOMMANDS)[number];\nexport type SafeGhSubcommandPath = (typeof SAFE_GH_SUBCOMMAND_PATHS)[number];\nexport interface SafeSubcommands {\n [command: string]: string[] | undefined;\n}\n\nexport const SAFE_BUILTIN_PLAN_TOOLS = new Set([\"read\", \"bash\", \"powershell\", \"grep\", \"find\", \"ls\"]);\nexport type PlanModeToolPolicy = \"read-only\" | \"limited\" | \"user-opt-in\" | \"blocked\";\n\nconst BLOCKED_BUILTIN_TOOLS = new Set([\"edit\", \"write\"]);\nconst MUTATING_COMMANDS = new Set([\n \"rm\",\n \"rmdir\",\n \"mv\",\n \"cp\",\n \"mkdir\",\n \"touch\",\n \"chmod\",\n \"chown\",\n \"chgrp\",\n \"ln\",\n \"tee\",\n \"truncate\",\n \"dd\",\n \"sudo\",\n \"su\",\n \"kill\",\n \"pkill\",\n \"killall\",\n \"reboot\",\n \"shutdown\",\n \"vim\",\n \"vi\",\n \"nano\",\n \"emacs\",\n \"code\",\n \"subl\",\n]);\nconst READ_ONLY_POWERSHELL_COMMANDS = new Set([\n \"format-list\",\n \"format-table\",\n \"get-childitem\",\n \"get-content\",\n \"get-item\",\n \"get-location\",\n \"measure-object\",\n \"out-string\",\n \"resolve-path\",\n \"select-string\",\n \"sort-object\",\n \"test-path\",\n \"write-output\",\n]);\nconst READ_ONLY_COMMANDS = new Set([\n \"cat\",\n \"head\",\n \"tail\",\n \"grep\",\n \"find\",\n \"ls\",\n \"pwd\",\n \"echo\",\n \"printf\",\n \"wc\",\n \"sort\",\n \"uniq\",\n \"diff\",\n \"file\",\n \"stat\",\n \"du\",\n \"df\",\n \"tree\",\n \"which\",\n \"whereis\",\n \"type\",\n \"printenv\",\n \"uname\",\n \"whoami\",\n \"id\",\n \"date\",\n \"uptime\",\n \"ps\",\n \"jq\",\n \"rg\",\n \"fd\",\n \"bat\",\n \"eza\",\n]);\n\n// `-i` edits in place for sed. For these inspection commands it is case-insensitive\n// search or inode output, which is how plan mode reads markdown and other text.\nconst INSPECTION_CASE_FLAG_COMMANDS = new Set([\"rg\", \"grep\", \"git\", \"diff\", \"fd\", \"ls\", \"sort\", \"find\", \"bat\", \"eza\"]);\n\nexport function isBuiltinTool(tool: ToolInfo) {\n const source = tool.sourceInfo;\n if (source?.source !== \"builtin\") return false;\n // Core tools own builtin:<name>; built-in extensions may own many tools or\n // expose model-only orchestration. Missing paths preserve legacy core policy.\n return !source.path || (source.path === `builtin:${tool.name}` && tool.exposure !== \"model-only\");\n}\n\nexport function classifyPlanModeTool(tool: ToolInfo): PlanModeToolPolicy {\n if (!tool.sourceInfo?.source) return \"blocked\";\n if (!isBuiltinTool(tool)) return \"user-opt-in\";\n if (BLOCKED_BUILTIN_TOOLS.has(tool.name)) return \"blocked\";\n if (tool.name === \"bash\" || tool.name === \"powershell\") return \"limited\";\n return SAFE_BUILTIN_PLAN_TOOLS.has(tool.name) ? \"read-only\" : \"blocked\";\n}\n\nexport function canSelectToolInPlanMode(tool: ToolInfo) {\n return classifyPlanModeTool(tool) !== \"blocked\";\n}\n\nexport function readCommand(input: unknown) {\n const command = input as { command?: unknown } | undefined;\n return typeof command?.command === \"string\" ? command.command : \"\";\n}\n\nexport function findBlockedCommandSegment(\n command: string,\n safeSubcommands: SafeSubcommands = {},\n workingDirectory?: string,\n platform: NodeJS.Platform = process.platform,\n): string | undefined {\n const segments = splitShellSegments(command);\n if (!segments || segments.length === 0) return command.trim() || \"(empty command)\";\n return segments.find((segment) => !isSafeSegment(segment, safeSubcommands, workingDirectory, platform));\n}\n\nexport function isSafeCommand(\n command: string,\n safeSubcommands: SafeSubcommands = {},\n workingDirectory?: string,\n platform: NodeJS.Platform = process.platform,\n) {\n return findBlockedCommandSegment(command, safeSubcommands, workingDirectory, platform) === undefined;\n}\n\nexport function findBlockedPowerShellCommandSegment(\n command: string,\n safeSubcommands: SafeSubcommands = {},\n workingDirectory?: string,\n): string | undefined {\n const segments = splitPowerShellSegments(command);\n if (!segments || segments.length === 0) return command.trim() || \"(empty command)\";\n return segments.find((segment) => !isSafePowerShellSegment(segment, safeSubcommands, workingDirectory));\n}\n\nexport function isSafePowerShellCommand(\n command: string,\n safeSubcommands: SafeSubcommands = {},\n workingDirectory?: string,\n) {\n return findBlockedPowerShellCommandSegment(command, safeSubcommands, workingDirectory) === undefined;\n}\n\nfunction matchesConfiguredSafeSubcommand(command: string, safeSubcommands: SafeSubcommands) {\n const candidate = command.trimStart();\n return Object.entries(safeSubcommands).some(([configuredCommand, subcommands]) =>\n subcommands?.some((subcommand) => {\n const prefix = `${configuredCommand.trim()} ${subcommand.trim()}`;\n if (!configuredCommand.trim() || !subcommand.trim() || !candidate.startsWith(prefix)) {\n return false;\n }\n const boundary = candidate[prefix.length];\n return boundary === undefined || /[\\s;&|<>()]/.test(boundary);\n }),\n );\n}\n\nfunction splitPowerShellSegments(command: string): string[] | undefined {\n const trimmed = command.trim();\n if (!trimmed || /[\\n\\r`\\u2018-\\u201e]/.test(trimmed)) return undefined;\n\n const segments: string[] = [];\n let quote: \"'\" | '\"' | undefined;\n let start = 0;\n for (let index = 0; index < trimmed.length; index += 1) {\n const character = trimmed[index];\n if (quote === \"'\") {\n if (character !== \"'\") continue;\n if (trimmed[index + 1] === \"'\") {\n index += 1;\n continue;\n }\n quote = undefined;\n continue;\n }\n if (quote === '\"') {\n if (character === \"$\" || character === \"`\") return undefined;\n if (character === '\"') quote = undefined;\n continue;\n }\n if (character === \"'\" || character === '\"') {\n quote = character;\n continue;\n }\n if ([\"$\", \"@\", \"#\", \"!\", \"?\", \"{\", \"}\", \"(\", \")\", \"[\", \"]\", \">\", \"<\"].includes(character)) {\n return undefined;\n }\n const next = trimmed[index + 1];\n if (character === \"&\" || (character === \"|\" && next === \"|\")) return undefined;\n const separatorLength = character === \";\" || character === \"|\" ? 1 : 0;\n if (separatorLength === 0) continue;\n const segment = trimmed.slice(start, index).trim();\n if (!segment) return undefined;\n segments.push(segment);\n index += separatorLength - 1;\n start = index + 1;\n }\n if (quote) return undefined;\n const finalSegment = trimmed.slice(start).trim();\n if (!finalSegment) return undefined;\n segments.push(finalSegment);\n return segments;\n}\n\nfunction isSafePowerShellSegment(segment: string, safeSubcommands: SafeSubcommands, workingDirectory?: string) {\n if (matchesConfiguredSafeSubcommand(segment, safeSubcommands)) return true;\n const tokens = powerShellWords(segment);\n if (!tokens || tokens.length === 0 || tokens.includes(\"--%\")) return false;\n const command = tokens[0]?.toLowerCase();\n if (!command) return false;\n const args = tokens.slice(1);\n if (READ_ONLY_POWERSHELL_COMMANDS.has(command)) return true;\n if (command === \"get-process\") return isSafeGetProcessArguments(args);\n if (command === \"get-service\") return isSafeGetServiceArguments(args);\n if (command !== \"git\" && command !== \"gh\") return false;\n return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);\n}\n\nfunction powerShellWords(segment: string): string[] | undefined {\n const words: string[] = [];\n let word = \"\";\n let hasWord = false;\n let quote: \"'\" | '\"' | undefined;\n for (let index = 0; index < segment.length; index += 1) {\n const character = segment[index];\n if (quote === \"'\") {\n if (character !== \"'\") {\n word += character;\n continue;\n }\n if (segment[index + 1] === \"'\") {\n word += \"'\";\n index += 1;\n continue;\n }\n quote = undefined;\n continue;\n }\n if (quote === '\"') {\n if (character === '\"') quote = undefined;\n else word += character;\n continue;\n }\n if (character === \"'\" || character === '\"') {\n quote = character;\n hasWord = true;\n } else if (/\\s/.test(character)) {\n if (hasWord) words.push(word);\n word = \"\";\n hasWord = false;\n } else {\n word += character;\n hasWord = true;\n }\n }\n if (quote) return undefined;\n if (hasWord) words.push(word);\n return words;\n}\n\nfunction splitShellSegments(command: string): string[] | undefined {\n const trimmed = command.trim();\n if (!trimmed || /[\\n\\r`]/.test(trimmed)) return undefined;\n\n const segments: string[] = [];\n let quote: \"'\" | '\"' | undefined;\n let escaped = false;\n let start = 0;\n for (let index = 0; index < trimmed.length; index += 1) {\n const character = trimmed[index];\n if (escaped) {\n escaped = false;\n continue;\n }\n if (character === \"\\\\\" && quote !== \"'\") {\n escaped = true;\n continue;\n }\n if (quote) {\n if (character === quote) quote = undefined;\n continue;\n }\n if (character === \"'\" || character === '\"') {\n quote = character;\n continue;\n }\n if (character === \">\" || character === \"<\" || character === \"(\" || character === \")\") {\n return undefined;\n }\n const next = trimmed[index + 1];\n if (character === \"&\" && next !== \"&\") return undefined;\n const separatorLength =\n character === \";\" || character === \"|\" ? (next === character ? 2 : 1) : character === \"&\" && next === \"&\" ? 2 : 0;\n if (separatorLength === 0) continue;\n const segment = trimmed.slice(start, index).trim();\n if (!segment) return undefined;\n segments.push(segment);\n index += separatorLength - 1;\n start = index + 1;\n }\n if (quote || escaped) return undefined;\n const finalSegment = trimmed.slice(start).trim();\n if (!finalSegment) return undefined;\n segments.push(finalSegment);\n return segments;\n}\n\nfunction isSafeSegment(\n segment: string,\n safeSubcommands: SafeSubcommands,\n workingDirectory: string | undefined,\n platform: NodeJS.Platform,\n) {\n if (matchesConfiguredSafeSubcommand(segment, safeSubcommands)) return true;\n if (hasShellExpansion(segment) || /(^|\\s)[A-Za-z_][A-Za-z0-9_]*=/.test(segment)) {\n return false;\n }\n const tokens = shellWords(segment);\n if (!tokens || tokens.length === 0) return false;\n const command = tokens[0]?.toLowerCase();\n if (!command || MUTATING_COMMANDS.has(command)) return false;\n const args = tokens.slice(1);\n if (!hasSafeArguments(command, args)) return false;\n if (command === \"hostname\") return args.length === 0;\n if (command === \"tasklist\") return platform === \"win32\" && isSafeTasklistArguments(args);\n if (READ_ONLY_COMMANDS.has(command)) return true;\n return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);\n}\n\nfunction hasShellExpansion(segment: string) {\n let quote: \"'\" | '\"' | undefined;\n let escaped = false;\n for (const character of segment) {\n if (escaped) {\n escaped = false;\n continue;\n }\n if (character === \"\\\\\" && quote !== \"'\") {\n escaped = true;\n continue;\n }\n if (quote) {\n if (character === quote) quote = undefined;\n else if (character === \"$\" && quote === '\"') return true;\n continue;\n }\n if (character === \"'\" || character === '\"') {\n quote = character;\n continue;\n }\n if ([\"$\", \"*\", \"?\", \"[\", \"{\"].includes(character)) return true;\n }\n return false;\n}\n\nfunction shellWords(segment: string): string[] | undefined {\n const words: string[] = [];\n let word = \"\";\n let quote: \"'\" | '\"' | undefined;\n let escaped = false;\n for (const character of segment) {\n if (escaped) {\n word += character;\n escaped = false;\n continue;\n }\n if (character === \"\\\\\" && quote !== \"'\") {\n escaped = true;\n continue;\n }\n if (quote) {\n if (character === quote) quote = undefined;\n else word += character;\n continue;\n }\n if (character === \"'\" || character === '\"') quote = character;\n else if (/\\s/.test(character)) {\n if (word) words.push(word);\n word = \"\";\n } else word += character;\n }\n if (quote || escaped) return undefined;\n if (word) words.push(word);\n return words;\n}\n\nfunction hasSafeArguments(command: string, args: string[]) {\n const forbidden = new Set([\"--in-place\", \"--fix\", \"--write\", \"-delete\", \"--delete\"]);\n if (!INSPECTION_CASE_FLAG_COMMANDS.has(command)) forbidden.add(\"-i\");\n if (args.some((argument) => forbidden.has(argument))) return false;\n if (\n command === \"sed\" &&\n args.some(\n (argument) => argument.startsWith(\"--in-place=\") || (/^-[^-]+/.test(argument) && argument.slice(1).includes(\"i\")),\n )\n ) {\n return false;\n }\n if (\n command === \"find\" &&\n args.some((argument) =>\n [\"-exec\", \"-execdir\", \"-ok\", \"-okdir\", \"-fprint\", \"-fprint0\", \"-fprintf\", \"-fls\"].includes(argument),\n )\n ) {\n return false;\n }\n if (command === \"date\" && args.some((argument) => argument === \"-s\" || argument.startsWith(\"--set\"))) {\n return false;\n }\n if (\n (command === \"sort\" || command === \"tree\") &&\n args.some(\n (argument) =>\n argument === \"-o\" ||\n (argument.startsWith(\"-o\") && !argument.startsWith(\"--\")) ||\n argument.startsWith(\"--output\"),\n )\n ) {\n return false;\n }\n if (\n command === \"sort\" &&\n args.some(\n (argument) =>\n argument === \"-T\" ||\n (argument.startsWith(\"-T\") && argument.length > 2) ||\n argument.startsWith(\"--temporary-directory\") ||\n argument.startsWith(\"--compress-program\"),\n )\n ) {\n return false;\n }\n if (command === \"diff\" && args.some((argument) => argument === \"--output\" || argument.startsWith(\"--output=\"))) {\n return false;\n }\n if (command === \"uniq\" && args.filter((argument) => !argument.startsWith(\"-\")).length > 1) {\n return false;\n }\n if (\n command === \"fd\" &&\n args.some((argument) =>\n [\"-x\", \"-X\", \"--exec\", \"--exec-batch\"].some((flag) => argument === flag || argument.startsWith(`${flag}=`)),\n )\n ) {\n return false;\n }\n if (command === \"rg\" && args.some((argument) => argument === \"--pre\" || argument.startsWith(\"--pre=\"))) {\n return false;\n }\n if (command === \"bat\" && args.some((argument) => argument === \"--pager\" || argument.startsWith(\"--pager=\"))) {\n return false;\n }\n return true;\n}\n\ntype ArgumentValidator = (args: string[]) => boolean;\nconst allowReadOnlyArguments: ArgumentValidator = () => true;\nconst BUILTIN_GIT_VALIDATORS: Record<BuiltinSafeGitSubcommand, ArgumentValidator> = {\n status: allowReadOnlyArguments,\n log: allowReadOnlyArguments,\n diff: allowReadOnlyArguments,\n show: allowReadOnlyArguments,\n branch: isSafeGitBranchArguments,\n remote: isSafeGitRemoteArguments,\n \"ls-files\": allowReadOnlyArguments,\n grep: isSafeGitGrepArguments,\n};\nconst CONFIGURABLE_GIT_VALIDATORS: Record<ConfigurableSafeGitSubcommand, ArgumentValidator> = {\n \"rev-parse\": allowReadOnlyArguments,\n blame: allowReadOnlyArguments,\n describe: allowReadOnlyArguments,\n \"merge-base\": allowReadOnlyArguments,\n \"ls-tree\": allowReadOnlyArguments,\n \"cat-file\": isSafeGitCatFileArguments,\n};\nconst GH_VALIDATORS: Record<SafeGhSubcommandPath, ArgumentValidator> = {\n \"pr view\": isSafeGhReadArguments,\n \"pr list\": isSafeGhReadArguments,\n \"issue view\": isSafeGhReadArguments,\n \"issue list\": isSafeGhReadArguments,\n};\n\nfunction isSafeStructuredCommand(\n command: string,\n args: string[],\n safeSubcommands: SafeSubcommands,\n workingDirectory?: string,\n) {\n if (command === \"git\") return isSafeGitCommand(args, safeSubcommands, workingDirectory);\n if (command === \"gh\") return isSafeGhCommand(args, safeSubcommands);\n\n const subcommandIndex = args.findIndex((argument) => !argument.startsWith(\"-\"));\n const subcommand = args[subcommandIndex]?.toLowerCase();\n const subcommandArgs = subcommandIndex >= 0 ? args.slice(subcommandIndex + 1) : [];\n if (command === \"sed\") {\n const script = args.find((argument) => !argument.startsWith(\"-\"));\n return (\n Boolean(script) &&\n (args.includes(\"-n\") || args.some((argument) => /^-[^-]*n[^-]*$/.test(argument))) &&\n /^\\d+(,\\d+)?p$/.test(script ?? \"\")\n );\n }\n if ([\"node\", \"python\", \"python3\", \"tsc\", \"biome\", \"ruff\", \"ty\"].includes(command)) {\n if (args.includes(\"--version\")) return true;\n return (\n command === \"tsc\" &&\n args.includes(\"--noEmit\") &&\n !args.some(\n (argument) =>\n argument === \"--incremental\" ||\n argument.startsWith(\"--incremental=\") ||\n argument === \"--tsBuildInfoFile\" ||\n argument.startsWith(\"--tsBuildInfoFile=\") ||\n argument === \"--generateTrace\" ||\n argument.startsWith(\"--generateTrace=\"),\n )\n );\n }\n if (command === \"npm\") {\n if (subcommand === \"audit\" && subcommandArgs.includes(\"fix\")) return false;\n if ([\"list\", \"ls\", \"view\", \"info\", \"search\", \"outdated\", \"audit\", \"test\"].includes(subcommand ?? \"\")) {\n return true;\n }\n return subcommand === \"run\" && [\"test\", \"check\", \"typecheck\", \"lint\"].includes(args[1] ?? \"\");\n }\n if ([\"cargo\", \"go\", \"pytest\", \"vitest\", \"jest\"].includes(command)) {\n return [\"test\", \"check\"].includes(subcommand ?? \"\") || [\"pytest\", \"vitest\", \"jest\"].includes(command);\n }\n return false;\n}\n\nfunction isSafeTasklistArguments(args: string[]) {\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index]?.toLowerCase();\n if ([\"/v\", \"/nh\", \"/svc\"].includes(argument ?? \"\")) continue;\n if (argument === \"/fo\") {\n const format = args[index + 1]?.toLowerCase();\n if (!format || ![\"table\", \"list\", \"csv\"].includes(format)) return false;\n index += 1;\n continue;\n }\n if (argument === \"/fi\") {\n const filter = args[index + 1];\n if (!filter || filter.startsWith(\"/\")) return false;\n index += 1;\n continue;\n }\n if (argument === \"/m\") {\n const module = args[index + 1];\n if (module && !module.startsWith(\"/\")) index += 1;\n continue;\n }\n return false;\n }\n return true;\n}\n\nfunction isSafeGetProcessArguments(args: string[]) {\n return hasSafePowerShellQueryArguments(\n args,\n new Set([\"-module\", \"-fileversioninfo\", \"-includeusername\"]),\n new Set([\"-name\", \"-id\"]),\n );\n}\n\nfunction isSafeGetServiceArguments(args: string[]) {\n return hasSafePowerShellQueryArguments(\n args,\n new Set([\"-dependentservices\", \"-requiredservices\"]),\n new Set([\"-name\", \"-displayname\", \"-include\", \"-exclude\"]),\n );\n}\n\nfunction hasSafePowerShellQueryArguments(\n args: string[],\n switches: ReadonlySet<string>,\n valueOptions: ReadonlySet<string>,\n) {\n let positionalValues = 0;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n const normalized = argument?.toLowerCase();\n if (!argument || !normalized) return false;\n if (!argument.startsWith(\"-\")) {\n positionalValues += 1;\n if (positionalValues > 1) return false;\n continue;\n }\n if (switches.has(normalized)) continue;\n if (!valueOptions.has(normalized)) return false;\n const value = args[index + 1];\n if (!value || value.startsWith(\"-\")) return false;\n index += 1;\n }\n return true;\n}\n\nfunction isSafeGitCommand(args: string[], safeSubcommands: SafeSubcommands, workingDirectory?: string) {\n const subcommandIndex = parseGitGlobalOptions(args, workingDirectory);\n if (subcommandIndex === undefined) return false;\n const subcommand = args[subcommandIndex]?.toLowerCase();\n if (!subcommand || subcommand.startsWith(\"-\")) return false;\n const subcommandArgs = args.slice(subcommandIndex + 1);\n const builtinValidator = (BUILTIN_GIT_VALIDATORS as Record<string, ArgumentValidator>)[subcommand];\n const configuredValidator = (CONFIGURABLE_GIT_VALIDATORS as Record<string, ArgumentValidator>)[subcommand];\n const configured = safeSubcommands.git?.includes(subcommand as SafeGitSubcommand) === true;\n const validator = builtinValidator ?? (configured ? configuredValidator : undefined);\n return validator !== undefined && hasSafeGitArguments(subcommand, subcommandArgs) && validator(subcommandArgs);\n}\n\nfunction parseGitGlobalOptions(args: string[], workingDirectory?: string) {\n let index = 0;\n while (index < args.length) {\n const argument = args[index];\n if (argument === \"--no-pager\") {\n index += 1;\n continue;\n }\n if (argument !== \"-C\") break;\n const directory = args[index + 1];\n if (!directory || !isCurrentWorkingDirectory(directory, workingDirectory)) return undefined;\n index += 2;\n }\n return index;\n}\n\nfunction isCurrentWorkingDirectory(directory: string, workingDirectory?: string) {\n if (!workingDirectory || directory.split(/[\\\\/]+/u).includes(\"..\")) return false;\n if (normalize(directory) === \".\") return true;\n return isAbsolute(directory) && normalize(directory) === normalize(workingDirectory);\n}\n\nfunction hasSafeGitArguments(subcommand: string, args: string[]) {\n return !args.some(\n (argument) =>\n argument === \"--help\" ||\n argument === \"--show-signature\" ||\n argument.startsWith(\"--show-signature=\") ||\n argument.includes(\"%G\") ||\n argument === \"--output\" ||\n argument.startsWith(\"--output=\") ||\n argument === \"--ext-diff\" ||\n argument.startsWith(\"--ext-diff=\") ||\n argument === \"--textconv\" ||\n argument.startsWith(\"--textconv=\") ||\n argument === \"--paginate\" ||\n argument === \"--open-files-in-pager\" ||\n argument.startsWith(\"--open-files-in-pager=\") ||\n (subcommand === \"grep\" && (argument === \"-O\" || argument.startsWith(\"-O\"))),\n );\n}\n\nfunction isSafeGitCatFileArguments(args: string[]) {\n return !args.some(\n (argument) =>\n matchesLongOptionPrefix(argument, \"--filters\", \"--fi\") || matchesLongOptionPrefix(argument, \"--textconv\", \"--t\"),\n );\n}\n\nfunction isSafeGitGrepArguments(args: string[]) {\n return !args.some(\n (argument) =>\n matchesLongOptionPrefix(argument, \"--textconv\", \"--textc\") ||\n matchesLongOptionPrefix(argument, \"--open-files-in-pager\", \"--op\") ||\n matchesLongOptionPrefix(argument, \"--ext-grep\", \"--ext\"),\n );\n}\n\nfunction matchesLongOptionPrefix(argument: string, option: string, shortest: string) {\n const optionName = argument.split(\"=\", 1)[0] ?? \"\";\n return optionName.length >= shortest.length && option.startsWith(optionName);\n}\n\nfunction isSafeGitBranchArguments(args: string[]) {\n if (args.some((argument) => !argument.startsWith(\"-\"))) return false;\n return !args.some(\n (argument) =>\n /^-[^-]*[dDmMcCu]/.test(argument) ||\n matchesLongOptionPrefix(argument, \"--delete\", \"--del\") ||\n matchesLongOptionPrefix(argument, \"--move\", \"--mov\") ||\n matchesLongOptionPrefix(argument, \"--copy\", \"--cop\") ||\n matchesLongOptionPrefix(argument, \"--edit-description\", \"--e\") ||\n matchesLongOptionPrefix(argument, \"--unset-upstream\", \"--u\") ||\n matchesLongOptionPrefix(argument, \"--set-upstream-to\", \"--set-u\") ||\n matchesLongOptionPrefix(argument, \"--create-reflog\", \"--creat\"),\n );\n}\n\nfunction isSafeGitRemoteArguments(args: string[]) {\n const actionIndex = args.findIndex((argument) => !argument.startsWith(\"-\"));\n if (actionIndex < 0) return true;\n const action = args[actionIndex];\n if (action === \"get-url\") return true;\n if (action !== \"show\") return false;\n\n const showArgs = args.slice(actionIndex + 1);\n if (showArgs.includes(\"--\")) return false;\n const remotes = showArgs.filter((argument) => !argument.startsWith(\"-\"));\n return remotes.length === 0 || (remotes.length === 1 && showArgs.includes(\"-n\"));\n}\n\nfunction isSafeGhCommand(args: string[], safeSubcommands: SafeSubcommands) {\n const group = args[0]?.toLowerCase();\n const action = args[1]?.toLowerCase();\n if (!group || !action || group.startsWith(\"-\") || action.startsWith(\"-\")) return false;\n const path = `${group} ${action}` as SafeGhSubcommandPath;\n if (!safeSubcommands.gh?.includes(path)) return false;\n const validator = (GH_VALIDATORS as Record<string, ArgumentValidator>)[path];\n return validator?.(args.slice(2)) ?? false;\n}\n\nfunction isSafeGhReadArguments(args: string[]) {\n return !args.some(isUnsafeGhReadArgument) && hasGhJsonOutput(args);\n}\n\nfunction isUnsafeGhReadArgument(argument: string) {\n return (\n argument.startsWith(\"-w\") ||\n argument === \"--web\" ||\n argument.startsWith(\"--web=\") ||\n argument === \"--browser\" ||\n argument.startsWith(\"--browser=\") ||\n argument === \"--paginate\" ||\n argument === \"--pager\" ||\n argument.startsWith(\"--pager=\") ||\n argument === \"--output\" ||\n argument.startsWith(\"--output=\")\n );\n}\n\nfunction hasGhJsonOutput(args: string[]) {\n let hasJson = false;\n for (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--json\") {\n const value = args[index + 1];\n if (!value || value.startsWith(\"-\")) return false;\n hasJson = true;\n index += 1;\n } else if (argument.startsWith(\"--json=\")) {\n if (argument === \"--json=\") return false;\n hasJson = true;\n }\n }\n return hasJson;\n}\n", "import type { ToolInfo } from \"@earendil-works/pi-coding-agent\";\nimport { planModeToolAvailability } from \"./tool-availability.js\";\nimport {\n canSelectToolInPlanMode,\n classifyPlanModeTool,\n isBuiltinTool,\n SAFE_BUILTIN_PLAN_TOOLS,\n} from \"./tool-policy.js\";\n\nexport function toolNameFromLegacyKey(key: string, tools: ToolInfo[]) {\n const directName = tools.find((tool) => tool.name === key)?.name;\n if (directName) return directName;\n const [name] = key.split(\"\\u001f\");\n return tools.find((tool) => tool.name === name) ? name : undefined;\n}\n\nexport function compareTools(left: ToolInfo, right: ToolInfo) {\n const leftBuiltin = isBuiltinTool(left);\n const rightBuiltin = isBuiltinTool(right);\n if (leftBuiltin !== rightBuiltin) return leftBuiltin ? -1 : 1;\n return left.name.localeCompare(right.name);\n}\n\nexport function toolPolicyLabel(tool: ToolInfo) {\n const policy = classifyPlanModeTool(tool);\n if (policy === \"read-only\") return \"built-in read-only\";\n if (policy === \"limited\") return \"built-in limited\";\n if (policy === \"blocked\") return tool.sourceInfo?.source ? \"built-in blocked\" : \"policy metadata unavailable\";\n return `user opt-in: ${toolSourceLabel(tool)}`;\n}\n\nexport function planModeToolSelection(tool: ToolInfo, activeNames: ReadonlySet<string>, retained: boolean) {\n const availability = planModeToolAvailability(tool, activeNames);\n const policyBlocked = !canSelectToolInPlanMode(tool);\n let unavailable: string | undefined;\n switch (availability) {\n case \"inactive\":\n unavailable = \"Not active in Pi; Plan mode will not activate it\";\n if (!policyBlocked && isBuiltinTool(tool) && [\"grep\", \"find\", \"ls\"].includes(tool.name)) {\n // ExtensionContext does not expose host-owned Pi settings; plain names also work before Pi 0.99.\n unavailable += `; on Pi with defaultTools support, use a full list including \"${tool.name}\" in this session's Pi settings (preserve existing/default tools), then restart Pi`;\n }\n if (retained) unavailable += \"; retained and resolved before the first request\";\n break;\n case \"hidden\":\n unavailable = \"Hidden in Pi; retained selection cannot enable it\";\n break;\n case \"unsupported\":\n unavailable = \"Unsupported tool exposure; Plan mode cannot enable it\";\n break;\n }\n const policy =\n (policyBlocked ? undefined : unavailable) ??\n [\n toolPolicyLabel(tool),\n ...(tool.exposure === \"codemode\" || tool.exposure === \"deferred\" ? [\"callable via other tools\"] : []),\n ...(tool.exposure === \"model-only\" ? [\"model calls only\"] : []),\n ].join(\" \u00B7 \");\n const description = tool.description ?? \"No description available\";\n const disabledReason = policyBlocked ? \"Blocked by Plan-mode policy\" : unavailable;\n const label = policyBlocked\n ? `${tool.name} \u2014 blocked by Plan policy`\n : availability === \"inactive\"\n ? `${tool.name} \u2014 inactive in Pi`\n : tool.name;\n return {\n label,\n description: `${policy} \u00B7 ${description}`,\n searchText: `${policy} ${description}`,\n disabled: disabledReason !== undefined,\n disabledReason,\n };\n}\n\nfunction toolSourceLabel(tool: ToolInfo) {\n const sourceInfo = tool.sourceInfo;\n const source = `${sourceInfo.scope}/${sourceInfo.source}`;\n return sourceInfo.path ? `${source} ${sourceInfo.path}` : source;\n}\n\nexport function unique(values: string[]) {\n return Array.from(new Set(values));\n}\n\nexport function filterAvailableSelectedToolNames(\n names: string[],\n tools: ToolInfo[],\n activeNames: ReadonlySet<string> = new Set(tools.map((tool) => tool.name)),\n) {\n const availableNames = new Set(\n tools\n .filter((tool) => canSelectToolInPlanMode(tool) && planModeToolAvailability(tool, activeNames) === \"available\")\n .map((tool) => tool.name),\n );\n return unique(names.filter((name) => availableNames.has(name)));\n}\n\nexport function defaultPlanModeToolNames(tools: ToolInfo[], configuredNames: string[] | undefined) {\n if (configuredNames !== undefined) return unique(configuredNames);\n return tools.filter((tool) => isBuiltinTool(tool) && SAFE_BUILTIN_PLAN_TOOLS.has(tool.name)).map((tool) => tool.name);\n}\n\ninterface PlanModeToolSelectionSnapshot {\n selectedToolNames?: string[];\n selectedToolKeys?: string[];\n defaultPlanTools?: string[];\n}\n\nexport function snapshotPlanModeSelectedNames(tools: ToolInfo[], selection: PlanModeToolSelectionSnapshot) {\n const selectedToolNames =\n selection.selectedToolNames ??\n selection.selectedToolKeys\n ?.map((key) => toolNameFromLegacyKey(key, tools))\n .filter((name): name is string => name !== undefined);\n return new Set(\n selectedToolNames === undefined\n ? defaultPlanModeToolNames(tools, selection.defaultPlanTools)\n : unique(selectedToolNames),\n );\n}\n"],
5
+ "mappings": ";;;;AAAA,SAAS,wBAAwB;AACjC,SAAS,gBAAgB;AAElB,IAAM,+BAA+B;AACrC,IAAM,6BAA6B;AACnC,IAAM,sBAAsB;AAQ5B,IAAM,4BAA4B;AAAA,EACvC,MAAM;AAAA,EACN,sBAAsB;AAAA,EACtB,UAAU,CAAC,MAAM;AAAA,EACjB,YAAY;AAAA,IACV,MAAM;AAAA,MACJ,MAAM;AAAA,MACN,WAAW;AAAA,MACX,WAAW;AAAA,MACX,aAAa;AAAA,IACf;AAAA,EACF;AACF;AAIO,SAAS,4BAA4B,OAAmD;AAC7F,MAAI,CAAC,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,UAAU;AACtD,WAAO,EAAE,IAAI,OAAO,OAAO,wBAAwB;AAAA,EACrD;AACA,QAAM,OAAO,MAAM,KAAK,KAAK;AAC7B,MAAI,CAAC,KAAM,QAAO,EAAE,IAAI,OAAO,OAAO,yBAAyB;AAC/D,MAAI,KAAK,SAAS,qBAAqB;AACrC,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,OAAO,wBAAwB,mBAAmB;AAAA,IACpD;AAAA,EACF;AACA,SAAO,EAAE,IAAI,MAAM,KAAK;AAC1B;AAEO,SAAS,0BAA0B,OAAgB;AACxD,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO;AAC7B,MAAI,MAAM,YAAY,8BAA8B,MAAM,WAAW,8BAA8B;AACjG,WAAO;AAAA,EACT;AACA,QAAM,aAAa,4BAA4B,EAAE,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AAgB;AACvC,QAAM,aAAa,KAAK;AACxB,QAAM,SAAS,GAAG,WAAW,KAAK,IAAI,WAAW,MAAM;AACvD,SAAO,WAAW,OAAO,GAAG,MAAM,IAAI,WAAW,IAAI,KAAK;AAC5D;AAEO,SAAS,OAAO,QAAkB;AACvC,SAAO,MAAM,KAAK,IAAI,IAAI,MAAM,CAAC;AACnC;AAEO,SAAS,iCACd,OACA,OACA,cAAmC,IAAI,IAAI,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI,CAAC,GACzE;AACA,QAAM,iBAAiB,IAAI;AAAA,IACzB,MACG,OAAO,CAAC,SAAS,wBAAwB,IAAI,KAAK,yBAAyB,MAAM,WAAW,MAAM,WAAW,EAC7G,IAAI,CAAC,SAAS,KAAK,IAAI;AAAA,EAC5B;AACA,SAAO,OAAO,MAAM,OAAO,CAAC,SAAS,eAAe,IAAI,IAAI,CAAC,CAAC;AAChE;AAEO,SAAS,yBAAyB,OAAmB,iBAAuC;AACjG,MAAI,oBAAoB,OAAW,QAAO,OAAO,eAAe;AAChE,SAAO,MAAM,OAAO,CAAC,SAAS,cAAc,IAAI,KAAK,wBAAwB,IAAI,KAAK,IAAI,CAAC,EAAE,IAAI,CAAC,SAAS,KAAK,IAAI;AACtH;AAQO,SAAS,8BAA8B,OAAmB,WAA0C;AACzG,QAAM,oBACJ,UAAU,qBACV,UAAU,kBACN,IAAI,CAAC,QAAQ,sBAAsB,KAAK,KAAK,CAAC,EAC/C,OAAO,CAAC,SAAyB,SAAS,MAAS;AACxD,SAAO,IAAI;AAAA,IACT,sBAAsB,SAClB,yBAAyB,OAAO,UAAU,gBAAgB,IAC1D,OAAO,iBAAiB;AAAA,EAC9B;AACF;",
6
6
  "names": ["mkdir", "writeFile", "dirname", "detail", "mkdir", "dirname", "writeFile", "isNodeError", "isRecord"]
7
7
  }
@@ -23,7 +23,7 @@ import {
23
23
  retentionLabel,
24
24
  snapshotAvailableImplementationModels,
25
25
  updatePlanModeSettings
26
- } from "./chunk-MJV6WNHK.ts";
26
+ } from "./chunk-W7D6N2MI.ts";
27
27
 
28
28
  // src/active-implementation-menu.ts
29
29
  import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
@@ -1019,4 +1019,4 @@ export {
1019
1019
  showReadyPlanMenu,
1020
1020
  showSavedPlanMenu
1021
1021
  };
1022
- //# sourceMappingURL=interactive-ui-F7FMN7FT.ts.map
1022
+ //# sourceMappingURL=interactive-ui-RG7CBW6F.ts.map
package/dist/index.ts CHANGED
@@ -48,7 +48,7 @@ import {
48
48
  snapshotAvailableImplementationModels,
49
49
  snapshotPlanModeSelectedNames,
50
50
  updatePlanModeSettings
51
- } from "./chunks/chunk-MJV6WNHK.ts";
51
+ } from "./chunks/chunk-W7D6N2MI.ts";
52
52
 
53
53
  // src/plan-mode.ts
54
54
  import { randomUUID as randomUUID2 } from "node:crypto";
@@ -1037,7 +1037,7 @@ function planMode(pi, dependencies = {}) {
1037
1037
  const loadInteractiveUi = () => {
1038
1038
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
1039
1039
  if (!interactiveUiPromise) {
1040
- interactiveUiPromise = import("./chunks/interactive-ui-F7FMN7FT.ts").catch((error) => {
1040
+ interactiveUiPromise = import("./chunks/interactive-ui-RG7CBW6F.ts").catch((error) => {
1041
1041
  interactiveUiPromise = void 0;
1042
1042
  throw error;
1043
1043
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-plan-mode",
3
- "version": "0.59.5",
3
+ "version": "0.59.6",
4
4
  "description": "Pi extension that adds a Codex-like read-only /plan collaboration mode.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -17,6 +17,7 @@
17
17
  "dist",
18
18
  "docs",
19
19
  "README.md",
20
+ "CHANGELOG.md",
20
21
  "LICENSE"
21
22
  ],
22
23
  "pi": {
@@ -36,8 +37,8 @@
36
37
  "@earendil-works/pi-tui": "*"
37
38
  },
38
39
  "devDependencies": {
39
- "@earendil-works/pi-coding-agent": "1.4.0",
40
- "@earendil-works/pi-tui": "1.4.0",
40
+ "@earendil-works/pi-coding-agent": "1.5.0",
41
+ "@earendil-works/pi-tui": "1.5.0",
41
42
  "esbuild": "0.28.2",
42
43
  "typescript": "7.0.2"
43
44
  },
@@ -47,6 +48,6 @@
47
48
  "directory": "packages/pi-plan-mode"
48
49
  },
49
50
  "dependencies": {
50
- "@narumitw/pi-tui-kit": "^0.68.1"
51
+ "@narumitw/pi-tui-kit": "^0.69.0"
51
52
  }
52
53
  }
@@ -186,6 +186,7 @@ export async function askPlanModeQuestions(
186
186
  })),
187
187
  }));
188
188
  const result = await runQuestionnaire(ctx, {
189
+ blocked: { kind: "question", message: "Answer Plan mode questions" },
189
190
  questions: runnerQuestions,
190
191
  allowNotes: true,
191
192
  maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,