@narumitw/pi-plan-mode 0.55.1 → 0.55.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -147,11 +147,17 @@ The optional native `powershell` tool must be active when an automatic Plan poli
147
147
  Built-in `edit` and `write`, `update_plan`, tools still inactive at the first request, and deselected tools are blocked at execution time even though active schemas remain visible.
148
148
  Extension and custom tools are denied by default because Pi tools do not expose standardized mutability metadata; explicitly allow a custom-tool name before starting only when you accept the risk.
149
149
  For example, you can opt into `firecrawl_scrape`, `firecrawl_search`, or `lsp_diagnostics` when you want to use the effective active tool during planning.
150
+ An active selectable tool omitted from the Plan policy reports that it needs explicit selection through `/plan tools` or `defaultPlanTools` before the next workflow.
151
+ Registered but inactive, unregistered, metadata-free, and built-in blocked tools report their distinct fail-closed reasons instead of suggesting that every denial is a missing selection.
152
+ A tool admitted before later deactivation can be reactivated and reused in the current workflow without restarting.
150
153
  After they become visible, the Plan-only helpers remain visible in Normal mode, but their handlers and the `tool_call` policy reject calls unless Plan mode owns the active workflow.
151
154
 
152
155
  Limited `bash` uses a fail-closed Bash policy, including when an extension overrides the canonical `bash` tool name.
153
156
  It accepts common inspection commands, read-only Git and npm queries, pipelines and command lists composed entirely of accepted commands, plus selected checks such as `npm test`, `npm run typecheck`, and `cargo test`.
154
- It rejects output/input redirects, shell expansion, substitutions, subshells, background jobs, mutating flags, dependency changes, editors, and unknown commands.
157
+ Reviewed Git inspections may place `--no-pager` before the accepted subcommand.
158
+ They may also place one or more complete `-C <path>` pairs before the accepted subcommand only when every path is `.` or the exact current Pi working directory.
159
+ Other targets are rejected so `git -C` cannot introduce executable configuration, hooks, filters, signing programs, or lazy-fetch remotes from another repository.
160
+ It rejects output/input redirects, shell expansion, substitutions, subshells, background jobs, incomplete or directory-changing `-C` pairs, other Git global options, Git config overrides, mutating flags, dependency changes, editors, and unknown commands.
155
161
 
156
162
  Limited `powershell` uses a separate fail-closed PowerShell policy, including when an extension overrides the canonical `powershell` tool name.
157
163
  It accepts canonical inspection cmdlets such as `Get-ChildItem`, `Get-Content`, `Get-Item`, `Get-Location`, `Resolve-Path`, `Select-String`, `Test-Path`, `Measure-Object`, `Sort-Object`, `Format-List`, `Format-Table`, `Out-String`, and `Write-Output`.
@@ -413,11 +419,13 @@ Duplicate values are removed in first-seen order.
413
419
  With the example configuration above, commands such as these are accepted:
414
420
 
415
421
  ```bash
422
+ git -C . status --short
416
423
  git rev-parse --show-toplevel
417
424
  git blame -- src/plan-mode.ts
418
425
  git diff --cached
419
426
  git show --stat --oneline HEAD
420
427
  git log -p -1 HEAD -- src/plan-mode.ts
428
+ git -C . diff --check
421
429
  gh pr view 218 --json number,title,state
422
430
  gh issue list --state open --json number,title,state
423
431
  ```
@@ -425,6 +433,11 @@ gh issue list --state open --json number,title,state
425
433
  The command-specific validators still reject unsafe forms, including:
426
434
 
427
435
  ```bash
436
+ git -C
437
+ git -C packages/pi-plan-mode status --short
438
+ git -C packages -C .. status --short
439
+ git -c core.fsmonitor=false -C . status --short
440
+ git -C . checkout main
428
441
  git blame --textconv -- src/plan-mode.ts
429
442
  git cat-file --filters HEAD
430
443
  git diff --ext-diff
@@ -446,7 +459,8 @@ GitHub CLI read paths require `--json <fields>` output so Plan mode does not rel
446
459
  Unknown `safeSubcommands` keys or values, non-array values, and non-string entries invalidate the entire settings file and trigger the normal warning/default fallback on session start.
447
460
 
448
461
  Read-only does not mean private: Git inspection can expose repository history and tracked secrets, while `gh` queries can expose remote repository, pull request, and issue data available to your authenticated account.
449
- The policy reduces accidental mutation and explicit helper execution; it is not a sandbox or a confidentiality boundary.
462
+ A `git -C <path>` inspection is accepted only when the path keeps Git in Pi's current working directory.
463
+ The policy reduces accidental mutation and cross-repository executable configuration; it is not a sandbox or a confidentiality boundary.
450
464
 
451
465
  ### Thinking level
452
466
 
@@ -387,6 +387,7 @@ function createImplementationRetentionCoordinator() {
387
387
  }
388
388
 
389
389
  // src/tool-policy.ts
390
+ import { isAbsolute, normalize } from "node:path";
390
391
  var BUILTIN_SAFE_GIT_SUBCOMMANDS = [
391
392
  "status",
392
393
  "log",
@@ -513,15 +514,17 @@ function readCommand(input) {
513
514
  const command = input;
514
515
  return typeof command?.command === "string" ? command.command : "";
515
516
  }
516
- function findBlockedCommandSegment(command, safeSubcommands = {}) {
517
+ function findBlockedCommandSegment(command, safeSubcommands = {}, workingDirectory) {
517
518
  const segments = splitShellSegments(command);
518
519
  if (!segments || segments.length === 0) return command.trim() || "(empty command)";
519
- return segments.find((segment) => !isSafeSegment(segment, safeSubcommands));
520
+ return segments.find((segment) => !isSafeSegment(segment, safeSubcommands, workingDirectory));
520
521
  }
521
- function findBlockedPowerShellCommandSegment(command, safeSubcommands = {}) {
522
+ function findBlockedPowerShellCommandSegment(command, safeSubcommands = {}, workingDirectory) {
522
523
  const segments = splitPowerShellSegments(command);
523
524
  if (!segments || segments.length === 0) return command.trim() || "(empty command)";
524
- return segments.find((segment) => !isSafePowerShellSegment(segment, safeSubcommands));
525
+ return segments.find(
526
+ (segment) => !isSafePowerShellSegment(segment, safeSubcommands, workingDirectory)
527
+ );
525
528
  }
526
529
  function splitPowerShellSegments(command) {
527
530
  const trimmed = command.trim();
@@ -568,7 +571,7 @@ function splitPowerShellSegments(command) {
568
571
  segments.push(finalSegment);
569
572
  return segments;
570
573
  }
571
- function isSafePowerShellSegment(segment, safeSubcommands) {
574
+ function isSafePowerShellSegment(segment, safeSubcommands, workingDirectory) {
572
575
  const tokens = powerShellWords(segment);
573
576
  if (!tokens || tokens.length === 0 || tokens.includes("--%")) return false;
574
577
  const command = tokens[0]?.toLowerCase();
@@ -576,7 +579,7 @@ function isSafePowerShellSegment(segment, safeSubcommands) {
576
579
  const args = tokens.slice(1);
577
580
  if (READ_ONLY_POWERSHELL_COMMANDS.has(command)) return true;
578
581
  if (command !== "git" && command !== "gh") return false;
579
- return isSafeStructuredCommand(command, args, safeSubcommands);
582
+ return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
580
583
  }
581
584
  function powerShellWords(segment) {
582
585
  const words = [];
@@ -663,7 +666,7 @@ function splitShellSegments(command) {
663
666
  segments.push(finalSegment);
664
667
  return segments;
665
668
  }
666
- function isSafeSegment(segment, safeSubcommands) {
669
+ function isSafeSegment(segment, safeSubcommands, workingDirectory) {
667
670
  if (hasShellExpansion(segment) || /(^|\s)[A-Za-z_][A-Za-z0-9_]*=/.test(segment)) {
668
671
  return false;
669
672
  }
@@ -674,7 +677,7 @@ function isSafeSegment(segment, safeSubcommands) {
674
677
  const args = tokens.slice(1);
675
678
  if (!hasSafeArguments(command, args)) return false;
676
679
  if (READ_ONLY_COMMANDS.has(command)) return true;
677
- return isSafeStructuredCommand(command, args, safeSubcommands);
680
+ return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
678
681
  }
679
682
  function hasShellExpansion(segment) {
680
683
  let quote;
@@ -805,8 +808,8 @@ var GH_VALIDATORS = {
805
808
  "issue view": isSafeGhReadArguments,
806
809
  "issue list": isSafeGhReadArguments
807
810
  };
808
- function isSafeStructuredCommand(command, args, safeSubcommands) {
809
- if (command === "git") return isSafeGitCommand(args, safeSubcommands);
811
+ function isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory) {
812
+ if (command === "git") return isSafeGitCommand(args, safeSubcommands, workingDirectory);
810
813
  if (command === "gh") return isSafeGhCommand(args, safeSubcommands);
811
814
  const subcommandIndex = args.findIndex((argument) => !argument.startsWith("-"));
812
815
  const subcommand = args[subcommandIndex]?.toLowerCase();
@@ -835,9 +838,9 @@ function isSafeStructuredCommand(command, args, safeSubcommands) {
835
838
  }
836
839
  return false;
837
840
  }
838
- function isSafeGitCommand(args, safeSubcommands) {
839
- let subcommandIndex = 0;
840
- while (args[subcommandIndex] === "--no-pager") subcommandIndex += 1;
841
+ function isSafeGitCommand(args, safeSubcommands, workingDirectory) {
842
+ const subcommandIndex = parseGitGlobalOptions(args, workingDirectory);
843
+ if (subcommandIndex === void 0) return false;
841
844
  const subcommand = args[subcommandIndex]?.toLowerCase();
842
845
  if (!subcommand || subcommand.startsWith("-")) return false;
843
846
  const subcommandArgs = args.slice(subcommandIndex + 1);
@@ -847,6 +850,26 @@ function isSafeGitCommand(args, safeSubcommands) {
847
850
  const validator = builtinValidator ?? (configured ? configuredValidator : void 0);
848
851
  return validator !== void 0 && hasSafeGitArguments(subcommand, subcommandArgs) && validator(subcommandArgs);
849
852
  }
853
+ function parseGitGlobalOptions(args, workingDirectory) {
854
+ let index = 0;
855
+ while (index < args.length) {
856
+ const argument = args[index];
857
+ if (argument === "--no-pager") {
858
+ index += 1;
859
+ continue;
860
+ }
861
+ if (argument !== "-C") break;
862
+ const directory = args[index + 1];
863
+ if (!directory || !isCurrentWorkingDirectory(directory, workingDirectory)) return void 0;
864
+ index += 2;
865
+ }
866
+ return index;
867
+ }
868
+ function isCurrentWorkingDirectory(directory, workingDirectory) {
869
+ if (!workingDirectory || directory.split(/[\\/]+/u).includes("..")) return false;
870
+ if (normalize(directory) === ".") return true;
871
+ return isAbsolute(directory) && normalize(directory) === normalize(workingDirectory);
872
+ }
850
873
  function hasSafeGitArguments(subcommand, args) {
851
874
  return !args.some(
852
875
  (argument) => argument === "--help" || argument === "--show-signature" || argument.startsWith("--show-signature=") || argument.includes("%G") || argument === "--output" || argument.startsWith("--output=") || argument === "--ext-diff" || argument.startsWith("--ext-diff=") || argument === "--textconv" || argument.startsWith("--textconv=") || argument === "--paginate" || argument === "--open-files-in-pager" || argument.startsWith("--open-files-in-pager=") || subcommand === "grep" && (argument === "-O" || argument.startsWith("-O"))
@@ -1704,4 +1727,4 @@ export {
1704
1727
  defaultPlanModeToolNames,
1705
1728
  snapshotPlanModeSelectedNames
1706
1729
  };
1707
- //# sourceMappingURL=chunk-AS76FCC5.js.map
1730
+ //# sourceMappingURL=chunk-TZVK4O2Q.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/completion-tool.ts", "../../src/message-transform.ts", "../../src/implementation-retention.ts", "../../src/tool-policy.ts", "../../src/settings.ts", "../../src/plan-export.ts", "../../src/question-tool.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\tversion: typeof PLAN_MODE_COMPLETE_VERSION;\n\tsource: typeof PLAN_MODE_COMPLETE_TOOL_NAME;\n\tplan: string;\n};\n\nexport const PLAN_MODE_COMPLETE_PARAMS = {\n\ttype: \"object\",\n\tadditionalProperties: false,\n\trequired: [\"plan\"],\n\tproperties: {\n\t\tplan: {\n\t\t\ttype: \"string\",\n\t\t\tminLength: 1,\n\t\t\tmaxLength: PLAN_MODE_MAX_CHARS,\n\t\t\tdescription: \"The complete decision-ready implementation plan in Markdown.\",\n\t\t},\n\t},\n} as const;\n\ntype NormalizePlanModeCompletionResult = { ok: true; plan: string } | { ok: false; error: string };\n\nexport function normalizePlanModeCompletion(input: unknown): NormalizePlanModeCompletionResult {\n\tif (!isRecord(input) || typeof input.plan !== \"string\") {\n\t\treturn { ok: false, error: \"plan must be a string\" };\n\t}\n\tconst plan = input.plan.trim();\n\tif (!plan) return { ok: false, error: \"plan must not be empty\" };\n\tif (plan.length > PLAN_MODE_MAX_CHARS) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `plan must not exceed ${PLAN_MODE_MAX_CHARS} characters`,\n\t\t};\n\t}\n\treturn { ok: true, plan };\n}\n\nexport function planFromCompletionDetails(value: unknown) {\n\tif (!isRecord(value)) return undefined;\n\tif (\n\t\tvalue.version !== PLAN_MODE_COMPLETE_VERSION ||\n\t\tvalue.source !== PLAN_MODE_COMPLETE_TOOL_NAME\n\t) {\n\t\treturn undefined;\n\t}\n\tconst normalized = normalizePlanModeCompletion({ plan: value.plan });\n\treturn normalized.ok ? normalized.plan : undefined;\n}\n\nexport function planModeCompleted(plan: string) {\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text: `**Proposed Plan**\\n\\n${plan}` }],\n\t\tdetails: {\n\t\t\tversion: PLAN_MODE_COMPLETE_VERSION,\n\t\t\tsource: PLAN_MODE_COMPLETE_TOOL_NAME,\n\t\t\tplan,\n\t\t} satisfies PlanModeCompletionDetails,\n\t\tterminate: true,\n\t};\n}\n\ntype PlanModeCompletionRenderResult = {\n\tcontent: Array<{ type: string; text?: string }>;\n\tdetails?: unknown;\n};\n\nexport function planModeCompletionMarkdown(result: PlanModeCompletionRenderResult) {\n\tconst content = result.content\n\t\t.filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n\t\t.map((block) => block.text)\n\t\t.join(\"\\n\")\n\t\t.trim();\n\tif (content) return content;\n\tconst plan = planFromCompletionDetails(result.details);\n\treturn plan ? `**Proposed Plan**\\n\\n${plan}` : \"\";\n}\n\nexport function renderPlanModeCompletion(result: PlanModeCompletionRenderResult) {\n\treturn new Markdown(planModeCompletionMarkdown(result), 0, 0, getMarkdownTheme());\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn 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\t\"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 =\n\t/^<proposed_plan>[\\t ]*\\r?\\n([\\s\\S]*?)\\r?\\n<\\/proposed_plan>[\\t ]*$/gm;\nconst PROPOSED_PLAN_BLOCK_PATTERN =\n\t/^<proposed_plan>[\\t ]*\\r?\\n[\\s\\S]*?\\r?\\n<\\/proposed_plan>[\\t ]*$/gm;\n\nexport type ProposedPlanParseResult =\n\t| { kind: \"absent\" }\n\t| { kind: \"valid\"; plan: string }\n\t| { kind: \"empty\" }\n\t| { kind: \"multiple\" }\n\t| { kind: \"malformed\" }\n\t| { kind: \"unclosed\" };\n\ntype SessionMessage = {\n\trole?: string;\n\tcontent?: unknown;\n\tstopReason?: string;\n};\n\ntype TextBlock = {\n\ttype?: string;\n\ttext?: string;\n};\n\nexport function parseProposedPlan(text: string): ProposedPlanParseResult {\n\tconst openingCount = text.match(/<proposed_plan>/gi)?.length ?? 0;\n\tconst closingCount = text.match(/<\\/proposed_plan>/gi)?.length ?? 0;\n\tif (openingCount === 0 && closingCount === 0) return { kind: \"absent\" };\n\tif (openingCount > 1 || closingCount > 1) return { kind: \"multiple\" };\n\tif (openingCount === 1 && closingCount === 0) return { kind: \"unclosed\" };\n\tif (openingCount !== 1 || closingCount !== 1) return { kind: \"malformed\" };\n\n\tconst matches = Array.from(text.matchAll(PROPOSED_PLAN_PATTERN));\n\tif (matches.length !== 1) return { kind: \"malformed\" };\n\tconst plan = matches[0]?.[1]?.trim() ?? \"\";\n\treturn plan ? { kind: \"valid\", plan } : { kind: \"empty\" };\n}\n\nexport function extractProposedPlan(text: string) {\n\tconst result = parseProposedPlan(text);\n\treturn result.kind === \"valid\" ? result.plan : undefined;\n}\n\nexport function invalidPlanMessage(kind: \"empty\" | \"multiple\" | \"malformed\" | \"unclosed\") {\n\tconst detail = {\n\t\tempty: \"the block is empty\",\n\t\tmultiple: \"more than one plan block was produced\",\n\t\tmalformed: \"the tags must be on their own lines\",\n\t\tunclosed: \"the closing tag is missing\",\n\t}[kind];\n\treturn `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\tif (!Array.isArray(messages)) return \"\";\n\tfor (const entry of [...messages].reverse()) {\n\t\tconst message = (entry as { message?: SessionMessage })?.message ?? (entry as SessionMessage);\n\t\tif (message?.role !== \"assistant\") continue;\n\t\tconst text = messageText(message);\n\t\tif (text) return text;\n\t}\n\treturn \"\";\n}\n\nexport function latestAssistantStopReason(messages: unknown) {\n\tif (!Array.isArray(messages)) return undefined;\n\tfor (const entry of [...messages].reverse()) {\n\t\tconst message = (entry as { message?: SessionMessage })?.message ?? (entry as SessionMessage);\n\t\tif (message?.role === \"assistant\") return message.stopReason;\n\t}\n\treturn undefined;\n}\n\nexport function messageTextContent(message: unknown) {\n\treturn messageText(\n\t\t(message as { message?: SessionMessage })?.message ?? (message as SessionMessage),\n\t);\n}\n\nexport function messageContainsLegacyPlanModeContextArtifact(message: unknown) {\n\treturn unwrapSessionMessage(message).customType === PLAN_CONTEXT_MESSAGE_TYPE;\n}\n\nexport function messageContainsPlanModeImplementationContextArtifact(message: unknown) {\n\treturn unwrapSessionMessage(message).customType === PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE;\n}\n\nexport function injectActiveImplementationContext(\n\tmessages: unknown[],\n\tactiveImplementation: ActiveImplementationPlan,\n) {\n\tlet foundCurrentContext = false;\n\tlet foundCurrentHandoff = false;\n\tconst expectedContext = activeImplementationContextContent(activeImplementation);\n\tconst messagesWithoutStaleContext = messages.filter((message) => {\n\t\tif (messageContainsPlanModeImplementationContextArtifact(message)) {\n\t\t\tconst candidate = unwrapSessionMessage(message);\n\t\t\tif (!foundCurrentContext && candidate.content === expectedContext) {\n\t\t\t\tfoundCurrentContext = true;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tif (!messageContainsPlanModeImplementationHandoff(message)) return true;\n\t\tif (\n\t\t\t!foundCurrentHandoff &&\n\t\t\tmessageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)\n\t\t) {\n\t\t\tfoundCurrentHandoff = true;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t});\n\tif (foundCurrentHandoff || foundCurrentContext) return messagesWithoutStaleContext;\n\n\tlet insertionIndex = 0;\n\twhile (isSummaryMessage(messagesWithoutStaleContext[insertionIndex])) insertionIndex += 1;\n\tconst contextMessage = {\n\t\trole: \"custom\" as const,\n\t\tcustomType: PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE,\n\t\tcontent: expectedContext,\n\t\tdisplay: false,\n\t\ttimestamp: activeImplementation.startedAt,\n\t};\n\treturn [\n\t\t...messagesWithoutStaleContext.slice(0, insertionIndex),\n\t\tcontextMessage,\n\t\t...messagesWithoutStaleContext.slice(insertionIndex),\n\t];\n}\n\nfunction activeImplementationContextContent(activeImplementation: ActiveImplementationPlan) {\n\treturn `[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\tconst candidate = unwrapSessionMessage(message);\n\treturn (\n\t\tcandidate.customType === PROPOSED_PLAN_MESSAGE_TYPE ||\n\t\t(candidate.role === \"toolResult\" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME)\n\t);\n}\n\ninterface HistoryImplementationArtifact {\n\tmessageIndex: number;\n\tkind: \"completion\" | \"legacy\" | \"presentation\";\n\ttoolCallId?: string;\n\ttoolCallMessageIndex?: 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(\n\tmessages: unknown[],\n): HistoryImplementationArtifact | undefined {\n\tfor (let index = messages.length - 1; index >= 0; index -= 1) {\n\t\tconst candidate = unwrapSessionMessage(messages[index]);\n\t\tif (\n\t\t\tcandidate.role !== \"user\" ||\n\t\t\tcontentText(candidate.content).trim() !== PLAN_HISTORY_IMPLEMENTATION_PROMPT\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst artifact = findHistoryImplementationArtifactBeforeKickoff(messages, index);\n\t\tif (artifact) return artifact;\n\t}\n\treturn undefined;\n}\n\nfunction findHistoryImplementationArtifactBeforeKickoff(\n\tmessages: unknown[],\n\tkickoffIndex: number,\n): HistoryImplementationArtifact | undefined {\n\tfor (let index = kickoffIndex - 1; index >= 0; index -= 1) {\n\t\tconst candidate = unwrapSessionMessage(messages[index]);\n\t\tif (candidate.role === \"user\" || isSummaryMessage(messages[index])) return undefined;\n\t\tif (candidate.role === \"toolResult\" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME) {\n\t\t\tconst toolCallId = candidate.toolCallId;\n\t\t\tconst toolCallMessageIndex = toolCallId\n\t\t\t\t? findPlanModeCompletionCallMessageIndex(messages, index, toolCallId)\n\t\t\t\t: undefined;\n\t\t\tif (toolCallId && toolCallMessageIndex !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tmessageIndex: index,\n\t\t\t\t\tkind: \"completion\",\n\t\t\t\t\ttoolCallId,\n\t\t\t\t\ttoolCallMessageIndex,\n\t\t\t\t};\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE) {\n\t\t\treturn { messageIndex: index, kind: \"presentation\" };\n\t\t}\n\t\tif (\n\t\t\tcandidate.role === \"assistant\" &&\n\t\t\tcontentText(candidate.content).match(PROPOSED_PLAN_BLOCK_PATTERN)\n\t\t) {\n\t\t\treturn { messageIndex: index, kind: \"legacy\" };\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction findPlanModeCompletionCallMessageIndex(\n\tmessages: unknown[],\n\tendIndex: number,\n\ttoolCallId: string,\n) {\n\tfor (let index = endIndex - 1; index >= 0; index -= 1) {\n\t\tconst candidate = unwrapSessionMessage(messages[index]);\n\t\tif (candidate.role === \"user\" || isSummaryMessage(messages[index])) return undefined;\n\t\tif (!Array.isArray(candidate.content)) continue;\n\t\tif (\n\t\t\tcandidate.content.some((block) => {\n\t\t\t\tconst toolCall = block as { type?: string; id?: string; name?: string };\n\t\t\t\treturn (\n\t\t\t\t\ttoolCall.type === \"toolCall\" &&\n\t\t\t\t\ttoolCall.id === toolCallId &&\n\t\t\t\t\ttoolCall.name === PLAN_MODE_COMPLETE_TOOL_NAME\n\t\t\t\t);\n\t\t\t})\n\t\t) {\n\t\t\treturn index;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport function messageContainsPlanModeImplementationHandoff(message: unknown) {\n\tconst candidate = unwrapSessionMessage(message);\n\treturn (\n\t\tcandidate.role === \"user\" &&\n\t\tcontentText(candidate.content).trimStart().startsWith(PLAN_IMPLEMENTATION_HANDOFF_PREFIX)\n\t);\n}\n\nexport function messageContainsExactPlanModeImplementationHandoff(message: unknown, plan: string) {\n\tconst candidate = unwrapSessionMessage(message);\n\tif (candidate.role !== \"user\") return false;\n\treturn (\n\t\tcontentText(candidate.content).trim() ===\n\t\t`${PLAN_IMPLEMENTATION_HANDOFF_PREFIX}\\n\\n${plan}`.trim()\n\t);\n}\n\nfunction isSummaryMessage(message: unknown) {\n\tconst role = unwrapSessionMessage(message)?.role;\n\treturn role === \"compactionSummary\" || role === \"branchSummary\";\n}\n\nexport function stripProposedPlanBlocksFromMessage<T>(message: T): T {\n\treturn replaceAssistantContent(message, stripProposedPlanBlocksFromContent);\n}\n\nexport function stripPlanModeCompletionCallsFromMessage<T>(\n\tmessage: T,\n\tpreservedToolCallId?: string,\n): T {\n\treturn replaceAssistantContent(message, (content) => {\n\t\tif (!Array.isArray(content)) return content;\n\t\tconst nextContent = content.filter((block) => {\n\t\t\tconst candidate = block as { type?: string; id?: string; name?: string };\n\t\t\treturn !(\n\t\t\t\tcandidate.type === \"toolCall\" &&\n\t\t\t\tcandidate.name === PLAN_MODE_COMPLETE_TOOL_NAME &&\n\t\t\t\t(!preservedToolCallId || candidate.id !== preservedToolCallId)\n\t\t\t);\n\t\t});\n\t\treturn nextContent.length === content.length ? content : nextContent;\n\t});\n}\n\nexport function isEmptyAssistantMessage(message: unknown) {\n\tconst candidate = unwrapSessionMessage(message);\n\treturn (\n\t\tcandidate.role === \"assistant\" &&\n\t\tArray.isArray(candidate.content) &&\n\t\tcandidate.content.length === 0\n\t);\n}\n\nfunction replaceAssistantContent<T>(message: T, transform: (content: unknown) => unknown): T {\n\tconst candidate = unwrapSessionMessage(message);\n\tif (candidate.role !== \"assistant\") return message;\n\n\tconst content = transform(candidate.content);\n\tif (content === candidate.content) return message;\n\n\tif (isSessionMessageEntry(message)) {\n\t\treturn { ...message, message: { ...candidate, content } };\n\t}\n\treturn { ...candidate, content } as T;\n}\n\nfunction unwrapSessionMessage(message: unknown) {\n\tconst entry = message as { message?: unknown } | null | undefined;\n\treturn (entry?.message ?? message ?? {}) as {\n\t\trole?: string;\n\t\tcustomType?: string;\n\t\ttoolName?: string;\n\t\ttoolCallId?: string;\n\t\tcontent?: unknown;\n\t};\n}\n\nfunction isSessionMessageEntry<T>(message: T): message is T & { message: SessionMessage } {\n\treturn typeof message === \"object\" && message !== null && \"message\" in message;\n}\n\nfunction stripProposedPlanBlocksFromContent(content: unknown) {\n\tif (typeof content === \"string\") return stripProposedPlanBlocks(content);\n\tif (!Array.isArray(content)) return content;\n\n\tlet changed = false;\n\tconst nextContent = content.map((block) => {\n\t\tconst textBlock = block as TextBlock;\n\t\tif (textBlock.type !== \"text\" || typeof textBlock.text !== \"string\") return block;\n\n\t\tconst text = stripProposedPlanBlocks(textBlock.text);\n\t\tif (text === textBlock.text) return block;\n\n\t\tchanged = true;\n\t\treturn { ...textBlock, text };\n\t});\n\treturn changed ? nextContent : content;\n}\n\nexport function stripProposedPlanBlocks(text: string) {\n\treturn text.replace(PROPOSED_PLAN_BLOCK_PATTERN, \"\");\n}\n\nfunction messageText(message: SessionMessage) {\n\treturn contentText(message.content);\n}\n\nfunction contentText(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return \"\";\n\treturn content\n\t\t.map((block) => {\n\t\t\tconst textBlock = block as TextBlock;\n\t\t\treturn textBlock.type === \"text\" && typeof textBlock.text === \"string\" ? textBlock.text : \"\";\n\t\t})\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\");\n}\n", "import {\n\tfindHistoryImplementationArtifact,\n\tinjectActiveImplementationContext,\n\tisEmptyAssistantMessage,\n\tmessageContainsExactPlanModeImplementationHandoff,\n\tmessageContainsInactivePlanModeArtifact,\n\tmessageContainsLegacyPlanModeContextArtifact,\n\tmessageContainsPlanModeImplementationContextArtifact,\n\tmessageContainsPlanModeImplementationHandoff,\n\tstripPlanModeCompletionCallsFromMessage,\n\tstripProposedPlanBlocksFromMessage,\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\treturn {\n\t\t\"clear-on-start\": \"Off \u2014 conversation history only\",\n\t\t\"clear-after-first-run\": \"Through first implementation run\",\n\t\tkeep: \"Until manually cleared\",\n\t}[retention];\n}\n\nexport function implementationRetentionPreview(retention: ImplementationPlanRetention) {\n\treturn {\n\t\t\"clear-on-start\": \"Plan reinjection: Off; use conversation history only.\",\n\t\t\"clear-after-first-run\": \"Plan reinjection: Through the first implementation run.\",\n\t\tkeep: \"Plan reinjection: Until /plan exit.\",\n\t}[retention];\n}\n\nexport interface ImplementationContextResult {\n\tmessages: unknown[];\n\tclearActiveImplementationId?: string;\n}\n\nexport interface ImplementationRetentionCoordinator {\n\trestore(activeImplementation: ActiveImplementationPlan | undefined): void;\n\ttransformContext(messages: unknown[], state: PlanModeState): ImplementationContextResult;\n\timplementationSettled(\n\t\tactiveImplementation: ActiveImplementationPlan | undefined,\n\t): string | undefined;\n\treset(): void;\n}\n\nexport function createImplementationRetentionCoordinator(): ImplementationRetentionCoordinator {\n\tlet implementationWithDeliveredContext: string | undefined;\n\tlet restoredImplementationAwaitingContext: string | undefined;\n\n\treturn {\n\t\trestore(activeImplementation) {\n\t\t\trestoredImplementationAwaitingContext =\n\t\t\t\tactiveImplementation && activeImplementation.retention !== \"keep\"\n\t\t\t\t\t? activeImplementation.id\n\t\t\t\t\t: undefined;\n\t\t},\n\t\ttransformContext(messages, state) {\n\t\t\tconst messagesWithoutLegacyContext = messages.filter(\n\t\t\t\t(message) => !messageContainsLegacyPlanModeContextArtifact(message),\n\t\t\t);\n\t\t\tif (state.enabled) {\n\t\t\t\treturn {\n\t\t\t\t\tmessages: messagesWithoutLegacyContext.filter(\n\t\t\t\t\t\t(message) =>\n\t\t\t\t\t\t\t!messageContainsPlanModeImplementationContextArtifact(message) &&\n\t\t\t\t\t\t\t!messageContainsPlanModeImplementationHandoff(message),\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst activeImplementation = state.activeImplementation;\n\t\t\tconst inactiveMessages = activeImplementation\n\t\t\t\t? messagesWithoutLegacyContext\n\t\t\t\t: messagesWithoutLegacyContext.filter(\n\t\t\t\t\t\t(message) =>\n\t\t\t\t\t\t\t!messageContainsPlanModeImplementationContextArtifact(message) &&\n\t\t\t\t\t\t\t!messageContainsPlanModeImplementationHandoff(message),\n\t\t\t\t\t);\n\t\t\tconst historyArtifact = activeImplementation\n\t\t\t\t? undefined\n\t\t\t\t: findHistoryImplementationArtifact(inactiveMessages);\n\t\t\tconst historyArtifactMessage = historyArtifact\n\t\t\t\t? inactiveMessages[historyArtifact.messageIndex]\n\t\t\t\t: undefined;\n\t\t\tconst historyToolCallMessage =\n\t\t\t\thistoryArtifact?.toolCallMessageIndex !== undefined\n\t\t\t\t\t? inactiveMessages[historyArtifact.toolCallMessageIndex]\n\t\t\t\t\t: undefined;\n\t\t\tconst filteredMessages = inactiveMessages\n\t\t\t\t.filter(\n\t\t\t\t\t(message) =>\n\t\t\t\t\t\tmessage === historyArtifactMessage || !messageContainsInactivePlanModeArtifact(message),\n\t\t\t\t)\n\t\t\t\t.map((message) =>\n\t\t\t\t\tmessage === historyArtifactMessage && historyArtifact?.kind === \"legacy\"\n\t\t\t\t\t\t? message\n\t\t\t\t\t\t: stripProposedPlanBlocksFromMessage(message),\n\t\t\t\t)\n\t\t\t\t.map((message) =>\n\t\t\t\t\tstripPlanModeCompletionCallsFromMessage(\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tmessage === historyToolCallMessage ? historyArtifact?.toolCallId : undefined,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.filter((message) => !isEmptyAssistantMessage(message));\n\t\t\tif (!activeImplementation) return { messages: filteredMessages };\n\n\t\t\tconst contextualMessages = injectActiveImplementationContext(\n\t\t\t\tfilteredMessages,\n\t\t\t\tactiveImplementation,\n\t\t\t);\n\t\t\t// A busy /plan implement queues its handoff behind an older run. Do not arm cleanup\n\t\t\t// until that exact handoff reaches context; a restored session has no older run to drain.\n\t\t\tconst deliveredCurrentHandoff =\n\t\t\t\trestoredImplementationAwaitingContext === activeImplementation.id ||\n\t\t\t\tfilteredMessages.some((message) =>\n\t\t\t\t\tmessageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan),\n\t\t\t\t);\n\t\t\tif (!deliveredCurrentHandoff) return { messages: contextualMessages };\n\t\t\trestoredImplementationAwaitingContext = undefined;\n\n\t\t\tif (activeImplementation.retention === \"clear-after-first-run\") {\n\t\t\t\timplementationWithDeliveredContext = activeImplementation.id;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tmessages: contextualMessages,\n\t\t\t\tclearActiveImplementationId:\n\t\t\t\t\tactiveImplementation.retention === \"clear-on-start\" ? activeImplementation.id : undefined,\n\t\t\t};\n\t\t},\n\t\timplementationSettled(activeImplementation) {\n\t\t\tif (\n\t\t\t\tactiveImplementation?.retention !== \"clear-after-first-run\" ||\n\t\t\t\timplementationWithDeliveredContext !== activeImplementation.id\n\t\t\t) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\timplementationWithDeliveredContext = undefined;\n\t\t\treturn activeImplementation.id;\n\t\t},\n\t\treset() {\n\t\t\timplementationWithDeliveredContext = undefined;\n\t\t\trestoredImplementationAwaitingContext = undefined;\n\t\t},\n\t};\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\t\"status\",\n\t\"log\",\n\t\"diff\",\n\t\"show\",\n\t\"branch\",\n\t\"remote\",\n\t\"ls-files\",\n\t\"grep\",\n] as const;\nexport const CONFIGURABLE_SAFE_GIT_SUBCOMMANDS = [\n\t\"rev-parse\",\n\t\"blame\",\n\t\"describe\",\n\t\"merge-base\",\n\t\"ls-tree\",\n\t\"cat-file\",\n] as const;\nexport const SAFE_GIT_SUBCOMMANDS = [\n\t...BUILTIN_SAFE_GIT_SUBCOMMANDS,\n\t...CONFIGURABLE_SAFE_GIT_SUBCOMMANDS,\n] 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\tgit?: SafeGitSubcommand[];\n\tgh?: SafeGhSubcommandPath[];\n}\n\nexport const SAFE_BUILTIN_PLAN_TOOLS = new Set([\n\t\"read\",\n\t\"bash\",\n\t\"powershell\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n]);\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\t\"rm\",\n\t\"rmdir\",\n\t\"mv\",\n\t\"cp\",\n\t\"mkdir\",\n\t\"touch\",\n\t\"chmod\",\n\t\"chown\",\n\t\"chgrp\",\n\t\"ln\",\n\t\"tee\",\n\t\"truncate\",\n\t\"dd\",\n\t\"sudo\",\n\t\"su\",\n\t\"kill\",\n\t\"pkill\",\n\t\"killall\",\n\t\"reboot\",\n\t\"shutdown\",\n\t\"vim\",\n\t\"vi\",\n\t\"nano\",\n\t\"emacs\",\n\t\"code\",\n\t\"subl\",\n]);\nconst READ_ONLY_POWERSHELL_COMMANDS = new Set([\n\t\"format-list\",\n\t\"format-table\",\n\t\"get-childitem\",\n\t\"get-content\",\n\t\"get-item\",\n\t\"get-location\",\n\t\"measure-object\",\n\t\"out-string\",\n\t\"resolve-path\",\n\t\"select-string\",\n\t\"sort-object\",\n\t\"test-path\",\n\t\"write-output\",\n]);\nconst READ_ONLY_COMMANDS = new Set([\n\t\"cat\",\n\t\"head\",\n\t\"tail\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"pwd\",\n\t\"echo\",\n\t\"printf\",\n\t\"wc\",\n\t\"sort\",\n\t\"uniq\",\n\t\"diff\",\n\t\"file\",\n\t\"stat\",\n\t\"du\",\n\t\"df\",\n\t\"tree\",\n\t\"which\",\n\t\"whereis\",\n\t\"type\",\n\t\"printenv\",\n\t\"uname\",\n\t\"whoami\",\n\t\"id\",\n\t\"date\",\n\t\"uptime\",\n\t\"ps\",\n\t\"jq\",\n\t\"rg\",\n\t\"fd\",\n\t\"bat\",\n\t\"eza\",\n]);\n\nexport function isBuiltinTool(tool: ToolInfo) {\n\treturn tool.sourceInfo.source === \"builtin\";\n}\n\nexport function classifyPlanModeTool(tool: ToolInfo): PlanModeToolPolicy {\n\tif (!isBuiltinTool(tool)) return \"user-opt-in\";\n\tif (BLOCKED_BUILTIN_TOOLS.has(tool.name)) return \"blocked\";\n\tif (tool.name === \"bash\" || tool.name === \"powershell\") return \"limited\";\n\treturn SAFE_BUILTIN_PLAN_TOOLS.has(tool.name) ? \"read-only\" : \"blocked\";\n}\n\nexport function canSelectToolInPlanMode(tool: ToolInfo) {\n\treturn classifyPlanModeTool(tool) !== \"blocked\";\n}\n\nexport function readCommand(input: unknown) {\n\tconst command = input as { command?: unknown } | undefined;\n\treturn typeof command?.command === \"string\" ? command.command : \"\";\n}\n\nexport function findBlockedCommandSegment(\n\tcommand: string,\n\tsafeSubcommands: SafeSubcommands = {},\n\tworkingDirectory?: string,\n): string | undefined {\n\tconst segments = splitShellSegments(command);\n\tif (!segments || segments.length === 0) return command.trim() || \"(empty command)\";\n\treturn segments.find((segment) => !isSafeSegment(segment, safeSubcommands, workingDirectory));\n}\n\nexport function isSafeCommand(\n\tcommand: string,\n\tsafeSubcommands: SafeSubcommands = {},\n\tworkingDirectory?: string,\n) {\n\treturn findBlockedCommandSegment(command, safeSubcommands, workingDirectory) === undefined;\n}\n\nexport function findBlockedPowerShellCommandSegment(\n\tcommand: string,\n\tsafeSubcommands: SafeSubcommands = {},\n\tworkingDirectory?: string,\n): string | undefined {\n\tconst segments = splitPowerShellSegments(command);\n\tif (!segments || segments.length === 0) return command.trim() || \"(empty command)\";\n\treturn segments.find(\n\t\t(segment) => !isSafePowerShellSegment(segment, safeSubcommands, workingDirectory),\n\t);\n}\n\nexport function isSafePowerShellCommand(\n\tcommand: string,\n\tsafeSubcommands: SafeSubcommands = {},\n\tworkingDirectory?: string,\n) {\n\treturn (\n\t\tfindBlockedPowerShellCommandSegment(command, safeSubcommands, workingDirectory) === undefined\n\t);\n}\n\nfunction splitPowerShellSegments(command: string): string[] | undefined {\n\tconst trimmed = command.trim();\n\tif (!trimmed || /[\\n\\r`\\u2018-\\u201e]/.test(trimmed)) return undefined;\n\n\tconst segments: string[] = [];\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet start = 0;\n\tfor (let index = 0; index < trimmed.length; index += 1) {\n\t\tconst character = trimmed[index];\n\t\tif (quote === \"'\") {\n\t\t\tif (character !== \"'\") continue;\n\t\t\tif (trimmed[index + 1] === \"'\") {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tquote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === '\"') {\n\t\t\tif (character === \"$\" || character === \"`\") return undefined;\n\t\t\tif (character === '\"') quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"') {\n\t\t\tquote = character;\n\t\t\tcontinue;\n\t\t}\n\t\tif ([\"$\", \"@\", \"#\", \"!\", \"?\", \"{\", \"}\", \"(\", \")\", \"[\", \"]\", \">\", \"<\"].includes(character)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst next = trimmed[index + 1];\n\t\tif (character === \"&\" || (character === \"|\" && next === \"|\")) return undefined;\n\t\tconst separatorLength = character === \";\" || character === \"|\" ? 1 : 0;\n\t\tif (separatorLength === 0) continue;\n\t\tconst segment = trimmed.slice(start, index).trim();\n\t\tif (!segment) return undefined;\n\t\tsegments.push(segment);\n\t\tindex += separatorLength - 1;\n\t\tstart = index + 1;\n\t}\n\tif (quote) return undefined;\n\tconst finalSegment = trimmed.slice(start).trim();\n\tif (!finalSegment) return undefined;\n\tsegments.push(finalSegment);\n\treturn segments;\n}\n\nfunction isSafePowerShellSegment(\n\tsegment: string,\n\tsafeSubcommands: SafeSubcommands,\n\tworkingDirectory?: string,\n) {\n\tconst tokens = powerShellWords(segment);\n\tif (!tokens || tokens.length === 0 || tokens.includes(\"--%\")) return false;\n\tconst command = tokens[0]?.toLowerCase();\n\tif (!command) return false;\n\tconst args = tokens.slice(1);\n\tif (READ_ONLY_POWERSHELL_COMMANDS.has(command)) return true;\n\tif (command !== \"git\" && command !== \"gh\") return false;\n\treturn isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);\n}\n\nfunction powerShellWords(segment: string): string[] | undefined {\n\tconst words: string[] = [];\n\tlet word = \"\";\n\tlet hasWord = false;\n\tlet quote: \"'\" | '\"' | undefined;\n\tfor (let index = 0; index < segment.length; index += 1) {\n\t\tconst character = segment[index];\n\t\tif (quote === \"'\") {\n\t\t\tif (character !== \"'\") {\n\t\t\t\tword += character;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (segment[index + 1] === \"'\") {\n\t\t\t\tword += \"'\";\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tquote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote === '\"') {\n\t\t\tif (character === '\"') quote = undefined;\n\t\t\telse word += character;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"') {\n\t\t\tquote = character;\n\t\t\thasWord = true;\n\t\t} else if (/\\s/.test(character)) {\n\t\t\tif (hasWord) words.push(word);\n\t\t\tword = \"\";\n\t\t\thasWord = false;\n\t\t} else {\n\t\t\tword += character;\n\t\t\thasWord = true;\n\t\t}\n\t}\n\tif (quote) return undefined;\n\tif (hasWord) words.push(word);\n\treturn words;\n}\n\nfunction splitShellSegments(command: string): string[] | undefined {\n\tconst trimmed = command.trim();\n\tif (!trimmed || /[\\n\\r`]/.test(trimmed)) return undefined;\n\n\tconst segments: string[] = [];\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tlet start = 0;\n\tfor (let index = 0; index < trimmed.length; index += 1) {\n\t\tconst character = trimmed[index];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (character === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"') {\n\t\t\tquote = character;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \">\" || character === \"<\" || character === \"(\" || character === \")\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst next = trimmed[index + 1];\n\t\tif (character === \"&\" && next !== \"&\") return undefined;\n\t\tconst separatorLength =\n\t\t\tcharacter === \";\" || character === \"|\"\n\t\t\t\t? next === character\n\t\t\t\t\t? 2\n\t\t\t\t\t: 1\n\t\t\t\t: character === \"&\" && next === \"&\"\n\t\t\t\t\t? 2\n\t\t\t\t\t: 0;\n\t\tif (separatorLength === 0) continue;\n\t\tconst segment = trimmed.slice(start, index).trim();\n\t\tif (!segment) return undefined;\n\t\tsegments.push(segment);\n\t\tindex += separatorLength - 1;\n\t\tstart = index + 1;\n\t}\n\tif (quote || escaped) return undefined;\n\tconst finalSegment = trimmed.slice(start).trim();\n\tif (!finalSegment) return undefined;\n\tsegments.push(finalSegment);\n\treturn segments;\n}\n\nfunction isSafeSegment(\n\tsegment: string,\n\tsafeSubcommands: SafeSubcommands,\n\tworkingDirectory?: string,\n) {\n\tif (hasShellExpansion(segment) || /(^|\\s)[A-Za-z_][A-Za-z0-9_]*=/.test(segment)) {\n\t\treturn false;\n\t}\n\tconst tokens = shellWords(segment);\n\tif (!tokens || tokens.length === 0) return false;\n\tconst command = tokens[0]?.toLowerCase();\n\tif (!command || MUTATING_COMMANDS.has(command)) return false;\n\tconst args = tokens.slice(1);\n\tif (!hasSafeArguments(command, args)) return false;\n\tif (READ_ONLY_COMMANDS.has(command)) return true;\n\treturn isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);\n}\n\nfunction hasShellExpansion(segment: string) {\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (const character of segment) {\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (character === quote) quote = undefined;\n\t\t\telse if (character === \"$\" && quote === '\"') return true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"') {\n\t\t\tquote = character;\n\t\t\tcontinue;\n\t\t}\n\t\tif ([\"$\", \"*\", \"?\", \"[\", \"{\"].includes(character)) return true;\n\t}\n\treturn false;\n}\n\nfunction shellWords(segment: string): string[] | undefined {\n\tconst words: string[] = [];\n\tlet word = \"\";\n\tlet quote: \"'\" | '\"' | undefined;\n\tlet escaped = false;\n\tfor (const character of segment) {\n\t\tif (escaped) {\n\t\t\tword += character;\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (character === quote) quote = undefined;\n\t\t\telse word += character;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"') quote = character;\n\t\telse if (/\\s/.test(character)) {\n\t\t\tif (word) words.push(word);\n\t\t\tword = \"\";\n\t\t} else word += character;\n\t}\n\tif (quote || escaped) return undefined;\n\tif (word) words.push(word);\n\treturn words;\n}\n\nfunction hasSafeArguments(command: string, args: string[]) {\n\tconst forbidden = new Set([\"-i\", \"--in-place\", \"--fix\", \"--write\", \"-delete\", \"--delete\"]);\n\tif (args.some((argument) => forbidden.has(argument))) return false;\n\tif (\n\t\tcommand === \"sed\" &&\n\t\targs.some(\n\t\t\t(argument) =>\n\t\t\t\targument.startsWith(\"--in-place=\") ||\n\t\t\t\t(/^-[^-]+/.test(argument) && argument.slice(1).includes(\"i\")),\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\tif (\n\t\tcommand === \"find\" &&\n\t\targs.some((argument) =>\n\t\t\t[\"-exec\", \"-execdir\", \"-ok\", \"-okdir\", \"-fprint\", \"-fprint0\", \"-fprintf\", \"-fls\"].includes(\n\t\t\t\targument,\n\t\t\t),\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\tif (\n\t\tcommand === \"date\" &&\n\t\targs.some((argument) => argument === \"-s\" || argument.startsWith(\"--set\"))\n\t) {\n\t\treturn false;\n\t}\n\tif (\n\t\t(command === \"sort\" || command === \"tree\") &&\n\t\targs.some(\n\t\t\t(argument) =>\n\t\t\t\targument === \"-o\" ||\n\t\t\t\t(argument.startsWith(\"-o\") && !argument.startsWith(\"--\")) ||\n\t\t\t\targument.startsWith(\"--output\"),\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\tif (\n\t\tcommand === \"sort\" &&\n\t\targs.some(\n\t\t\t(argument) =>\n\t\t\t\targument === \"-T\" ||\n\t\t\t\t(argument.startsWith(\"-T\") && argument.length > 2) ||\n\t\t\t\targument.startsWith(\"--temporary-directory\") ||\n\t\t\t\targument.startsWith(\"--compress-program\"),\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\tif (\n\t\tcommand === \"diff\" &&\n\t\targs.some((argument) => argument === \"--output\" || argument.startsWith(\"--output=\"))\n\t) {\n\t\treturn false;\n\t}\n\tif (command === \"uniq\" && args.filter((argument) => !argument.startsWith(\"-\")).length > 1) {\n\t\treturn false;\n\t}\n\tif (\n\t\tcommand === \"fd\" &&\n\t\targs.some((argument) =>\n\t\t\t[\"-x\", \"-X\", \"--exec\", \"--exec-batch\"].some(\n\t\t\t\t(flag) => argument === flag || argument.startsWith(`${flag}=`),\n\t\t\t),\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\tif (\n\t\tcommand === \"rg\" &&\n\t\targs.some((argument) => argument === \"--pre\" || argument.startsWith(\"--pre=\"))\n\t) {\n\t\treturn false;\n\t}\n\tif (\n\t\tcommand === \"bat\" &&\n\t\targs.some((argument) => argument === \"--pager\" || argument.startsWith(\"--pager=\"))\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\ntype ArgumentValidator = (args: string[]) => boolean;\nconst allowReadOnlyArguments: ArgumentValidator = () => true;\nconst BUILTIN_GIT_VALIDATORS: Record<BuiltinSafeGitSubcommand, ArgumentValidator> = {\n\tstatus: allowReadOnlyArguments,\n\tlog: allowReadOnlyArguments,\n\tdiff: allowReadOnlyArguments,\n\tshow: allowReadOnlyArguments,\n\tbranch: isSafeGitBranchArguments,\n\tremote: isSafeGitRemoteArguments,\n\t\"ls-files\": allowReadOnlyArguments,\n\tgrep: isSafeGitGrepArguments,\n};\nconst CONFIGURABLE_GIT_VALIDATORS: Record<ConfigurableSafeGitSubcommand, ArgumentValidator> = {\n\t\"rev-parse\": allowReadOnlyArguments,\n\tblame: allowReadOnlyArguments,\n\tdescribe: allowReadOnlyArguments,\n\t\"merge-base\": allowReadOnlyArguments,\n\t\"ls-tree\": allowReadOnlyArguments,\n\t\"cat-file\": isSafeGitCatFileArguments,\n};\nconst GH_VALIDATORS: Record<SafeGhSubcommandPath, ArgumentValidator> = {\n\t\"pr view\": isSafeGhReadArguments,\n\t\"pr list\": isSafeGhReadArguments,\n\t\"issue view\": isSafeGhReadArguments,\n\t\"issue list\": isSafeGhReadArguments,\n};\n\nfunction isSafeStructuredCommand(\n\tcommand: string,\n\targs: string[],\n\tsafeSubcommands: SafeSubcommands,\n\tworkingDirectory?: string,\n) {\n\tif (command === \"git\") return isSafeGitCommand(args, safeSubcommands, workingDirectory);\n\tif (command === \"gh\") return isSafeGhCommand(args, safeSubcommands);\n\n\tconst subcommandIndex = args.findIndex((argument) => !argument.startsWith(\"-\"));\n\tconst subcommand = args[subcommandIndex]?.toLowerCase();\n\tconst subcommandArgs = subcommandIndex >= 0 ? args.slice(subcommandIndex + 1) : [];\n\tif (command === \"sed\") {\n\t\tconst script = args.find((argument) => !argument.startsWith(\"-\"));\n\t\treturn (\n\t\t\tBoolean(script) &&\n\t\t\t(args.includes(\"-n\") || args.some((argument) => /^-[^-]*n[^-]*$/.test(argument))) &&\n\t\t\t/^\\d+(,\\d+)?p$/.test(script ?? \"\")\n\t\t);\n\t}\n\tif ([\"node\", \"python\", \"python3\", \"tsc\", \"biome\", \"ruff\", \"ty\"].includes(command)) {\n\t\tif (args.includes(\"--version\")) return true;\n\t\treturn (\n\t\t\tcommand === \"tsc\" &&\n\t\t\targs.includes(\"--noEmit\") &&\n\t\t\t!args.some(\n\t\t\t\t(argument) =>\n\t\t\t\t\targument === \"--incremental\" ||\n\t\t\t\t\targument.startsWith(\"--incremental=\") ||\n\t\t\t\t\targument === \"--tsBuildInfoFile\" ||\n\t\t\t\t\targument.startsWith(\"--tsBuildInfoFile=\") ||\n\t\t\t\t\targument === \"--generateTrace\" ||\n\t\t\t\t\targument.startsWith(\"--generateTrace=\"),\n\t\t\t)\n\t\t);\n\t}\n\tif (command === \"npm\") {\n\t\tif (subcommand === \"audit\" && subcommandArgs.includes(\"fix\")) return false;\n\t\tif (\n\t\t\t[\"list\", \"ls\", \"view\", \"info\", \"search\", \"outdated\", \"audit\", \"test\"].includes(\n\t\t\t\tsubcommand ?? \"\",\n\t\t\t)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\treturn subcommand === \"run\" && [\"test\", \"check\", \"typecheck\", \"lint\"].includes(args[1] ?? \"\");\n\t}\n\tif ([\"cargo\", \"go\", \"pytest\", \"vitest\", \"jest\"].includes(command)) {\n\t\treturn (\n\t\t\t[\"test\", \"check\"].includes(subcommand ?? \"\") || [\"pytest\", \"vitest\", \"jest\"].includes(command)\n\t\t);\n\t}\n\treturn false;\n}\n\nfunction isSafeGitCommand(\n\targs: string[],\n\tsafeSubcommands: SafeSubcommands,\n\tworkingDirectory?: string,\n) {\n\tconst subcommandIndex = parseGitGlobalOptions(args, workingDirectory);\n\tif (subcommandIndex === undefined) return false;\n\tconst subcommand = args[subcommandIndex]?.toLowerCase();\n\tif (!subcommand || subcommand.startsWith(\"-\")) return false;\n\tconst subcommandArgs = args.slice(subcommandIndex + 1);\n\tconst builtinValidator = (BUILTIN_GIT_VALIDATORS as Record<string, ArgumentValidator>)[\n\t\tsubcommand\n\t];\n\tconst configuredValidator = (CONFIGURABLE_GIT_VALIDATORS as Record<string, ArgumentValidator>)[\n\t\tsubcommand\n\t];\n\tconst configured = safeSubcommands.git?.includes(subcommand as SafeGitSubcommand) === true;\n\tconst validator = builtinValidator ?? (configured ? configuredValidator : undefined);\n\treturn (\n\t\tvalidator !== undefined &&\n\t\thasSafeGitArguments(subcommand, subcommandArgs) &&\n\t\tvalidator(subcommandArgs)\n\t);\n}\n\nfunction parseGitGlobalOptions(args: string[], workingDirectory?: string) {\n\tlet index = 0;\n\twhile (index < args.length) {\n\t\tconst argument = args[index];\n\t\tif (argument === \"--no-pager\") {\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (argument !== \"-C\") break;\n\t\tconst directory = args[index + 1];\n\t\tif (!directory || !isCurrentWorkingDirectory(directory, workingDirectory)) return undefined;\n\t\tindex += 2;\n\t}\n\treturn index;\n}\n\nfunction isCurrentWorkingDirectory(directory: string, workingDirectory?: string) {\n\tif (!workingDirectory || directory.split(/[\\\\/]+/u).includes(\"..\")) return false;\n\tif (normalize(directory) === \".\") return true;\n\treturn isAbsolute(directory) && normalize(directory) === normalize(workingDirectory);\n}\n\nfunction hasSafeGitArguments(subcommand: string, args: string[]) {\n\treturn !args.some(\n\t\t(argument) =>\n\t\t\targument === \"--help\" ||\n\t\t\targument === \"--show-signature\" ||\n\t\t\targument.startsWith(\"--show-signature=\") ||\n\t\t\targument.includes(\"%G\") ||\n\t\t\targument === \"--output\" ||\n\t\t\targument.startsWith(\"--output=\") ||\n\t\t\targument === \"--ext-diff\" ||\n\t\t\targument.startsWith(\"--ext-diff=\") ||\n\t\t\targument === \"--textconv\" ||\n\t\t\targument.startsWith(\"--textconv=\") ||\n\t\t\targument === \"--paginate\" ||\n\t\t\targument === \"--open-files-in-pager\" ||\n\t\t\targument.startsWith(\"--open-files-in-pager=\") ||\n\t\t\t(subcommand === \"grep\" && (argument === \"-O\" || argument.startsWith(\"-O\"))),\n\t);\n}\n\nfunction isSafeGitCatFileArguments(args: string[]) {\n\treturn !args.some(\n\t\t(argument) =>\n\t\t\tmatchesLongOptionPrefix(argument, \"--filters\", \"--fi\") ||\n\t\t\tmatchesLongOptionPrefix(argument, \"--textconv\", \"--t\"),\n\t);\n}\n\nfunction isSafeGitGrepArguments(args: string[]) {\n\treturn !args.some(\n\t\t(argument) =>\n\t\t\tmatchesLongOptionPrefix(argument, \"--textconv\", \"--textc\") ||\n\t\t\tmatchesLongOptionPrefix(argument, \"--open-files-in-pager\", \"--op\") ||\n\t\t\tmatchesLongOptionPrefix(argument, \"--ext-grep\", \"--ext\"),\n\t);\n}\n\nfunction matchesLongOptionPrefix(argument: string, option: string, shortest: string) {\n\tconst optionName = argument.split(\"=\", 1)[0] ?? \"\";\n\treturn optionName.length >= shortest.length && option.startsWith(optionName);\n}\n\nfunction isSafeGitBranchArguments(args: string[]) {\n\tif (args.some((argument) => !argument.startsWith(\"-\"))) return false;\n\treturn !args.some(\n\t\t(argument) =>\n\t\t\t/^-[^-]*[dDmMcCu]/.test(argument) ||\n\t\t\tmatchesLongOptionPrefix(argument, \"--delete\", \"--del\") ||\n\t\t\tmatchesLongOptionPrefix(argument, \"--move\", \"--mov\") ||\n\t\t\tmatchesLongOptionPrefix(argument, \"--copy\", \"--cop\") ||\n\t\t\tmatchesLongOptionPrefix(argument, \"--edit-description\", \"--e\") ||\n\t\t\tmatchesLongOptionPrefix(argument, \"--unset-upstream\", \"--u\") ||\n\t\t\tmatchesLongOptionPrefix(argument, \"--set-upstream-to\", \"--set-u\") ||\n\t\t\tmatchesLongOptionPrefix(argument, \"--create-reflog\", \"--creat\"),\n\t);\n}\n\nfunction isSafeGitRemoteArguments(args: string[]) {\n\tconst actionIndex = args.findIndex((argument) => !argument.startsWith(\"-\"));\n\tif (actionIndex < 0) return true;\n\tconst action = args[actionIndex];\n\tif (action === \"get-url\") return true;\n\tif (action !== \"show\") return false;\n\n\tconst showArgs = args.slice(actionIndex + 1);\n\tif (showArgs.includes(\"--\")) return false;\n\tconst remotes = showArgs.filter((argument) => !argument.startsWith(\"-\"));\n\treturn remotes.length === 0 || (remotes.length === 1 && showArgs.includes(\"-n\"));\n}\n\nfunction isSafeGhCommand(args: string[], safeSubcommands: SafeSubcommands) {\n\tconst group = args[0]?.toLowerCase();\n\tconst action = args[1]?.toLowerCase();\n\tif (!group || !action || group.startsWith(\"-\") || action.startsWith(\"-\")) return false;\n\tconst path = `${group} ${action}` as SafeGhSubcommandPath;\n\tif (!safeSubcommands.gh?.includes(path)) return false;\n\tconst validator = (GH_VALIDATORS as Record<string, ArgumentValidator>)[path];\n\treturn validator?.(args.slice(2)) ?? false;\n}\n\nfunction isSafeGhReadArguments(args: string[]) {\n\treturn !args.some(isUnsafeGhReadArgument) && hasGhJsonOutput(args);\n}\n\nfunction isUnsafeGhReadArgument(argument: string) {\n\treturn (\n\t\targument.startsWith(\"-w\") ||\n\t\targument === \"--web\" ||\n\t\targument.startsWith(\"--web=\") ||\n\t\targument === \"--browser\" ||\n\t\targument.startsWith(\"--browser=\") ||\n\t\targument === \"--paginate\" ||\n\t\targument === \"--pager\" ||\n\t\targument.startsWith(\"--pager=\") ||\n\t\targument === \"--output\" ||\n\t\targument.startsWith(\"--output=\")\n\t);\n}\n\nfunction hasGhJsonOutput(args: string[]) {\n\tlet hasJson = false;\n\tfor (let index = 0; index < args.length; index += 1) {\n\t\tconst argument = args[index];\n\t\tif (argument === \"--json\") {\n\t\t\tconst value = args[index + 1];\n\t\t\tif (!value || value.startsWith(\"-\")) return false;\n\t\t\thasJson = true;\n\t\t\tindex += 1;\n\t\t} else if (argument.startsWith(\"--json=\")) {\n\t\t\tif (argument === \"--json=\") return false;\n\t\t\thasJson = true;\n\t\t}\n\t}\n\treturn hasJson;\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 {\n\tSAFE_GH_SUBCOMMAND_PATHS,\n\tSAFE_GIT_SUBCOMMANDS,\n\ttype SafeGhSubcommandPath,\n\ttype SafeGitSubcommand,\n\ttype SafeSubcommands,\n} 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\t\"inherit\",\n\t\"off\",\n\t\"minimal\",\n\t\"low\",\n\t\"medium\",\n\t\"high\",\n\t\"xhigh\",\n\t\"max\",\n] as const;\nexport const IMPLEMENTATION_PLAN_RETENTIONS = [\n\t\"clear-on-start\",\n\t\"clear-after-first-run\",\n\t\"keep\",\n] as const;\nexport const DEFAULT_PLAN_EXPORT_PATH = \"PLAN.md\";\nconst MODIFIERS = new Set([\"ctrl\", \"shift\", \"alt\", \"super\"]);\nconst BASE_KEYS = new Set([\n\t...\"abcdefghijklmnopqrstuvwxyz0123456789\",\n\t\"`\",\n\t\"-\",\n\t\"=\",\n\t\"[\",\n\t\"]\",\n\t\"\\\\\",\n\t\";\",\n\t\"'\",\n\t\",\",\n\t\".\",\n\t\"/\",\n\t\"!\",\n\t\"@\",\n\t\"#\",\n\t\"$\",\n\t\"%\",\n\t\"^\",\n\t\"&\",\n\t\"*\",\n\t\"(\",\n\t\")\",\n\t\"_\",\n\t\"+\",\n\t\"|\",\n\t\"~\",\n\t\"{\",\n\t\"}\",\n\t\":\",\n\t\"<\",\n\t\">\",\n\t\"?\",\n\t\"escape\",\n\t\"esc\",\n\t\"enter\",\n\t\"return\",\n\t\"tab\",\n\t\"space\",\n\t\"backspace\",\n\t\"delete\",\n\t\"insert\",\n\t\"clear\",\n\t\"home\",\n\t\"end\",\n\t\"pageup\",\n\t\"pagedown\",\n\t\"up\",\n\t\"down\",\n\t\"left\",\n\t\"right\",\n\t...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 = Exclude<PlanModeThinkingLevel, \"inherit\">;\nexport interface PlanModeSettings {\n\tthinkingLevel: PlanModeThinkingLevel;\n\tdefaultPlanTools?: string[];\n\timplementationPlanRetention?: ImplementationPlanRetention;\n\tdefaultPlanExportPath?: string;\n\tsafeSubcommands?: SafeSubcommands;\n\ttoggleShortcut?: KeyId;\n}\nexport interface PlanModeSettingsPatch {\n\tthinkingLevel?: PlanModeThinkingLevel;\n\tdefaultPlanTools?: readonly string[] | null;\n\timplementationPlanRetention?: ImplementationPlanRetention;\n\tdefaultPlanExportPath?: string | null;\n\ttoggleShortcut?: KeyId | null;\n}\nexport interface UpdatePlanModeSettingsOptions {\n\tsettingsPath?: string;\n\tlegacySettingsPath?: string;\n\tsignal?: AbortSignal;\n\tbeforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;\n}\nexport type PlanModeSettingsLoadResult =\n\t| { kind: \"missing\"; notice?: string }\n\t| { kind: \"invalid\"; reason: string; notice?: string }\n\t| { kind: \"loaded\"; settings: PlanModeSettings; notice?: string };\n\ntype SettingsDocument = Record<string, unknown>;\ntype SettingsSnapshot = {\n\tresult: PlanModeSettingsLoadResult;\n\tdocument?: SettingsDocument;\n};\n\nconst mutationQueues = new Map<string, Promise<void>>();\n\nexport function planModeSettingsPath() {\n\treturn join(getAgentDir(), PLAN_MODE_SETTINGS_FILE);\n}\n\nfunction legacyPlanModeSettingsPath() {\n\treturn join(getAgentDir(), LEGACY_PLAN_MODE_SETTINGS_FILE);\n}\n\nexport function normalizePlanModeSettings(value: unknown): PlanModeSettings | undefined {\n\tif (!isSettingsDocument(value)) return undefined;\n\tconst thinkingLevel = Object.hasOwn(value, \"thinkingLevel\")\n\t\t? Reflect.get(value, \"thinkingLevel\")\n\t\t: \"inherit\";\n\tif (!PLAN_MODE_THINKING_LEVELS.includes(thinkingLevel as PlanModeThinkingLevel)) {\n\t\treturn undefined;\n\t}\n\tconst settings: PlanModeSettings = {\n\t\tthinkingLevel: thinkingLevel as PlanModeThinkingLevel,\n\t};\n\tif (Object.hasOwn(value, \"defaultPlanTools\")) {\n\t\tconst defaultPlanTools = normalizeToolNames(Reflect.get(value, \"defaultPlanTools\"));\n\t\tif (!defaultPlanTools) return undefined;\n\t\tsettings.defaultPlanTools = defaultPlanTools;\n\t}\n\tif (Object.hasOwn(value, \"implementationPlanRetention\")) {\n\t\tconst implementationPlanRetention = Reflect.get(value, \"implementationPlanRetention\");\n\t\tif (\n\t\t\t!IMPLEMENTATION_PLAN_RETENTIONS.includes(\n\t\t\t\timplementationPlanRetention as ImplementationPlanRetention,\n\t\t\t)\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tsettings.implementationPlanRetention =\n\t\t\timplementationPlanRetention as ImplementationPlanRetention;\n\t}\n\tif (Object.hasOwn(value, \"defaultPlanExportPath\")) {\n\t\tconst defaultPlanExportPath = normalizePlanExportPath(\n\t\t\tReflect.get(value, \"defaultPlanExportPath\"),\n\t\t);\n\t\tif (!defaultPlanExportPath) return undefined;\n\t\tsettings.defaultPlanExportPath = defaultPlanExportPath;\n\t}\n\tif (Object.hasOwn(value, \"toggleShortcut\")) {\n\t\tconst toggleShortcut = normalizeKeyId(Reflect.get(value, \"toggleShortcut\"));\n\t\tif (!toggleShortcut) return undefined;\n\t\tsettings.toggleShortcut = toggleShortcut;\n\t}\n\tif (Object.hasOwn(value, \"safeSubcommands\")) {\n\t\tconst safeSubcommands = normalizeSafeSubcommands(Reflect.get(value, \"safeSubcommands\"));\n\t\tif (!safeSubcommands) return undefined;\n\t\tsettings.safeSubcommands = safeSubcommands;\n\t}\n\treturn settings;\n}\n\nfunction normalizeToolNames(value: unknown) {\n\tif (\n\t\t!Array.isArray(value) ||\n\t\t!value.every((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n\t) {\n\t\treturn undefined;\n\t}\n\treturn Array.from(new Set(value));\n}\n\nfunction normalizePlanExportPath(value: unknown) {\n\tif (typeof value !== \"string\") return undefined;\n\tconst normalized = value.trim();\n\tif (\n\t\t!normalized ||\n\t\tnormalized.length > MAX_PLAN_EXPORT_PATH_LENGTH ||\n\t\t!/[^@\\s]/u.test(normalized) ||\n\t\t[...normalized].some((character) => {\n\t\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\t\treturn codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n\t\t})\n\t) {\n\t\treturn undefined;\n\t}\n\treturn normalized;\n}\n\nexport function normalizeKeyId(value: unknown): KeyId | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst normalized = value.trim().toLowerCase();\n\tconst base = [...BASE_KEYS]\n\t\t.sort((left, right) => right.length - left.length)\n\t\t.find((candidate) => normalized === candidate || normalized.endsWith(`+${candidate}`));\n\tif (!base) return undefined;\n\tconst prefix = normalized.slice(0, normalized.length - base.length);\n\tif (!prefix) return base as KeyId;\n\tif (/^f(?:[1-9]|1[0-2])$/.test(base) || !prefix.endsWith(\"+\")) return undefined;\n\tconst modifiers = prefix.slice(0, -1).split(\"+\");\n\tif (\n\t\tmodifiers.length === 0 ||\n\t\tmodifiers.some((modifier) => !MODIFIERS.has(modifier)) ||\n\t\tnew Set(modifiers).size !== modifiers.length\n\t) {\n\t\treturn undefined;\n\t}\n\treturn normalized as KeyId;\n}\n\nfunction normalizeSafeSubcommands(value: unknown): SafeSubcommands | undefined {\n\tif (!isSettingsDocument(value)) return undefined;\n\tif (Object.keys(value).some((key) => key !== \"git\" && key !== \"gh\")) return undefined;\n\n\tconst safeSubcommands: SafeSubcommands = {};\n\tif (Object.hasOwn(value, \"git\")) {\n\t\tconst git = normalizeKnownValues(Reflect.get(value, \"git\"), SAFE_GIT_SUBCOMMANDS);\n\t\tif (!git) return undefined;\n\t\tsafeSubcommands.git = git as SafeGitSubcommand[];\n\t}\n\tif (Object.hasOwn(value, \"gh\")) {\n\t\tconst gh = normalizeKnownValues(Reflect.get(value, \"gh\"), SAFE_GH_SUBCOMMAND_PATHS);\n\t\tif (!gh) return undefined;\n\t\tsafeSubcommands.gh = gh as SafeGhSubcommandPath[];\n\t}\n\treturn safeSubcommands;\n}\n\nfunction normalizeKnownValues(value: unknown, supported: readonly string[]) {\n\tif (\n\t\t!Array.isArray(value) ||\n\t\t!value.every((item): item is string => typeof item === \"string\" && supported.includes(item))\n\t) {\n\t\treturn undefined;\n\t}\n\treturn Array.from(new Set(value));\n}\n\nexport async function readPlanModeSettings(\n\tsettingsPath?: string,\n): Promise<PlanModeSettingsLoadResult> {\n\tif (settingsPath) {\n\t\tawait awaitPlanModeSettingsWrites(settingsPath);\n\t\treturn (await readSettingsSnapshot(settingsPath)).result;\n\t}\n\tconst canonicalPath = planModeSettingsPath();\n\tawait awaitPlanModeSettingsWrites(canonicalPath);\n\tconst canonical = await readSettingsSnapshot(canonicalPath);\n\tconst legacyPath = legacyPlanModeSettingsPath();\n\tif (canonical.result.kind !== \"missing\") {\n\t\treturn (await pathExists(legacyPath))\n\t\t\t? {\n\t\t\t\t\t...canonical.result,\n\t\t\t\t\tnotice: `${LEGACY_PLAN_MODE_SETTINGS_FILE} ignored because ${PLAN_MODE_SETTINGS_FILE} takes precedence.`,\n\t\t\t\t}\n\t\t\t: canonical.result;\n\t}\n\n\tconst legacy = await readSettingsSnapshot(legacyPath);\n\tconst raced = await readSettingsSnapshot(canonicalPath);\n\tif (raced.result.kind !== \"missing\") return raced.result;\n\treturn legacy.result.kind === \"loaded\"\n\t\t? {\n\t\t\t\t...legacy.result,\n\t\t\t\tnotice: `Using legacy ${LEGACY_PLAN_MODE_SETTINGS_FILE}; rename it to ${PLAN_MODE_SETTINGS_FILE}. The legacy file was not modified.`,\n\t\t\t}\n\t\t: legacy.result;\n}\n\nexport function updatePlanModeSettings(\n\tpatch: PlanModeSettingsPatch,\n\toptions: UpdatePlanModeSettingsOptions = {},\n): Promise<PlanModeSettings> {\n\tconst settingsPath = options.settingsPath ?? planModeSettingsPath();\n\tconst legacySettingsPath =\n\t\toptions.legacySettingsPath ?? (options.settingsPath ? undefined : legacyPlanModeSettingsPath());\n\treturn enqueueMutation(settingsPath, async () => {\n\t\toptions.signal?.throwIfAborted();\n\t\tconst current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);\n\t\tconst updated: SettingsDocument = { ...current };\n\t\tif (patch.thinkingLevel !== undefined) updated.thinkingLevel = patch.thinkingLevel;\n\t\tif (patch.defaultPlanTools === null) delete updated.defaultPlanTools;\n\t\telse if (patch.defaultPlanTools !== undefined) {\n\t\t\tupdated.defaultPlanTools = [...patch.defaultPlanTools];\n\t\t}\n\t\tif (patch.implementationPlanRetention !== undefined) {\n\t\t\tupdated.implementationPlanRetention = patch.implementationPlanRetention;\n\t\t}\n\t\tif (patch.defaultPlanExportPath === null) delete updated.defaultPlanExportPath;\n\t\telse if (patch.defaultPlanExportPath !== undefined) {\n\t\t\tupdated.defaultPlanExportPath = patch.defaultPlanExportPath;\n\t\t}\n\t\tif (patch.toggleShortcut === null) delete updated.toggleShortcut;\n\t\telse if (patch.toggleShortcut !== undefined) {\n\t\t\tupdated.toggleShortcut = patch.toggleShortcut;\n\t\t}\n\t\tconst settings = normalizePlanModeSettings(updated);\n\t\tif (!settings) throw invalidSettingsError(settingsPath, \"invalid settings shape\");\n\t\tawait publishSettings(settingsPath, updated, options.signal, options.beforeRename);\n\t\treturn settings;\n\t});\n}\n\nexport async function awaitPlanModeSettingsWrites(\n\tsettingsPath = planModeSettingsPath(),\n): Promise<void> {\n\tawait mutationQueues.get(settingsPath);\n}\n\nfunction enqueueMutation<T>(settingsPath: string, mutation: () => Promise<T>): Promise<T> {\n\tconst previous = mutationQueues.get(settingsPath) ?? Promise.resolve();\n\tconst result = previous.then(mutation, mutation);\n\tconst settled = result.then(\n\t\t() => undefined,\n\t\t() => undefined,\n\t);\n\tmutationQueues.set(settingsPath, settled);\n\tvoid settled.finally(() => {\n\t\tif (mutationQueues.get(settingsPath) === settled) mutationQueues.delete(settingsPath);\n\t});\n\treturn result;\n}\n\nasync function readSettingsDocumentForUpdate(\n\tsettingsPath: string,\n\tlegacySettingsPath: string | undefined,\n): Promise<SettingsDocument> {\n\tconst canonical = await readSettingsSnapshot(settingsPath);\n\tif (canonical.result.kind === \"loaded\") return canonical.document ?? {};\n\tif (canonical.result.kind === \"invalid\") {\n\t\tthrow invalidSettingsError(settingsPath, canonical.result.reason);\n\t}\n\tif (!legacySettingsPath) return {};\n\n\tconst legacy = await readSettingsSnapshot(legacySettingsPath);\n\tconst raced = await readSettingsSnapshot(settingsPath);\n\tif (raced.result.kind === \"loaded\") return raced.document ?? {};\n\tif (raced.result.kind === \"invalid\") {\n\t\tthrow invalidSettingsError(settingsPath, raced.result.reason);\n\t}\n\tif (legacy.result.kind === \"invalid\") {\n\t\tthrow invalidSettingsError(legacySettingsPath, legacy.result.reason);\n\t}\n\treturn legacy.document ?? {};\n}\n\nasync function readSettingsSnapshot(settingsPath: string): Promise<SettingsSnapshot> {\n\tlet contents: string;\n\ttry {\n\t\tcontents = await readSettingsContents(settingsPath);\n\t} catch (error: unknown) {\n\t\tif (isNodeError(error) && error.code === \"ENOENT\") return { result: { kind: \"missing\" } };\n\t\treturn { result: { kind: \"invalid\", reason: safeReadError(error) } };\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(contents) as unknown;\n\t} catch {\n\t\treturn { result: { kind: \"invalid\", reason: \"invalid JSON\" } };\n\t}\n\tconst settings = normalizePlanModeSettings(parsed);\n\tif (!settings || !isSettingsDocument(parsed)) {\n\t\treturn { result: { kind: \"invalid\", reason: \"invalid settings shape\" } };\n\t}\n\treturn { document: parsed, result: { kind: \"loaded\", settings } };\n}\n\nasync function readSettingsContents(settingsPath: string): Promise<string> {\n\tconst flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0);\n\tconst handle = await open(settingsPath, flags);\n\ttry {\n\t\tconst stats = await handle.stat();\n\t\tif (!stats.isFile()) throw new Error(\"settings path is not a regular file\");\n\t\tif (stats.size > MAX_SETTINGS_BYTES) {\n\t\t\tthrow new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);\n\t\t}\n\t\tconst buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);\n\t\tlet offset = 0;\n\t\twhile (offset < buffer.byteLength) {\n\t\t\tconst { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);\n\t\t\tif (bytesRead === 0) break;\n\t\t\toffset += bytesRead;\n\t\t}\n\t\tif (offset > MAX_SETTINGS_BYTES) {\n\t\t\tthrow new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);\n\t\t}\n\t\ttry {\n\t\t\treturn new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n\t\t\t\tbuffer.subarray(0, offset),\n\t\t\t);\n\t\t} catch {\n\t\t\tthrow new Error(\"settings file is not valid UTF-8\");\n\t\t}\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\nasync function publishSettings(\n\tsettingsPath: string,\n\tdocument: SettingsDocument,\n\tsignal?: AbortSignal,\n\tbeforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>,\n): Promise<void> {\n\tsignal?.throwIfAborted();\n\tconst contents = `${JSON.stringify(document, null, 2)}\\n`;\n\tif (Buffer.byteLength(contents, \"utf8\") > MAX_SETTINGS_BYTES) {\n\t\tthrow new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);\n\t}\n\tconst directory = dirname(settingsPath);\n\tawait mkdir(directory, { recursive: true });\n\tsignal?.throwIfAborted();\n\tconst temporaryPath = join(\n\t\tdirectory,\n\t\t`.${basename(settingsPath)}.${process.pid}.${randomUUID()}.tmp`,\n\t);\n\ttry {\n\t\tawait writeFile(temporaryPath, contents, {\n\t\t\tencoding: \"utf8\",\n\t\t\tflag: \"wx\",\n\t\t\tmode: 0o600,\n\t\t\tsignal,\n\t\t});\n\t\tawait beforeRename?.(temporaryPath, settingsPath);\n\t\tsignal?.throwIfAborted();\n\t\tawait rename(temporaryPath, settingsPath);\n\t} finally {\n\t\tawait rm(temporaryPath, { force: true }).catch(() => undefined);\n\t}\n}\n\nfunction isSettingsDocument(value: unknown): value is SettingsDocument {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nasync function pathExists(path: string) {\n\ttry {\n\t\tconst handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n\t\tawait handle.close();\n\t\treturn true;\n\t} catch (error: unknown) {\n\t\treturn !(isNodeError(error) && error.code === \"ENOENT\");\n\t}\n}\n\nfunction invalidSettingsError(settingsPath: string, reason: string) {\n\treturn new Error(`pi-plan-mode settings at ${settingsPath} are invalid: ${reason}`);\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n\nfunction safeReadError(error: unknown) {\n\tif (isNodeError(error) && error.code === \"ELOOP\") return \"settings path is not a regular file\";\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nexport function configuredThinkingLevel(\n\tsettings: PlanModeSettings,\n): PlanModeFixedThinkingLevel | undefined {\n\treturn settings.thinkingLevel === \"inherit\" ? undefined : settings.thinkingLevel;\n}\n\nexport function configuredImplementationPlanRetention(\n\tsettings: PlanModeSettings,\n): ImplementationPlanRetention {\n\treturn settings.implementationPlanRetention ?? \"clear-on-start\";\n}\n\nexport function configuredPlanExportPath(settings: PlanModeSettings) {\n\treturn settings.defaultPlanExportPath ?? DEFAULT_PLAN_EXPORT_PATH;\n}\n\nexport function configuredPlanModeToggleShortcut(settings: PlanModeSettings): KeyId | undefined {\n\treturn settings.toggleShortcut;\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\tpath: string;\n}\n\nexport interface PlanExportDestination {\n\tconfiguredPath: string;\n\tresolvedPath: string;\n}\n\nexport interface PlanExportLifecycle {\n\tsignal: AbortSignal;\n\tisCurrent(): boolean;\n\tgetState?(): PlanModeState;\n\tfinishReady?(): void;\n}\n\nexport async function exportStoredPlan(\n\tstate: PlanModeState,\n\trequestedPath: string | undefined,\n\tctx: ExtensionContext,\n\tlifecycle?: PlanExportLifecycle,\n\tdefaultPath = DEFAULT_PLAN_EXPORT_PATH,\n) {\n\tconst plan =\n\t\t(state.enabled ? state.latestPlan : undefined)?.trim() ??\n\t\tstate.savedPlan?.plan.trim() ??\n\t\tstate.activeImplementation?.plan.trim();\n\tif (!plan) {\n\t\tconst error = new Error(\n\t\t\t\"No completed plan is available to export. Use /plan finalize when planning is complete.\",\n\t\t);\n\t\tif (!ctx.hasUI) throw error;\n\t\tctx.ui.notify(error.message, \"warning\");\n\t\treturn false;\n\t}\n\n\tconst isCurrent = () =>\n\t\t!lifecycle ||\n\t\t(lifecycle.isCurrent() && (!lifecycle.getState || lifecycle.getState() === state));\n\tlet result: PlanExportResult;\n\ttry {\n\t\tresult = await exportPlanToFile(\n\t\t\tplan,\n\t\t\trequestedPath,\n\t\t\tctx.cwd,\n\t\t\tlifecycle?.signal,\n\t\t\tisCurrent,\n\t\t\tdefaultPath,\n\t\t);\n\t} catch (error: unknown) {\n\t\tif (lifecycle?.signal.aborted || !isCurrent()) return false;\n\t\tif (!ctx.hasUI) throw error;\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tctx.ui.notify(safeNotification(`Unable to export plan: ${detail}`), \"error\");\n\t\treturn false;\n\t}\n\n\tif (!isCurrent()) return false;\n\tconst finishedReady =\n\t\tstate.enabled && Boolean(state.latestPlan?.trim()) && lifecycle?.finishReady !== undefined;\n\tif (finishedReady) lifecycle.finishReady?.();\n\tconst detail = finishedReady ? \" Plan mode disabled.\" : \"\";\n\tctx.ui.notify(safeNotification(`Plan exported to ${result.path}.${detail}`), \"info\");\n\treturn true;\n}\n\nexport async function exportPlanToFile(\n\tplan: string,\n\trequestedPath: string | undefined,\n\tcwd: string,\n\tsignal?: AbortSignal,\n\tisCurrent: () => boolean = () => true,\n\tdefaultPath = DEFAULT_PLAN_EXPORT_PATH,\n): Promise<PlanExportResult> {\n\tconst path = resolvePlanExportPath(requestedPath, cwd, defaultPath);\n\tawait withFileMutationQueue(path, async () => {\n\t\tthrowIfCancelled(signal, isCurrent);\n\t\tawait mkdir(dirname(path), { recursive: true });\n\t\tthrowIfCancelled(signal, isCurrent);\n\t\ttry {\n\t\t\tawait writeFile(path, `${plan}\\n`, { encoding: \"utf8\", flag: \"wx\" });\n\t\t} catch (error: unknown) {\n\t\t\tif (isNodeError(error) && error.code === \"EEXIST\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Plan export target already exists: ${path}. Choose another path or remove it first.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t});\n\treturn { path };\n}\n\nexport function planExportDestination(defaultPath: string, cwd: string): PlanExportDestination {\n\treturn {\n\t\tconfiguredPath: safeNotification(defaultPath),\n\t\tresolvedPath: safeNotification(resolvePlanExportPath(undefined, cwd, defaultPath)),\n\t};\n}\n\nexport function resolvePlanExportPath(\n\trequestedPath: string | undefined,\n\tcwd: string,\n\tdefaultPath = DEFAULT_PLAN_EXPORT_PATH,\n) {\n\tconst rawPath = requestedPath?.trim() || defaultPath;\n\tconst normalizedPath = rawPath.startsWith(\"@\") ? rawPath.slice(1) : rawPath;\n\tif (!normalizedPath.trim()) throw new Error(\"Plan export path must not be empty.\");\n\tif (normalizedPath.includes(\"\\0\")) {\n\t\tthrow new Error(\"Plan export path must not contain NUL bytes.\");\n\t}\n\treturn resolve(cwd, normalizedPath);\n}\n\nfunction safeNotification(value: string) {\n\tlet sanitized = \"\";\n\tfor (const character of stripVTControlCharacters(value)) {\n\t\tconst codePoint = character.codePointAt(0);\n\t\tsanitized +=\n\t\t\tcodePoint !== undefined && codePoint > 0x1f && !(codePoint >= 0x7f && codePoint <= 0x9f)\n\t\t\t\t? character\n\t\t\t\t: \" \";\n\t}\n\treturn sanitized;\n}\n\nfunction throwIfCancelled(signal: AbortSignal | undefined, isCurrent: () => boolean) {\n\tif (!signal?.aborted && isCurrent()) return;\n\tthrow signal?.reason instanceof Error\n\t\t? signal.reason\n\t\t: new DOMException(\"Plan export cancelled\", \"AbortError\");\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport type {\n\tQuestionnaireAnswer,\n\tQuestionnaireQuestion,\n\tRunQuestionnaireResult,\n} 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\tlabel: string;\n\tdescription?: string;\n};\n\nexport type PlanModeQuestion = {\n\tid: string;\n\theader: string;\n\tquestion: string;\n\toptions: PlanModeQuestionOption[];\n};\n\nexport type PlanModeQuestionAnswer = {\n\tid: string;\n\theader: string;\n\tquestion: string;\n\tanswer: string;\n\twasCustom: boolean;\n\toptionIndex?: number;\n\tnote?: string;\n};\n\ntype PlanModeQuestionReason =\n\t| \"cancelled\"\n\t| \"ui_unavailable\"\n\t| \"plan_mode_inactive\"\n\t| \"invalid_input\";\n\ntype PlanModeQuestionDetails = {\n\tcancelled: boolean;\n\treason?: PlanModeQuestionReason;\n\tquestions: PlanModeQuestion[];\n\tanswers?: PlanModeQuestionAnswer[];\n};\n\nexport const PLAN_MODE_QUESTION_PARAMS = {\n\ttype: \"object\",\n\tadditionalProperties: false,\n\trequired: [\"questions\"],\n\tproperties: {\n\t\tquestions: {\n\t\t\ttype: \"array\",\n\t\t\tminItems: 1,\n\t\t\tmaxItems: 3,\n\t\t\tdescription: \"Questions to show the user. Prefer 1 and do not exceed 3.\",\n\t\t\titems: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tadditionalProperties: false,\n\t\t\t\trequired: [\"id\", \"header\", \"question\", \"options\"],\n\t\t\t\tproperties: {\n\t\t\t\t\tid: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"Stable identifier for mapping answers (snake_case).\",\n\t\t\t\t\t},\n\t\t\t\t\theader: {\n\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\tdescription: \"Short header label shown in the UI (12 or fewer chars).\",\n\t\t\t\t\t},\n\t\t\t\t\tquestion: { type: \"string\", description: \"Single-sentence prompt shown to the user.\" },\n\t\t\t\t\toptions: {\n\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\tminItems: 2,\n\t\t\t\t\t\tmaxItems: 4,\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"Provide 2-4 mutually exclusive choices. Put the recommended option first when there is a clear default.\",\n\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t\t\trequired: [\"label\", \"description\"],\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\tlabel: { type: \"string\", description: \"User-facing label (1-5 words).\" },\n\t\t\t\t\t\t\t\tdescription: {\n\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\tdescription: \"One short sentence explaining impact/tradeoff if selected.\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t},\n} as const;\n\ntype NormalizePlanModeQuestionParamsResult =\n\t| { ok: true; questions: PlanModeQuestion[] }\n\t| { ok: false; error: string };\n\nexport function normalizePlanModeQuestionParams(\n\tinput: unknown,\n): NormalizePlanModeQuestionParamsResult {\n\tif (!isRecord(input) || !Array.isArray(input.questions)) {\n\t\treturn { ok: false, error: \"questions must be an array\" };\n\t}\n\tif (input.questions.length < 1 || input.questions.length > 3) {\n\t\treturn { ok: false, error: \"questions must contain 1-3 items\" };\n\t}\n\n\tconst questions: PlanModeQuestion[] = [];\n\tfor (const [questionIndex, rawQuestion] of input.questions.entries()) {\n\t\tif (!isRecord(rawQuestion)) {\n\t\t\treturn { ok: false, error: `question ${questionIndex + 1} must be an object` };\n\t\t}\n\t\tconst id = stringField(rawQuestion.id);\n\t\tconst header = stringField(rawQuestion.header);\n\t\tconst question = stringField(rawQuestion.question);\n\t\tif (!id || !header || !question) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `question ${questionIndex + 1} requires non-empty id, header, and question`,\n\t\t\t};\n\t\t}\n\t\tif (!Array.isArray(rawQuestion.options)) {\n\t\t\treturn { ok: false, error: `question ${questionIndex + 1} options must be an array` };\n\t\t}\n\t\tif (rawQuestion.options.length < 2 || rawQuestion.options.length > 4) {\n\t\t\treturn { ok: false, error: `question ${questionIndex + 1} options must contain 2-4 items` };\n\t\t}\n\t\tconst options: PlanModeQuestionOption[] = [];\n\t\tfor (const [optionIndex, rawOption] of rawQuestion.options.entries()) {\n\t\t\tif (!isRecord(rawOption)) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `question ${questionIndex + 1} option ${optionIndex + 1} must be an object`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst label = stringField(rawOption.label);\n\t\t\tif (!label) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `question ${questionIndex + 1} option ${optionIndex + 1} requires a label`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst description = stringField(rawOption.description);\n\t\t\tif (!description) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `question ${questionIndex + 1} option ${optionIndex + 1} requires a description`,\n\t\t\t\t};\n\t\t\t}\n\t\t\toptions.push({ label, description });\n\t\t}\n\t\tquestions.push({ id, header, question, options });\n\t}\n\treturn { ok: true, questions };\n}\n\nexport async function answerPlanModeQuestions(\n\tquestions: PlanModeQuestion[],\n\tctx: ExtensionContext,\n\tlifecycle: { isCurrent(): boolean; isEnabled(): boolean },\n) {\n\tconst answers = await askPlanModeQuestions(\n\t\tquestions,\n\t\tctx,\n\t\t() => lifecycle.isCurrent() && lifecycle.isEnabled(),\n\t);\n\tif (!lifecycle.isCurrent()) {\n\t\treturn planModeQuestionCancelled(\n\t\t\tquestions,\n\t\t\t\"cancelled\",\n\t\t\t\"Plan-mode question cancelled because the session changed.\",\n\t\t);\n\t}\n\tif (!lifecycle.isEnabled()) {\n\t\treturn planModeQuestionCancelled(\n\t\t\tquestions,\n\t\t\t\"plan_mode_inactive\",\n\t\t\t\"Plan-mode question cancelled because Plan mode is no longer active.\",\n\t\t);\n\t}\n\tif (!answers) {\n\t\treturn planModeQuestionCancelled(\n\t\t\tquestions,\n\t\t\t\"cancelled\",\n\t\t\t\"User cancelled the Plan-mode question prompt.\",\n\t\t);\n\t}\n\treturn planModeQuestionAnswered(questions, answers);\n}\n\nexport async function askPlanModeQuestions(\n\tquestions: PlanModeQuestion[],\n\tctx: ExtensionContext,\n\tshouldContinue: () => boolean = () => true,\n): Promise<PlanModeQuestionAnswer[] | undefined> {\n\tconst { runQuestionnaire, sanitizeTerminalText } = await import(\"@narumitw/pi-tui-kit\");\n\tif (!shouldContinue()) return undefined;\n\tconst runnerQuestions: QuestionnaireQuestion<string>[] = questions.map((question, index) => ({\n\t\tid: String(index),\n\t\theader: displayText(question.header, `Question ${index + 1}`, sanitizeTerminalText),\n\t\tprompt: displayText(question.question, `Question ${index + 1}`, sanitizeTerminalText),\n\t\toptions: question.options.map((option, optionIndex) => ({\n\t\t\t...option,\n\t\t\tlabel: displayText(option.label, `Option ${optionIndex + 1}`, sanitizeTerminalText),\n\t\t})),\n\t}));\n\tconst result = await runQuestionnaire(ctx, {\n\t\tquestions: runnerQuestions,\n\t\tallowNotes: true,\n\t\tmaxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,\n\t\tsignal: ctx.signal,\n\t\tisCurrent: shouldContinue,\n\t});\n\tif (!shouldContinue()) return undefined;\n\treturn mapQuestionnaireResult(questions, result);\n}\n\nfunction mapQuestionnaireResult(\n\tquestions: PlanModeQuestion[],\n\tresult: RunQuestionnaireResult<string>,\n): PlanModeQuestionAnswer[] | undefined {\n\tif (result.kind !== \"submitted\") return undefined;\n\tif (result.answers.length !== questions.length) {\n\t\tthrow new Error(\"Questionnaire returned an incomplete answer set\");\n\t}\n\n\tconst answers = new Map<number, QuestionnaireAnswer<string>>();\n\tfor (const answer of result.answers) {\n\t\tconst index = Number(answer.questionId);\n\t\tif (!Number.isSafeInteger(index) || String(index) !== answer.questionId || !questions[index]) {\n\t\t\tthrow new Error(\"Questionnaire returned an answer for an unknown question\");\n\t\t}\n\t\tif (answers.has(index)) throw new Error(\"Questionnaire returned duplicate answers\");\n\t\tif (answer.wasCustom) {\n\t\t\tif (answer.optionIndex !== undefined) {\n\t\t\t\tthrow new Error(\"Questionnaire returned a custom answer with an option index\");\n\t\t\t}\n\t\t\tif (!answer.answer.trim()) return undefined;\n\t\t} else if (\n\t\t\tanswer.optionIndex === undefined ||\n\t\t\t!questions[index]?.options[answer.optionIndex - 1]\n\t\t) {\n\t\t\tthrow new Error(\"Questionnaire returned an invalid selected option\");\n\t\t}\n\t\tanswers.set(index, answer);\n\t}\n\n\treturn questions.map((question, index) => {\n\t\tconst answer = answers.get(index);\n\t\tif (!answer) throw new Error(\"Questionnaire returned an incomplete answer set\");\n\t\tconst answerText = answer.wasCustom\n\t\t\t? answer.answer\n\t\t\t: (question.options[(answer.optionIndex ?? 0) - 1]?.label ?? answer.answer);\n\t\treturn answerFor(question, answerText, {\n\t\t\twasCustom: answer.wasCustom,\n\t\t\toptionIndex: answer.optionIndex,\n\t\t\tnote: answer.note,\n\t\t});\n\t});\n}\n\nfunction displayText(value: string, fallback: string, sanitize: (value: string) => string): string {\n\tconst sanitized = sanitize(value);\n\treturn sanitized.trim() ? sanitized : fallback;\n}\n\nfunction answerFor(\n\tquestion: PlanModeQuestion,\n\tanswer: string,\n\toptions: { wasCustom: boolean; optionIndex?: number; note?: string },\n): PlanModeQuestionAnswer {\n\tconst result: PlanModeQuestionAnswer = {\n\t\tid: question.id,\n\t\theader: question.header,\n\t\tquestion: question.question,\n\t\tanswer,\n\t\twasCustom: options.wasCustom,\n\t};\n\tif (options.optionIndex !== undefined) result.optionIndex = options.optionIndex;\n\tif (options.note !== undefined) result.note = options.note;\n\treturn result;\n}\n\nexport function planModeQuestionAnswered(\n\tquestions: PlanModeQuestion[],\n\tanswers: PlanModeQuestionAnswer[],\n) {\n\treturn {\n\t\tcontent: [\n\t\t\t{ type: \"text\" as const, text: formatPlanModeQuestionPayload({ cancelled: false, answers }) },\n\t\t],\n\t\tdetails: { cancelled: false, questions, answers } satisfies PlanModeQuestionDetails,\n\t};\n}\n\nexport function planModeQuestionCancelled(\n\tquestions: PlanModeQuestion[],\n\treason: PlanModeQuestionReason,\n\tmessage: string,\n) {\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\" as const,\n\t\t\t\ttext: formatPlanModeQuestionPayload({ cancelled: true, reason, message }),\n\t\t\t},\n\t\t],\n\t\tdetails: { cancelled: true, reason, questions } satisfies PlanModeQuestionDetails,\n\t};\n}\n\nfunction formatPlanModeQuestionPayload(payload: {\n\tcancelled: boolean;\n\treason?: PlanModeQuestionReason;\n\tmessage?: string;\n\tanswers?: PlanModeQuestionAnswer[];\n}) {\n\treturn JSON.stringify(payload, null, 2);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction stringField(value: unknown) {\n\treturn typeof value === \"string\" ? value.trim() : undefined;\n}\n", "import type { ToolInfo } from \"@earendil-works/pi-coding-agent\";\nimport {\n\tcanSelectToolInPlanMode,\n\tclassifyPlanModeTool,\n\tisBuiltinTool,\n\tSAFE_BUILTIN_PLAN_TOOLS,\n} from \"./tool-policy.js\";\n\nexport function toolNameFromLegacyKey(key: string, tools: ToolInfo[]) {\n\tconst directName = tools.find((tool) => tool.name === key)?.name;\n\tif (directName) return directName;\n\tconst [name] = key.split(\"\\u001f\");\n\treturn tools.find((tool) => tool.name === name) ? name : undefined;\n}\n\nexport function compareTools(left: ToolInfo, right: ToolInfo) {\n\tconst leftBuiltin = isBuiltinTool(left);\n\tconst rightBuiltin = isBuiltinTool(right);\n\tif (leftBuiltin !== rightBuiltin) return leftBuiltin ? -1 : 1;\n\treturn left.name.localeCompare(right.name);\n}\n\nexport function toolPolicyLabel(tool: ToolInfo) {\n\tconst policy = classifyPlanModeTool(tool);\n\tif (policy === \"read-only\") return \"built-in read-only\";\n\tif (policy === \"limited\") return \"built-in limited\";\n\tif (policy === \"blocked\") return \"built-in blocked\";\n\treturn `user opt-in: ${toolSourceLabel(tool)}`;\n}\n\nfunction toolSourceLabel(tool: ToolInfo) {\n\tconst sourceInfo = tool.sourceInfo;\n\tconst source = `${sourceInfo.scope}/${sourceInfo.source}`;\n\treturn sourceInfo.path ? `${source} ${sourceInfo.path}` : source;\n}\n\nexport function unique(values: string[]) {\n\treturn Array.from(new Set(values));\n}\n\nexport function filterAvailableSelectedToolNames(names: string[], tools: ToolInfo[]) {\n\tconst availableNames = new Set(tools.filter(canSelectToolInPlanMode).map((tool) => tool.name));\n\treturn unique(names.filter((name) => availableNames.has(name)));\n}\n\nexport function defaultPlanModeToolNames(tools: ToolInfo[], configuredNames: string[] | undefined) {\n\tif (configuredNames !== undefined) return unique(configuredNames);\n\treturn tools\n\t\t.filter((tool) => isBuiltinTool(tool) && SAFE_BUILTIN_PLAN_TOOLS.has(tool.name))\n\t\t.map((tool) => tool.name);\n}\n\ninterface PlanModeToolSelectionSnapshot {\n\tselectedToolNames?: string[];\n\tselectedToolKeys?: string[];\n\tdefaultPlanTools?: string[];\n}\n\nexport function snapshotPlanModeSelectedNames(\n\ttools: ToolInfo[],\n\tselection: PlanModeToolSelectionSnapshot,\n) {\n\tconst selectedToolNames =\n\t\tselection.selectedToolNames ??\n\t\tselection.selectedToolKeys\n\t\t\t?.map((key) => toolNameFromLegacyKey(key, tools))\n\t\t\t.filter((name): name is string => name !== undefined);\n\treturn new Set(\n\t\tselectedToolNames === undefined\n\t\t\t? defaultPlanModeToolNames(tools, selection.defaultPlanTools)\n\t\t\t: unique(selectedToolNames),\n\t);\n}\n"],
5
+ "mappings": ";;;;AAAA,SAAS,wBAAwB;AACjC,SAAS,gBAAgB;AAElB,IAAM,+BAA+B;AACrC,IAAM,6BAA6B;AACnC,IAAM,sBAAsB;AAQ5B,IAAM,4BAA4B;AAAA,EACxC,MAAM;AAAA,EACN,sBAAsB;AAAA,EACtB,UAAU,CAAC,MAAM;AAAA,EACjB,YAAY;AAAA,IACX,MAAM;AAAA,MACL,MAAM;AAAA,MACN,WAAW;AAAA,MACX,WAAW;AAAA,MACX,aAAa;AAAA,IACd;AAAA,EACD;AACD;AAIO,SAAS,4BAA4B,OAAmD;AAC9F,MAAI,CAAC,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,UAAU;AACvD,WAAO,EAAE,IAAI,OAAO,OAAO,wBAAwB;AAAA,EACpD;AACA,QAAM,OAAO,MAAM,KAAK,KAAK;AAC7B,MAAI,CAAC,KAAM,QAAO,EAAE,IAAI,OAAO,OAAO,yBAAyB;AAC/D,MAAI,KAAK,SAAS,qBAAqB;AACtC,WAAO;AAAA,MACN,IAAI;AAAA,MACJ,OAAO,wBAAwB,mBAAmB;AAAA,IACnD;AAAA,EACD;AACA,SAAO,EAAE,IAAI,MAAM,KAAK;AACzB;AAEO,SAAS,0BAA0B,OAAgB;AACzD,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO;AAC7B,MACC,MAAM,YAAY,8BAClB,MAAM,WAAW,8BAChB;AACD,WAAO;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,QAAO;AACnC,MAAI,WAAW,UAAW,QAAO;AACjC,MAAI,WAAW,UAAW,QAAO;AACjC,SAAO,gBAAgB,gBAAgB,IAAI,CAAC;AAC7C;AAEA,SAAS,gBAAgB,MAAgB;AACxC,QAAM,aAAa,KAAK;AACxB,QAAM,SAAS,GAAG,WAAW,KAAK,IAAI,WAAW,MAAM;AACvD,SAAO,WAAW,OAAO,GAAG,MAAM,IAAI,WAAW,IAAI,KAAK;AAC3D;AAEO,SAAS,OAAO,QAAkB;AACxC,SAAO,MAAM,KAAK,IAAI,IAAI,MAAM,CAAC;AAClC;AAOO,SAAS,yBAAyB,OAAmB,iBAAuC;AAClG,MAAI,oBAAoB,OAAW,QAAO,OAAO,eAAe;AAChE,SAAO,MACL,OAAO,CAAC,SAAS,cAAc,IAAI,KAAK,wBAAwB,IAAI,KAAK,IAAI,CAAC,EAC9E,IAAI,CAAC,SAAS,KAAK,IAAI;AAC1B;AAQO,SAAS,8BACf,OACA,WACC;AACD,QAAM,oBACL,UAAU,qBACV,UAAU,kBACP,IAAI,CAAC,QAAQ,sBAAsB,KAAK,KAAK,CAAC,EAC/C,OAAO,CAAC,SAAyB,SAAS,MAAS;AACtD,SAAO,IAAI;AAAA,IACV,sBAAsB,SACnB,yBAAyB,OAAO,UAAU,gBAAgB,IAC1D,OAAO,iBAAiB;AAAA,EAC5B;AACD;",
6
+ "names": ["mkdir", "writeFile", "dirname", "detail", "mkdir", "dirname", "writeFile", "isNodeError", "isRecord"]
7
+ }
@@ -17,7 +17,7 @@ import {
17
17
  retentionLabel,
18
18
  toolPolicyLabel,
19
19
  updatePlanModeSettings
20
- } from "./chunk-AS76FCC5.js";
20
+ } from "./chunk-TZVK4O2Q.js";
21
21
 
22
22
  // src/active-implementation-menu.ts
23
23
  import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
@@ -740,4 +740,4 @@ export {
740
740
  showReadyPlanMenu,
741
741
  showSavedPlanMenu
742
742
  };
743
- //# sourceMappingURL=interactive-ui-UCL5UIJN.js.map
743
+ //# sourceMappingURL=interactive-ui-S7ZRCAGJ.js.map
package/dist/index.ts CHANGED
@@ -40,7 +40,7 @@ import {
40
40
  snapshotPlanModeSelectedNames,
41
41
  toolPolicyLabel,
42
42
  updatePlanModeSettings
43
- } from "./chunks/chunk-AS76FCC5.js";
43
+ } from "./chunks/chunk-TZVK4O2Q.js";
44
44
 
45
45
  // src/plan-mode.ts
46
46
  import { randomUUID as randomUUID2 } from "node:crypto";
@@ -874,7 +874,7 @@ function planMode(pi, dependencies = {}) {
874
874
  const loadInteractiveUi = () => {
875
875
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
876
876
  if (!interactiveUiPromise) {
877
- interactiveUiPromise = import("./chunks/interactive-ui-UCL5UIJN.js").catch((error) => {
877
+ interactiveUiPromise = import("./chunks/interactive-ui-S7ZRCAGJ.js").catch((error) => {
878
878
  interactiveUiPromise = void 0;
879
879
  throw error;
880
880
  });
@@ -1250,7 +1250,7 @@ function planMode(pi, dependencies = {}) {
1250
1250
  currentSessionContext = void 0;
1251
1251
  }
1252
1252
  });
1253
- pi.on("tool_call", async (event) => {
1253
+ pi.on("tool_call", async (event, ctx) => {
1254
1254
  const requiredHelper = event.toolName === PLAN_MODE_QUESTION_TOOL_NAME || event.toolName === PLAN_MODE_COMPLETE_TOOL_NAME;
1255
1255
  if (!state.enabled) {
1256
1256
  if (!requiredHelper) return;
@@ -1272,22 +1272,39 @@ function planMode(pi, dependencies = {}) {
1272
1272
  };
1273
1273
  }
1274
1274
  if (requiredHelper) return;
1275
+ const calledTool = toolByName(event.toolName);
1276
+ const activeToolNames = new Set(safeGetActiveTools());
1277
+ if (!calledTool) {
1278
+ return {
1279
+ block: true,
1280
+ reason: activeToolNames.has(event.toolName) ? `Plan mode blocks tool '${event.toolName}' because its safe policy metadata is unavailable.` : `Plan mode blocks tool '${event.toolName}' because it is not registered or active. Register and activate it before starting the next Plan workflow.`
1281
+ };
1282
+ }
1283
+ if (classifyPlanModeTool(calledTool) === "blocked") {
1284
+ return {
1285
+ block: true,
1286
+ reason: `Plan mode blocks tool '${event.toolName}' because its built-in policy is blocked and settings cannot enable it.`
1287
+ };
1288
+ }
1275
1289
  const allowedToolNames = new Set(planModePolicyToolNames());
1276
- if (!allowedToolNames.has(event.toolName)) {
1290
+ if (!activeToolNames.has(event.toolName)) {
1277
1291
  return {
1278
1292
  block: true,
1279
- reason: `Plan mode blocks tool '${event.toolName}' because it is unavailable or not selected by the Plan policy.`
1293
+ reason: allowedToolNames.has(event.toolName) ? `Plan mode blocks tool '${event.toolName}' because it was admitted to the active Plan workflow but is currently inactive. Reactivate it to continue without restarting.` : `Plan mode blocks tool '${event.toolName}' because it is registered but inactive. Activate it before starting the next Plan workflow.`
1280
1294
  };
1281
1295
  }
1282
- const calledTool = toolByName(event.toolName);
1283
- if (!calledTool || classifyPlanModeTool(calledTool) === "blocked") {
1296
+ if (!allowedToolNames.has(event.toolName)) {
1284
1297
  return {
1285
1298
  block: true,
1286
- reason: `Plan mode blocks tool '${event.toolName}' because its safe policy metadata is unavailable.`
1299
+ reason: workflowDesiredToolNames().has(event.toolName) ? `Plan mode blocks tool '${event.toolName}' because it was not available when the active Plan workflow froze its tool policy. Exit Plan mode, then start again after the tool is active.` : `Plan mode blocks tool '${event.toolName}' because it is not selected by the Plan policy. Exit Plan mode, then enable it with /plan tools or defaultPlanTools before starting again.`
1287
1300
  };
1288
1301
  }
1289
1302
  if (event.toolName === "bash") {
1290
- const blocked = findBlockedCommandSegment(readCommand(event.input), settings.safeSubcommands);
1303
+ const blocked = findBlockedCommandSegment(
1304
+ readCommand(event.input),
1305
+ settings.safeSubcommands,
1306
+ ctx.cwd
1307
+ );
1291
1308
  if (blocked !== void 0) {
1292
1309
  return {
1293
1310
  block: true,
@@ -1299,7 +1316,8 @@ Blocked command: ${blocked}`
1299
1316
  if (event.toolName === "powershell") {
1300
1317
  const blocked = findBlockedPowerShellCommandSegment(
1301
1318
  readCommand(event.input),
1302
- settings.safeSubcommands
1319
+ settings.safeSubcommands,
1320
+ ctx.cwd
1303
1321
  );
1304
1322
  if (blocked !== void 0) {
1305
1323
  return {
@@ -1858,6 +1876,13 @@ ${intent.plan}`,
1858
1876
  if (state.enabled) return workflowAllowedToolNames ?? [];
1859
1877
  return computePlanModePolicyToolNames();
1860
1878
  }
1879
+ function workflowDesiredToolNames() {
1880
+ const policy = state.workflowToolPolicy;
1881
+ if (!state.enabled || !policy) return /* @__PURE__ */ new Set();
1882
+ return new Set(
1883
+ policy.kind === "automatic" ? automaticPlanModeToolNames() : policy.desiredNames ?? []
1884
+ );
1885
+ }
1861
1886
  function beginWorkflowToolPolicy() {
1862
1887
  const kind = toolPolicySelectionIsExplicit() ? "explicit" : "automatic";
1863
1888
  const desiredNames = desiredPlanModeToolNames();