@narumitw/pi-plan-mode 0.54.0 → 0.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -27
- package/dist/chunks/{chunk-U5CQ7RQX.js → chunk-KSGLZ4S2.js} +240 -255
- package/dist/chunks/chunk-KSGLZ4S2.js.map +7 -0
- package/dist/chunks/{interactive-ui-W3VYAJIQ.js → interactive-ui-PSDKEVVG.js} +2 -32
- package/dist/chunks/interactive-ui-PSDKEVVG.js.map +7 -0
- package/dist/index.ts +39 -283
- package/dist/index.ts.map +3 -3
- package/package.json +1 -1
- package/src/plan-mode.ts +28 -203
- package/src/required-tools.ts +17 -0
- package/src/settings-menu.ts +0 -34
- package/src/settings.ts +0 -19
- package/dist/chunks/chunk-U5CQ7RQX.js.map +0 -7
- package/dist/chunks/interactive-ui-W3VYAJIQ.js.map +0 -7
- package/src/helper-tool-visibility.ts +0 -142
package/dist/index.ts.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/plan-mode.ts", "../src/command.ts", "../src/extension-runtime.ts", "../src/finalization-request.ts", "../src/fresh-implementation.ts", "../src/prompt.ts", "../src/mode-contract.ts", "../src/
|
|
4
|
-
"sourcesContent": ["import { randomUUID } from \"node:crypto\";\nimport { watch } from \"node:fs\";\nimport { basename, dirname } from \"node:path\";\nimport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n} from \"@earendil-works/pi-coding-agent\";\nimport { completePlanArguments } from \"./command.js\";\nimport {\n\tnormalizePlanModeCompletion,\n\tPLAN_MODE_COMPLETE_PARAMS,\n\tPLAN_MODE_COMPLETE_TOOL_NAME,\n\tplanModeCompleted,\n\trenderPlanModeCompletion,\n} from \"./completion-tool.js\";\nimport { isStaleExtensionContextError } from \"./extension-runtime.js\";\nimport {\n\tcreateFinalizationRequestCoordinator,\n\tFINALIZE_PLAN_PROMPT,\n\ttype FinalizationRunOutcome,\n\tRETRY_FINALIZE_PLAN_PROMPT,\n} from \"./finalization-request.js\";\nimport {\n\tformatHistoryImplementationPrompt,\n\tformatImplementationHandoff,\n\tformatTransferredPlanPrompt,\n\tstartFreshImplementationFromState,\n} from \"./fresh-implementation.js\";\nimport {\n\tPlanModeHelperVisibilityPolicy,\n\ttype PlanModeHelperVisibilitySnapshot,\n} from \"./helper-tool-visibility.js\";\nimport {\n\tcreateImplementationRetentionCoordinator,\n\timplementationRetentionPreview,\n} from \"./implementation-retention.js\";\nimport {\n\tinvalidPlanMessage,\n\tlatestAssistantStopReason,\n\tlatestAssistantText,\n\tmessageTextContent,\n\tparseProposedPlan,\n} from \"./message-transform.js\";\nimport {\n\tcreateModeContractMessage,\n\thasModeContractArtifact,\n\tlatestModeContract,\n\tMODE_CONTRACT_MESSAGE_TYPE,\n\ttype PlanModeContract,\n\treconcileModeContract,\n} from \"./mode-contract.js\";\nimport { createPlanActionController } from \"./plan-action-controller.js\";\nimport { createPlanExportController } from \"./plan-export-controller.js\";\nimport {\n\tclearPlanModeUi,\n\tplanModeStatusText as formatPlanModeStatusText,\n\tshowStoredPlan,\n\tupdatePlanModeUi,\n} from \"./presentation.js\";\nimport {\n\tanswerPlanModeQuestions,\n\tnormalizePlanModeQuestionParams,\n\tPLAN_MODE_QUESTION_PARAMS,\n\tPLAN_MODE_QUESTION_TOOL_NAME,\n\tplanModeQuestionCancelled,\n} from \"./question-tool.js\";\nimport { withRequiredPlanModeTools } from \"./required-tools.js\";\nimport {\n\tpreflightSavedPlanImplementation,\n\tsavedPlanBlocksNewWorkflow,\n} from \"./saved-plan-preflight.js\";\nimport {\n\tawaitPlanModeSettingsWrites,\n\tconfiguredImplementationPlanRetention,\n\tconfiguredPlanModeToggleShortcut,\n\tconfiguredPlanModeToolVisibility,\n\tconfiguredThinkingLevel,\n\ttype PlanModeSettings,\n\ttype PlanModeSettingsPatch,\n\ttype PlanModeToolVisibility,\n\tplanModeSettingsPath,\n\treadPlanModeSettings,\n\ttype UpdatePlanModeSettingsOptions,\n\tupdatePlanModeSettings,\n} from \"./settings.js\";\nimport { type PlanCompletionSource, type PlanModeState, restorePlanModeState } from \"./state.js\";\nimport {\n\tcanSelectToolInPlanMode,\n\tclassifyPlanModeTool,\n\tfindBlockedCommandSegment,\n\tfindBlockedPowerShellCommandSegment,\n\treadCommand,\n} from \"./tool-policy.js\";\nimport {\n\tcompareTools,\n\tfilterAvailableSelectedToolNames,\n\tsnapshotPlanModeSelectedNames,\n\ttoolPolicyLabel,\n} from \"./tool-selection.js\";\nimport { WorkflowMutex, type WorkflowMutexOwner } from \"./workflow-mutex.js\";\n\nconst STATE_ENTRY_TYPE = \"plan-mode-state\";\nconst PROPOSED_PLAN_MESSAGE_TYPE = \"proposed-plan\";\nconst BLOCKED_MUTATING_TOOLS = new Set([\"edit\", \"write\", \"update_plan\"]);\nconst DEFAULT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\"];\ninterface ReadyPresentationIntent {\n\tnonce: number;\n\tplan: string;\n\tsource: PlanCompletionSource;\n}\ntype InteractiveUi = typeof import(\"./interactive-ui.js\");\n\ninterface PlanModeDependencies {\n\treadSettings?(): ReturnType<typeof readPlanModeSettings>;\n\tupdateSettings?(\n\t\tpatch: PlanModeSettingsPatch,\n\t\toptions?: UpdatePlanModeSettingsOptions,\n\t): ReturnType<typeof updatePlanModeSettings>;\n\tsettingsPath?: string;\n\tloadInteractiveUi?(): Promise<InteractiveUi>;\n}\n\n// Keep session state, persistence, tool, thinking, and mutex commits in this one closure so an\n// activation path cannot bypass the same atomic transition by crossing module-owned state.\nexport default function planMode(pi: ExtensionAPI, dependencies: PlanModeDependencies = {}) {\n\tconst workflowMutex = new WorkflowMutex(pi);\n\tconst helperVisibility = new PlanModeHelperVisibilityPolicy(pi);\n\tlet workflowOwner: WorkflowMutexOwner | undefined;\n\tlet currentSession: object | undefined;\n\tlet currentSessionContext: ExtensionContext | undefined;\n\tlet interactiveUiPromise: Promise<InteractiveUi> | undefined;\n\tconst loadInteractiveUi = () => {\n\t\tif (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();\n\t\tif (!interactiveUiPromise) {\n\t\t\tinteractiveUiPromise = import(\"./interactive-ui.js\").catch((error) => {\n\t\t\t\tinteractiveUiPromise = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\t\treturn interactiveUiPromise;\n\t};\n\tconst explicitPlanModeSettingsPath = dependencies.settingsPath;\n\tlet state: PlanModeState = { enabled: false, awaitingAction: false };\n\tlet settings: PlanModeSettings = { thinkingLevel: \"inherit\" };\n\tlet toggleShortcut: ReturnType<typeof configuredPlanModeToggleShortcut>;\n\tconst clearPlanModeShortcutHandler = () => {};\n\tlet activeToolBaseline: string[] = [];\n\tlet workflowAllowedToolNames: string[] | undefined;\n\tlet publishedContractMode: PlanModeContract | undefined;\n\tlet modeContractsRelevant = false;\n\tlet readyPresentationIntent: ReadyPresentationIntent | undefined;\n\tlet latestCommandContext: ExtensionCommandContext | undefined;\n\tlet nextReadyPresentationNonce = 0;\n\tlet menuGeneration = 0;\n\tlet workflowGeneration = 0;\n\tlet refreshStateBeforeFirstAgentStart = false;\n\tlet menuController = new AbortController();\n\tlet settingsWatch: ReturnType<typeof watch> | undefined;\n\tlet settingsReloadTimer: ReturnType<typeof setTimeout> | undefined;\n\tconst implementationRetention = createImplementationRetentionCoordinator();\n\tconst finalizationRequest = createFinalizationRequestCoordinator();\n\tconst persistState = () => pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, state);\n\tconst planExports = createPlanExportController({\n\t\tgetState: () => state,\n\t\tgetSettings: () => settings,\n\t\tfinishReady: (ctx) => {\n\t\t\texitPlanMode(ctx);\n\t\t},\n\t});\n\tconst planActions = createPlanActionController({\n\t\tloadInteractiveUi,\n\t\tgetState: () => state,\n\t\tcaptureLifecycle: captureMenuLifecycle,\n\t\tstatusText: planStatusText,\n\t\timplementationOutcome,\n\t\tgetExportDestination: (ctx) => planExports.getDestination(ctx),\n\t\tshow: (ctx) => showStoredPlan(pi, ctx, state),\n\t\tfinalize: requestFinalPlan,\n\t\timplementHere: startImplementation,\n\t\timplementFresh: startFreshImplementation,\n\t\texportPlan: exportPlan,\n\t\tsettings: showSettings,\n\t\tsave: savePlanForLater,\n\t\tstay: updateUi,\n\t\texitReady: (ctx) => {\n\t\t\tif (exitPlanMode(ctx)) {\n\t\t\t\tctx.ui.notify(\"Plan mode disabled. Proposed plan discarded.\", \"info\");\n\t\t\t}\n\t\t},\n\t\tclearSaved: (ctx) => {\n\t\t\tif (exitPlanMode(ctx)) ctx.ui.notify(\"Saved plan cleared.\", \"info\");\n\t\t},\n\t});\n\n\tpi.registerTool({\n\t\tname: PLAN_MODE_QUESTION_TOOL_NAME,\n\t\tlabel: \"Plan question\",\n\t\tdescription:\n\t\t\t\"Ask the user one to three Plan-mode clarification questions with meaningful options, then wait for the answer. Only available while Plan mode is active.\",\n\t\tpromptSnippet: \"Ask user decision questions while Plan mode is active\",\n\t\tpromptGuidelines: [\n\t\t\t\"In Plan mode, use plan_mode_question for important preferences, tradeoffs, or assumptions that cannot be discovered from read-only exploration.\",\n\t\t],\n\t\tparameters: PLAN_MODE_QUESTION_PARAMS,\n\t\tasync execute(_toolCallId, params: unknown, _signal, _onUpdate, ctx) {\n\t\t\tif (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {\n\t\t\t\treturn planModeQuestionCancelled(\n\t\t\t\t\t[],\n\t\t\t\t\t\"plan_mode_inactive\",\n\t\t\t\t\t\"Error: plan_mode_question is only available while Plan mode is active.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst parsed = normalizePlanModeQuestionParams(params);\n\t\t\tif (!parsed.ok) {\n\t\t\t\treturn planModeQuestionCancelled([], \"invalid_input\", `Error: ${parsed.error}`);\n\t\t\t}\n\t\t\tfinalizationRequest.satisfy();\n\n\t\t\tif (!ctx.hasUI) {\n\t\t\t\treturn planModeQuestionCancelled(\n\t\t\t\t\tparsed.questions,\n\t\t\t\t\t\"ui_unavailable\",\n\t\t\t\t\t\"Unable to ask Plan-mode questions because interactive UI is not available.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst sessionGeneration = menuGeneration;\n\t\t\tconst questionWorkflowGeneration = workflowGeneration;\n\t\t\tconst questionOwner = workflowOwner;\n\t\t\treturn answerPlanModeQuestions(parsed.questions, ctx, {\n\t\t\t\tisCurrent: () =>\n\t\t\t\t\tsessionGeneration === menuGeneration &&\n\t\t\t\t\tquestionWorkflowGeneration === workflowGeneration &&\n\t\t\t\t\tworkflowMutex.isOwner(questionOwner),\n\t\t\t\tisEnabled: () => state.enabled,\n\t\t\t});\n\t\t},\n\t});\n\n\tpi.registerTool({\n\t\tname: PLAN_MODE_COMPLETE_TOOL_NAME,\n\t\tlabel: \"Complete plan\",\n\t\tdescription:\n\t\t\t\"Submit the complete decision-ready implementation plan for user review. Only available while Plan mode is active, and must be the final standalone action.\",\n\t\tpromptSnippet: \"Submit the final Plan-mode implementation plan\",\n\t\tpromptGuidelines: [\n\t\t\t\"Call plan_mode_complete alone as the final action only after the implementation plan is decision-complete.\",\n\t\t],\n\t\tparameters: PLAN_MODE_COMPLETE_PARAMS,\n\t\trenderResult: renderPlanModeCompletion,\n\t\tasync execute(_toolCallId, params: unknown, _signal, _onUpdate, ctx) {\n\t\t\tif (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {\n\t\t\t\tthrow new Error(\"plan_mode_complete is only available while Plan mode is active\");\n\t\t\t}\n\t\t\tconst parsed = normalizePlanModeCompletion(params);\n\t\t\tif (!parsed.ok) throw new Error(parsed.error);\n\n\t\t\tacceptCompletedPlan(parsed.plan, PLAN_MODE_COMPLETE_TOOL_NAME, ctx);\n\t\t\treturn planModeCompleted(parsed.plan);\n\t\t},\n\t});\n\n\tpi.registerCommand(\"plan\", {\n\t\tdescription: \"Enter or manage Codex-like Plan mode\",\n\t\tgetArgumentCompletions: completePlanArguments,\n\t\thandler: async (args, ctx) => {\n\t\t\tlatestCommandContext = ctx;\n\t\t\tconst prompt = args.trim();\n\t\t\tconst command = prompt.toLowerCase();\n\t\t\tif (command === \"start\") {\n\t\t\t\tif (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))\n\t\t\t\t\treturn;\n\t\t\t\tif (state.enabled) {\n\t\t\t\t\tctx.ui.notify(\"Plan mode is already active.\", \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (enterPlanMode(ctx)) {\n\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t\"Plan mode enabled. I will explore and plan, but not modify files.\",\n\t\t\t\t\t\t\"info\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"show\") {\n\t\t\t\tshowStoredPlan(pi, ctx, state);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"finalize\") {\n\t\t\t\trequestFinalPlan(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"implement\") {\n\t\t\t\tif (!(state.enabled && state.latestPlan?.trim()) && !state.savedPlan?.plan.trim()) {\n\t\t\t\t\tctx.ui.notify(\"No completed plan is available to implement.\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait startImplementation(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"save\") {\n\t\t\t\tsavePlanForLater(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst exportMatch = /^export(?:\\s+([\\s\\S]+))?$/iu.exec(prompt);\n\t\t\tif (exportMatch) {\n\t\t\t\tconst lifecycle = captureMenuLifecycle();\n\t\t\t\tawait exportPlan(ctx, exportMatch[1], lifecycle.signal, lifecycle.isCurrent);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"exit\" || command === \"off\") {\n\t\t\t\tconst notification = planModeDisableNotification();\n\t\t\t\tif (exitPlanMode(ctx)) ctx.ui.notify(notification, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"tools\") {\n\t\t\t\tif (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))\n\t\t\t\t\treturn;\n\t\t\t\tif (state.enabled) {\n\t\t\t\t\tconst message =\n\t\t\t\t\t\t\"Plan-mode tools are locked while Planning is active. Exit Plan mode and choose tools before starting again.\";\n\t\t\t\t\tif (!ctx.hasUI) throw new Error(message);\n\t\t\t\t\tctx.ui.notify(message, \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!ctx.hasUI) {\n\t\t\t\t\tthrow new Error(\"/plan tools requires TUI or RPC mode and is unavailable here.\");\n\t\t\t\t}\n\t\t\t\tawait showLaunchMenu(ctx, \"tools\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (prompt) {\n\t\t\t\tif (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))\n\t\t\t\t\treturn;\n\t\t\t\tenterPlanModeWithPrompt(prompt, ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!ctx.hasUI) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"The interactive /plan menu is unavailable in print and JSON modes. Use /plan start or /plan <prompt>.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!state.enabled) {\n\t\t\t\tif (state.activeImplementation && ctx.hasUI) {\n\t\t\t\t\tawait showActivePlanMenu(ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (state.savedPlan) {\n\t\t\t\t\tawait planActions.showSaved(ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait showLaunchMenu(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait planActions.showCurrent(ctx);\n\t\t},\n\t});\n\n\tconst applyPlanModeShortcut = (\n\t\tnextShortcut: ReturnType<typeof configuredPlanModeToggleShortcut>,\n\t) => {\n\t\tif (toggleShortcut && toggleShortcut !== nextShortcut) {\n\t\t\tpi.registerShortcut(toggleShortcut, {\n\t\t\t\thandler: clearPlanModeShortcutHandler,\n\t\t\t});\n\t\t}\n\t\tif (!nextShortcut) {\n\t\t\ttoggleShortcut = undefined;\n\t\t\treturn;\n\t\t}\n\t\tif (toggleShortcut === nextShortcut) return;\n\t\tpi.registerShortcut(nextShortcut, {\n\t\t\tdescription: \"Toggle Plan mode\",\n\t\t\thandler: (ctx) => {\n\t\t\t\ttogglePlanMode(ctx);\n\t\t\t},\n\t\t});\n\t\ttoggleShortcut = nextShortcut;\n\t};\n\n\tconst readPlanModeRuntimeSettings = async () => {\n\t\treturn dependencies.readSettings?.() ?? readPlanModeSettings(explicitPlanModeSettingsPath);\n\t};\n\n\tconst applyPlanModeSettings = async (\n\t\tgeneration: number,\n\t\tctx: ExtensionContext | undefined,\n\t\tshowWarnings: boolean,\n\t\tapplyWatchedVisibility = false,\n\t) => {\n\t\tconst loadedSettings = await readPlanModeRuntimeSettings();\n\t\tif (generation !== menuGeneration || menuController.signal.aborted) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst previousSettings = settings;\n\t\tconst nextSettings =\n\t\t\tloadedSettings.kind === \"loaded\"\n\t\t\t\t? loadedSettings.settings\n\t\t\t\t: ({ thinkingLevel: \"inherit\" } satisfies PlanModeSettings);\n\t\tif (applyWatchedVisibility && ctx) {\n\t\t\tapplyWatchedHelperVisibility(previousSettings, nextSettings, ctx);\n\t\t}\n\t\tsettings = nextSettings;\n\t\tapplyPlanModeShortcut(configuredPlanModeToggleShortcut(settings));\n\t\tif (!ctx || !showWarnings) return loadedSettings;\n\t\tif (loadedSettings.kind === \"invalid\") {\n\t\t\tctx.ui.notify(`pi-plan-mode settings ignored: ${loadedSettings.reason}`, \"warning\");\n\t\t}\n\t\tif (loadedSettings.notice) {\n\t\t\tctx.ui.notify(loadedSettings.notice, \"warning\");\n\t\t}\n\t\treturn loadedSettings;\n\t};\n\n\tconst stopPlanModeSettingsWatch = () => {\n\t\tif (settingsReloadTimer) {\n\t\t\tclearTimeout(settingsReloadTimer);\n\t\t\tsettingsReloadTimer = undefined;\n\t\t}\n\t\tsettingsWatch?.close();\n\t\tsettingsWatch = undefined;\n\t};\n\n\tconst schedulePlanModeSettingsReload = (generation: number) => {\n\t\tif (settingsReloadTimer) {\n\t\t\tclearTimeout(settingsReloadTimer);\n\t\t\tsettingsReloadTimer = undefined;\n\t\t}\n\t\tsettingsReloadTimer = setTimeout(() => {\n\t\t\tsettingsReloadTimer = undefined;\n\t\t\tvoid applyPlanModeSettings(generation, currentSessionContext, false, true);\n\t\t}, 75);\n\t};\n\n\tconst startPlanModeSettingsWatch = (generation: number) => {\n\t\tstopPlanModeSettingsWatch();\n\t\tif (dependencies.readSettings) return;\n\t\tconst pathToWatch = explicitPlanModeSettingsPath ?? planModeSettingsPath();\n\t\ttry {\n\t\t\tconst directory = dirname(pathToWatch);\n\t\t\tconst fileName = basename(pathToWatch);\n\t\t\tconst watcher = watch(directory, { persistent: false }, (event, changedFile) => {\n\t\t\t\tif (event !== \"rename\" && event !== \"change\") return;\n\t\t\t\tif (!changedFile || changedFile.toString() !== fileName) return;\n\t\t\t\tschedulePlanModeSettingsReload(generation);\n\t\t\t});\n\t\t\twatcher.on(\"error\", () => {\n\t\t\t\tstopPlanModeSettingsWatch();\n\t\t\t});\n\t\t\tsettingsWatch = watcher;\n\t\t} catch {\n\t\t\tstopPlanModeSettingsWatch();\n\t\t}\n\t};\n\n\tpi.on(\"session_start\", async (event, ctx) => {\n\t\tconst generation = ++menuGeneration;\n\t\tconst previousToolVisibility = configuredPlanModeToolVisibility(settings);\n\t\tfinalizationRequest.reset();\n\t\tcurrentSession = ctx.sessionManager;\n\t\tcurrentSessionContext = ctx;\n\t\tworkflowOwner = undefined;\n\t\tworkflowMutex.bindSession(ctx.sessionManager);\n\t\tcaptureToolBaseline();\n\t\trefreshStateBeforeFirstAgentStart = event.reason === \"new\";\n\t\tmenuController.abort(new DOMException(\"Plan-mode session replaced\", \"AbortError\"));\n\t\tmenuController = new AbortController();\n\t\treadyPresentationIntent = undefined;\n\t\tlatestCommandContext = undefined;\n\t\tworkflowAllowedToolNames = undefined;\n\t\timplementationRetention.reset();\n\t\tsettings = { thinkingLevel: \"inherit\" };\n\t\tconst branch = ctx.sessionManager.getBranch();\n\t\tconst restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);\n\t\trestoreModeContractTracking(branch, restoredState);\n\t\tstate = { enabled: false, awaitingAction: false };\n\t\tawait applyPlanModeSettings(generation, ctx, true);\n\t\tif (generation !== menuGeneration || menuController.signal.aborted) return;\n\t\tstartPlanModeSettingsWatch(generation);\n\t\tif (restoredState.enabled) {\n\t\t\tif (!installRestoredState(restoredState, ctx, previousToolVisibility)) return;\n\t\t} else {\n\t\t\treconcileInactiveHelperVisibility(previousToolVisibility, ctx);\n\t\t\tif (!installRestoredState(restoredState, ctx)) return;\n\t\t}\n\t\timplementationRetention.restore(state.activeImplementation);\n\t\tupdateUi(ctx);\n\t});\n\n\tpi.on(\"session_before_tree\", (event, ctx) => {\n\t\tconst target = ctx.sessionManager.getEntry(event.preparation.targetId);\n\t\tif (target?.type !== \"custom_message\" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {\n\t\t\treturn;\n\t\t}\n\t\tif (ctx.hasUI) {\n\t\t\tctx.ui.notify(\n\t\t\t\t\"Plan mode transition markers are internal. Select the adjacent conversation entry instead.\",\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\t\treturn { cancel: true };\n\t});\n\n\tpi.on(\"session_tree\", (_event, ctx) => {\n\t\tadvanceWorkflowGeneration();\n\t\tmenuGeneration += 1;\n\t\tmenuController.abort(new DOMException(\"Plan-mode tree branch changed\", \"AbortError\"));\n\t\tmenuController = new AbortController();\n\t\treadyPresentationIntent = undefined;\n\t\tlatestCommandContext = undefined;\n\t\timplementationRetention.reset();\n\t\tconst branch = ctx.sessionManager.getBranch();\n\t\tconst restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);\n\t\trestoreModeContractTracking(branch, restoredState);\n\t\tif (!installRestoredState(restoredState, ctx)) return;\n\t\timplementationRetention.restore(state.activeImplementation);\n\t\tstartPlanModeSettingsWatch(menuGeneration);\n\t\tupdateUi(ctx);\n\t});\n\n\tpi.on(\"thinking_level_select\", (event) => {\n\t\tif (!state.enabled || !state.appliedThinkingLevel) return;\n\t\tif (event.level !== state.appliedThinkingLevel) {\n\t\t\tstate = {\n\t\t\t\t...state,\n\t\t\t\tmanualThinkingLevel: event.level,\n\t\t\t\tpreviousThinkingLevel: undefined,\n\t\t\t\tappliedThinkingLevel: undefined,\n\t\t\t};\n\t\t\tpersistState();\n\t\t}\n\t});\n\n\tpi.on(\"session_shutdown\", async (_event, ctx) => {\n\t\tconst shutdownSession = ctx.sessionManager;\n\t\tfinalizationRequest.reset();\n\t\tmenuGeneration += 1;\n\t\tmenuController.abort(new DOMException(\"Plan-mode session shut down\", \"AbortError\"));\n\t\treadyPresentationIntent = undefined;\n\t\tlatestCommandContext = undefined;\n\t\trefreshStateBeforeFirstAgentStart = false;\n\t\timplementationRetention.reset();\n\t\tawait awaitPlanModeSettingsWrites(dependencies.settingsPath);\n\t\tif (currentSession !== undefined && currentSession !== shutdownSession) {\n\t\t\tworkflowMutex.unbindSession(shutdownSession);\n\t\t\treturn;\n\t\t}\n\t\tcaptureManualThinkingLevel();\n\t\tpersistState();\n\t\tif (state.enabled) restoreThinkingLevel();\n\t\tstopPlanModeSettingsWatch();\n\t\tclearUi(ctx);\n\t\treleaseWorkflowOwner();\n\t\tworkflowMutex.unbindSession(ctx.sessionManager);\n\t\tif (currentSession === ctx.sessionManager) {\n\t\t\tcurrentSession = undefined;\n\t\t\tcurrentSessionContext = undefined;\n\t\t}\n\t});\n\n\tpi.on(\"tool_call\", async (event) => {\n\t\tconst requiredHelper =\n\t\t\tevent.toolName === PLAN_MODE_QUESTION_TOOL_NAME ||\n\t\t\tevent.toolName === PLAN_MODE_COMPLETE_TOOL_NAME;\n\t\tif (!state.enabled) {\n\t\t\tif (!requiredHelper) return;\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `${event.toolName} is only available while Plan mode is active.`,\n\t\t\t};\n\t\t}\n\t\tif (!workflowMutex.isOwner(workflowOwner)) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `Plan mode blocks tool '${event.toolName}' because workflow ownership is unavailable.`,\n\t\t\t};\n\t\t}\n\t\tif (BLOCKED_MUTATING_TOOLS.has(event.toolName)) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason:\n\t\t\t\t\tevent.toolName === \"update_plan\"\n\t\t\t\t\t\t? \"Plan mode blocks update_plan because it tracks execution progress rather than conversational planning.\"\n\t\t\t\t\t\t: `Plan mode blocks mutating tool '${event.toolName}'.`,\n\t\t\t};\n\t\t}\n\t\tif (requiredHelper) return;\n\n\t\tconst allowedToolNames = new Set(planModePolicyToolNames());\n\t\tif (!allowedToolNames.has(event.toolName)) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `Plan mode blocks tool '${event.toolName}' because it is unavailable or not selected by the Plan policy.`,\n\t\t\t};\n\t\t}\n\t\tconst calledTool = toolByName(event.toolName);\n\t\tif (!calledTool || classifyPlanModeTool(calledTool) === \"blocked\") {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `Plan mode blocks tool '${event.toolName}' because its safe policy metadata is unavailable.`,\n\t\t\t};\n\t\t}\n\t\tif (event.toolName === \"bash\") {\n\t\t\tconst blocked = findBlockedCommandSegment(readCommand(event.input), settings.safeSubcommands);\n\t\t\tif (blocked !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tblock: true,\n\t\t\t\t\treason: `Plan mode blocks bash commands outside its reviewed inspection policy or containing explicitly unsafe arguments.\\nBlocked command: ${blocked}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tif (event.toolName === \"powershell\") {\n\t\t\tconst blocked = findBlockedPowerShellCommandSegment(\n\t\t\t\treadCommand(event.input),\n\t\t\t\tsettings.safeSubcommands,\n\t\t\t);\n\t\t\tif (blocked !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tblock: true,\n\t\t\t\t\treason: `Plan mode blocks PowerShell commands outside its reviewed inspection policy or containing explicitly unsafe syntax.\\nBlocked command: ${blocked}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t});\n\n\tpi.on(\"message_start\", (event) => {\n\t\tif (\n\t\t\tstate.enabled &&\n\t\t\tevent.message.role === \"user\" &&\n\t\t\tmessageTextContent(event.message).trim() === FINALIZE_PLAN_PROMPT\n\t\t) {\n\t\t\tfinalizationRequest.request(workflowGeneration);\n\t\t}\n\t});\n\n\tpi.on(\"context\", async (event, ctx) => {\n\t\tconst result = implementationRetention.transformContext(event.messages, state);\n\t\tif (result.clearActiveImplementationId) {\n\t\t\tclearActiveImplementation(result.clearActiveImplementationId, ctx);\n\t\t}\n\t\tconst messages =\n\t\t\tstate.enabled || modeContractsRelevant\n\t\t\t\t? reconcileModeContract(result.messages, state.enabled ? \"plan\" : \"normal\")\n\t\t\t\t: result.messages;\n\t\treturn { messages: messages as typeof event.messages };\n\t});\n\n\tpi.on(\"before_agent_start\", (_event, ctx) => {\n\t\tif (refreshStateBeforeFirstAgentStart) {\n\t\t\trefreshStateBeforeFirstAgentStart = false;\n\t\t\timplementationRetention.reset();\n\t\t\tconst branch = ctx.sessionManager.getBranch();\n\t\t\tconst restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);\n\t\t\trestoreModeContractTracking(branch, restoredState);\n\t\t\tif (!installRestoredState(restoredState, ctx)) return;\n\t\t\timplementationRetention.restore(state.activeImplementation);\n\t\t\tupdateUi(ctx);\n\t\t}\n\t\tif (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;\n\t\tif (state.latestPlan || state.awaitingAction) {\n\t\t\treadyPresentationIntent = undefined;\n\t\t\tstate = {\n\t\t\t\t...state,\n\t\t\t\tlatestPlan: undefined,\n\t\t\t\tlatestPlanSource: undefined,\n\t\t\t\tawaitingAction: false,\n\t\t\t};\n\t\t\tpersistState();\n\t\t\tupdateUi(ctx);\n\t\t}\n\t});\n\n\tpi.on(\"agent_end\", async (event, ctx) => {\n\t\tif (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;\n\n\t\tconst text = latestAssistantText(event.messages);\n\t\tconst parsedPlan = parseProposedPlan(text);\n\t\tif (parsedPlan.kind !== \"valid\") {\n\t\t\tfinalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));\n\t\t\tif (parsedPlan.kind !== \"absent\") {\n\t\t\t\tctx.ui.notify(invalidPlanMessage(parsedPlan.kind), \"warning\");\n\t\t\t}\n\t\t\tpersistState();\n\t\t\tupdateUi(ctx);\n\t\t\treturn;\n\t\t}\n\t\tacceptCompletedPlan(parsedPlan.plan, \"legacy_proposed_plan\", ctx);\n\t});\n\n\tpi.on(\"agent_settled\", async (_event, ctx) => {\n\t\tconst settledImplementationId = implementationRetention.implementationSettled(\n\t\t\tstate.activeImplementation,\n\t\t);\n\t\tif (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);\n\n\t\tif (\n\t\t\tfinalizationRequest.hasPendingRequest() &&\n\t\t\tstate.enabled &&\n\t\t\tworkflowMutex.isOwner(workflowOwner)\n\t\t) {\n\t\t\tif (!ctx.isIdle() || ctx.hasPendingMessages()) return;\n\t\t\tconst action = finalizationRequest.settle(workflowGeneration);\n\t\t\tif (action === \"retry\") {\n\t\t\t\tif (sendPlanModeUserMessage(RETRY_FINALIZE_PLAN_PROMPT, ctx)) return;\n\t\t\t\tfinalizationRequest.reset();\n\t\t\t}\n\t\t\tif (action === \"failed\") {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Plan finalization ended twice without a structured question or completed plan. Plan mode remains active; revise the plan or run /plan finalize again.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst intent = readyPresentationIntent;\n\t\tif (!intent || !readyPresentationIsCurrent(intent)) return;\n\t\tif (!ctx.isIdle() || ctx.hasPendingMessages()) return;\n\n\t\treadyPresentationIntent = undefined;\n\t\ttry {\n\t\t\tif (intent.source === \"legacy_proposed_plan\") {\n\t\t\t\tpi.sendMessage(\n\t\t\t\t\t{\n\t\t\t\t\t\tcustomType: PROPOSED_PLAN_MESSAGE_TYPE,\n\t\t\t\t\t\tcontent: `**Proposed Plan**\\n\\n${intent.plan}`,\n\t\t\t\t\t\tdisplay: true,\n\t\t\t\t\t},\n\t\t\t\t\t{ triggerTurn: false },\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (ctx.hasUI && completedPlanIsCurrent(intent)) {\n\t\t\t\tawait planActions.showReady(latestCommandContext ?? ctx);\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\tif (!isStaleExtensionContextError(error)) throw error;\n\t\t}\n\t});\n\n\tfunction enterPlanMode(\n\t\tctx: ExtensionContext,\n\t\tcandidate: Pick<PlanModeState, \"selectedToolNames\" | \"selectedToolKeys\"> = state,\n\t) {\n\t\tif (!state.enabled && !allowModeTransition(ctx, \"start Plan mode\")) return false;\n\t\tbindWorkflowSessionIfNeeded(ctx);\n\t\tif (state.enabled) return workflowMutex.isOwner(workflowOwner);\n\t\tconst owner = workflowMutex.acquire();\n\t\tif (!owner) return reportWorkflowBusy(ctx);\n\t\tworkflowOwner = owner;\n\n\t\tconst previousState = state;\n\t\tconst previousHelperVisibility = helperVisibility.snapshot();\n\t\ttry {\n\t\t\thelperVisibility.prepareActivation(ctx);\n\t\t\tif (!publishModeContract(\"plan\", ctx)) {\n\t\t\t\thelperVisibility.restore(previousHelperVisibility);\n\t\t\t\treleaseWorkflowOwner();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\thelperVisibility.restore(previousHelperVisibility);\n\t\t\treleaseWorkflowOwner();\n\t\t\treturn reportHelperActivationFailure(ctx, error);\n\t\t}\n\t\tadvanceWorkflowGeneration();\n\t\ttry {\n\t\t\tmodeContractsRelevant = true;\n\t\t\tstate = {\n\t\t\t\t...state,\n\t\t\t\tenabled: true,\n\t\t\t\tawaitingAction: false,\n\t\t\t\tsavedPlan: undefined,\n\t\t\t\tactiveImplementation: undefined,\n\t\t\t\tselectedToolNames: candidate.selectedToolNames,\n\t\t\t\tselectedToolKeys: candidate.selectedToolKeys,\n\t\t\t};\n\t\t\tworkflowAllowedToolNames = computePlanModePolicyToolNames();\n\t\t\tapplyPlanThinkingLevel();\n\t\t\tpersistState();\n\t\t\tupdateUi(ctx);\n\t\t\treturn true;\n\t\t} catch (error: unknown) {\n\t\t\trollbackNewActivation(previousState, ctx, undefined, previousHelperVisibility);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tfunction enterPlanModeWithPrompt(prompt: string, ctx: ExtensionContext) {\n\t\tconst previousState = state;\n\t\tconst previousOwner = workflowOwner;\n\t\tconst previousHelperVisibility = helperVisibility.snapshot();\n\t\tconst wasEnabled = state.enabled;\n\t\tif (!enterPlanMode(ctx)) return;\n\t\tif (!wasEnabled) {\n\t\t\tctx.ui.notify(\"Plan mode enabled. I will explore and plan, but not modify files.\", \"info\");\n\t\t}\n\t\tif (sendPlanModeUserMessage(prompt, ctx)) return;\n\t\tif (wasEnabled) return;\n\t\trollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility);\n\t}\n\n\tfunction exitPlanMode(ctx: ExtensionContext) {\n\t\tif (!allowModeTransition(ctx, \"leave or clear Plan mode\")) return false;\n\t\tconst wasEnabled = state.enabled;\n\t\tif ((wasEnabled || modeContractsRelevant) && !publishModeContract(\"normal\", ctx)) {\n\t\t\treturn false;\n\t\t}\n\t\tadvanceWorkflowGeneration();\n\t\treadyPresentationIntent = undefined;\n\t\tworkflowAllowedToolNames = undefined;\n\t\tstate = {\n\t\t\t...state,\n\t\t\tenabled: false,\n\t\t\tlatestPlan: undefined,\n\t\t\tlatestPlanSource: undefined,\n\t\t\tawaitingAction: false,\n\t\t\tsavedPlan: undefined,\n\t\t\tactiveImplementation: undefined,\n\t\t\tmanualThinkingLevel: undefined,\n\t\t};\n\t\tif (wasEnabled) {\n\t\t\trestoreThinkingLevel();\n\t\t\tstate = { ...state, manualThinkingLevel: undefined };\n\t\t}\n\t\tpersistState();\n\t\tupdateUi(ctx);\n\t\tif (wasEnabled) releaseWorkflowOwner();\n\t\treturn true;\n\t}\n\n\tfunction restoreModeContractTracking(branch: unknown[], restoredState: PlanModeState) {\n\t\tpublishedContractMode = latestModeContract(branch)?.mode;\n\t\tmodeContractsRelevant =\n\t\t\thasModeContractArtifact(branch) ||\n\t\t\trestoredState.enabled ||\n\t\t\trestoredState.savedPlan !== undefined ||\n\t\t\trestoredState.activeImplementation !== undefined;\n\t}\n\n\tfunction publishModeContract(mode: PlanModeContract, ctx: ExtensionContext) {\n\t\tif (publishedContractMode === mode) return true;\n\t\tconst { role: _role, timestamp: _timestamp, ...message } = createModeContractMessage(mode);\n\t\ttry {\n\t\t\tpi.sendMessage(message, { triggerTurn: false });\n\t\t\tpublishedContractMode = mode;\n\t\t\tmodeContractsRelevant = true;\n\t\t\treturn true;\n\t\t} catch (error: unknown) {\n\t\t\tconst detail = safeTerminalText(error instanceof Error ? error.message : String(error));\n\t\t\tconst notification = `Unable to publish the ${mode === \"plan\" ? \"Plan\" : \"Normal\"} mode contract: ${detail}`;\n\t\t\tif (!ctx.hasUI) throw new Error(notification, { cause: error });\n\t\t\tctx.ui.notify(notification, \"error\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfunction sendPlanModeUserMessage(message: string, ctx: ExtensionContext) {\n\t\ttry {\n\t\t\tif (ctx.isIdle()) pi.sendUserMessage(message);\n\t\t\telse pi.sendUserMessage(message, { deliverAs: \"followUp\" });\n\t\t\treturn true;\n\t\t} catch (error: unknown) {\n\t\t\tconst detail = safeTerminalText(error instanceof Error ? error.message : String(error));\n\t\t\tctx.ui.notify(`Unable to send Plan-mode message: ${detail}`, \"error\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfunction acceptCompletedPlan(plan: string, source: PlanCompletionSource, ctx: ExtensionContext) {\n\t\tconst normalized = normalizePlanModeCompletion({ plan });\n\t\tif (!normalized.ok) {\n\t\t\tctx.ui.notify(`Proposed plan is not ready: ${normalized.error}.`, \"warning\");\n\t\t\tpersistState();\n\t\t\tupdateUi(ctx);\n\t\t\treturn;\n\t\t}\n\t\tfinalizationRequest.satisfy();\n\t\tif (\n\t\t\tstate.enabled &&\n\t\t\tstate.awaitingAction &&\n\t\t\tstate.latestPlan === normalized.plan &&\n\t\t\tstate.latestPlanSource === source\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tstate = {\n\t\t\t...state,\n\t\t\tlatestPlan: normalized.plan,\n\t\t\tlatestPlanSource: source,\n\t\t\tawaitingAction: true,\n\t\t};\n\t\treadyPresentationIntent = {\n\t\t\tnonce: ++nextReadyPresentationNonce,\n\t\t\tplan: normalized.plan,\n\t\t\tsource,\n\t\t};\n\t\tpersistState();\n\t\tupdateUi(ctx);\n\t}\n\n\tfunction completedPlanIsCurrent(intent: ReadyPresentationIntent) {\n\t\treturn (\n\t\t\tstate.enabled &&\n\t\t\tworkflowMutex.isOwner(workflowOwner) &&\n\t\t\tstate.awaitingAction &&\n\t\t\tstate.latestPlan === intent.plan &&\n\t\t\tstate.latestPlanSource === intent.source\n\t\t);\n\t}\n\n\tfunction readyPresentationIsCurrent(intent: ReadyPresentationIntent) {\n\t\treturn completedPlanIsCurrent(intent) && readyPresentationIntent?.nonce === intent.nonce;\n\t}\n\n\tfunction togglePlanMode(ctx: ExtensionContext) {\n\t\tif (state.enabled) {\n\t\t\tconst notification = planModeDisableNotification();\n\t\t\tif (exitPlanMode(ctx)) ctx.ui.notify(notification, \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined)) return;\n\t\tif (enterPlanMode(ctx)) {\n\t\t\tctx.ui.notify(\"Plan mode enabled. I will explore and plan, but not modify files.\", \"info\");\n\t\t}\n\t}\n\n\tfunction planModeDisableNotification() {\n\t\treturn state.activeImplementation\n\t\t\t? \"Active implementation plan cleared.\"\n\t\t\t: state.savedPlan\n\t\t\t\t? \"Saved plan cleared.\"\n\t\t\t\t: state.latestPlan\n\t\t\t\t\t? \"Plan mode disabled. Proposed plan discarded.\"\n\t\t\t\t\t: \"Plan mode disabled.\";\n\t}\n\n\tfunction requestFinalPlan(ctx: ExtensionContext) {\n\t\tif (!state.enabled) {\n\t\t\tctx.ui.notify(\"Plan mode is not active. Use /plan first.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tfinalizationRequest.request(workflowGeneration);\n\t\tif (!sendPlanModeUserMessage(FINALIZE_PLAN_PROMPT, ctx)) finalizationRequest.reset();\n\t}\n\n\tfunction savePlanForLater(ctx: ExtensionContext) {\n\t\tconst plan = state.enabled ? state.latestPlan?.trim() : undefined;\n\t\tif (!plan) {\n\t\t\tconst message = \"No completed plan is available to save.\";\n\t\t\tif (!ctx.hasUI) throw new Error(message);\n\t\t\tctx.ui.notify(message, \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tconst source = state.latestPlanSource ?? \"legacy_proposed_plan\";\n\t\tif (!allowModeTransition(ctx, \"save the plan and leave Plan mode\")) return;\n\n\t\tif (!publishModeContract(\"normal\", ctx)) return;\n\t\tadvanceWorkflowGeneration();\n\t\treadyPresentationIntent = undefined;\n\t\tworkflowAllowedToolNames = undefined;\n\t\tstate = {\n\t\t\t...state,\n\t\t\tenabled: false,\n\t\t\tlatestPlan: undefined,\n\t\t\tlatestPlanSource: undefined,\n\t\t\tawaitingAction: false,\n\t\t\tsavedPlan: { plan, source },\n\t\t\tactiveImplementation: undefined,\n\t\t\tmanualThinkingLevel: undefined,\n\t\t};\n\t\trestoreThinkingLevel();\n\t\tstate = { ...state, manualThinkingLevel: undefined };\n\t\tpersistState();\n\t\tupdateUi(ctx);\n\t\treleaseWorkflowOwner();\n\t\tctx.ui.notify(\"Plan saved for later. Plan mode disabled.\", \"info\");\n\t}\n\n\tasync function startFreshImplementation(ctx: ExtensionContext, menuIsCurrent: () => boolean) {\n\t\tawait startFreshImplementationFromState(ctx, {\n\t\t\tgetState: () => state,\n\t\t\tmenuIsCurrent,\n\t\t\tretention: configuredImplementationPlanRetention(settings),\n\t\t\tstateEntryType: STATE_ENTRY_TYPE,\n\t\t});\n\t}\n\n\tasync function startImplementation(ctx: ExtensionContext) {\n\t\tconst savedPlan = state.enabled ? undefined : state.savedPlan;\n\t\tconst initialPlan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();\n\t\tif (!initialPlan) {\n\t\t\tctx.ui.notify(\"Plan mode disabled. No proposed plan is available to implement.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (!allowModeTransition(ctx, \"start plan implementation\")) return;\n\t\tif (savedPlan) {\n\t\t\tconst sessionGeneration = menuGeneration;\n\t\t\tconst planWorkflowGeneration = workflowGeneration;\n\t\t\tconst isCurrent = () =>\n\t\t\t\tsessionGeneration === menuGeneration &&\n\t\t\t\tplanWorkflowGeneration === workflowGeneration &&\n\t\t\t\t!menuController.signal.aborted &&\n\t\t\t\t!state.enabled &&\n\t\t\t\tstate.savedPlan === savedPlan;\n\t\t\tif (!(await preflightSavedPlanImplementation(ctx, isCurrent))) return;\n\t\t\tif (!allowModeTransition(ctx, \"start plan implementation\")) return;\n\t\t}\n\t\tconst plan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();\n\t\tconst source =\n\t\t\t(state.enabled ? state.latestPlanSource : savedPlan?.source) ?? \"legacy_proposed_plan\";\n\t\tif (!plan) return;\n\n\t\tconst previousState = state;\n\t\tconst previousIntent = readyPresentationIntent;\n\t\tconst wasEnabled = state.enabled;\n\t\tif (!publishModeContract(\"normal\", ctx)) return;\n\t\tadvanceWorkflowGeneration();\n\t\tconst retention = configuredImplementationPlanRetention(settings);\n\t\tconst usesConversationHistory = retention === \"clear-on-start\";\n\t\treadyPresentationIntent = undefined;\n\t\tworkflowAllowedToolNames = undefined;\n\t\tstate = {\n\t\t\t...state,\n\t\t\tenabled: false,\n\t\t\tlatestPlan: undefined,\n\t\t\tlatestPlanSource: undefined,\n\t\t\tawaitingAction: false,\n\t\t\tsavedPlan: undefined,\n\t\t\tactiveImplementation: usesConversationHistory\n\t\t\t\t? undefined\n\t\t\t\t: {\n\t\t\t\t\t\tid: randomUUID(),\n\t\t\t\t\t\tplan,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tstartedAt: Date.now(),\n\t\t\t\t\t\tretention,\n\t\t\t\t\t},\n\t\t\tmanualThinkingLevel: undefined,\n\t\t};\n\t\tif (wasEnabled) {\n\t\t\trestoreThinkingLevel();\n\t\t\tstate = { ...state, manualThinkingLevel: undefined };\n\t\t}\n\t\tpersistState();\n\t\tupdateUi(ctx);\n\n\t\tconst handoff = usesConversationHistory\n\t\t\t? wasEnabled\n\t\t\t\t? formatHistoryImplementationPrompt()\n\t\t\t\t: formatTransferredPlanPrompt(plan, false)\n\t\t\t: formatImplementationHandoff(plan);\n\t\tconst sent = sendPlanModeUserMessage(handoff, ctx);\n\t\tif (!sent) {\n\t\t\tstate = previousState;\n\t\t\treadyPresentationIntent = previousIntent;\n\t\t\tif (wasEnabled) {\n\t\t\t\tpublishModeContract(\"plan\", ctx);\n\t\t\t\tworkflowAllowedToolNames = computePlanModePolicyToolNames();\n\t\t\t\tapplyPlanThinkingLevel();\n\t\t\t}\n\t\t\tpersistState();\n\t\t\tupdateUi(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (wasEnabled) releaseWorkflowOwner();\n\t}\n\n\tfunction clearActiveImplementation(id: string, ctx: ExtensionContext) {\n\t\tif (state.activeImplementation?.id !== id) return false;\n\t\tadvanceWorkflowGeneration();\n\t\tstate = { ...state, activeImplementation: undefined };\n\t\tpersistState();\n\t\tupdateUi(ctx);\n\t\treturn true;\n\t}\n\n\tasync function exportPlan(\n\t\tctx: ExtensionContext,\n\t\tpath: string | undefined,\n\t\tsignal: AbortSignal,\n\t\tisCurrent: () => boolean,\n\t) {\n\t\tconst exitsReadyPlan = state.enabled && Boolean(state.latestPlan?.trim());\n\t\tif (exitsReadyPlan && !allowModeTransition(ctx, \"export the ready plan and leave Plan mode\")) {\n\t\t\treturn false;\n\t\t}\n\t\treturn planExports.export(path, ctx, signal, () => {\n\t\t\treturn isCurrent() && (!exitsReadyPlan || ctx.isIdle());\n\t\t});\n\t}\n\n\tasync function showLaunchMenu(ctx: ExtensionContext, initialScreen: \"main\" | \"tools\" = \"main\") {\n\t\tconst lifecycle = captureMenuLifecycle();\n\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\tconst ui = await loadInteractiveUi();\n\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\tconst tools = selectableTools();\n\t\tawait ui.showPlanLaunchMenu(ctx, {\n\t\t\tstatusText: helperVisibility.toolsAvailable()\n\t\t\t\t? \"Status: Off \u2014 Plan helper tools are visible for this runtime.\"\n\t\t\t\t: \"Status: Off \u2014 Plan helper tools load on the first Plan start.\",\n\t\t\tinitialScreen,\n\t\t\tgetSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),\n\t\t\ttoolSummary: (selectedNames) => {\n\t\t\t\tconst allowed = tools\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(tool) =>\n\t\t\t\t\t\t\ttoolIsActive(tool.name) &&\n\t\t\t\t\t\t\tselectedNames.has(tool.name) &&\n\t\t\t\t\t\t\tcanSelectToolInPlanMode(tool),\n\t\t\t\t\t)\n\t\t\t\t\t.map((tool) => tool.name);\n\t\t\t\treturn `Plan policy will allow: ${allowed.length > 0 ? allowed.join(\", \") : \"none\"}.`;\n\t\t\t},\n\t\t\ttools: tools.map((tool) => {\n\t\t\t\tconst selectable = canSelectToolInPlanMode(tool);\n\t\t\t\tconst active = toolIsActive(tool.name);\n\t\t\t\tconst policy = active ? toolPolicyLabel(tool) : \"not active in this Pi session\";\n\t\t\t\tconst description = tool.description ?? \"No description available\";\n\t\t\t\treturn {\n\t\t\t\t\tname: tool.name,\n\t\t\t\t\tdescription: `${policy} \u00B7 ${description}`,\n\t\t\t\t\tsearchText: [policy, description].join(\" \"),\n\t\t\t\t\tdisabled: !selectable || !active,\n\t\t\t\t\tdisabledReason: !active\n\t\t\t\t\t\t? \"Not active in Pi; Plan mode will not activate it\"\n\t\t\t\t\t\t: selectable\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: \"Blocked by Plan-mode policy\",\n\t\t\t\t};\n\t\t\t}),\n\t\t\t...lifecycle,\n\t\t\tstart: (signal) => {\n\t\t\t\tif (signal.aborted || !lifecycle.isCurrent()) return;\n\t\t\t\tif (enterPlanMode(ctx)) {\n\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t\"Plan mode enabled. I will explore and plan, but not modify files.\",\n\t\t\t\t\t\t\"info\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\tstartWithTools: (names, signal) => {\n\t\t\t\tif (signal.aborted || !lifecycle.isCurrent()) return;\n\t\t\t\tconst selectedToolNames = filterAvailableSelectedToolNames(names, activePlanPolicyTools());\n\t\t\t\tif (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: undefined })) {\n\t\t\t\t\tctx.ui.notify(\"Plan mode enabled with the selected tools.\", \"info\");\n\t\t\t\t}\n\t\t\t},\n\t\t\tsettings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),\n\t\t});\n\t}\n\n\tasync function showActivePlanMenu(ctx: ExtensionContext) {\n\t\tif (!ctx.hasUI) {\n\t\t\tctx.ui.notify(planStatusText(), \"info\");\n\t\t\treturn;\n\t\t}\n\t\tconst lifecycle = captureMenuLifecycle();\n\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\tconst ui = await loadInteractiveUi();\n\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\tawait ui.showActiveImplementationMenu(ctx, {\n\t\t\tstatusText: planStatusText(),\n\t\t\tgetExportDestination: () => planExports.getDestination(ctx),\n\t\t\tsignal: lifecycle.signal,\n\t\t\tisCurrent: lifecycle.isCurrent,\n\t\t\tshow: () => showStoredPlan(pi, ctx, state),\n\t\t\texportPlan: (path, signal) => planExports.export(path, ctx, signal, lifecycle.isCurrent),\n\t\t\tsettings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),\n\t\t\tstartNew: () => {\n\t\t\t\tif (enterPlanMode(ctx)) {\n\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t\"Plan mode enabled. I will explore and plan, but not modify files.\",\n\t\t\t\t\t\t\"info\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\tclear: () => {\n\t\t\t\tif (exitPlanMode(ctx)) ctx.ui.notify(\"Active implementation plan cleared.\", \"info\");\n\t\t\t},\n\t\t});\n\t}\n\n\tasync function showSettings(\n\t\tctx: ExtensionContext,\n\t\tsignal: AbortSignal,\n\t\tisCurrent: () => boolean,\n\t) {\n\t\tif (!isCurrent() || signal.aborted) return false;\n\t\tconst ui = await loadInteractiveUi();\n\t\tif (!isCurrent() || signal.aborted) return false;\n\t\tconst result = await ui.showPlanModeSettings(ctx, {\n\t\t\ttools: selectableTools(),\n\t\t\tactiveToolNames: activeToolBaseline,\n\t\t\tsignal,\n\t\t\tisCurrent,\n\t\t\tsettingsPath: dependencies.settingsPath,\n\t\t\tupdateSettings: (patch, options) => updateSettingsWithRuntime(patch, options, ctx, isCurrent),\n\t\t\tonSaved: (saved) => {\n\t\t\t\tif (!isCurrent()) return;\n\t\t\t\tsettings = saved;\n\t\t\t\tapplyPlanModeShortcut(configuredPlanModeToggleShortcut(saved));\n\t\t\t},\n\t\t\t...(dependencies.readSettings\n\t\t\t\t? { readSettings: async () => dependencies.readSettings?.() ?? { kind: \"missing\" } }\n\t\t\t\t: {}),\n\t\t});\n\t\treturn result.kind === \"closed\" && \"reason\" in result && result.reason === \"close\";\n\t}\n\n\tasync function updateSettingsWithRuntime(\n\t\tpatch: PlanModeSettingsPatch,\n\t\toptions: UpdatePlanModeSettingsOptions | undefined,\n\t\tctx: ExtensionContext,\n\t\tisCurrent: () => boolean,\n\t) {\n\t\tconst previousVisibility = configuredPlanModeToolVisibility(settings);\n\t\tconst nextVisibility = patch.toolVisibility ?? previousVisibility;\n\t\tconst persistSettings = dependencies.updateSettings ?? updatePlanModeSettings;\n\t\tif (nextVisibility === previousVisibility) {\n\t\t\treturn persistSettings(patch, options);\n\t\t}\n\t\tif (!ctx.isIdle()) {\n\t\t\tthrow new Error(\"Wait for Pi to become idle before changing Plan tool visibility.\");\n\t\t}\n\t\tbindWorkflowSessionIfNeeded(ctx);\n\t\tconst applicationSession = ctx.sessionManager;\n\t\tconst applicationGeneration = menuGeneration;\n\t\tconst applicationIsCurrent = () =>\n\t\t\tcurrentSession === applicationSession &&\n\t\t\tmenuGeneration === applicationGeneration &&\n\t\t\tisCurrent();\n\t\tconst retainedOwner = workflowMutex.isOwner(workflowOwner);\n\t\tconst temporaryOwner = retainedOwner ? workflowOwner : workflowMutex.acquire();\n\t\tif (!temporaryOwner) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Another workflow is active in this session. Plan tool visibility was not changed.\",\n\t\t\t);\n\t\t}\n\t\tconst visibilitySnapshot = helperVisibility.snapshot();\n\t\ttry {\n\t\t\thelperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);\n\t\t\tconst saved = await persistSettings(patch, options);\n\t\t\tif (!applicationIsCurrent()) {\n\t\t\t\tthrow new DOMException(\"Plan settings session replaced\", \"AbortError\");\n\t\t\t}\n\t\t\tsettings = saved;\n\t\t\tapplyPlanModeShortcut(configuredPlanModeToggleShortcut(saved));\n\t\t\treturn saved;\n\t\t} catch (error) {\n\t\t\tif (applicationIsCurrent()) {\n\t\t\t\ttry {\n\t\t\t\t\thelperVisibility.restore(visibilitySnapshot);\n\t\t\t\t} catch (rollbackError) {\n\t\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t\t[error, rollbackError],\n\t\t\t\t\t\t\"Plan tool visibility settings failed and runtime rollback was incomplete.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tif (!retainedOwner) workflowMutex.release(temporaryOwner);\n\t\t\tif (!isCurrent()) latestCommandContext = undefined;\n\t\t}\n\t}\n\n\tfunction allowModeTransition(ctx: ExtensionContext, action: string) {\n\t\tif (ctx.isIdle()) return true;\n\t\tconst message = `Cannot ${action} while an agent run is active. Wait for the run to settle, then retry.`;\n\t\tif (!ctx.hasUI) throw new Error(message);\n\t\tctx.ui.notify(message, \"warning\");\n\t\treturn false;\n\t}\n\n\tfunction advanceWorkflowGeneration() {\n\t\tworkflowGeneration += 1;\n\t\tfinalizationRequest.reset();\n\t}\n\n\tfunction finalizationRunOutcome(messages: unknown): FinalizationRunOutcome {\n\t\tconst stopReason = latestAssistantStopReason(messages);\n\t\tif (stopReason === undefined || stopReason === \"stop\") return \"normal\";\n\t\tif (stopReason === \"aborted\") return \"cancelled\";\n\t\treturn \"error\";\n\t}\n\n\tfunction captureMenuLifecycle() {\n\t\tconst sessionGeneration = menuGeneration;\n\t\tconst planWorkflowGeneration = workflowGeneration;\n\t\tconst owner = workflowOwner;\n\t\tconst controller = menuController;\n\t\treturn {\n\t\t\tsignal: controller.signal,\n\t\t\tisCurrent: () =>\n\t\t\t\tsessionGeneration === menuGeneration &&\n\t\t\t\tplanWorkflowGeneration === workflowGeneration &&\n\t\t\t\t!controller.signal.aborted &&\n\t\t\t\t(!state.enabled || workflowMutex.isOwner(owner)),\n\t\t};\n\t}\n\n\tfunction captureToolBaseline() {\n\t\tactiveToolBaseline = withRequiredPlanModeTools(safeGetActiveTools());\n\t}\n\n\tfunction applyWatchedHelperVisibility(\n\t\tpreviousSettings: PlanModeSettings,\n\t\tnextSettings: PlanModeSettings,\n\t\tctx: ExtensionContext,\n\t) {\n\t\tconst previousVisibility = configuredPlanModeToolVisibility(previousSettings);\n\t\tconst nextVisibility = configuredPlanModeToolVisibility(nextSettings);\n\t\tif (previousVisibility === nextVisibility) return;\n\t\tif (state.enabled) {\n\t\t\thelperVisibility.deferVisibilityChange(nextVisibility);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tif (!ctx.isIdle()) {\n\t\t\t\thelperVisibility.deferVisibilityChange(nextVisibility);\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\thelperVisibility.deferVisibilityChange(nextVisibility);\n\t\t\treturn;\n\t\t}\n\t\tconst owner = workflowMutex.acquire();\n\t\tif (!owner) {\n\t\t\thelperVisibility.deferVisibilityChange(nextVisibility);\n\t\t\treturn;\n\t\t}\n\t\tconst snapshot = helperVisibility.snapshot();\n\t\ttry {\n\t\t\thelperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);\n\t\t} catch (error: unknown) {\n\t\t\thelperVisibility.restore(snapshot);\n\t\t\thelperVisibility.deferVisibilityChange(nextVisibility);\n\t\t\tif (ctx.hasUI) {\n\t\t\t\tconst detail = safeTerminalText(error instanceof Error ? error.message : String(error));\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`Could not apply reloaded Plan tool visibility; the current tool envelope remains unchanged until a later safe boundary: ${detail}`,\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t}\n\t\t} finally {\n\t\t\tworkflowMutex.release(owner);\n\t\t}\n\t}\n\n\tfunction reconcileInactiveHelperVisibility(\n\t\tpreviousVisibility: PlanModeToolVisibility,\n\t\tctx: ExtensionContext,\n\t) {\n\t\tconst owner = workflowMutex.acquire();\n\t\tif (!owner) {\n\t\t\tif (ctx.hasUI) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Plan tool visibility was deferred because another workflow is active in this session.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tconst snapshot = helperVisibility.snapshot();\n\t\ttry {\n\t\t\tconst visibility = configuredPlanModeToolVisibility(settings);\n\t\t\thelperVisibility.prepareSessionStart(visibility, previousVisibility);\n\t\t\thelperVisibility.reconcileInactiveState(visibility);\n\t\t\treturn true;\n\t\t} catch (error: unknown) {\n\t\t\thelperVisibility.restore(snapshot);\n\t\t\tif (ctx.hasUI) {\n\t\t\t\tconst detail = safeTerminalText(error instanceof Error ? error.message : String(error));\n\t\t\t\tctx.ui.notify(`Could not apply Plan tool visibility: ${detail}`, \"error\");\n\t\t\t}\n\t\t\treturn false;\n\t\t} finally {\n\t\t\tworkflowMutex.release(owner);\n\t\t}\n\t}\n\n\tfunction planModePolicyToolNames() {\n\t\treturn workflowAllowedToolNames ?? computePlanModePolicyToolNames();\n\t}\n\n\tfunction computePlanModePolicyToolNames() {\n\t\tconst tools = activePlanPolicyTools();\n\t\tconst selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());\n\t\treturn tools\n\t\t\t.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool))\n\t\t\t.map((tool) => tool.name);\n\t}\n\n\tfunction toolSelectionSnapshot() {\n\t\treturn {\n\t\t\tselectedToolNames: state.selectedToolNames,\n\t\t\tselectedToolKeys: state.selectedToolKeys,\n\t\t\tdefaultPlanTools: settings.defaultPlanTools,\n\t\t};\n\t}\n\n\tfunction selectableTools() {\n\t\treturn safeGetAllTools()\n\t\t\t.filter(\n\t\t\t\t(tool) =>\n\t\t\t\t\ttool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME,\n\t\t\t)\n\t\t\t.sort(compareTools);\n\t}\n\n\tfunction activePlanPolicyTools() {\n\t\tconst activeNames = new Set(activeToolBaseline);\n\t\treturn selectableTools().filter((tool) => activeNames.has(tool.name));\n\t}\n\n\tfunction toolIsActive(toolName: string) {\n\t\treturn activeToolBaseline.includes(toolName);\n\t}\n\n\tfunction safeGetAllTools() {\n\t\ttry {\n\t\t\treturn pi.getAllTools();\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\tfunction applyPlanThinkingLevel() {\n\t\tif (state.manualThinkingLevel) {\n\t\t\tif (pi.getThinkingLevel() !== state.manualThinkingLevel) {\n\t\t\t\tpi.setThinkingLevel(state.manualThinkingLevel);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst configured = configuredThinkingLevel(settings);\n\t\tif (!configured) {\n\t\t\tstate = {\n\t\t\t\t...state,\n\t\t\t\tpreviousThinkingLevel: undefined,\n\t\t\t\tappliedThinkingLevel: undefined,\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\t\tconst current = pi.getThinkingLevel();\n\t\tif (!state.appliedThinkingLevel) state.previousThinkingLevel = current;\n\t\tif (current !== configured) pi.setThinkingLevel(configured);\n\t\tstate.appliedThinkingLevel = pi.getThinkingLevel();\n\t}\n\n\tfunction captureManualThinkingLevel() {\n\t\tif (!state.appliedThinkingLevel) return;\n\t\tconst current = pi.getThinkingLevel();\n\t\tif (current === state.appliedThinkingLevel) return;\n\t\tstate = {\n\t\t\t...state,\n\t\t\tmanualThinkingLevel: current,\n\t\t\tpreviousThinkingLevel: undefined,\n\t\t\tappliedThinkingLevel: undefined,\n\t\t};\n\t}\n\n\tfunction restoreThinkingLevel() {\n\t\tcaptureManualThinkingLevel();\n\t\tconst { appliedThinkingLevel, previousThinkingLevel } = state;\n\t\tif (\n\t\t\tappliedThinkingLevel &&\n\t\t\tpreviousThinkingLevel &&\n\t\t\tpi.getThinkingLevel() === appliedThinkingLevel\n\t\t) {\n\t\t\tpi.setThinkingLevel(previousThinkingLevel);\n\t\t}\n\t\tstate = { ...state, appliedThinkingLevel: undefined, previousThinkingLevel: undefined };\n\t}\n\n\tfunction safeGetActiveTools() {\n\t\ttry {\n\t\t\treturn pi.getActiveTools();\n\t\t} catch {\n\t\t\treturn DEFAULT_TOOLS;\n\t\t}\n\t}\n\n\tfunction installRestoredState(\n\t\tcandidate: PlanModeState,\n\t\tctx: ExtensionContext,\n\t\tpreviousToolVisibility?: PlanModeToolVisibility,\n\t) {\n\t\tconst previousState = state;\n\t\tconst previousWorkflowAllowedToolNames = workflowAllowedToolNames;\n\t\tconst previousOwner = workflowOwner;\n\t\tconst previousHelperVisibility = helperVisibility.snapshot();\n\t\tconst wasEnabled = state.enabled;\n\t\tif (candidate.enabled && !workflowMutex.isOwner(workflowOwner)) {\n\t\t\tconst owner = workflowMutex.acquire();\n\t\t\tif (!owner) {\n\t\t\t\tstate = { enabled: false, awaitingAction: false };\n\t\t\t\tworkflowAllowedToolNames = undefined;\n\t\t\t\treportRestoredWorkflowBusy(ctx);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tworkflowOwner = owner;\n\t\t}\n\n\t\ttry {\n\t\t\tif (candidate.enabled) {\n\t\t\t\tconst visibility = configuredPlanModeToolVisibility(settings);\n\t\t\t\tif (previousToolVisibility === undefined) {\n\t\t\t\t\thelperVisibility.prepareActivation(ctx);\n\t\t\t\t} else {\n\t\t\t\t\ttry {\n\t\t\t\t\t\thelperVisibility.prepareSessionStart(visibility, previousToolVisibility);\n\t\t\t\t\t\thelperVisibility.prepareActivation(ctx);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\thelperVisibility.restore(previousHelperVisibility);\n\t\t\t\t\t\tstate = { enabled: false, awaitingAction: false };\n\t\t\t\t\t\tworkflowAllowedToolNames = undefined;\n\t\t\t\t\t\tif (workflowOwner !== previousOwner) {\n\t\t\t\t\t\t\tworkflowMutex.release(workflowOwner);\n\t\t\t\t\t\t\tworkflowOwner = previousOwner;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treportRestoredHelpersUnavailable(ctx);\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (wasEnabled && !candidate.enabled) {\n\t\t\t\treadyPresentationIntent = undefined;\n\t\t\t\trestoreThinkingLevel();\n\t\t\t}\n\t\t\tstate = candidate;\n\t\t\tworkflowAllowedToolNames = state.enabled ? computePlanModePolicyToolNames() : undefined;\n\t\t\tif (state.enabled) applyPlanThinkingLevel();\n\t\t\telse if (wasEnabled) releaseWorkflowOwner();\n\t\t\treturn true;\n\t\t} catch (error: unknown) {\n\t\t\ttry {\n\t\t\t\tif (!wasEnabled && state.enabled) restoreThinkingLevel();\n\t\t\t} finally {\n\t\t\t\tstate = previousState;\n\t\t\t\tworkflowAllowedToolNames = previousWorkflowAllowedToolNames;\n\t\t\t\thelperVisibility.restore(previousHelperVisibility);\n\t\t\t\tif (workflowOwner !== previousOwner) {\n\t\t\t\t\tworkflowMutex.release(workflowOwner);\n\t\t\t\t\tworkflowOwner = previousOwner;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tfunction rollbackNewActivation(\n\t\tpreviousState: PlanModeState,\n\t\tctx: ExtensionContext,\n\t\tpreviousOwner?: WorkflowMutexOwner,\n\t\tpreviousHelperVisibility?: PlanModeHelperVisibilitySnapshot,\n\t) {\n\t\tconst activatedOwner = workflowOwner;\n\t\treadyPresentationIntent = undefined;\n\t\ttry {\n\t\t\tif (state.enabled) {\n\t\t\t\tpublishModeContract(\"normal\", ctx);\n\t\t\t\trestoreThinkingLevel();\n\t\t\t}\n\t\t} finally {\n\t\t\tstate = previousState;\n\t\t\tworkflowAllowedToolNames = undefined;\n\t\t\ttry {\n\t\t\t\tif (previousHelperVisibility) helperVisibility.restore(previousHelperVisibility);\n\t\t\t\tpersistState();\n\t\t\t\tupdateUi(ctx);\n\t\t\t} finally {\n\t\t\t\tif (activatedOwner !== previousOwner) {\n\t\t\t\t\tworkflowMutex.release(activatedOwner);\n\t\t\t\t\tworkflowOwner = previousOwner;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction bindWorkflowSessionIfNeeded(ctx: ExtensionContext) {\n\t\tif (currentSession === ctx.sessionManager) return;\n\t\tcurrentSession = ctx.sessionManager;\n\t\tworkflowOwner = undefined;\n\t\tworkflowMutex.bindSession(ctx.sessionManager);\n\t}\n\n\tfunction releaseWorkflowOwner() {\n\t\tconst owner = workflowOwner;\n\t\tworkflowMutex.release(owner);\n\t\tif (!workflowMutex.isOwner(owner)) workflowOwner = undefined;\n\t}\n\n\tfunction reportWorkflowBusy(ctx: ExtensionContext) {\n\t\tconst message = \"Another workflow is active in this session. End it before starting Plan mode.\";\n\t\tif (!ctx.hasUI) throw new Error(message);\n\t\tctx.ui.notify(message, \"warning\");\n\t\treturn false;\n\t}\n\n\tfunction reportRestoredWorkflowBusy(ctx: ExtensionContext) {\n\t\tif (!ctx.hasUI) return;\n\t\tctx.ui.notify(\n\t\t\t\"Plan mode was not restored because another workflow is active in this session. Reload or start Plan mode after it ends.\",\n\t\t\t\"warning\",\n\t\t);\n\t}\n\n\tfunction reportRestoredHelpersUnavailable(ctx: ExtensionContext) {\n\t\tif (!ctx.hasUI) return;\n\t\tctx.ui.notify(\n\t\t\t\"Plan mode was not restored because its helper tools are unavailable under the active tool policy.\",\n\t\t\t\"warning\",\n\t\t);\n\t}\n\n\tfunction reportHelperActivationFailure(ctx: ExtensionContext, error: unknown) {\n\t\tconst detail = safeTerminalText(error instanceof Error ? error.message : String(error));\n\t\tconst message = `Cannot start Plan mode: ${detail}.`;\n\t\tif (!ctx.hasUI) throw new Error(message, { cause: error });\n\t\tctx.ui.notify(message, \"error\");\n\t\treturn false;\n\t}\n\n\tfunction updateUi(ctx: ExtensionContext) {\n\t\tupdatePlanModeUi(ctx, state, formatToolSummary);\n\t}\n\n\tfunction clearUi(ctx: ExtensionContext) {\n\t\tclearPlanModeUi(ctx);\n\t}\n\n\tfunction planStatusText() {\n\t\treturn formatPlanModeStatusText(state, formatToolSummary);\n\t}\n\n\tfunction implementationOutcome() {\n\t\treturn implementationRetentionPreview(configuredImplementationPlanRetention(settings));\n\t}\n\n\tfunction formatToolSummary() {\n\t\tconst names = planModePolicyToolNames();\n\t\treturn `Plan policy allows: ${names.length > 0 ? names.join(\", \") : \"none\"}. Model-visible tools stay unchanged.`;\n\t}\n\n\tfunction toolByName(toolName: string) {\n\t\treturn safeGetAllTools().find((candidate) => candidate.name === toolName);\n\t}\n\n\tfunction safeTerminalText(value: string) {\n\t\treturn [...value]\n\t\t\t.map((character) => {\n\t\t\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\t\t\treturn codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n\t\t\t})\n\t\t\t.join(\"\")\n\t\t\t.trim();\n\t}\n}\n\nexport { completePlanArguments } from \"./command.js\";\nexport {\n\textractProposedPlan,\n\tlatestAssistantText,\n\tparseProposedPlan,\n\tstripProposedPlanBlocks,\n\tstripProposedPlanBlocksFromMessage,\n} from \"./message-transform.js\";\nexport {\n\tcreateModeContractMessage,\n\tmodeContractContent,\n\treconcileModeContract,\n} from \"./mode-contract.js\";\nexport { buildPlanModePrompt } from \"./prompt.js\";\nexport { normalizePlanModeQuestionParams } from \"./question-tool.js\";\nexport { withRequiredPlanModeTools } from \"./required-tools.js\";\nexport { normalizePlanModeSettings, readPlanModeSettings } from \"./settings.js\";\nexport { canSelectToolInPlanMode, classifyPlanModeTool, isSafeCommand } from \"./tool-policy.js\";\n", "export interface CommandArgumentCompletion {\n\tvalue: string;\n\tlabel: string;\n\tdescription?: string;\n}\n\nconst PLAN_COMMAND_COMPLETIONS: readonly CommandArgumentCompletion[] = [\n\t{ value: \"start\", label: \"start\", description: \"Start Plan mode without sending a prompt\" },\n\t{ value: \"show\", label: \"show\", description: \"Show the ready, saved, or active plan\" },\n\t{ value: \"finalize\", label: \"finalize\", description: \"Request a completed plan\" },\n\t{ value: \"implement\", label: \"implement\", description: \"Implement the completed or saved plan\" },\n\t{ value: \"save\", label: \"save\", description: \"Save the completed plan for later\" },\n\t{ value: \"export\", label: \"export\", description: \"Export the stored plan to a Markdown file\" },\n\t{ value: \"exit\", label: \"exit\", description: \"Leave Plan mode or clear a saved/active plan\" },\n\t{ value: \"off\", label: \"off\", description: \"Leave Plan mode or clear a saved/active plan\" },\n\t{\n\t\tvalue: \"tools\",\n\t\tlabel: \"tools\",\n\t\tdescription: \"Choose tools before starting this Plan workflow\",\n\t},\n];\n\nexport function completePlanArguments(argumentPrefix: string): CommandArgumentCompletion[] | null {\n\tconst prefix = argumentPrefix.trimStart().toLowerCase();\n\tif (prefix === \"\") return [...PLAN_COMMAND_COMPLETIONS];\n\tif (/\\s/.test(prefix)) return null;\n\n\tconst matches = PLAN_COMMAND_COMPLETIONS.filter((item) => item.value.startsWith(prefix));\n\treturn matches.length > 0 ? [...matches] : null;\n}\n", "export function isStaleExtensionContextError(error: unknown) {\n\treturn (\n\t\terror instanceof Error &&\n\t\t(error.message.includes(\"This extension ctx is stale after session replacement or reload\") ||\n\t\t\terror.message.includes(\"Extension context is no longer active\"))\n\t);\n}\n", "export const FINALIZE_PLAN_PROMPT =\n\t\"Finalize the current implementation plan now. If any material decision remains, use plan_mode_question instead. Otherwise call plan_mode_complete alone as your final action with the complete decision-ready plan.\";\n\nexport const RETRY_FINALIZE_PLAN_PROMPT =\n\t\"Your previous finalization response did not call plan_mode_question or plan_mode_complete. Both tools are available in the current Plan-mode request. If a material decision remains, call plan_mode_question now. Otherwise call plan_mode_complete alone with the complete decision-ready plan. Do not respond with prose about tool availability.\";\n\nexport type FinalizationRunOutcome = \"normal\" | \"cancelled\" | \"error\";\nexport type FinalizationSettlementAction = \"retry\" | \"failed\" | undefined;\n\ninterface PendingFinalizationRequest {\n\tworkflowGeneration: number;\n\tretryCount: number;\n\tawaitingSettlement: boolean;\n}\n\nexport function createFinalizationRequestCoordinator() {\n\tlet pending: PendingFinalizationRequest | undefined;\n\n\treturn {\n\t\trequest(workflowGeneration: number) {\n\t\t\tpending = { workflowGeneration, retryCount: 0, awaitingSettlement: false };\n\t\t},\n\t\tsatisfy() {\n\t\t\tpending = undefined;\n\t\t},\n\t\tobserveRunEnd(workflowGeneration: number, outcome: FinalizationRunOutcome) {\n\t\t\tif (!pending || pending.workflowGeneration !== workflowGeneration) return;\n\t\t\tif (outcome !== \"normal\") {\n\t\t\t\tpending = undefined;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpending.awaitingSettlement = true;\n\t\t},\n\t\tsettle(workflowGeneration: number): FinalizationSettlementAction {\n\t\t\tif (\n\t\t\t\t!pending ||\n\t\t\t\tpending.workflowGeneration !== workflowGeneration ||\n\t\t\t\t!pending.awaitingSettlement\n\t\t\t) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tif (pending.retryCount === 0) {\n\t\t\t\tpending.retryCount = 1;\n\t\t\t\tpending.awaitingSettlement = false;\n\t\t\t\treturn \"retry\";\n\t\t\t}\n\t\t\tpending = undefined;\n\t\t\treturn \"failed\";\n\t\t},\n\t\treset() {\n\t\t\tpending = undefined;\n\t\t},\n\t\thasPendingRequest() {\n\t\t\treturn pending !== undefined;\n\t\t},\n\t};\n}\n", "import { randomUUID } from \"node:crypto\";\nimport type { ExtensionCommandContext, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { PLAN_HISTORY_IMPLEMENTATION_PROMPT } from \"./message-transform.js\";\nimport { createModeContractMessage } from \"./mode-contract.js\";\nimport type { ImplementationPlanRetention } from \"./settings.js\";\nimport type { PlanCompletionSource, PlanModeState } from \"./state.js\";\n\ntype NewSessionOptions = Exclude<Parameters<ExtensionCommandContext[\"newSession\"]>[0], undefined>;\ntype ReplacementContext = Parameters<NonNullable<NewSessionOptions[\"withSession\"]>>[0];\n\nexport interface FreshImplementationRequest {\n\tplan: string;\n\tsource: PlanCompletionSource;\n\tretention: ImplementationPlanRetention;\n\tstateEntryType: string;\n\tisCurrent(): boolean;\n}\n\ninterface FreshImplementationFromStateOptions {\n\tgetState(): PlanModeState;\n\tmenuIsCurrent(): boolean;\n\tretention: ImplementationPlanRetention;\n\tstateEntryType: string;\n}\n\nexport type FreshImplementationResult =\n\t| { kind: \"started\" }\n\t| { kind: \"cancelled\" }\n\t| { kind: \"partial\" }\n\t| { kind: \"rejected\" }\n\t| { kind: \"stale\" };\n\nexport function formatImplementationHandoff(plan: string) {\n\treturn `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:\\n\\n${plan}`;\n}\n\nexport function formatHistoryImplementationPrompt() {\n\treturn PLAN_HISTORY_IMPLEMENTATION_PROMPT;\n}\n\nexport function formatTransferredPlanPrompt(plan: string, fresh: boolean) {\n\tconst destination = fresh ? \" in a fresh context\" : \"\";\n\treturn `A previous agent produced the plan below to accomplish the user's task. Implement the plan${destination}. Treat the plan as the source of user intent, re-read files as needed, and carry the work through implementation and verification.\\n\\n${plan}`;\n}\n\nexport async function startFreshImplementationFromState(\n\tctx: ExtensionContext,\n\toptions: FreshImplementationFromStateOptions,\n) {\n\tif (!isCommandContext(ctx)) {\n\t\tctx.ui.notify(\n\t\t\t\"Fresh implementation requires the interactive /plan command. Reopen /plan and try again.\",\n\t\t\t\"warning\",\n\t\t);\n\t\treturn { kind: \"rejected\" } as const;\n\t}\n\tconst initialState = options.getState();\n\tconst savedPlan = initialState.enabled ? undefined : initialState.savedPlan;\n\tconst plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();\n\tconst source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;\n\tif (!plan || !source) {\n\t\tctx.ui.notify(\"No completed plan is available to implement.\", \"warning\");\n\t\treturn { kind: \"rejected\" } as const;\n\t}\n\tconst wasEnabled = initialState.enabled;\n\tconst isCurrent = () => {\n\t\tconst current = options.getState();\n\t\treturn (\n\t\t\toptions.menuIsCurrent() &&\n\t\t\tcurrent.enabled === wasEnabled &&\n\t\t\t(wasEnabled\n\t\t\t\t? current.latestPlan === plan && current.latestPlanSource === source\n\t\t\t\t: current.savedPlan === savedPlan)\n\t\t);\n\t};\n\treturn startFreshImplementationSession(ctx, {\n\t\tplan,\n\t\tsource,\n\t\tretention: options.retention,\n\t\tstateEntryType: options.stateEntryType,\n\t\tisCurrent,\n\t});\n}\n\nexport async function startFreshImplementationSession(\n\tctx: ExtensionCommandContext,\n\trequest: FreshImplementationRequest,\n): Promise<FreshImplementationResult> {\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") {\n\t\tthrow new Error(\"Fresh plan implementation is unavailable in print/JSON mode. Use TUI or RPC.\");\n\t}\n\n\tawait ctx.waitForIdle();\n\tif (!request.isCurrent()) return { kind: \"stale\" };\n\tif (!(await preflightModel(ctx, request.isCurrent))) return { kind: \"rejected\" };\n\tif (!request.isCurrent()) return { kind: \"stale\" };\n\n\tconst usesConversationHistory = request.retention === \"clear-on-start\";\n\tconst destinationState: PlanModeState | undefined = usesConversationHistory\n\t\t? undefined\n\t\t: {\n\t\t\t\tenabled: false,\n\t\t\t\tawaitingAction: false,\n\t\t\t\tactiveImplementation: {\n\t\t\t\t\tid: randomUUID(),\n\t\t\t\t\tplan: request.plan,\n\t\t\t\t\tsource: request.source,\n\t\t\t\t\tstartedAt: Date.now(),\n\t\t\t\t\tretention: request.retention,\n\t\t\t\t},\n\t\t\t};\n\tconst handoff = usesConversationHistory\n\t\t? formatTransferredPlanPrompt(request.plan, true)\n\t\t: formatImplementationHandoff(request.plan);\n\tconst parentSession = ctx.sessionManager.getSessionFile();\n\tlet setupError: string | undefined;\n\tlet kickoffError: string | undefined;\n\n\tif (ctx.mode === \"rpc\") safeNotify(ctx, \"Starting fresh implementation session\u2026\", \"info\");\n\n\tlet result: Awaited<ReturnType<ExtensionCommandContext[\"newSession\"]>>;\n\ttry {\n\t\tresult = await ctx.newSession({\n\t\t\t...(parentSession ? { parentSession } : {}),\n\t\t\tsetup: async (sessionManager) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst contract = createModeContractMessage(\"normal\");\n\t\t\t\t\tsessionManager.appendCustomMessageEntry(\n\t\t\t\t\t\tcontract.customType,\n\t\t\t\t\t\tcontract.content,\n\t\t\t\t\t\tcontract.display,\n\t\t\t\t\t\tcontract.details,\n\t\t\t\t\t);\n\t\t\t\t\tif (destinationState) {\n\t\t\t\t\t\tsessionManager.appendCustomEntry(request.stateEntryType, destinationState);\n\t\t\t\t\t}\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tsetupError = safeErrorDetail(error);\n\t\t\t\t}\n\t\t\t},\n\t\t\twithSession: async (replacementCtx) => {\n\t\t\t\tif (setupError) {\n\t\t\t\t\trecoverSetupFailure(replacementCtx, handoff, setupError);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait replacementCtx.sendUserMessage(handoff);\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tkickoffError = safeErrorDetail(error);\n\t\t\t\t\tconst recoveredInEditor =\n\t\t\t\t\t\tusesConversationHistory && safeSetEditorText(replacementCtx, handoff);\n\t\t\t\t\tsafeNotify(\n\t\t\t\t\t\treplacementCtx,\n\t\t\t\t\t\tusesConversationHistory\n\t\t\t\t\t\t\t? recoveredInEditor\n\t\t\t\t\t\t\t\t? `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request is in the editor; submit it or resume the parent planning session.`\n\t\t\t\t\t\t\t\t: `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request could not be restored to the editor; resume the parent planning session.`\n\t\t\t\t\t\t\t: `Fresh session created, but implementation did not start: ${kickoffError}. Send a message to continue, use /plan exit to clear the active plan, or resume the parent planning session.`,\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsafeNotify(\n\t\t\t\t\treplacementCtx,\n\t\t\t\t\t\"Fresh implementation session started. Only the approved plan was transferred.\",\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\t} catch (error: unknown) {\n\t\tsafeNotify(\n\t\t\tctx,\n\t\t\t`Unable to start a fresh implementation session: ${safeErrorDetail(error)}. The source plan remains available; retry or resume the planning session.`,\n\t\t\t\"error\",\n\t\t);\n\t\treturn { kind: \"rejected\" };\n\t}\n\n\tif (result.cancelled) {\n\t\tsafeNotify(ctx, \"Fresh implementation cancelled. The plan remains available.\", \"info\");\n\t\treturn { kind: \"cancelled\" };\n\t}\n\treturn setupError || kickoffError ? { kind: \"partial\" } : { kind: \"started\" };\n}\n\nasync function preflightModel(ctx: ExtensionCommandContext, isCurrent: () => boolean) {\n\tconst model = ctx.model;\n\tif (!model) {\n\t\tctx.ui.notify(\"Unable to implement the plan: no model is selected.\", \"warning\");\n\t\treturn false;\n\t}\n\tlet auth: Awaited<ReturnType<ExtensionCommandContext[\"modelRegistry\"][\"getApiKeyAndHeaders\"]>>;\n\ttry {\n\t\tauth = await ctx.modelRegistry.getApiKeyAndHeaders(model);\n\t} catch (error: unknown) {\n\t\tif (isCurrent()) {\n\t\t\tctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(error)}`, \"error\");\n\t\t}\n\t\treturn false;\n\t}\n\tif (!isCurrent()) return false;\n\tif (!auth.ok) {\n\t\tctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(auth.error)}`, \"warning\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction recoverSetupFailure(ctx: ReplacementContext, handoff: string, setupError: string) {\n\tconst recoveredInEditor = safeSetEditorText(ctx, handoff);\n\tsafeNotify(\n\t\tctx,\n\t\trecoveredInEditor\n\t\t\t? `Fresh session created, but the active plan could not be saved: ${setupError}. The implementation request is in the editor; submit it to continue or resume the parent planning session.`\n\t\t\t: `Fresh session created, but the active plan could not be saved: ${setupError}. The implementation request could not be restored to the editor; resume the parent planning session.`,\n\t\t\"error\",\n\t);\n}\n\nfunction safeSetEditorText(ctx: Pick<ExtensionContext, \"ui\">, text: string) {\n\ttry {\n\t\tctx.ui.setEditorText(text);\n\t\treturn true;\n\t} catch {\n\t\t// A replacement context can become stale while Pi reports a partial handoff.\n\t\treturn false;\n\t}\n}\n\nfunction safeNotify(\n\tctx: Pick<ExtensionContext, \"ui\">,\n\tmessage: string,\n\tlevel: \"info\" | \"warning\" | \"error\",\n) {\n\ttry {\n\t\tctx.ui.notify(message, level);\n\t} catch {\n\t\t// A source or replacement context can become stale during session replacement.\n\t}\n}\n\nfunction isCommandContext(ctx: ExtensionContext): ctx is ExtensionCommandContext {\n\treturn typeof (ctx as Partial<ExtensionCommandContext>).newSession === \"function\";\n}\n\nfunction safeErrorDetail(error: unknown) {\n\tconst detail = error instanceof Error ? error.message : String(error);\n\tconst normalized =\n\t\t[...detail]\n\t\t\t.map((character) => {\n\t\t\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\t\t\treturn codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n\t\t\t})\n\t\t\t.join(\"\")\n\t\t\t.replace(/\\s+/gu, \" \")\n\t\t\t.trim() || \"unknown error\";\n\tconst characters = [...normalized];\n\treturn characters.length > 500 ? `${characters.slice(0, 499).join(\"\")}\u2026` : normalized;\n}\n", "const PLAN_CONTEXT_MARKER = \"[CODEX-LIKE PLAN MODE ACTIVE]\";\n\nexport function buildPlanModePrompt() {\n\treturn `${PLAN_CONTEXT_MARKER}\n# Plan Mode (Conversational)\n\nYou are in Plan Mode, a Codex-like collaboration mode for producing a decision-complete implementation plan. Chat your way to the plan before finalizing it. A final plan must leave no implementation decisions unresolved.\n\n## Mode rules\n\n- Stay in Plan Mode until a developer or extension explicitly exits it.\n- Treat requests to implement as requests to plan the implementation; do not edit files or carry out the plan.\n- Do not use update_plan/TODO tooling in Plan Mode; Plan Mode is conversational planning, not execution progress tracking.\n- Plan Mode keeps the session's model-visible tool schemas unchanged and enforces a runtime policy allowlist. Non-built-in tools are denied by default and may be allowed only when already active in Pi and explicitly selected by the user at their own risk.\n- Do not perform mutating actions: no edit/write tools, no patching, no formatting that rewrites files, no dependency installation, no commits, no migrations.\n\n## Phase 1 \u2014 Ground in the environment\n\n- Explore first and ask second. Use non-mutating exploration to read files, search, inspect configuration, run read-only checks, and resolve discoverable facts.\n- Before asking the user any question, perform at least one targeted non-mutating exploration pass unless no local environment or repository is available.\n- Do not ask questions that can be answered from repository or system truth. Ask only when multiple plausible choices remain, a needed identifier/context is missing, or the ambiguity is product intent.\n\n## Phase 2 \u2014 Intent chat\n\n- Keep asking until you can clearly state the goal, success criteria, in/out of scope, constraints, current state, and key preferences/tradeoffs.\n- Bias toward questions over guessing: if a high-impact ambiguity remains, do not produce a proposed plan yet.\n- For an unanswered preference or tradeoff, use the recommended option only when it is low risk and record that default as an explicit assumption in the final plan.\n\n## Phase 3 \u2014 Implementation chat\n\n- Once intent is stable, keep asking until the spec is decision-complete: approach, interfaces, data flow, edge cases/failure modes, testing and acceptance criteria, and any migration or compatibility constraints.\n- Use plan_mode_question for important preferences, tradeoffs, or assumption locks that cannot be discovered by non-mutating exploration. Ask 1-3 concise questions with 2-4 meaningful options. Do not include filler options.\n- Treat plan_mode_question and plan_mode_complete as callable when they are listed in the current request's active tools. Do not infer that they are unavailable from earlier modes or conversation history.\n- If a Plan tool call returns an actual error, respond to that error. Do not replace an available structured tool call with prose claiming that the tool is unavailable.\n- If plan_mode_question returns cancelled or ui_unavailable, do not jump straight to a final plan when the missing answer is high impact. Ask one concise plain-text question or proceed only with a clearly stated low-risk assumption.\n\n## Ending each turn\n\nEvery Plan-mode turn that advances or finalizes the plan must end in exactly one of these ways:\n\n- If a material decision remains, use plan_mode_question. If interactive UI is unavailable, ask one concise plain-text question instead.\n- If the implementation plan is decision-complete, call plan_mode_complete alone as your final action. Do not call other tools in the same batch and do not emit a normal assistant response after it.\n\nIf a follow-up asks only for clarification and does not change or challenge the plan, answer it directly, then call plan_mode_complete alone as the final action with the complete unchanged plan so it remains available for implementation.\n\nNever end with prose that merely announces you are about to present, write, or finalize the plan. Submit the actual plan with plan_mode_complete in that turn.\n\n## Completion rule\n\nOnly call plan_mode_complete when the plan leaves no implementation decisions unresolved. Pass the complete plan as Markdown with:\n\n- A clear title\n- A brief summary\n- Important changes to behavior, public APIs, interfaces, or types\n- Test cases and verification scenarios\n- Explicit assumptions and defaults chosen where needed\n\nKeep the plan concise, human and agent digestible, and free of open decisions. Prefer grouped behavior-level changes over file-by-file or symbol-by-symbol inventories. Do not ask \"should I proceed?\"; plan_mode_complete opens the Plan-mode ready flow.\n\nIf the user requests revisions after a completed plan, the next plan_mode_complete call must contain a complete replacement, not a delta. If there is not enough information for a complete replacement, continue planning with plan_mode_question instead of calling plan_mode_complete.`;\n}\n", "import { buildPlanModePrompt } from \"./prompt.js\";\n\nexport const MODE_CONTRACT_MESSAGE_TYPE = \"plan-mode-transition\";\nexport const MODE_CONTRACT_VERSION = 1;\nexport type PlanModeContract = \"plan\" | \"normal\";\n\nconst PLAN_CONTRACT_MARKER = `[PI PLAN MODE CONTRACT v${MODE_CONTRACT_VERSION}: PLAN]`;\nconst NORMAL_CONTRACT_MARKER = `[PI PLAN MODE CONTRACT v${MODE_CONTRACT_VERSION}: NORMAL]`;\nconst NORMAL_CONTRACT = `${NORMAL_CONTRACT_MARKER}\nPlan Mode is no longer active.\nFollow the user's current Normal-mode request and ordinary system instructions.\nEarlier Plan-mode restrictions no longer apply, but retain the planning conversation as context.\nThe visible tool schemas are session capabilities; use only tools appropriate for the current request.`;\n\ninterface ContractMessage {\n\trole?: string;\n\tcustomType?: string;\n\tcontent?: unknown;\n\tdetails?: unknown;\n}\n\nexport function modeContractContent(mode: PlanModeContract) {\n\treturn mode === \"plan\" ? `${PLAN_CONTRACT_MARKER}\\n${buildPlanModePrompt()}` : NORMAL_CONTRACT;\n}\n\nexport function createModeContractMessage(mode: PlanModeContract, timestamp = Date.now()) {\n\treturn {\n\t\trole: \"custom\" as const,\n\t\tcustomType: MODE_CONTRACT_MESSAGE_TYPE,\n\t\tcontent: modeContractContent(mode),\n\t\tdisplay: false,\n\t\tdetails: { version: MODE_CONTRACT_VERSION, mode },\n\t\ttimestamp,\n\t};\n}\n\nexport function modeContractFromMessage(message: unknown): PlanModeContract | undefined {\n\tconst candidate = unwrapMessage(message);\n\tif (candidate.customType !== MODE_CONTRACT_MESSAGE_TYPE) return undefined;\n\tif (candidate.content === modeContractContent(\"plan\")) return \"plan\";\n\tif (candidate.content === modeContractContent(\"normal\")) return \"normal\";\n\treturn undefined;\n}\n\nexport function hasModeContractArtifact(messages: readonly unknown[]) {\n\treturn messages.some(\n\t\t(message) => unwrapMessage(message).customType === MODE_CONTRACT_MESSAGE_TYPE,\n\t);\n}\n\nexport function latestModeContract(messages: readonly unknown[]) {\n\tfor (let index = messages.length - 1; index >= 0; index -= 1) {\n\t\tconst mode = modeContractFromMessage(messages[index]);\n\t\tif (mode) return { index, mode };\n\t}\n\treturn undefined;\n}\n\nexport function reconcileModeContract(messages: unknown[], expected: PlanModeContract) {\n\tconst latest = latestModeContract(messages);\n\tif (latest?.mode === expected) return messages;\n\n\tconst latestContractIndex = findLatestContractArtifactIndex(messages);\n\tconst insertionIndex =\n\t\tlatestContractIndex >= 0 ? latestContractIndex + 1 : leadingSummaryBoundary(messages);\n\treturn [\n\t\t...messages.slice(0, insertionIndex),\n\t\tcreateModeContractMessage(expected, 0),\n\t\t...messages.slice(insertionIndex),\n\t];\n}\n\nfunction findLatestContractArtifactIndex(messages: readonly unknown[]) {\n\tfor (let index = messages.length - 1; index >= 0; index -= 1) {\n\t\tif (unwrapMessage(messages[index]).customType === MODE_CONTRACT_MESSAGE_TYPE) return index;\n\t}\n\treturn -1;\n}\n\nfunction leadingSummaryBoundary(messages: readonly unknown[]) {\n\tlet index = 0;\n\twhile (index < messages.length) {\n\t\tconst role = unwrapMessage(messages[index]).role;\n\t\tif (role !== \"compactionSummary\" && role !== \"branchSummary\") break;\n\t\tindex += 1;\n\t}\n\treturn index;\n}\n\nfunction unwrapMessage(message: unknown): ContractMessage {\n\tconst entry = message as { message?: unknown } | undefined;\n\treturn (entry?.message ?? message ?? {}) as ContractMessage;\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { PLAN_MODE_COMPLETE_TOOL_NAME } from \"./completion-tool.js\";\nimport { PLAN_MODE_QUESTION_TOOL_NAME } from \"./question-tool.js\";\nimport type { PlanModeToolVisibility } from \"./settings.js\";\n\nexport const PLAN_MODE_HELPER_TOOL_NAMES = [\n\tPLAN_MODE_QUESTION_TOOL_NAME,\n\tPLAN_MODE_COMPLETE_TOOL_NAME,\n] as const;\n\nexport interface PlanModeHelperVisibilitySnapshot {\n\tactiveTools: string[];\n\thelperToolsUnlocked: boolean;\n\thelperToolsHiddenByPolicy: string[];\n}\n\ninterface ToolVisibilityContext {\n\tisIdle?: () => boolean;\n}\n\nexport class PlanModeHelperVisibilityPolicy {\n\tprivate unlocked = false;\n\tprivate readonly hiddenByPolicy = new Set<string>();\n\n\tconstructor(private readonly pi: Pick<ExtensionAPI, \"getActiveTools\" | \"setActiveTools\">) {}\n\n\tisUnlocked() {\n\t\treturn this.unlocked;\n\t}\n\n\thasHiddenTools() {\n\t\treturn this.hiddenByPolicy.size > 0;\n\t}\n\n\ttoolsAvailable() {\n\t\tconst active = new Set(this.pi.getActiveTools());\n\t\treturn PLAN_MODE_HELPER_TOOL_NAMES.every((name) => active.has(name));\n\t}\n\n\tprepareSessionStart(visibility: PlanModeToolVisibility, previous: PlanModeToolVisibility) {\n\t\tif (visibility === \"after-first-plan\" && previous === \"always\") this.lock();\n\t\tif (visibility === \"always\") this.reveal();\n\t}\n\n\treconcileInactiveState(visibility: PlanModeToolVisibility) {\n\t\tif (visibility === \"after-first-plan\" && !this.unlocked) this.hideIfLocked();\n\t}\n\n\tdeferVisibilityChange(visibility: PlanModeToolVisibility) {\n\t\tif (visibility === \"after-first-plan\") this.lock();\n\t}\n\n\tprepareActivation(ctx: ToolVisibilityContext) {\n\t\tif (!this.toolsAvailable() && ctx.isIdle?.() !== true) {\n\t\t\tthrow new Error(\"wait until Pi is idle before revealing the Plan tools\");\n\t\t}\n\t\tthis.reveal();\n\t}\n\n\tapplyVisibilityChange(\n\t\tprevious: PlanModeToolVisibility,\n\t\tnext: PlanModeToolVisibility,\n\t\tctx: ToolVisibilityContext,\n\t) {\n\t\tif (previous === next) return;\n\t\tif (next === \"always\") {\n\t\t\tif (!this.toolsAvailable() && ctx.isIdle?.() !== true) {\n\t\t\t\tthrow new Error(\"Wait for Pi to become idle before revealing Plan tools.\");\n\t\t\t}\n\t\t\tthis.reveal();\n\t\t\treturn;\n\t\t}\n\t\tif (ctx.isIdle?.() !== true) {\n\t\t\tthrow new Error(\"Wait for Pi to become idle before hiding Plan tools.\");\n\t\t}\n\t\tthis.lock();\n\t\tthis.hideIfLocked();\n\t}\n\n\thideIfLocked() {\n\t\tif (this.unlocked) return;\n\t\tconst active = this.pi.getActiveTools();\n\t\tconst hidden = active.filter((name) => this.isHelperTool(name));\n\t\tif (hidden.length === 0) return;\n\t\tthis.pi.setActiveTools(active.filter((name) => !this.isHelperTool(name)));\n\t\tfor (const name of hidden) this.hiddenByPolicy.add(name);\n\t}\n\n\tsnapshot(): PlanModeHelperVisibilitySnapshot {\n\t\treturn {\n\t\t\tactiveTools: this.pi.getActiveTools(),\n\t\t\thelperToolsUnlocked: this.unlocked,\n\t\t\thelperToolsHiddenByPolicy: [...this.hiddenByPolicy],\n\t\t};\n\t}\n\n\trestore(snapshot: PlanModeHelperVisibilitySnapshot) {\n\t\tthis.pi.setActiveTools(snapshot.activeTools);\n\t\tthis.unlocked = snapshot.helperToolsUnlocked;\n\t\tthis.hiddenByPolicy.clear();\n\t\tfor (const name of snapshot.helperToolsHiddenByPolicy) this.hiddenByPolicy.add(name);\n\t}\n\n\tprivate reveal() {\n\t\tconst snapshot = this.snapshot();\n\t\ttry {\n\t\t\tconst active = this.pi.getActiveTools();\n\t\t\tconst canonical = [\n\t\t\t\t...active.filter((name) => !this.isHelperTool(name)),\n\t\t\t\t...PLAN_MODE_HELPER_TOOL_NAMES,\n\t\t\t];\n\t\t\tif (\n\t\t\t\tcanonical.length !== active.length ||\n\t\t\t\tcanonical.some((name, index) => name !== active[index])\n\t\t\t) {\n\t\t\t\tthis.pi.setActiveTools(canonical);\n\t\t\t}\n\t\t\tif (!this.toolsAvailable()) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"plan_mode_question and plan_mode_complete are unavailable; leave the restrictive tool mode before starting Plan mode\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.unlockAndForgetHidden();\n\t\t} catch (error) {\n\t\t\tthis.restore(snapshot);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate lock() {\n\t\tthis.unlocked = false;\n\t}\n\n\tprivate unlockAndForgetHidden() {\n\t\tthis.unlocked = true;\n\t\tthis.hiddenByPolicy.clear();\n\t}\n\n\tprivate isHelperTool(name: string) {\n\t\treturn (PLAN_MODE_HELPER_TOOL_NAMES as readonly string[]).includes(name);\n\t}\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport type { PlanExportDestination } from \"./plan-export.js\";\nimport type { PlanModeState } from \"./state.js\";\n\ntype InteractiveUi = typeof import(\"./interactive-ui.js\");\n\ninterface MenuLifecycle {\n\tsignal: AbortSignal;\n\tisCurrent(): boolean;\n}\n\ninterface PlanActionControllerOptions {\n\tloadInteractiveUi(): Promise<InteractiveUi>;\n\tgetState(): PlanModeState;\n\tcaptureLifecycle(): MenuLifecycle;\n\tstatusText(): string;\n\timplementationOutcome(): string;\n\tgetExportDestination(ctx: ExtensionContext): PlanExportDestination;\n\tshow(ctx: ExtensionContext): void;\n\tfinalize(ctx: ExtensionContext): void;\n\timplementHere(ctx: ExtensionContext): void | Promise<void>;\n\timplementFresh(ctx: ExtensionContext, isCurrent: () => boolean): void | Promise<void>;\n\texportPlan(\n\t\tctx: ExtensionContext,\n\t\tpath: string,\n\t\tsignal: AbortSignal,\n\t\tisCurrent: () => boolean,\n\t): Promise<boolean>;\n\tsettings(ctx: ExtensionContext, signal: AbortSignal, isCurrent: () => boolean): Promise<boolean>;\n\tsave(ctx: ExtensionContext): void;\n\tstay(ctx: ExtensionContext): void;\n\texitReady(ctx: ExtensionContext): void;\n\tclearSaved(ctx: ExtensionContext): void;\n}\n\nexport function createPlanActionController(options: PlanActionControllerOptions) {\n\tconst freshAction = (ctx: ExtensionContext, lifecycle: MenuLifecycle, signal: AbortSignal) =>\n\t\toptions.implementFresh(ctx, () => lifecycle.isCurrent() && !signal.aborted);\n\n\treturn {\n\t\tasync showSaved(ctx: ExtensionContext) {\n\t\t\tconst lifecycle = options.captureLifecycle();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tconst ui = await options.loadInteractiveUi();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tawait ui.showSavedPlanMenu(ctx, {\n\t\t\t\tstatusText: options.statusText(),\n\t\t\t\timplementationOutcome: options.implementationOutcome,\n\t\t\t\tgetExportDestination: () => options.getExportDestination(ctx),\n\t\t\t\tsignal: lifecycle.signal,\n\t\t\t\tisCurrent: lifecycle.isCurrent,\n\t\t\t\tshow: () => options.show(ctx),\n\t\t\t\timplementHere: () => options.implementHere(ctx),\n\t\t\t\timplementFresh: (signal) => freshAction(ctx, lifecycle, signal),\n\t\t\t\texportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),\n\t\t\t\tsettings: (signal) => options.settings(ctx, signal, lifecycle.isCurrent),\n\t\t\t\tclear: () => options.clearSaved(ctx),\n\t\t\t});\n\t\t},\n\t\tasync showCurrent(ctx: ExtensionContext) {\n\t\t\tif (!ctx.hasUI) {\n\t\t\t\tctx.ui.notify(options.statusText(), \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst lifecycle = options.captureLifecycle();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tconst ui = await options.loadInteractiveUi();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tawait ui.showPlanModeMenu(ctx, {\n\t\t\t\tstatusText: options.statusText(),\n\t\t\t\thasReadyPlan: options.getState().latestPlan !== undefined,\n\t\t\t\timplementationOutcome: options.implementationOutcome,\n\t\t\t\tgetExportDestination: () => options.getExportDestination(ctx),\n\t\t\t\t...lifecycle,\n\t\t\t\tshow: () => options.show(ctx),\n\t\t\t\tfinalize: () => options.finalize(ctx),\n\t\t\t\timplementHere: () => options.implementHere(ctx),\n\t\t\t\timplementFresh: (signal) => freshAction(ctx, lifecycle, signal),\n\t\t\t\texportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),\n\t\t\t\tsave: () => options.save(ctx),\n\t\t\t\tstay: () => options.stay(ctx),\n\t\t\t\texit: () => options.exitReady(ctx),\n\t\t\t});\n\t\t},\n\t\tasync showReady(ctx: ExtensionContext) {\n\t\t\tconst lifecycle = options.captureLifecycle();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tconst ui = await options.loadInteractiveUi();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tawait ui.showReadyPlanMenu(ctx, {\n\t\t\t\t...lifecycle,\n\t\t\t\timplementationOutcome: options.implementationOutcome,\n\t\t\t\tgetExportDestination: () => options.getExportDestination(ctx),\n\t\t\t\timplementHere: () => options.implementHere(ctx),\n\t\t\t\timplementFresh: (signal) => freshAction(ctx, lifecycle, signal),\n\t\t\t\texportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),\n\t\t\t\tsave: () => options.save(ctx),\n\t\t\t\tstay: () => undefined,\n\t\t\t\texit: () => options.exitReady(ctx),\n\t\t\t});\n\t\t},\n\t};\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { exportStoredPlan, planExportDestination } from \"./plan-export.js\";\nimport { configuredPlanExportPath, type PlanModeSettings } from \"./settings.js\";\nimport type { PlanModeState } from \"./state.js\";\n\ninterface PlanExportControllerOptions {\n\tgetState(): PlanModeState;\n\tgetSettings(): PlanModeSettings;\n\tfinishReady(ctx: ExtensionContext): void;\n}\n\nexport function createPlanExportController(options: PlanExportControllerOptions) {\n\treturn {\n\t\texport(\n\t\t\tpath: string | undefined,\n\t\t\tctx: ExtensionContext,\n\t\t\tsignal: AbortSignal,\n\t\t\tisCurrent: () => boolean,\n\t\t) {\n\t\t\tconst state = options.getState();\n\t\t\treturn exportStoredPlan(\n\t\t\t\tstate,\n\t\t\t\tpath,\n\t\t\t\tctx,\n\t\t\t\t{\n\t\t\t\t\tsignal,\n\t\t\t\t\tisCurrent,\n\t\t\t\t\tgetState: options.getState,\n\t\t\t\t\tfinishReady: () => options.finishReady(ctx),\n\t\t\t\t},\n\t\t\t\tconfiguredPlanExportPath(options.getSettings()),\n\t\t\t);\n\t\t},\n\t\tgetDestination(ctx: ExtensionContext) {\n\t\t\treturn planExportDestination(configuredPlanExportPath(options.getSettings()), ctx.cwd);\n\t\t},\n\t};\n}\n", "import type { ExtensionAPI, ExtensionContext, Theme } from \"@earendil-works/pi-coding-agent\";\nimport { stripTerminalSequences, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport type { PlanModeState } from \"./state.js\";\n\nconst STATUS_KEY = \"plan-mode\";\nconst PLAN_WIDGET_KEY = \"plan-mode-plan\";\nconst BIDI_CONTROLS = /[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/gu;\n\nexport function updatePlanModeUi(\n\tctx: ExtensionContext,\n\tstate: PlanModeState,\n\ttoolSummary: () => string,\n) {\n\tctx.ui.setStatus(STATUS_KEY, formatStatus(state));\n\tlet lines: string[] | undefined;\n\tif (state.enabled && state.latestPlan) {\n\t\tlines = [\"Proposed plan ready\", \"Use /plan to implement, save, revise, or exit Plan mode.\"];\n\t} else if (state.enabled) {\n\t\tlines = [\n\t\t\t\"Plan mode: planning\",\n\t\t\ttoolSummary(),\n\t\t\t\"Finish with plan_mode_complete when decision-ready.\",\n\t\t];\n\t} else if (state.savedPlan) {\n\t\tlines = [\"Plan saved for later\", \"Use /plan to show, implement, or clear it.\"];\n\t} else if (state.activeImplementation) {\n\t\tlines = [\"Implementation plan active\", \"Use /plan to show, replace, or clear it.\"];\n\t}\n\n\tpublishPlanModeWidget(ctx, lines);\n}\n\nexport function renderPlanModeWidget(\n\tlines: readonly string[],\n\ttheme: Theme,\n\twidth: number,\n): string[] {\n\tconst renderWidth = Math.max(0, width);\n\treturn [\n\t\ttheme.fg(\"borderMuted\", \"\u2500\".repeat(renderWidth)),\n\t\t...lines.map((line) => truncateToWidth(sanitizePlanModeWidgetLine(line), renderWidth, \"\")),\n\t];\n}\n\nexport function sanitizePlanModeWidgetLine(value: string): string {\n\tlet text = \"\";\n\tfor (const character of stripTerminalSequences(value).replace(BIDI_CONTROLS, \"\")) {\n\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\tconst isControl = codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n\t\ttext += isControl ? \" \" : character;\n\t}\n\treturn text;\n}\n\nexport function clearPlanModeUi(ctx: ExtensionContext) {\n\tctx.ui.setStatus(STATUS_KEY, undefined);\n\tctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);\n}\n\nexport function showStoredPlan(pi: ExtensionAPI, ctx: ExtensionContext, state: PlanModeState) {\n\tconst readyPlan = state.enabled ? state.latestPlan?.trim() : undefined;\n\tconst savedPlan = state.savedPlan?.plan.trim();\n\tif (savedPlan && (ctx.mode === \"print\" || ctx.mode === \"json\")) {\n\t\tthrow new Error(\"Saved plan display is unavailable in print/JSON mode. Use TUI or RPC.\");\n\t}\n\tconst activePlan = state.activeImplementation?.plan.trim();\n\tconst plan = readyPlan ?? savedPlan ?? activePlan;\n\tif (!plan) {\n\t\tctx.ui.notify(\n\t\t\t\"No completed plan is available. Use /plan finalize when planning is complete.\",\n\t\t\t\"info\",\n\t\t);\n\t\treturn;\n\t}\n\tconst title = readyPlan\n\t\t? \"Proposed Plan\"\n\t\t: savedPlan\n\t\t\t? \"Saved Plan\"\n\t\t\t: \"Active Implementation Plan\";\n\tshowPlanModePlan(pi, ctx, title, plan);\n}\n\nexport function showPlanModePlan(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\ttitle: string,\n\tplan: string,\n) {\n\ttry {\n\t\tpi.sendMessage(\n\t\t\t{\n\t\t\t\tcustomType: \"proposed-plan\",\n\t\t\t\tcontent: `**${title}**\\n\\n${plan}`,\n\t\t\t\tdisplay: true,\n\t\t\t},\n\t\t\t{ triggerTurn: false },\n\t\t);\n\t} catch (error: unknown) {\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tctx.ui.notify(`Unable to show completed plan: ${detail}`, \"error\");\n\t}\n}\n\nexport function planModeStatusText(state: PlanModeState, toolSummary: () => string) {\n\tif (state.enabled) {\n\t\tif (state.latestPlan) {\n\t\t\treturn `Plan mode is active and a proposed plan is ready. ${toolSummary()}`;\n\t\t}\n\t\treturn `Plan mode is active. ${toolSummary()} Explore, ask, and finish with plan_mode_complete when decision-ready.`;\n\t}\n\tif (state.savedPlan) return \"A plan is saved for later.\";\n\tif (state.activeImplementation) return \"An implementation plan is active.\";\n\treturn \"Plan mode is off.\";\n}\n\nfunction publishPlanModeWidget(ctx: ExtensionContext, lines: readonly string[] | undefined) {\n\tif (!lines) {\n\t\tctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);\n\t\treturn;\n\t}\n\tif (ctx.mode !== \"tui\") {\n\t\tctx.ui.setWidget(PLAN_WIDGET_KEY, [...lines]);\n\t\treturn;\n\t}\n\n\tconst snapshot = [...lines];\n\tctx.ui.setWidget(PLAN_WIDGET_KEY, (_tui, theme) => ({\n\t\trender: (width) => renderPlanModeWidget(snapshot, theme, width),\n\t\tinvalidate: () => {},\n\t}));\n}\n\nfunction formatStatus(state: PlanModeState) {\n\tif (state.enabled) {\n\t\tif (state.awaitingAction || state.latestPlan) return \"plan ready\";\n\t\treturn \"plan active\";\n\t}\n\tif (state.savedPlan) return \"plan saved\";\n\tif (state.activeImplementation) return \"plan implementing\";\n\treturn undefined;\n}\n", "import { PLAN_MODE_COMPLETE_TOOL_NAME } from \"./completion-tool.js\";\nimport { PLAN_MODE_QUESTION_TOOL_NAME } from \"./question-tool.js\";\nimport { unique } from \"./tool-selection.js\";\n\nexport function withRequiredPlanModeTools(toolNames: string[]) {\n\treturn unique([\n\t\t...withoutRequiredPlanModeTools(toolNames),\n\t\tPLAN_MODE_QUESTION_TOOL_NAME,\n\t\tPLAN_MODE_COMPLETE_TOOL_NAME,\n\t]);\n}\n\nexport function withoutRequiredPlanModeTools(toolNames: string[]) {\n\treturn toolNames.filter(\n\t\t(toolName) =>\n\t\t\ttoolName !== PLAN_MODE_QUESTION_TOOL_NAME && toolName !== PLAN_MODE_COMPLETE_TOOL_NAME,\n\t);\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\n\nexport function savedPlanBlocksNewWorkflow(ctx: ExtensionContext, hasSavedPlan: boolean) {\n\tif (!hasSavedPlan) return false;\n\tconst message =\n\t\t\"A plan is saved for later. Implement or clear it before starting another Plan-mode workflow.\";\n\tif (!ctx.hasUI) throw new Error(message);\n\tctx.ui.notify(message, \"warning\");\n\treturn true;\n}\n\nexport async function preflightSavedPlanImplementation(\n\tctx: ExtensionContext,\n\tisCurrent: () => boolean,\n) {\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") {\n\t\tthrow new Error(\"Saved plan implementation is unavailable in print/JSON mode. Use TUI or RPC.\");\n\t}\n\tconst model = ctx.model;\n\tif (!model) {\n\t\tctx.ui.notify(\"Unable to implement saved plan: no model is selected.\", \"warning\");\n\t\treturn false;\n\t}\n\tlet auth: Awaited<ReturnType<ExtensionContext[\"modelRegistry\"][\"getApiKeyAndHeaders\"]>>;\n\ttry {\n\t\tauth = await ctx.modelRegistry.getApiKeyAndHeaders(model);\n\t} catch (error: unknown) {\n\t\tif (!isCurrent()) return false;\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tctx.ui.notify(`Unable to implement saved plan: ${detail}`, \"error\");\n\t\treturn false;\n\t}\n\tif (!isCurrent()) return false;\n\tif (!auth.ok) {\n\t\tctx.ui.notify(`Unable to implement saved plan: ${auth.error}`, \"warning\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n", "import {\n\tnormalizePlanModeCompletion,\n\tPLAN_MODE_COMPLETE_TOOL_NAME,\n\tplanFromCompletionDetails,\n} from \"./completion-tool.js\";\nimport {\n\tIMPLEMENTATION_PLAN_RETENTIONS,\n\ttype ImplementationPlanRetention,\n\tPLAN_MODE_THINKING_LEVELS,\n\ttype PlanModeFixedThinkingLevel,\n} from \"./settings.js\";\n\nexport type PlanCompletionSource = typeof PLAN_MODE_COMPLETE_TOOL_NAME | \"legacy_proposed_plan\";\n\nexport interface ActiveImplementationPlan {\n\tid: string;\n\tplan: string;\n\tsource: PlanCompletionSource;\n\tstartedAt: number;\n\tretention?: ImplementationPlanRetention;\n}\n\nexport interface SavedPlan {\n\tplan: string;\n\tsource: PlanCompletionSource;\n}\n\nexport interface PlanModeState {\n\tenabled: boolean;\n\tlatestPlan?: string;\n\tlatestPlanSource?: PlanCompletionSource;\n\tawaitingAction: boolean;\n\tsavedPlan?: SavedPlan;\n\tactiveImplementation?: ActiveImplementationPlan;\n\tselectedToolNames?: string[];\n\tselectedToolKeys?: string[];\n\tpreviousThinkingLevel?: PlanModeFixedThinkingLevel;\n\tappliedThinkingLevel?: PlanModeFixedThinkingLevel;\n\tmanualThinkingLevel?: PlanModeFixedThinkingLevel;\n}\n\ntype SessionEntry = {\n\ttype?: string;\n\tcustomType?: string;\n\tdata?: unknown;\n\tmessage?: {\n\t\trole?: string;\n\t\ttoolName?: string;\n\t\tdetails?: unknown;\n\t};\n};\n\nexport function restorePlanModeState(entries: unknown[], stateEntryType: string): PlanModeState {\n\tconst branch = entries as SessionEntry[];\n\tlet stateEntryIndex = -1;\n\tfor (let index = branch.length - 1; index >= 0; index -= 1) {\n\t\tconst candidate = branch[index];\n\t\tif (candidate?.type === \"custom\" && candidate.customType === stateEntryType) {\n\t\t\tstateEntryIndex = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst entry = branch[stateEntryIndex];\n\tif (!isRecord(entry?.data)) return { enabled: false, awaitingAction: false };\n\n\tconst enabled = entry.data.enabled === true;\n\tconst persistedSource = enabled ? planCompletionSource(entry.data.latestPlanSource) : undefined;\n\tconst persistedPlan = enabled ? normalizePersistedPlan(entry.data.latestPlan) : undefined;\n\tconst recoveredPlan =\n\t\tenabled && !persistedPlan ? latestCompletionPlan(branch.slice(stateEntryIndex + 1)) : undefined;\n\tconst latestPlan = persistedPlan ?? recoveredPlan;\n\tconst activeImplementation = enabled\n\t\t? undefined\n\t\t: normalizeActiveImplementation(entry.data.activeImplementation);\n\tconst savedPlan =\n\t\tenabled || activeImplementation ? undefined : normalizeSavedPlan(entry.data.savedPlan);\n\treturn {\n\t\tenabled,\n\t\tlatestPlan,\n\t\tlatestPlanSource: enabled\n\t\t\t? ((persistedPlan ? persistedSource : undefined) ??\n\t\t\t\t(recoveredPlan ? PLAN_MODE_COMPLETE_TOOL_NAME : undefined))\n\t\t\t: undefined,\n\t\tawaitingAction: enabled && latestPlan !== undefined,\n\t\tsavedPlan,\n\t\tactiveImplementation,\n\t\tselectedToolNames: stringArray(entry.data.selectedToolNames),\n\t\tselectedToolKeys: stringArray(entry.data.selectedToolKeys),\n\t\tpreviousThinkingLevel: enabled\n\t\t\t? fixedThinkingLevel(entry.data.previousThinkingLevel)\n\t\t\t: undefined,\n\t\tappliedThinkingLevel: enabled ? fixedThinkingLevel(entry.data.appliedThinkingLevel) : undefined,\n\t\tmanualThinkingLevel: enabled ? fixedThinkingLevel(entry.data.manualThinkingLevel) : undefined,\n\t};\n}\n\nfunction normalizeSavedPlan(value: unknown): SavedPlan | undefined {\n\tif (!isRecord(value)) return undefined;\n\tconst source = planCompletionSource(value.source);\n\tconst normalized = normalizePlanModeCompletion({ plan: value.plan });\n\tif (!source || !normalized.ok) return undefined;\n\treturn { plan: normalized.plan, source };\n}\n\nfunction normalizeActiveImplementation(value: unknown): ActiveImplementationPlan | undefined {\n\tif (!isRecord(value)) return undefined;\n\tconst id =\n\t\ttypeof value.id === \"string\" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value.id)\n\t\t\t? value.id\n\t\t\t: undefined;\n\tconst source = planCompletionSource(value.source);\n\tconst normalized = normalizePlanModeCompletion({ plan: value.plan });\n\tconst startedAt =\n\t\ttypeof value.startedAt === \"number\" &&\n\t\tNumber.isSafeInteger(value.startedAt) &&\n\t\tvalue.startedAt >= 0\n\t\t\t? value.startedAt\n\t\t\t: undefined;\n\tif (!id || !source || !normalized.ok || startedAt === undefined) return undefined;\n\tconst retention = IMPLEMENTATION_PLAN_RETENTIONS.includes(\n\t\tvalue.retention as ImplementationPlanRetention,\n\t)\n\t\t? (value.retention as ImplementationPlanRetention)\n\t\t: \"keep\";\n\treturn { id, plan: normalized.plan, source, startedAt, retention };\n}\n\nfunction normalizePersistedPlan(value: unknown) {\n\tconst normalized = normalizePlanModeCompletion({ plan: value });\n\treturn normalized.ok ? normalized.plan : undefined;\n}\n\nfunction latestCompletionPlan(entries: SessionEntry[]) {\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst message = entries[index]?.message;\n\t\tif (message?.role !== \"toolResult\" || message.toolName !== PLAN_MODE_COMPLETE_TOOL_NAME) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst plan = planFromCompletionDetails(message.details);\n\t\tif (plan) return plan;\n\t}\n\treturn undefined;\n}\n\nfunction planCompletionSource(value: unknown): PlanCompletionSource | undefined {\n\treturn value === PLAN_MODE_COMPLETE_TOOL_NAME || value === \"legacy_proposed_plan\"\n\t\t? value\n\t\t: undefined;\n}\n\nfunction fixedThinkingLevel(value: unknown): PlanModeFixedThinkingLevel | undefined {\n\treturn typeof value === \"string\" &&\n\t\tvalue !== \"inherit\" &&\n\t\tPLAN_MODE_THINKING_LEVELS.includes(value as (typeof PLAN_MODE_THINKING_LEVELS)[number])\n\t\t? (value as PlanModeFixedThinkingLevel)\n\t\t: undefined;\n}\n\nfunction stringArray(value: unknown) {\n\treturn Array.isArray(value) && value.every((item): item is string => typeof item === \"string\")\n\t\t? Array.from(new Set(value))\n\t\t: undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\n\nexport const WORKFLOW_MUTEX_CHANNEL = \"workflow:mutex:v1\";\nexport const AGENT_WORKFLOW_GROUP = \"agent-workflow\";\n\nexport type WorkflowMutexOwner = symbol;\n\ninterface WorkflowMutexAttemptV1 {\n\tsession: object;\n\tgroup: string;\n\tbusy: boolean;\n}\n\nexport class WorkflowMutex {\n\tprivate session: object | undefined;\n\tprivate readonly heldGroups = new Map<string, WorkflowMutexOwner>();\n\tprivate generation = 0;\n\n\tconstructor(private readonly pi: Pick<ExtensionAPI, \"events\">) {\n\t\tpi.events.on(WORKFLOW_MUTEX_CHANNEL, (payload) => {\n\t\t\tthis.answer(payload);\n\t\t});\n\t}\n\n\tbindSession(session: object): void {\n\t\tthis.generation += 1;\n\t\tthis.heldGroups.clear();\n\t\tthis.session = session;\n\t}\n\n\tunbindSession(session: object): void {\n\t\tif (this.session !== session) return;\n\t\tthis.generation += 1;\n\t\tthis.heldGroups.clear();\n\t\tthis.session = undefined;\n\t}\n\n\tacquire(group = AGENT_WORKFLOW_GROUP): WorkflowMutexOwner | undefined {\n\t\tconst session = this.session;\n\t\tconst generation = this.generation;\n\t\tif (!session || this.heldGroups.has(group)) return undefined;\n\n\t\tconst attempt: WorkflowMutexAttemptV1 = { session, group, busy: false };\n\t\ttry {\n\t\t\tthis.pi.events.emit(WORKFLOW_MUTEX_CHANNEL, attempt);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (\n\t\t\tthis.session !== session ||\n\t\t\tthis.generation !== generation ||\n\t\t\tattempt.session !== session ||\n\t\t\tattempt.group !== group ||\n\t\t\tattempt.busy !== false ||\n\t\t\tthis.heldGroups.has(group)\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst owner = Symbol(group);\n\t\tthis.heldGroups.set(group, owner);\n\t\treturn owner;\n\t}\n\n\tisOwner(owner: WorkflowMutexOwner | undefined, group = AGENT_WORKFLOW_GROUP): boolean {\n\t\treturn owner !== undefined && this.heldGroups.get(group) === owner;\n\t}\n\n\trelease(owner: WorkflowMutexOwner | undefined, group = AGENT_WORKFLOW_GROUP): void {\n\t\tif (!this.isOwner(owner, group)) return;\n\t\tthis.heldGroups.delete(group);\n\t}\n\n\tprivate answer(payload: unknown): void {\n\t\ttry {\n\t\t\tif (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) return;\n\t\t\tconst attempt = payload as Partial<WorkflowMutexAttemptV1>;\n\t\t\tif (attempt.session !== this.session) return;\n\t\t\tif (attempt.group !== AGENT_WORKFLOW_GROUP) return;\n\t\t\tif (typeof attempt.busy !== \"boolean\") return;\n\t\t\tif (!this.heldGroups.has(attempt.group)) return;\n\t\t\tattempt.busy = true;\n\t\t} catch {\n\t\t\t// Protocol listeners must ignore unusual objects without interrupting sibling listeners.\n\t\t}\n\t}\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,aAAa;AACtB,SAAS,UAAU,eAAe;;;ACIlC,IAAM,2BAAiE;AAAA,EACtE,EAAE,OAAO,SAAS,OAAO,SAAS,aAAa,2CAA2C;AAAA,EAC1F,EAAE,OAAO,QAAQ,OAAO,QAAQ,aAAa,wCAAwC;AAAA,EACrF,EAAE,OAAO,YAAY,OAAO,YAAY,aAAa,2BAA2B;AAAA,EAChF,EAAE,OAAO,aAAa,OAAO,aAAa,aAAa,wCAAwC;AAAA,EAC/F,EAAE,OAAO,QAAQ,OAAO,QAAQ,aAAa,oCAAoC;AAAA,EACjF,EAAE,OAAO,UAAU,OAAO,UAAU,aAAa,4CAA4C;AAAA,EAC7F,EAAE,OAAO,QAAQ,OAAO,QAAQ,aAAa,+CAA+C;AAAA,EAC5F,EAAE,OAAO,OAAO,OAAO,OAAO,aAAa,+CAA+C;AAAA,EAC1F;AAAA,IACC,OAAO;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AAC,cAAc;AACnB,YAAM,YAAY,UAAU,YAAY,CAAC,KAAK;AAC9C,aAAO,aAAa,MAAS,aAAa,OAAQ,aAAa,MAAQ,MAAM;AAAA,IAC9E,CAAC,EACA,KAAK,EAAE,EACP,KAAK;AAAA,EACR;AACD;",
|
|
3
|
+
"sources": ["../src/plan-mode.ts", "../src/command.ts", "../src/extension-runtime.ts", "../src/finalization-request.ts", "../src/fresh-implementation.ts", "../src/prompt.ts", "../src/mode-contract.ts", "../src/plan-action-controller.ts", "../src/plan-export-controller.ts", "../src/presentation.ts", "../src/required-tools.ts", "../src/saved-plan-preflight.ts", "../src/state.ts", "../src/workflow-mutex.ts"],
|
|
4
|
+
"sourcesContent": ["import { randomUUID } from \"node:crypto\";\nimport { watch } from \"node:fs\";\nimport { basename, dirname } from \"node:path\";\nimport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n} from \"@earendil-works/pi-coding-agent\";\nimport { completePlanArguments } from \"./command.js\";\nimport {\n\tnormalizePlanModeCompletion,\n\tPLAN_MODE_COMPLETE_PARAMS,\n\tPLAN_MODE_COMPLETE_TOOL_NAME,\n\tplanModeCompleted,\n\trenderPlanModeCompletion,\n} from \"./completion-tool.js\";\nimport { isStaleExtensionContextError } from \"./extension-runtime.js\";\nimport {\n\tcreateFinalizationRequestCoordinator,\n\tFINALIZE_PLAN_PROMPT,\n\ttype FinalizationRunOutcome,\n\tRETRY_FINALIZE_PLAN_PROMPT,\n} from \"./finalization-request.js\";\nimport {\n\tformatHistoryImplementationPrompt,\n\tformatImplementationHandoff,\n\tformatTransferredPlanPrompt,\n\tstartFreshImplementationFromState,\n} from \"./fresh-implementation.js\";\nimport {\n\tcreateImplementationRetentionCoordinator,\n\timplementationRetentionPreview,\n} from \"./implementation-retention.js\";\nimport {\n\tinvalidPlanMessage,\n\tlatestAssistantStopReason,\n\tlatestAssistantText,\n\tmessageTextContent,\n\tparseProposedPlan,\n} from \"./message-transform.js\";\nimport {\n\tcreateModeContractMessage,\n\thasModeContractArtifact,\n\tlatestModeContract,\n\tMODE_CONTRACT_MESSAGE_TYPE,\n\ttype PlanModeContract,\n\treconcileModeContract,\n} from \"./mode-contract.js\";\nimport { createPlanActionController } from \"./plan-action-controller.js\";\nimport { createPlanExportController } from \"./plan-export-controller.js\";\nimport {\n\tclearPlanModeUi,\n\tplanModeStatusText as formatPlanModeStatusText,\n\tshowStoredPlan,\n\tupdatePlanModeUi,\n} from \"./presentation.js\";\nimport {\n\tanswerPlanModeQuestions,\n\tnormalizePlanModeQuestionParams,\n\tPLAN_MODE_QUESTION_PARAMS,\n\tPLAN_MODE_QUESTION_TOOL_NAME,\n\tplanModeQuestionCancelled,\n} from \"./question-tool.js\";\nimport {\n\tassertPlanModeHelperToolsAvailable,\n\tplanModeHelperToolsAvailable,\n\twithRequiredPlanModeTools,\n} from \"./required-tools.js\";\nimport {\n\tpreflightSavedPlanImplementation,\n\tsavedPlanBlocksNewWorkflow,\n} from \"./saved-plan-preflight.js\";\nimport {\n\tawaitPlanModeSettingsWrites,\n\tconfiguredImplementationPlanRetention,\n\tconfiguredPlanModeToggleShortcut,\n\tconfiguredThinkingLevel,\n\ttype PlanModeSettings,\n\ttype PlanModeSettingsPatch,\n\tplanModeSettingsPath,\n\treadPlanModeSettings,\n\ttype UpdatePlanModeSettingsOptions,\n\tupdatePlanModeSettings,\n} from \"./settings.js\";\nimport { type PlanCompletionSource, type PlanModeState, restorePlanModeState } from \"./state.js\";\nimport {\n\tcanSelectToolInPlanMode,\n\tclassifyPlanModeTool,\n\tfindBlockedCommandSegment,\n\tfindBlockedPowerShellCommandSegment,\n\treadCommand,\n} from \"./tool-policy.js\";\nimport {\n\tcompareTools,\n\tfilterAvailableSelectedToolNames,\n\tsnapshotPlanModeSelectedNames,\n\ttoolPolicyLabel,\n} from \"./tool-selection.js\";\nimport { WorkflowMutex, type WorkflowMutexOwner } from \"./workflow-mutex.js\";\n\nconst STATE_ENTRY_TYPE = \"plan-mode-state\";\nconst PROPOSED_PLAN_MESSAGE_TYPE = \"proposed-plan\";\nconst BLOCKED_MUTATING_TOOLS = new Set([\"edit\", \"write\", \"update_plan\"]);\nconst DEFAULT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\"];\ninterface ReadyPresentationIntent {\n\tnonce: number;\n\tplan: string;\n\tsource: PlanCompletionSource;\n}\ntype InteractiveUi = typeof import(\"./interactive-ui.js\");\n\ninterface PlanModeDependencies {\n\treadSettings?(): ReturnType<typeof readPlanModeSettings>;\n\tupdateSettings?(\n\t\tpatch: PlanModeSettingsPatch,\n\t\toptions?: UpdatePlanModeSettingsOptions,\n\t): ReturnType<typeof updatePlanModeSettings>;\n\tsettingsPath?: string;\n\tloadInteractiveUi?(): Promise<InteractiveUi>;\n}\n\n// Keep session state, persistence, tool, thinking, and mutex commits in this one closure so an\n// activation path cannot bypass the same atomic transition by crossing module-owned state.\nexport default function planMode(pi: ExtensionAPI, dependencies: PlanModeDependencies = {}) {\n\tconst workflowMutex = new WorkflowMutex(pi);\n\tlet workflowOwner: WorkflowMutexOwner | undefined;\n\tlet currentSession: object | undefined;\n\tlet currentSessionContext: ExtensionContext | undefined;\n\tlet interactiveUiPromise: Promise<InteractiveUi> | undefined;\n\tconst loadInteractiveUi = () => {\n\t\tif (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();\n\t\tif (!interactiveUiPromise) {\n\t\t\tinteractiveUiPromise = import(\"./interactive-ui.js\").catch((error) => {\n\t\t\t\tinteractiveUiPromise = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\t\treturn interactiveUiPromise;\n\t};\n\tconst explicitPlanModeSettingsPath = dependencies.settingsPath;\n\tlet state: PlanModeState = { enabled: false, awaitingAction: false };\n\tlet settings: PlanModeSettings = { thinkingLevel: \"inherit\" };\n\tlet toggleShortcut: ReturnType<typeof configuredPlanModeToggleShortcut>;\n\tconst clearPlanModeShortcutHandler = () => {};\n\tlet activeToolBaseline: string[] = [];\n\tlet workflowAllowedToolNames: string[] | undefined;\n\tlet publishedContractMode: PlanModeContract | undefined;\n\tlet modeContractsRelevant = false;\n\tlet readyPresentationIntent: ReadyPresentationIntent | undefined;\n\tlet latestCommandContext: ExtensionCommandContext | undefined;\n\tlet nextReadyPresentationNonce = 0;\n\tlet menuGeneration = 0;\n\tlet workflowGeneration = 0;\n\tlet refreshStateBeforeFirstAgentStart = false;\n\tlet menuController = new AbortController();\n\tlet settingsWatch: ReturnType<typeof watch> | undefined;\n\tlet settingsReloadTimer: ReturnType<typeof setTimeout> | undefined;\n\tconst implementationRetention = createImplementationRetentionCoordinator();\n\tconst finalizationRequest = createFinalizationRequestCoordinator();\n\tconst persistState = () => pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, state);\n\tconst planExports = createPlanExportController({\n\t\tgetState: () => state,\n\t\tgetSettings: () => settings,\n\t\tfinishReady: (ctx) => {\n\t\t\texitPlanMode(ctx);\n\t\t},\n\t});\n\tconst planActions = createPlanActionController({\n\t\tloadInteractiveUi,\n\t\tgetState: () => state,\n\t\tcaptureLifecycle: captureMenuLifecycle,\n\t\tstatusText: planStatusText,\n\t\timplementationOutcome,\n\t\tgetExportDestination: (ctx) => planExports.getDestination(ctx),\n\t\tshow: (ctx) => showStoredPlan(pi, ctx, state),\n\t\tfinalize: requestFinalPlan,\n\t\timplementHere: startImplementation,\n\t\timplementFresh: startFreshImplementation,\n\t\texportPlan: exportPlan,\n\t\tsettings: showSettings,\n\t\tsave: savePlanForLater,\n\t\tstay: updateUi,\n\t\texitReady: (ctx) => {\n\t\t\tif (exitPlanMode(ctx)) {\n\t\t\t\tctx.ui.notify(\"Plan mode disabled. Proposed plan discarded.\", \"info\");\n\t\t\t}\n\t\t},\n\t\tclearSaved: (ctx) => {\n\t\t\tif (exitPlanMode(ctx)) ctx.ui.notify(\"Saved plan cleared.\", \"info\");\n\t\t},\n\t});\n\n\tpi.registerTool({\n\t\tname: PLAN_MODE_QUESTION_TOOL_NAME,\n\t\tlabel: \"Plan question\",\n\t\tdescription:\n\t\t\t\"Ask one to three structured questions only when the latest effective Plan contract explicitly says /plan mode is active. Tool visibility alone does not activate Plan mode. Never call for ordinary planning requests, the writing-plans skill, roadmaps, checklists, or plan-file work.\",\n\t\tparameters: PLAN_MODE_QUESTION_PARAMS,\n\t\tasync execute(_toolCallId, params: unknown, _signal, _onUpdate, ctx) {\n\t\t\tif (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {\n\t\t\t\treturn planModeQuestionCancelled(\n\t\t\t\t\t[],\n\t\t\t\t\t\"plan_mode_inactive\",\n\t\t\t\t\t\"Error: plan_mode_question is only available while Plan mode is active.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst parsed = normalizePlanModeQuestionParams(params);\n\t\t\tif (!parsed.ok) {\n\t\t\t\treturn planModeQuestionCancelled([], \"invalid_input\", `Error: ${parsed.error}`);\n\t\t\t}\n\t\t\tfinalizationRequest.satisfy();\n\n\t\t\tif (!ctx.hasUI) {\n\t\t\t\treturn planModeQuestionCancelled(\n\t\t\t\t\tparsed.questions,\n\t\t\t\t\t\"ui_unavailable\",\n\t\t\t\t\t\"Unable to ask Plan-mode questions because interactive UI is not available.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst sessionGeneration = menuGeneration;\n\t\t\tconst questionWorkflowGeneration = workflowGeneration;\n\t\t\tconst questionOwner = workflowOwner;\n\t\t\treturn answerPlanModeQuestions(parsed.questions, ctx, {\n\t\t\t\tisCurrent: () =>\n\t\t\t\t\tsessionGeneration === menuGeneration &&\n\t\t\t\t\tquestionWorkflowGeneration === workflowGeneration &&\n\t\t\t\t\tworkflowMutex.isOwner(questionOwner),\n\t\t\t\tisEnabled: () => state.enabled,\n\t\t\t});\n\t\t},\n\t});\n\n\tpi.registerTool({\n\t\tname: PLAN_MODE_COMPLETE_TOOL_NAME,\n\t\tlabel: \"Complete plan\",\n\t\tdescription:\n\t\t\t\"Submit a decision-ready plan only when the latest effective Plan contract explicitly says /plan mode is active, and call it alone as the final action. Tool visibility alone does not activate Plan mode. Never call for ordinary planning requests, the writing-plans skill, roadmaps, checklists, or plan-file work.\",\n\t\tparameters: PLAN_MODE_COMPLETE_PARAMS,\n\t\trenderResult: renderPlanModeCompletion,\n\t\tasync execute(_toolCallId, params: unknown, _signal, _onUpdate, ctx) {\n\t\t\tif (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {\n\t\t\t\tthrow new Error(\"plan_mode_complete is only available while Plan mode is active\");\n\t\t\t}\n\t\t\tconst parsed = normalizePlanModeCompletion(params);\n\t\t\tif (!parsed.ok) throw new Error(parsed.error);\n\n\t\t\tacceptCompletedPlan(parsed.plan, PLAN_MODE_COMPLETE_TOOL_NAME, ctx);\n\t\t\treturn planModeCompleted(parsed.plan);\n\t\t},\n\t});\n\n\tpi.registerCommand(\"plan\", {\n\t\tdescription: \"Enter or manage Codex-like Plan mode\",\n\t\tgetArgumentCompletions: completePlanArguments,\n\t\thandler: async (args, ctx) => {\n\t\t\tlatestCommandContext = ctx;\n\t\t\tconst prompt = args.trim();\n\t\t\tconst command = prompt.toLowerCase();\n\t\t\tif (command === \"start\") {\n\t\t\t\tif (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))\n\t\t\t\t\treturn;\n\t\t\t\tif (state.enabled) {\n\t\t\t\t\tctx.ui.notify(\"Plan mode is already active.\", \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (enterPlanMode(ctx)) {\n\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t\"Plan mode enabled. I will explore and plan, but not modify files.\",\n\t\t\t\t\t\t\"info\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"show\") {\n\t\t\t\tshowStoredPlan(pi, ctx, state);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"finalize\") {\n\t\t\t\trequestFinalPlan(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"implement\") {\n\t\t\t\tif (!(state.enabled && state.latestPlan?.trim()) && !state.savedPlan?.plan.trim()) {\n\t\t\t\t\tctx.ui.notify(\"No completed plan is available to implement.\", \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait startImplementation(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"save\") {\n\t\t\t\tsavePlanForLater(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst exportMatch = /^export(?:\\s+([\\s\\S]+))?$/iu.exec(prompt);\n\t\t\tif (exportMatch) {\n\t\t\t\tconst lifecycle = captureMenuLifecycle();\n\t\t\t\tawait exportPlan(ctx, exportMatch[1], lifecycle.signal, lifecycle.isCurrent);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"exit\" || command === \"off\") {\n\t\t\t\tconst notification = planModeDisableNotification();\n\t\t\t\tif (exitPlanMode(ctx)) ctx.ui.notify(notification, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (command === \"tools\") {\n\t\t\t\tif (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))\n\t\t\t\t\treturn;\n\t\t\t\tif (state.enabled) {\n\t\t\t\t\tconst message =\n\t\t\t\t\t\t\"Plan-mode tools are locked while Planning is active. Exit Plan mode and choose tools before starting again.\";\n\t\t\t\t\tif (!ctx.hasUI) throw new Error(message);\n\t\t\t\t\tctx.ui.notify(message, \"warning\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!ctx.hasUI) {\n\t\t\t\t\tthrow new Error(\"/plan tools requires TUI or RPC mode and is unavailable here.\");\n\t\t\t\t}\n\t\t\t\tawait showLaunchMenu(ctx, \"tools\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (prompt) {\n\t\t\t\tif (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled))\n\t\t\t\t\treturn;\n\t\t\t\tenterPlanModeWithPrompt(prompt, ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!ctx.hasUI) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"The interactive /plan menu is unavailable in print and JSON modes. Use /plan start or /plan <prompt>.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!state.enabled) {\n\t\t\t\tif (state.activeImplementation && ctx.hasUI) {\n\t\t\t\t\tawait showActivePlanMenu(ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (state.savedPlan) {\n\t\t\t\t\tawait planActions.showSaved(ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait showLaunchMenu(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait planActions.showCurrent(ctx);\n\t\t},\n\t});\n\n\tconst applyPlanModeShortcut = (\n\t\tnextShortcut: ReturnType<typeof configuredPlanModeToggleShortcut>,\n\t) => {\n\t\tif (toggleShortcut && toggleShortcut !== nextShortcut) {\n\t\t\tpi.registerShortcut(toggleShortcut, {\n\t\t\t\thandler: clearPlanModeShortcutHandler,\n\t\t\t});\n\t\t}\n\t\tif (!nextShortcut) {\n\t\t\ttoggleShortcut = undefined;\n\t\t\treturn;\n\t\t}\n\t\tif (toggleShortcut === nextShortcut) return;\n\t\tpi.registerShortcut(nextShortcut, {\n\t\t\tdescription: \"Toggle Plan mode\",\n\t\t\thandler: (ctx) => {\n\t\t\t\ttogglePlanMode(ctx);\n\t\t\t},\n\t\t});\n\t\ttoggleShortcut = nextShortcut;\n\t};\n\n\tconst readPlanModeRuntimeSettings = async () => {\n\t\treturn dependencies.readSettings?.() ?? readPlanModeSettings(explicitPlanModeSettingsPath);\n\t};\n\n\tconst applyPlanModeSettings = async (\n\t\tgeneration: number,\n\t\tctx: ExtensionContext | undefined,\n\t\tshowWarnings: boolean,\n\t) => {\n\t\tconst loadedSettings = await readPlanModeRuntimeSettings();\n\t\tif (generation !== menuGeneration || menuController.signal.aborted) {\n\t\t\treturn undefined;\n\t\t}\n\t\tsettings =\n\t\t\tloadedSettings.kind === \"loaded\"\n\t\t\t\t? loadedSettings.settings\n\t\t\t\t: ({ thinkingLevel: \"inherit\" } satisfies PlanModeSettings);\n\t\tapplyPlanModeShortcut(configuredPlanModeToggleShortcut(settings));\n\t\tif (!ctx || !showWarnings) return loadedSettings;\n\t\tif (loadedSettings.kind === \"invalid\") {\n\t\t\tctx.ui.notify(`pi-plan-mode settings ignored: ${loadedSettings.reason}`, \"warning\");\n\t\t}\n\t\tif (loadedSettings.notice) {\n\t\t\tctx.ui.notify(loadedSettings.notice, \"warning\");\n\t\t}\n\t\treturn loadedSettings;\n\t};\n\n\tconst stopPlanModeSettingsWatch = () => {\n\t\tif (settingsReloadTimer) {\n\t\t\tclearTimeout(settingsReloadTimer);\n\t\t\tsettingsReloadTimer = undefined;\n\t\t}\n\t\tsettingsWatch?.close();\n\t\tsettingsWatch = undefined;\n\t};\n\n\tconst schedulePlanModeSettingsReload = (generation: number) => {\n\t\tif (settingsReloadTimer) {\n\t\t\tclearTimeout(settingsReloadTimer);\n\t\t\tsettingsReloadTimer = undefined;\n\t\t}\n\t\tsettingsReloadTimer = setTimeout(() => {\n\t\t\tsettingsReloadTimer = undefined;\n\t\t\tvoid applyPlanModeSettings(generation, currentSessionContext, false);\n\t\t}, 75);\n\t};\n\n\tconst startPlanModeSettingsWatch = (generation: number) => {\n\t\tstopPlanModeSettingsWatch();\n\t\tif (dependencies.readSettings) return;\n\t\tconst pathToWatch = explicitPlanModeSettingsPath ?? planModeSettingsPath();\n\t\ttry {\n\t\t\tconst directory = dirname(pathToWatch);\n\t\t\tconst fileName = basename(pathToWatch);\n\t\t\tconst watcher = watch(directory, { persistent: false }, (event, changedFile) => {\n\t\t\t\tif (event !== \"rename\" && event !== \"change\") return;\n\t\t\t\tif (!changedFile || changedFile.toString() !== fileName) return;\n\t\t\t\tschedulePlanModeSettingsReload(generation);\n\t\t\t});\n\t\t\twatcher.on(\"error\", () => {\n\t\t\t\tstopPlanModeSettingsWatch();\n\t\t\t});\n\t\t\tsettingsWatch = watcher;\n\t\t} catch {\n\t\t\tstopPlanModeSettingsWatch();\n\t\t}\n\t};\n\n\tpi.on(\"session_start\", async (event, ctx) => {\n\t\tconst generation = ++menuGeneration;\n\t\tfinalizationRequest.reset();\n\t\tcurrentSession = ctx.sessionManager;\n\t\tcurrentSessionContext = ctx;\n\t\tworkflowOwner = undefined;\n\t\tworkflowMutex.bindSession(ctx.sessionManager);\n\t\tcaptureToolBaseline();\n\t\trefreshStateBeforeFirstAgentStart = event.reason === \"new\";\n\t\tmenuController.abort(new DOMException(\"Plan-mode session replaced\", \"AbortError\"));\n\t\tmenuController = new AbortController();\n\t\treadyPresentationIntent = undefined;\n\t\tlatestCommandContext = undefined;\n\t\tworkflowAllowedToolNames = undefined;\n\t\timplementationRetention.reset();\n\t\tsettings = { thinkingLevel: \"inherit\" };\n\t\tconst branch = ctx.sessionManager.getBranch();\n\t\tconst restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);\n\t\trestoreModeContractTracking(branch, restoredState);\n\t\tstate = { enabled: false, awaitingAction: false };\n\t\tawait applyPlanModeSettings(generation, ctx, true);\n\t\tif (generation !== menuGeneration || menuController.signal.aborted) return;\n\t\tstartPlanModeSettingsWatch(generation);\n\t\tif (!installRestoredState(restoredState, ctx)) return;\n\t\timplementationRetention.restore(state.activeImplementation);\n\t\tupdateUi(ctx);\n\t});\n\n\tpi.on(\"session_before_tree\", (event, ctx) => {\n\t\tconst target = ctx.sessionManager.getEntry(event.preparation.targetId);\n\t\tif (target?.type !== \"custom_message\" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {\n\t\t\treturn;\n\t\t}\n\t\tif (ctx.hasUI) {\n\t\t\tctx.ui.notify(\n\t\t\t\t\"Plan mode transition markers are internal. Select the adjacent conversation entry instead.\",\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\t\treturn { cancel: true };\n\t});\n\n\tpi.on(\"session_tree\", (_event, ctx) => {\n\t\tadvanceWorkflowGeneration();\n\t\tmenuGeneration += 1;\n\t\tmenuController.abort(new DOMException(\"Plan-mode tree branch changed\", \"AbortError\"));\n\t\tmenuController = new AbortController();\n\t\treadyPresentationIntent = undefined;\n\t\tlatestCommandContext = undefined;\n\t\timplementationRetention.reset();\n\t\tconst branch = ctx.sessionManager.getBranch();\n\t\tconst restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);\n\t\trestoreModeContractTracking(branch, restoredState);\n\t\tif (!installRestoredState(restoredState, ctx)) return;\n\t\timplementationRetention.restore(state.activeImplementation);\n\t\tstartPlanModeSettingsWatch(menuGeneration);\n\t\tupdateUi(ctx);\n\t});\n\n\tpi.on(\"thinking_level_select\", (event) => {\n\t\tif (!state.enabled || !state.appliedThinkingLevel) return;\n\t\tif (event.level !== state.appliedThinkingLevel) {\n\t\t\tstate = {\n\t\t\t\t...state,\n\t\t\t\tmanualThinkingLevel: event.level,\n\t\t\t\tpreviousThinkingLevel: undefined,\n\t\t\t\tappliedThinkingLevel: undefined,\n\t\t\t};\n\t\t\tpersistState();\n\t\t}\n\t});\n\n\tpi.on(\"session_shutdown\", async (_event, ctx) => {\n\t\tconst shutdownSession = ctx.sessionManager;\n\t\tfinalizationRequest.reset();\n\t\tmenuGeneration += 1;\n\t\tmenuController.abort(new DOMException(\"Plan-mode session shut down\", \"AbortError\"));\n\t\treadyPresentationIntent = undefined;\n\t\tlatestCommandContext = undefined;\n\t\trefreshStateBeforeFirstAgentStart = false;\n\t\timplementationRetention.reset();\n\t\tawait awaitPlanModeSettingsWrites(dependencies.settingsPath);\n\t\tif (currentSession !== undefined && currentSession !== shutdownSession) {\n\t\t\tworkflowMutex.unbindSession(shutdownSession);\n\t\t\treturn;\n\t\t}\n\t\tcaptureManualThinkingLevel();\n\t\tpersistState();\n\t\tif (state.enabled) restoreThinkingLevel();\n\t\tstopPlanModeSettingsWatch();\n\t\tclearUi(ctx);\n\t\treleaseWorkflowOwner();\n\t\tworkflowMutex.unbindSession(ctx.sessionManager);\n\t\tif (currentSession === ctx.sessionManager) {\n\t\t\tcurrentSession = undefined;\n\t\t\tcurrentSessionContext = undefined;\n\t\t}\n\t});\n\n\tpi.on(\"tool_call\", async (event) => {\n\t\tconst requiredHelper =\n\t\t\tevent.toolName === PLAN_MODE_QUESTION_TOOL_NAME ||\n\t\t\tevent.toolName === PLAN_MODE_COMPLETE_TOOL_NAME;\n\t\tif (!state.enabled) {\n\t\t\tif (!requiredHelper) return;\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `${event.toolName} is only available while Plan mode is active.`,\n\t\t\t};\n\t\t}\n\t\tif (!workflowMutex.isOwner(workflowOwner)) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `Plan mode blocks tool '${event.toolName}' because workflow ownership is unavailable.`,\n\t\t\t};\n\t\t}\n\t\tif (BLOCKED_MUTATING_TOOLS.has(event.toolName)) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason:\n\t\t\t\t\tevent.toolName === \"update_plan\"\n\t\t\t\t\t\t? \"Plan mode blocks update_plan because it tracks execution progress rather than conversational planning.\"\n\t\t\t\t\t\t: `Plan mode blocks mutating tool '${event.toolName}'.`,\n\t\t\t};\n\t\t}\n\t\tif (requiredHelper) return;\n\n\t\tconst allowedToolNames = new Set(planModePolicyToolNames());\n\t\tif (!allowedToolNames.has(event.toolName)) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `Plan mode blocks tool '${event.toolName}' because it is unavailable or not selected by the Plan policy.`,\n\t\t\t};\n\t\t}\n\t\tconst calledTool = toolByName(event.toolName);\n\t\tif (!calledTool || classifyPlanModeTool(calledTool) === \"blocked\") {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `Plan mode blocks tool '${event.toolName}' because its safe policy metadata is unavailable.`,\n\t\t\t};\n\t\t}\n\t\tif (event.toolName === \"bash\") {\n\t\t\tconst blocked = findBlockedCommandSegment(readCommand(event.input), settings.safeSubcommands);\n\t\t\tif (blocked !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tblock: true,\n\t\t\t\t\treason: `Plan mode blocks bash commands outside its reviewed inspection policy or containing explicitly unsafe arguments.\\nBlocked command: ${blocked}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tif (event.toolName === \"powershell\") {\n\t\t\tconst blocked = findBlockedPowerShellCommandSegment(\n\t\t\t\treadCommand(event.input),\n\t\t\t\tsettings.safeSubcommands,\n\t\t\t);\n\t\t\tif (blocked !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tblock: true,\n\t\t\t\t\treason: `Plan mode blocks PowerShell commands outside its reviewed inspection policy or containing explicitly unsafe syntax.\\nBlocked command: ${blocked}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t});\n\n\tpi.on(\"message_start\", (event) => {\n\t\tif (\n\t\t\tstate.enabled &&\n\t\t\tevent.message.role === \"user\" &&\n\t\t\tmessageTextContent(event.message).trim() === FINALIZE_PLAN_PROMPT\n\t\t) {\n\t\t\tfinalizationRequest.request(workflowGeneration);\n\t\t}\n\t});\n\n\tpi.on(\"context\", async (event, ctx) => {\n\t\tconst result = implementationRetention.transformContext(event.messages, state);\n\t\tif (result.clearActiveImplementationId) {\n\t\t\tclearActiveImplementation(result.clearActiveImplementationId, ctx);\n\t\t}\n\t\tconst messages =\n\t\t\tstate.enabled || modeContractsRelevant\n\t\t\t\t? reconcileModeContract(result.messages, state.enabled ? \"plan\" : \"normal\")\n\t\t\t\t: result.messages;\n\t\treturn { messages: messages as typeof event.messages };\n\t});\n\n\tpi.on(\"before_agent_start\", (_event, ctx) => {\n\t\tif (refreshStateBeforeFirstAgentStart) {\n\t\t\trefreshStateBeforeFirstAgentStart = false;\n\t\t\timplementationRetention.reset();\n\t\t\tconst branch = ctx.sessionManager.getBranch();\n\t\t\tconst restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);\n\t\t\trestoreModeContractTracking(branch, restoredState);\n\t\t\tif (!installRestoredState(restoredState, ctx)) return;\n\t\t\timplementationRetention.restore(state.activeImplementation);\n\t\t\tupdateUi(ctx);\n\t\t}\n\t\tif (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;\n\t\tif (state.latestPlan || state.awaitingAction) {\n\t\t\treadyPresentationIntent = undefined;\n\t\t\tstate = {\n\t\t\t\t...state,\n\t\t\t\tlatestPlan: undefined,\n\t\t\t\tlatestPlanSource: undefined,\n\t\t\t\tawaitingAction: false,\n\t\t\t};\n\t\t\tpersistState();\n\t\t\tupdateUi(ctx);\n\t\t}\n\t});\n\n\tpi.on(\"agent_end\", async (event, ctx) => {\n\t\tif (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;\n\n\t\tconst text = latestAssistantText(event.messages);\n\t\tconst parsedPlan = parseProposedPlan(text);\n\t\tif (parsedPlan.kind !== \"valid\") {\n\t\t\tfinalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));\n\t\t\tif (parsedPlan.kind !== \"absent\") {\n\t\t\t\tctx.ui.notify(invalidPlanMessage(parsedPlan.kind), \"warning\");\n\t\t\t}\n\t\t\tpersistState();\n\t\t\tupdateUi(ctx);\n\t\t\treturn;\n\t\t}\n\t\tacceptCompletedPlan(parsedPlan.plan, \"legacy_proposed_plan\", ctx);\n\t});\n\n\tpi.on(\"agent_settled\", async (_event, ctx) => {\n\t\tconst settledImplementationId = implementationRetention.implementationSettled(\n\t\t\tstate.activeImplementation,\n\t\t);\n\t\tif (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);\n\n\t\tif (\n\t\t\tfinalizationRequest.hasPendingRequest() &&\n\t\t\tstate.enabled &&\n\t\t\tworkflowMutex.isOwner(workflowOwner)\n\t\t) {\n\t\t\tif (!ctx.isIdle() || ctx.hasPendingMessages()) return;\n\t\t\tconst action = finalizationRequest.settle(workflowGeneration);\n\t\t\tif (action === \"retry\") {\n\t\t\t\tif (sendPlanModeUserMessage(RETRY_FINALIZE_PLAN_PROMPT, ctx)) return;\n\t\t\t\tfinalizationRequest.reset();\n\t\t\t}\n\t\t\tif (action === \"failed\") {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Plan finalization ended twice without a structured question or completed plan. Plan mode remains active; revise the plan or run /plan finalize again.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst intent = readyPresentationIntent;\n\t\tif (!intent || !readyPresentationIsCurrent(intent)) return;\n\t\tif (!ctx.isIdle() || ctx.hasPendingMessages()) return;\n\n\t\treadyPresentationIntent = undefined;\n\t\ttry {\n\t\t\tif (intent.source === \"legacy_proposed_plan\") {\n\t\t\t\tpi.sendMessage(\n\t\t\t\t\t{\n\t\t\t\t\t\tcustomType: PROPOSED_PLAN_MESSAGE_TYPE,\n\t\t\t\t\t\tcontent: `**Proposed Plan**\\n\\n${intent.plan}`,\n\t\t\t\t\t\tdisplay: true,\n\t\t\t\t\t},\n\t\t\t\t\t{ triggerTurn: false },\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (ctx.hasUI && completedPlanIsCurrent(intent)) {\n\t\t\t\tawait planActions.showReady(latestCommandContext ?? ctx);\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\tif (!isStaleExtensionContextError(error)) throw error;\n\t\t}\n\t});\n\n\tfunction enterPlanMode(\n\t\tctx: ExtensionContext,\n\t\tcandidate: Pick<PlanModeState, \"selectedToolNames\" | \"selectedToolKeys\"> = state,\n\t) {\n\t\tif (!state.enabled && !allowModeTransition(ctx, \"start Plan mode\")) return false;\n\t\tbindWorkflowSessionIfNeeded(ctx);\n\t\tif (state.enabled) return workflowMutex.isOwner(workflowOwner);\n\t\tconst owner = workflowMutex.acquire();\n\t\tif (!owner) return reportWorkflowBusy(ctx);\n\t\tworkflowOwner = owner;\n\n\t\tconst previousState = state;\n\t\ttry {\n\t\t\tassertPlanModeHelperToolsAvailable(safeGetActiveTools());\n\t\t\tif (!publishModeContract(\"plan\", ctx)) {\n\t\t\t\treleaseWorkflowOwner();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\treleaseWorkflowOwner();\n\t\t\treturn reportHelperActivationFailure(ctx, error);\n\t\t}\n\t\tadvanceWorkflowGeneration();\n\t\ttry {\n\t\t\tmodeContractsRelevant = true;\n\t\t\tstate = {\n\t\t\t\t...state,\n\t\t\t\tenabled: true,\n\t\t\t\tawaitingAction: false,\n\t\t\t\tsavedPlan: undefined,\n\t\t\t\tactiveImplementation: undefined,\n\t\t\t\tselectedToolNames: candidate.selectedToolNames,\n\t\t\t\tselectedToolKeys: candidate.selectedToolKeys,\n\t\t\t};\n\t\t\tworkflowAllowedToolNames = computePlanModePolicyToolNames();\n\t\t\tapplyPlanThinkingLevel();\n\t\t\tpersistState();\n\t\t\tupdateUi(ctx);\n\t\t\treturn true;\n\t\t} catch (error: unknown) {\n\t\t\trollbackNewActivation(previousState, ctx);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tfunction enterPlanModeWithPrompt(prompt: string, ctx: ExtensionContext) {\n\t\tconst previousState = state;\n\t\tconst previousOwner = workflowOwner;\n\t\tconst wasEnabled = state.enabled;\n\t\tif (!enterPlanMode(ctx)) return;\n\t\tif (!wasEnabled) {\n\t\t\tctx.ui.notify(\"Plan mode enabled. I will explore and plan, but not modify files.\", \"info\");\n\t\t}\n\t\tif (sendPlanModeUserMessage(prompt, ctx)) return;\n\t\tif (wasEnabled) return;\n\t\trollbackNewActivation(previousState, ctx, previousOwner);\n\t}\n\n\tfunction exitPlanMode(ctx: ExtensionContext) {\n\t\tif (!allowModeTransition(ctx, \"leave or clear Plan mode\")) return false;\n\t\tconst wasEnabled = state.enabled;\n\t\tif ((wasEnabled || modeContractsRelevant) && !publishModeContract(\"normal\", ctx)) {\n\t\t\treturn false;\n\t\t}\n\t\tadvanceWorkflowGeneration();\n\t\treadyPresentationIntent = undefined;\n\t\tworkflowAllowedToolNames = undefined;\n\t\tstate = {\n\t\t\t...state,\n\t\t\tenabled: false,\n\t\t\tlatestPlan: undefined,\n\t\t\tlatestPlanSource: undefined,\n\t\t\tawaitingAction: false,\n\t\t\tsavedPlan: undefined,\n\t\t\tactiveImplementation: undefined,\n\t\t\tmanualThinkingLevel: undefined,\n\t\t};\n\t\tif (wasEnabled) {\n\t\t\trestoreThinkingLevel();\n\t\t\tstate = { ...state, manualThinkingLevel: undefined };\n\t\t}\n\t\tpersistState();\n\t\tupdateUi(ctx);\n\t\tif (wasEnabled) releaseWorkflowOwner();\n\t\treturn true;\n\t}\n\n\tfunction restoreModeContractTracking(branch: unknown[], restoredState: PlanModeState) {\n\t\tpublishedContractMode = latestModeContract(branch)?.mode;\n\t\tmodeContractsRelevant =\n\t\t\thasModeContractArtifact(branch) ||\n\t\t\trestoredState.enabled ||\n\t\t\trestoredState.savedPlan !== undefined ||\n\t\t\trestoredState.activeImplementation !== undefined;\n\t}\n\n\tfunction publishModeContract(mode: PlanModeContract, ctx: ExtensionContext) {\n\t\tif (publishedContractMode === mode) return true;\n\t\tconst { role: _role, timestamp: _timestamp, ...message } = createModeContractMessage(mode);\n\t\ttry {\n\t\t\tpi.sendMessage(message, { triggerTurn: false });\n\t\t\tpublishedContractMode = mode;\n\t\t\tmodeContractsRelevant = true;\n\t\t\treturn true;\n\t\t} catch (error: unknown) {\n\t\t\tconst detail = safeTerminalText(error instanceof Error ? error.message : String(error));\n\t\t\tconst notification = `Unable to publish the ${mode === \"plan\" ? \"Plan\" : \"Normal\"} mode contract: ${detail}`;\n\t\t\tif (!ctx.hasUI) throw new Error(notification, { cause: error });\n\t\t\tctx.ui.notify(notification, \"error\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfunction sendPlanModeUserMessage(message: string, ctx: ExtensionContext) {\n\t\ttry {\n\t\t\tif (ctx.isIdle()) pi.sendUserMessage(message);\n\t\t\telse pi.sendUserMessage(message, { deliverAs: \"followUp\" });\n\t\t\treturn true;\n\t\t} catch (error: unknown) {\n\t\t\tconst detail = safeTerminalText(error instanceof Error ? error.message : String(error));\n\t\t\tctx.ui.notify(`Unable to send Plan-mode message: ${detail}`, \"error\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfunction acceptCompletedPlan(plan: string, source: PlanCompletionSource, ctx: ExtensionContext) {\n\t\tconst normalized = normalizePlanModeCompletion({ plan });\n\t\tif (!normalized.ok) {\n\t\t\tctx.ui.notify(`Proposed plan is not ready: ${normalized.error}.`, \"warning\");\n\t\t\tpersistState();\n\t\t\tupdateUi(ctx);\n\t\t\treturn;\n\t\t}\n\t\tfinalizationRequest.satisfy();\n\t\tif (\n\t\t\tstate.enabled &&\n\t\t\tstate.awaitingAction &&\n\t\t\tstate.latestPlan === normalized.plan &&\n\t\t\tstate.latestPlanSource === source\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tstate = {\n\t\t\t...state,\n\t\t\tlatestPlan: normalized.plan,\n\t\t\tlatestPlanSource: source,\n\t\t\tawaitingAction: true,\n\t\t};\n\t\treadyPresentationIntent = {\n\t\t\tnonce: ++nextReadyPresentationNonce,\n\t\t\tplan: normalized.plan,\n\t\t\tsource,\n\t\t};\n\t\tpersistState();\n\t\tupdateUi(ctx);\n\t}\n\n\tfunction completedPlanIsCurrent(intent: ReadyPresentationIntent) {\n\t\treturn (\n\t\t\tstate.enabled &&\n\t\t\tworkflowMutex.isOwner(workflowOwner) &&\n\t\t\tstate.awaitingAction &&\n\t\t\tstate.latestPlan === intent.plan &&\n\t\t\tstate.latestPlanSource === intent.source\n\t\t);\n\t}\n\n\tfunction readyPresentationIsCurrent(intent: ReadyPresentationIntent) {\n\t\treturn completedPlanIsCurrent(intent) && readyPresentationIntent?.nonce === intent.nonce;\n\t}\n\n\tfunction togglePlanMode(ctx: ExtensionContext) {\n\t\tif (state.enabled) {\n\t\t\tconst notification = planModeDisableNotification();\n\t\t\tif (exitPlanMode(ctx)) ctx.ui.notify(notification, \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined)) return;\n\t\tif (enterPlanMode(ctx)) {\n\t\t\tctx.ui.notify(\"Plan mode enabled. I will explore and plan, but not modify files.\", \"info\");\n\t\t}\n\t}\n\n\tfunction planModeDisableNotification() {\n\t\treturn state.activeImplementation\n\t\t\t? \"Active implementation plan cleared.\"\n\t\t\t: state.savedPlan\n\t\t\t\t? \"Saved plan cleared.\"\n\t\t\t\t: state.latestPlan\n\t\t\t\t\t? \"Plan mode disabled. Proposed plan discarded.\"\n\t\t\t\t\t: \"Plan mode disabled.\";\n\t}\n\n\tfunction requestFinalPlan(ctx: ExtensionContext) {\n\t\tif (!state.enabled) {\n\t\t\tctx.ui.notify(\"Plan mode is not active. Use /plan first.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tfinalizationRequest.request(workflowGeneration);\n\t\tif (!sendPlanModeUserMessage(FINALIZE_PLAN_PROMPT, ctx)) finalizationRequest.reset();\n\t}\n\n\tfunction savePlanForLater(ctx: ExtensionContext) {\n\t\tconst plan = state.enabled ? state.latestPlan?.trim() : undefined;\n\t\tif (!plan) {\n\t\t\tconst message = \"No completed plan is available to save.\";\n\t\t\tif (!ctx.hasUI) throw new Error(message);\n\t\t\tctx.ui.notify(message, \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tconst source = state.latestPlanSource ?? \"legacy_proposed_plan\";\n\t\tif (!allowModeTransition(ctx, \"save the plan and leave Plan mode\")) return;\n\n\t\tif (!publishModeContract(\"normal\", ctx)) return;\n\t\tadvanceWorkflowGeneration();\n\t\treadyPresentationIntent = undefined;\n\t\tworkflowAllowedToolNames = undefined;\n\t\tstate = {\n\t\t\t...state,\n\t\t\tenabled: false,\n\t\t\tlatestPlan: undefined,\n\t\t\tlatestPlanSource: undefined,\n\t\t\tawaitingAction: false,\n\t\t\tsavedPlan: { plan, source },\n\t\t\tactiveImplementation: undefined,\n\t\t\tmanualThinkingLevel: undefined,\n\t\t};\n\t\trestoreThinkingLevel();\n\t\tstate = { ...state, manualThinkingLevel: undefined };\n\t\tpersistState();\n\t\tupdateUi(ctx);\n\t\treleaseWorkflowOwner();\n\t\tctx.ui.notify(\"Plan saved for later. Plan mode disabled.\", \"info\");\n\t}\n\n\tasync function startFreshImplementation(ctx: ExtensionContext, menuIsCurrent: () => boolean) {\n\t\tawait startFreshImplementationFromState(ctx, {\n\t\t\tgetState: () => state,\n\t\t\tmenuIsCurrent,\n\t\t\tretention: configuredImplementationPlanRetention(settings),\n\t\t\tstateEntryType: STATE_ENTRY_TYPE,\n\t\t});\n\t}\n\n\tasync function startImplementation(ctx: ExtensionContext) {\n\t\tconst savedPlan = state.enabled ? undefined : state.savedPlan;\n\t\tconst initialPlan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();\n\t\tif (!initialPlan) {\n\t\t\tctx.ui.notify(\"Plan mode disabled. No proposed plan is available to implement.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (!allowModeTransition(ctx, \"start plan implementation\")) return;\n\t\tif (savedPlan) {\n\t\t\tconst sessionGeneration = menuGeneration;\n\t\t\tconst planWorkflowGeneration = workflowGeneration;\n\t\t\tconst isCurrent = () =>\n\t\t\t\tsessionGeneration === menuGeneration &&\n\t\t\t\tplanWorkflowGeneration === workflowGeneration &&\n\t\t\t\t!menuController.signal.aborted &&\n\t\t\t\t!state.enabled &&\n\t\t\t\tstate.savedPlan === savedPlan;\n\t\t\tif (!(await preflightSavedPlanImplementation(ctx, isCurrent))) return;\n\t\t\tif (!allowModeTransition(ctx, \"start plan implementation\")) return;\n\t\t}\n\t\tconst plan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();\n\t\tconst source =\n\t\t\t(state.enabled ? state.latestPlanSource : savedPlan?.source) ?? \"legacy_proposed_plan\";\n\t\tif (!plan) return;\n\n\t\tconst previousState = state;\n\t\tconst previousIntent = readyPresentationIntent;\n\t\tconst wasEnabled = state.enabled;\n\t\tif (!publishModeContract(\"normal\", ctx)) return;\n\t\tadvanceWorkflowGeneration();\n\t\tconst retention = configuredImplementationPlanRetention(settings);\n\t\tconst usesConversationHistory = retention === \"clear-on-start\";\n\t\treadyPresentationIntent = undefined;\n\t\tworkflowAllowedToolNames = undefined;\n\t\tstate = {\n\t\t\t...state,\n\t\t\tenabled: false,\n\t\t\tlatestPlan: undefined,\n\t\t\tlatestPlanSource: undefined,\n\t\t\tawaitingAction: false,\n\t\t\tsavedPlan: undefined,\n\t\t\tactiveImplementation: usesConversationHistory\n\t\t\t\t? undefined\n\t\t\t\t: {\n\t\t\t\t\t\tid: randomUUID(),\n\t\t\t\t\t\tplan,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tstartedAt: Date.now(),\n\t\t\t\t\t\tretention,\n\t\t\t\t\t},\n\t\t\tmanualThinkingLevel: undefined,\n\t\t};\n\t\tif (wasEnabled) {\n\t\t\trestoreThinkingLevel();\n\t\t\tstate = { ...state, manualThinkingLevel: undefined };\n\t\t}\n\t\tpersistState();\n\t\tupdateUi(ctx);\n\n\t\tconst handoff = usesConversationHistory\n\t\t\t? wasEnabled\n\t\t\t\t? formatHistoryImplementationPrompt()\n\t\t\t\t: formatTransferredPlanPrompt(plan, false)\n\t\t\t: formatImplementationHandoff(plan);\n\t\tconst sent = sendPlanModeUserMessage(handoff, ctx);\n\t\tif (!sent) {\n\t\t\tstate = previousState;\n\t\t\treadyPresentationIntent = previousIntent;\n\t\t\tif (wasEnabled) {\n\t\t\t\tpublishModeContract(\"plan\", ctx);\n\t\t\t\tworkflowAllowedToolNames = computePlanModePolicyToolNames();\n\t\t\t\tapplyPlanThinkingLevel();\n\t\t\t}\n\t\t\tpersistState();\n\t\t\tupdateUi(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (wasEnabled) releaseWorkflowOwner();\n\t}\n\n\tfunction clearActiveImplementation(id: string, ctx: ExtensionContext) {\n\t\tif (state.activeImplementation?.id !== id) return false;\n\t\tadvanceWorkflowGeneration();\n\t\tstate = { ...state, activeImplementation: undefined };\n\t\tpersistState();\n\t\tupdateUi(ctx);\n\t\treturn true;\n\t}\n\n\tasync function exportPlan(\n\t\tctx: ExtensionContext,\n\t\tpath: string | undefined,\n\t\tsignal: AbortSignal,\n\t\tisCurrent: () => boolean,\n\t) {\n\t\tconst exitsReadyPlan = state.enabled && Boolean(state.latestPlan?.trim());\n\t\tif (exitsReadyPlan && !allowModeTransition(ctx, \"export the ready plan and leave Plan mode\")) {\n\t\t\treturn false;\n\t\t}\n\t\treturn planExports.export(path, ctx, signal, () => {\n\t\t\treturn isCurrent() && (!exitsReadyPlan || ctx.isIdle());\n\t\t});\n\t}\n\n\tasync function showLaunchMenu(ctx: ExtensionContext, initialScreen: \"main\" | \"tools\" = \"main\") {\n\t\tconst lifecycle = captureMenuLifecycle();\n\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\tconst ui = await loadInteractiveUi();\n\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\tconst tools = selectableTools();\n\t\tawait ui.showPlanLaunchMenu(ctx, {\n\t\t\tstatusText: planModeHelperToolsAvailable(safeGetActiveTools())\n\t\t\t\t? \"Status: Off \u2014 visible Plan helpers stay inactive until /plan starts.\"\n\t\t\t\t: \"Status: Off \u2014 required Plan helpers are unavailable under the active tool policy.\",\n\t\t\tinitialScreen,\n\t\t\tgetSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),\n\t\t\ttoolSummary: (selectedNames) => {\n\t\t\t\tconst allowed = tools\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(tool) =>\n\t\t\t\t\t\t\ttoolIsActive(tool.name) &&\n\t\t\t\t\t\t\tselectedNames.has(tool.name) &&\n\t\t\t\t\t\t\tcanSelectToolInPlanMode(tool),\n\t\t\t\t\t)\n\t\t\t\t\t.map((tool) => tool.name);\n\t\t\t\treturn `Plan policy will allow: ${allowed.length > 0 ? allowed.join(\", \") : \"none\"}.`;\n\t\t\t},\n\t\t\ttools: tools.map((tool) => {\n\t\t\t\tconst selectable = canSelectToolInPlanMode(tool);\n\t\t\t\tconst active = toolIsActive(tool.name);\n\t\t\t\tconst policy = active ? toolPolicyLabel(tool) : \"not active in this Pi session\";\n\t\t\t\tconst description = tool.description ?? \"No description available\";\n\t\t\t\treturn {\n\t\t\t\t\tname: tool.name,\n\t\t\t\t\tdescription: `${policy} \u00B7 ${description}`,\n\t\t\t\t\tsearchText: [policy, description].join(\" \"),\n\t\t\t\t\tdisabled: !selectable || !active,\n\t\t\t\t\tdisabledReason: !active\n\t\t\t\t\t\t? \"Not active in Pi; Plan mode will not activate it\"\n\t\t\t\t\t\t: selectable\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: \"Blocked by Plan-mode policy\",\n\t\t\t\t};\n\t\t\t}),\n\t\t\t...lifecycle,\n\t\t\tstart: (signal) => {\n\t\t\t\tif (signal.aborted || !lifecycle.isCurrent()) return;\n\t\t\t\tif (enterPlanMode(ctx)) {\n\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t\"Plan mode enabled. I will explore and plan, but not modify files.\",\n\t\t\t\t\t\t\"info\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\tstartWithTools: (names, signal) => {\n\t\t\t\tif (signal.aborted || !lifecycle.isCurrent()) return;\n\t\t\t\tconst selectedToolNames = filterAvailableSelectedToolNames(names, activePlanPolicyTools());\n\t\t\t\tif (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: undefined })) {\n\t\t\t\t\tctx.ui.notify(\"Plan mode enabled with the selected tools.\", \"info\");\n\t\t\t\t}\n\t\t\t},\n\t\t\tsettings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),\n\t\t});\n\t}\n\n\tasync function showActivePlanMenu(ctx: ExtensionContext) {\n\t\tif (!ctx.hasUI) {\n\t\t\tctx.ui.notify(planStatusText(), \"info\");\n\t\t\treturn;\n\t\t}\n\t\tconst lifecycle = captureMenuLifecycle();\n\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\tconst ui = await loadInteractiveUi();\n\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\tawait ui.showActiveImplementationMenu(ctx, {\n\t\t\tstatusText: planStatusText(),\n\t\t\tgetExportDestination: () => planExports.getDestination(ctx),\n\t\t\tsignal: lifecycle.signal,\n\t\t\tisCurrent: lifecycle.isCurrent,\n\t\t\tshow: () => showStoredPlan(pi, ctx, state),\n\t\t\texportPlan: (path, signal) => planExports.export(path, ctx, signal, lifecycle.isCurrent),\n\t\t\tsettings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),\n\t\t\tstartNew: () => {\n\t\t\t\tif (enterPlanMode(ctx)) {\n\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t\"Plan mode enabled. I will explore and plan, but not modify files.\",\n\t\t\t\t\t\t\"info\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\tclear: () => {\n\t\t\t\tif (exitPlanMode(ctx)) ctx.ui.notify(\"Active implementation plan cleared.\", \"info\");\n\t\t\t},\n\t\t});\n\t}\n\n\tasync function showSettings(\n\t\tctx: ExtensionContext,\n\t\tsignal: AbortSignal,\n\t\tisCurrent: () => boolean,\n\t) {\n\t\tif (!isCurrent() || signal.aborted) return false;\n\t\tconst ui = await loadInteractiveUi();\n\t\tif (!isCurrent() || signal.aborted) return false;\n\t\tconst result = await ui.showPlanModeSettings(ctx, {\n\t\t\ttools: selectableTools(),\n\t\t\tactiveToolNames: activeToolBaseline,\n\t\t\tsignal,\n\t\t\tisCurrent,\n\t\t\tsettingsPath: dependencies.settingsPath,\n\t\t\tupdateSettings: dependencies.updateSettings ?? updatePlanModeSettings,\n\t\t\tonSaved: (saved) => {\n\t\t\t\tif (!isCurrent()) return;\n\t\t\t\tsettings = saved;\n\t\t\t\tapplyPlanModeShortcut(configuredPlanModeToggleShortcut(saved));\n\t\t\t},\n\t\t\t...(dependencies.readSettings\n\t\t\t\t? { readSettings: async () => dependencies.readSettings?.() ?? { kind: \"missing\" } }\n\t\t\t\t: {}),\n\t\t});\n\t\treturn result.kind === \"closed\" && \"reason\" in result && result.reason === \"close\";\n\t}\n\n\tfunction allowModeTransition(ctx: ExtensionContext, action: string) {\n\t\tif (ctx.isIdle()) return true;\n\t\tconst message = `Cannot ${action} while an agent run is active. Wait for the run to settle, then retry.`;\n\t\tif (!ctx.hasUI) throw new Error(message);\n\t\tctx.ui.notify(message, \"warning\");\n\t\treturn false;\n\t}\n\n\tfunction advanceWorkflowGeneration() {\n\t\tworkflowGeneration += 1;\n\t\tfinalizationRequest.reset();\n\t}\n\n\tfunction finalizationRunOutcome(messages: unknown): FinalizationRunOutcome {\n\t\tconst stopReason = latestAssistantStopReason(messages);\n\t\tif (stopReason === undefined || stopReason === \"stop\") return \"normal\";\n\t\tif (stopReason === \"aborted\") return \"cancelled\";\n\t\treturn \"error\";\n\t}\n\n\tfunction captureMenuLifecycle() {\n\t\tconst sessionGeneration = menuGeneration;\n\t\tconst planWorkflowGeneration = workflowGeneration;\n\t\tconst owner = workflowOwner;\n\t\tconst controller = menuController;\n\t\treturn {\n\t\t\tsignal: controller.signal,\n\t\t\tisCurrent: () =>\n\t\t\t\tsessionGeneration === menuGeneration &&\n\t\t\t\tplanWorkflowGeneration === workflowGeneration &&\n\t\t\t\t!controller.signal.aborted &&\n\t\t\t\t(!state.enabled || workflowMutex.isOwner(owner)),\n\t\t};\n\t}\n\n\tfunction captureToolBaseline() {\n\t\tactiveToolBaseline = withRequiredPlanModeTools(safeGetActiveTools());\n\t}\n\n\tfunction planModePolicyToolNames() {\n\t\treturn workflowAllowedToolNames ?? computePlanModePolicyToolNames();\n\t}\n\n\tfunction computePlanModePolicyToolNames() {\n\t\tconst tools = activePlanPolicyTools();\n\t\tconst selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());\n\t\treturn tools\n\t\t\t.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool))\n\t\t\t.map((tool) => tool.name);\n\t}\n\n\tfunction toolSelectionSnapshot() {\n\t\treturn {\n\t\t\tselectedToolNames: state.selectedToolNames,\n\t\t\tselectedToolKeys: state.selectedToolKeys,\n\t\t\tdefaultPlanTools: settings.defaultPlanTools,\n\t\t};\n\t}\n\n\tfunction selectableTools() {\n\t\treturn safeGetAllTools()\n\t\t\t.filter(\n\t\t\t\t(tool) =>\n\t\t\t\t\ttool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME,\n\t\t\t)\n\t\t\t.sort(compareTools);\n\t}\n\n\tfunction activePlanPolicyTools() {\n\t\tconst activeNames = new Set(activeToolBaseline);\n\t\treturn selectableTools().filter((tool) => activeNames.has(tool.name));\n\t}\n\n\tfunction toolIsActive(toolName: string) {\n\t\treturn activeToolBaseline.includes(toolName);\n\t}\n\n\tfunction safeGetAllTools() {\n\t\ttry {\n\t\t\treturn pi.getAllTools();\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\tfunction applyPlanThinkingLevel() {\n\t\tif (state.manualThinkingLevel) {\n\t\t\tif (pi.getThinkingLevel() !== state.manualThinkingLevel) {\n\t\t\t\tpi.setThinkingLevel(state.manualThinkingLevel);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst configured = configuredThinkingLevel(settings);\n\t\tif (!configured) {\n\t\t\tstate = {\n\t\t\t\t...state,\n\t\t\t\tpreviousThinkingLevel: undefined,\n\t\t\t\tappliedThinkingLevel: undefined,\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\t\tconst current = pi.getThinkingLevel();\n\t\tif (!state.appliedThinkingLevel) state.previousThinkingLevel = current;\n\t\tif (current !== configured) pi.setThinkingLevel(configured);\n\t\tstate.appliedThinkingLevel = pi.getThinkingLevel();\n\t}\n\n\tfunction captureManualThinkingLevel() {\n\t\tif (!state.appliedThinkingLevel) return;\n\t\tconst current = pi.getThinkingLevel();\n\t\tif (current === state.appliedThinkingLevel) return;\n\t\tstate = {\n\t\t\t...state,\n\t\t\tmanualThinkingLevel: current,\n\t\t\tpreviousThinkingLevel: undefined,\n\t\t\tappliedThinkingLevel: undefined,\n\t\t};\n\t}\n\n\tfunction restoreThinkingLevel() {\n\t\tcaptureManualThinkingLevel();\n\t\tconst { appliedThinkingLevel, previousThinkingLevel } = state;\n\t\tif (\n\t\t\tappliedThinkingLevel &&\n\t\t\tpreviousThinkingLevel &&\n\t\t\tpi.getThinkingLevel() === appliedThinkingLevel\n\t\t) {\n\t\t\tpi.setThinkingLevel(previousThinkingLevel);\n\t\t}\n\t\tstate = { ...state, appliedThinkingLevel: undefined, previousThinkingLevel: undefined };\n\t}\n\n\tfunction safeGetActiveTools() {\n\t\ttry {\n\t\t\treturn pi.getActiveTools();\n\t\t} catch {\n\t\t\treturn DEFAULT_TOOLS;\n\t\t}\n\t}\n\n\tfunction installRestoredState(candidate: PlanModeState, ctx: ExtensionContext) {\n\t\tconst previousState = state;\n\t\tconst previousWorkflowAllowedToolNames = workflowAllowedToolNames;\n\t\tconst previousOwner = workflowOwner;\n\t\tconst wasEnabled = state.enabled;\n\t\tif (candidate.enabled && !workflowMutex.isOwner(workflowOwner)) {\n\t\t\tconst owner = workflowMutex.acquire();\n\t\t\tif (!owner) {\n\t\t\t\tstate = { enabled: false, awaitingAction: false };\n\t\t\t\tworkflowAllowedToolNames = undefined;\n\t\t\t\treportRestoredWorkflowBusy(ctx);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tworkflowOwner = owner;\n\t\t}\n\n\t\ttry {\n\t\t\tif (candidate.enabled) {\n\t\t\t\ttry {\n\t\t\t\t\tassertPlanModeHelperToolsAvailable(safeGetActiveTools());\n\t\t\t\t} catch {\n\t\t\t\t\tstate = { enabled: false, awaitingAction: false };\n\t\t\t\t\tworkflowAllowedToolNames = undefined;\n\t\t\t\t\tif (workflowOwner !== previousOwner) {\n\t\t\t\t\t\tworkflowMutex.release(workflowOwner);\n\t\t\t\t\t\tworkflowOwner = previousOwner;\n\t\t\t\t\t}\n\t\t\t\t\treportRestoredHelpersUnavailable(ctx);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (wasEnabled && !candidate.enabled) {\n\t\t\t\treadyPresentationIntent = undefined;\n\t\t\t\trestoreThinkingLevel();\n\t\t\t}\n\t\t\tstate = candidate;\n\t\t\tworkflowAllowedToolNames = state.enabled ? computePlanModePolicyToolNames() : undefined;\n\t\t\tif (state.enabled) applyPlanThinkingLevel();\n\t\t\telse if (wasEnabled) releaseWorkflowOwner();\n\t\t\treturn true;\n\t\t} catch (error: unknown) {\n\t\t\ttry {\n\t\t\t\tif (!wasEnabled && state.enabled) restoreThinkingLevel();\n\t\t\t} finally {\n\t\t\t\tstate = previousState;\n\t\t\t\tworkflowAllowedToolNames = previousWorkflowAllowedToolNames;\n\t\t\t\tif (workflowOwner !== previousOwner) {\n\t\t\t\t\tworkflowMutex.release(workflowOwner);\n\t\t\t\t\tworkflowOwner = previousOwner;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tfunction rollbackNewActivation(\n\t\tpreviousState: PlanModeState,\n\t\tctx: ExtensionContext,\n\t\tpreviousOwner?: WorkflowMutexOwner,\n\t) {\n\t\tconst activatedOwner = workflowOwner;\n\t\treadyPresentationIntent = undefined;\n\t\ttry {\n\t\t\tif (state.enabled) {\n\t\t\t\tpublishModeContract(\"normal\", ctx);\n\t\t\t\trestoreThinkingLevel();\n\t\t\t}\n\t\t} finally {\n\t\t\tstate = previousState;\n\t\t\tworkflowAllowedToolNames = undefined;\n\t\t\ttry {\n\t\t\t\tpersistState();\n\t\t\t\tupdateUi(ctx);\n\t\t\t} finally {\n\t\t\t\tif (activatedOwner !== previousOwner) {\n\t\t\t\t\tworkflowMutex.release(activatedOwner);\n\t\t\t\t\tworkflowOwner = previousOwner;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction bindWorkflowSessionIfNeeded(ctx: ExtensionContext) {\n\t\tif (currentSession === ctx.sessionManager) return;\n\t\tcurrentSession = ctx.sessionManager;\n\t\tworkflowOwner = undefined;\n\t\tworkflowMutex.bindSession(ctx.sessionManager);\n\t}\n\n\tfunction releaseWorkflowOwner() {\n\t\tconst owner = workflowOwner;\n\t\tworkflowMutex.release(owner);\n\t\tif (!workflowMutex.isOwner(owner)) workflowOwner = undefined;\n\t}\n\n\tfunction reportWorkflowBusy(ctx: ExtensionContext) {\n\t\tconst message = \"Another workflow is active in this session. End it before starting Plan mode.\";\n\t\tif (!ctx.hasUI) throw new Error(message);\n\t\tctx.ui.notify(message, \"warning\");\n\t\treturn false;\n\t}\n\n\tfunction reportRestoredWorkflowBusy(ctx: ExtensionContext) {\n\t\tif (!ctx.hasUI) return;\n\t\tctx.ui.notify(\n\t\t\t\"Plan mode was not restored because another workflow is active in this session. Reload or start Plan mode after it ends.\",\n\t\t\t\"warning\",\n\t\t);\n\t}\n\n\tfunction reportRestoredHelpersUnavailable(ctx: ExtensionContext) {\n\t\tif (!ctx.hasUI) return;\n\t\tctx.ui.notify(\n\t\t\t\"Plan mode was not restored because its helper tools are unavailable under the active tool policy.\",\n\t\t\t\"warning\",\n\t\t);\n\t}\n\n\tfunction reportHelperActivationFailure(ctx: ExtensionContext, error: unknown) {\n\t\tconst detail = safeTerminalText(error instanceof Error ? error.message : String(error));\n\t\tconst message = `Cannot start Plan mode: ${detail}.`;\n\t\tif (!ctx.hasUI) throw new Error(message, { cause: error });\n\t\tctx.ui.notify(message, \"error\");\n\t\treturn false;\n\t}\n\n\tfunction updateUi(ctx: ExtensionContext) {\n\t\tupdatePlanModeUi(ctx, state, formatToolSummary);\n\t}\n\n\tfunction clearUi(ctx: ExtensionContext) {\n\t\tclearPlanModeUi(ctx);\n\t}\n\n\tfunction planStatusText() {\n\t\treturn formatPlanModeStatusText(state, formatToolSummary);\n\t}\n\n\tfunction implementationOutcome() {\n\t\treturn implementationRetentionPreview(configuredImplementationPlanRetention(settings));\n\t}\n\n\tfunction formatToolSummary() {\n\t\tconst names = planModePolicyToolNames();\n\t\treturn `Plan policy allows: ${names.length > 0 ? names.join(\", \") : \"none\"}. Model-visible tools stay unchanged.`;\n\t}\n\n\tfunction toolByName(toolName: string) {\n\t\treturn safeGetAllTools().find((candidate) => candidate.name === toolName);\n\t}\n\n\tfunction safeTerminalText(value: string) {\n\t\treturn [...value]\n\t\t\t.map((character) => {\n\t\t\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\t\t\treturn codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n\t\t\t})\n\t\t\t.join(\"\")\n\t\t\t.trim();\n\t}\n}\n\nexport { completePlanArguments } from \"./command.js\";\nexport {\n\textractProposedPlan,\n\tlatestAssistantText,\n\tparseProposedPlan,\n\tstripProposedPlanBlocks,\n\tstripProposedPlanBlocksFromMessage,\n} from \"./message-transform.js\";\nexport {\n\tcreateModeContractMessage,\n\tmodeContractContent,\n\treconcileModeContract,\n} from \"./mode-contract.js\";\nexport { buildPlanModePrompt } from \"./prompt.js\";\nexport { normalizePlanModeQuestionParams } from \"./question-tool.js\";\nexport { withRequiredPlanModeTools } from \"./required-tools.js\";\nexport { normalizePlanModeSettings, readPlanModeSettings } from \"./settings.js\";\nexport { canSelectToolInPlanMode, classifyPlanModeTool, isSafeCommand } from \"./tool-policy.js\";\n", "export interface CommandArgumentCompletion {\n\tvalue: string;\n\tlabel: string;\n\tdescription?: string;\n}\n\nconst PLAN_COMMAND_COMPLETIONS: readonly CommandArgumentCompletion[] = [\n\t{ value: \"start\", label: \"start\", description: \"Start Plan mode without sending a prompt\" },\n\t{ value: \"show\", label: \"show\", description: \"Show the ready, saved, or active plan\" },\n\t{ value: \"finalize\", label: \"finalize\", description: \"Request a completed plan\" },\n\t{ value: \"implement\", label: \"implement\", description: \"Implement the completed or saved plan\" },\n\t{ value: \"save\", label: \"save\", description: \"Save the completed plan for later\" },\n\t{ value: \"export\", label: \"export\", description: \"Export the stored plan to a Markdown file\" },\n\t{ value: \"exit\", label: \"exit\", description: \"Leave Plan mode or clear a saved/active plan\" },\n\t{ value: \"off\", label: \"off\", description: \"Leave Plan mode or clear a saved/active plan\" },\n\t{\n\t\tvalue: \"tools\",\n\t\tlabel: \"tools\",\n\t\tdescription: \"Choose tools before starting this Plan workflow\",\n\t},\n];\n\nexport function completePlanArguments(argumentPrefix: string): CommandArgumentCompletion[] | null {\n\tconst prefix = argumentPrefix.trimStart().toLowerCase();\n\tif (prefix === \"\") return [...PLAN_COMMAND_COMPLETIONS];\n\tif (/\\s/.test(prefix)) return null;\n\n\tconst matches = PLAN_COMMAND_COMPLETIONS.filter((item) => item.value.startsWith(prefix));\n\treturn matches.length > 0 ? [...matches] : null;\n}\n", "export function isStaleExtensionContextError(error: unknown) {\n\treturn (\n\t\terror instanceof Error &&\n\t\t(error.message.includes(\"This extension ctx is stale after session replacement or reload\") ||\n\t\t\terror.message.includes(\"Extension context is no longer active\"))\n\t);\n}\n", "export const FINALIZE_PLAN_PROMPT =\n\t\"Finalize the current implementation plan now. If any material decision remains, use plan_mode_question instead. Otherwise call plan_mode_complete alone as your final action with the complete decision-ready plan.\";\n\nexport const RETRY_FINALIZE_PLAN_PROMPT =\n\t\"Your previous finalization response did not call plan_mode_question or plan_mode_complete. Both tools are available in the current Plan-mode request. If a material decision remains, call plan_mode_question now. Otherwise call plan_mode_complete alone with the complete decision-ready plan. Do not respond with prose about tool availability.\";\n\nexport type FinalizationRunOutcome = \"normal\" | \"cancelled\" | \"error\";\nexport type FinalizationSettlementAction = \"retry\" | \"failed\" | undefined;\n\ninterface PendingFinalizationRequest {\n\tworkflowGeneration: number;\n\tretryCount: number;\n\tawaitingSettlement: boolean;\n}\n\nexport function createFinalizationRequestCoordinator() {\n\tlet pending: PendingFinalizationRequest | undefined;\n\n\treturn {\n\t\trequest(workflowGeneration: number) {\n\t\t\tpending = { workflowGeneration, retryCount: 0, awaitingSettlement: false };\n\t\t},\n\t\tsatisfy() {\n\t\t\tpending = undefined;\n\t\t},\n\t\tobserveRunEnd(workflowGeneration: number, outcome: FinalizationRunOutcome) {\n\t\t\tif (!pending || pending.workflowGeneration !== workflowGeneration) return;\n\t\t\tif (outcome !== \"normal\") {\n\t\t\t\tpending = undefined;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpending.awaitingSettlement = true;\n\t\t},\n\t\tsettle(workflowGeneration: number): FinalizationSettlementAction {\n\t\t\tif (\n\t\t\t\t!pending ||\n\t\t\t\tpending.workflowGeneration !== workflowGeneration ||\n\t\t\t\t!pending.awaitingSettlement\n\t\t\t) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tif (pending.retryCount === 0) {\n\t\t\t\tpending.retryCount = 1;\n\t\t\t\tpending.awaitingSettlement = false;\n\t\t\t\treturn \"retry\";\n\t\t\t}\n\t\t\tpending = undefined;\n\t\t\treturn \"failed\";\n\t\t},\n\t\treset() {\n\t\t\tpending = undefined;\n\t\t},\n\t\thasPendingRequest() {\n\t\t\treturn pending !== undefined;\n\t\t},\n\t};\n}\n", "import { randomUUID } from \"node:crypto\";\nimport type { ExtensionCommandContext, ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { PLAN_HISTORY_IMPLEMENTATION_PROMPT } from \"./message-transform.js\";\nimport { createModeContractMessage } from \"./mode-contract.js\";\nimport type { ImplementationPlanRetention } from \"./settings.js\";\nimport type { PlanCompletionSource, PlanModeState } from \"./state.js\";\n\ntype NewSessionOptions = Exclude<Parameters<ExtensionCommandContext[\"newSession\"]>[0], undefined>;\ntype ReplacementContext = Parameters<NonNullable<NewSessionOptions[\"withSession\"]>>[0];\n\nexport interface FreshImplementationRequest {\n\tplan: string;\n\tsource: PlanCompletionSource;\n\tretention: ImplementationPlanRetention;\n\tstateEntryType: string;\n\tisCurrent(): boolean;\n}\n\ninterface FreshImplementationFromStateOptions {\n\tgetState(): PlanModeState;\n\tmenuIsCurrent(): boolean;\n\tretention: ImplementationPlanRetention;\n\tstateEntryType: string;\n}\n\nexport type FreshImplementationResult =\n\t| { kind: \"started\" }\n\t| { kind: \"cancelled\" }\n\t| { kind: \"partial\" }\n\t| { kind: \"rejected\" }\n\t| { kind: \"stale\" };\n\nexport function formatImplementationHandoff(plan: string) {\n\treturn `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:\\n\\n${plan}`;\n}\n\nexport function formatHistoryImplementationPrompt() {\n\treturn PLAN_HISTORY_IMPLEMENTATION_PROMPT;\n}\n\nexport function formatTransferredPlanPrompt(plan: string, fresh: boolean) {\n\tconst destination = fresh ? \" in a fresh context\" : \"\";\n\treturn `A previous agent produced the plan below to accomplish the user's task. Implement the plan${destination}. Treat the plan as the source of user intent, re-read files as needed, and carry the work through implementation and verification.\\n\\n${plan}`;\n}\n\nexport async function startFreshImplementationFromState(\n\tctx: ExtensionContext,\n\toptions: FreshImplementationFromStateOptions,\n) {\n\tif (!isCommandContext(ctx)) {\n\t\tctx.ui.notify(\n\t\t\t\"Fresh implementation requires the interactive /plan command. Reopen /plan and try again.\",\n\t\t\t\"warning\",\n\t\t);\n\t\treturn { kind: \"rejected\" } as const;\n\t}\n\tconst initialState = options.getState();\n\tconst savedPlan = initialState.enabled ? undefined : initialState.savedPlan;\n\tconst plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();\n\tconst source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;\n\tif (!plan || !source) {\n\t\tctx.ui.notify(\"No completed plan is available to implement.\", \"warning\");\n\t\treturn { kind: \"rejected\" } as const;\n\t}\n\tconst wasEnabled = initialState.enabled;\n\tconst isCurrent = () => {\n\t\tconst current = options.getState();\n\t\treturn (\n\t\t\toptions.menuIsCurrent() &&\n\t\t\tcurrent.enabled === wasEnabled &&\n\t\t\t(wasEnabled\n\t\t\t\t? current.latestPlan === plan && current.latestPlanSource === source\n\t\t\t\t: current.savedPlan === savedPlan)\n\t\t);\n\t};\n\treturn startFreshImplementationSession(ctx, {\n\t\tplan,\n\t\tsource,\n\t\tretention: options.retention,\n\t\tstateEntryType: options.stateEntryType,\n\t\tisCurrent,\n\t});\n}\n\nexport async function startFreshImplementationSession(\n\tctx: ExtensionCommandContext,\n\trequest: FreshImplementationRequest,\n): Promise<FreshImplementationResult> {\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") {\n\t\tthrow new Error(\"Fresh plan implementation is unavailable in print/JSON mode. Use TUI or RPC.\");\n\t}\n\n\tawait ctx.waitForIdle();\n\tif (!request.isCurrent()) return { kind: \"stale\" };\n\tif (!(await preflightModel(ctx, request.isCurrent))) return { kind: \"rejected\" };\n\tif (!request.isCurrent()) return { kind: \"stale\" };\n\n\tconst usesConversationHistory = request.retention === \"clear-on-start\";\n\tconst destinationState: PlanModeState | undefined = usesConversationHistory\n\t\t? undefined\n\t\t: {\n\t\t\t\tenabled: false,\n\t\t\t\tawaitingAction: false,\n\t\t\t\tactiveImplementation: {\n\t\t\t\t\tid: randomUUID(),\n\t\t\t\t\tplan: request.plan,\n\t\t\t\t\tsource: request.source,\n\t\t\t\t\tstartedAt: Date.now(),\n\t\t\t\t\tretention: request.retention,\n\t\t\t\t},\n\t\t\t};\n\tconst handoff = usesConversationHistory\n\t\t? formatTransferredPlanPrompt(request.plan, true)\n\t\t: formatImplementationHandoff(request.plan);\n\tconst parentSession = ctx.sessionManager.getSessionFile();\n\tlet setupError: string | undefined;\n\tlet kickoffError: string | undefined;\n\n\tif (ctx.mode === \"rpc\") safeNotify(ctx, \"Starting fresh implementation session\u2026\", \"info\");\n\n\tlet result: Awaited<ReturnType<ExtensionCommandContext[\"newSession\"]>>;\n\ttry {\n\t\tresult = await ctx.newSession({\n\t\t\t...(parentSession ? { parentSession } : {}),\n\t\t\tsetup: async (sessionManager) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst contract = createModeContractMessage(\"normal\");\n\t\t\t\t\tsessionManager.appendCustomMessageEntry(\n\t\t\t\t\t\tcontract.customType,\n\t\t\t\t\t\tcontract.content,\n\t\t\t\t\t\tcontract.display,\n\t\t\t\t\t\tcontract.details,\n\t\t\t\t\t);\n\t\t\t\t\tif (destinationState) {\n\t\t\t\t\t\tsessionManager.appendCustomEntry(request.stateEntryType, destinationState);\n\t\t\t\t\t}\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tsetupError = safeErrorDetail(error);\n\t\t\t\t}\n\t\t\t},\n\t\t\twithSession: async (replacementCtx) => {\n\t\t\t\tif (setupError) {\n\t\t\t\t\trecoverSetupFailure(replacementCtx, handoff, setupError);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait replacementCtx.sendUserMessage(handoff);\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tkickoffError = safeErrorDetail(error);\n\t\t\t\t\tconst recoveredInEditor =\n\t\t\t\t\t\tusesConversationHistory && safeSetEditorText(replacementCtx, handoff);\n\t\t\t\t\tsafeNotify(\n\t\t\t\t\t\treplacementCtx,\n\t\t\t\t\t\tusesConversationHistory\n\t\t\t\t\t\t\t? recoveredInEditor\n\t\t\t\t\t\t\t\t? `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request is in the editor; submit it or resume the parent planning session.`\n\t\t\t\t\t\t\t\t: `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request could not be restored to the editor; resume the parent planning session.`\n\t\t\t\t\t\t\t: `Fresh session created, but implementation did not start: ${kickoffError}. Send a message to continue, use /plan exit to clear the active plan, or resume the parent planning session.`,\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsafeNotify(\n\t\t\t\t\treplacementCtx,\n\t\t\t\t\t\"Fresh implementation session started. Only the approved plan was transferred.\",\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\t} catch (error: unknown) {\n\t\tsafeNotify(\n\t\t\tctx,\n\t\t\t`Unable to start a fresh implementation session: ${safeErrorDetail(error)}. The source plan remains available; retry or resume the planning session.`,\n\t\t\t\"error\",\n\t\t);\n\t\treturn { kind: \"rejected\" };\n\t}\n\n\tif (result.cancelled) {\n\t\tsafeNotify(ctx, \"Fresh implementation cancelled. The plan remains available.\", \"info\");\n\t\treturn { kind: \"cancelled\" };\n\t}\n\treturn setupError || kickoffError ? { kind: \"partial\" } : { kind: \"started\" };\n}\n\nasync function preflightModel(ctx: ExtensionCommandContext, isCurrent: () => boolean) {\n\tconst model = ctx.model;\n\tif (!model) {\n\t\tctx.ui.notify(\"Unable to implement the plan: no model is selected.\", \"warning\");\n\t\treturn false;\n\t}\n\tlet auth: Awaited<ReturnType<ExtensionCommandContext[\"modelRegistry\"][\"getApiKeyAndHeaders\"]>>;\n\ttry {\n\t\tauth = await ctx.modelRegistry.getApiKeyAndHeaders(model);\n\t} catch (error: unknown) {\n\t\tif (isCurrent()) {\n\t\t\tctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(error)}`, \"error\");\n\t\t}\n\t\treturn false;\n\t}\n\tif (!isCurrent()) return false;\n\tif (!auth.ok) {\n\t\tctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(auth.error)}`, \"warning\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction recoverSetupFailure(ctx: ReplacementContext, handoff: string, setupError: string) {\n\tconst recoveredInEditor = safeSetEditorText(ctx, handoff);\n\tsafeNotify(\n\t\tctx,\n\t\trecoveredInEditor\n\t\t\t? `Fresh session created, but the active plan could not be saved: ${setupError}. The implementation request is in the editor; submit it to continue or resume the parent planning session.`\n\t\t\t: `Fresh session created, but the active plan could not be saved: ${setupError}. The implementation request could not be restored to the editor; resume the parent planning session.`,\n\t\t\"error\",\n\t);\n}\n\nfunction safeSetEditorText(ctx: Pick<ExtensionContext, \"ui\">, text: string) {\n\ttry {\n\t\tctx.ui.setEditorText(text);\n\t\treturn true;\n\t} catch {\n\t\t// A replacement context can become stale while Pi reports a partial handoff.\n\t\treturn false;\n\t}\n}\n\nfunction safeNotify(\n\tctx: Pick<ExtensionContext, \"ui\">,\n\tmessage: string,\n\tlevel: \"info\" | \"warning\" | \"error\",\n) {\n\ttry {\n\t\tctx.ui.notify(message, level);\n\t} catch {\n\t\t// A source or replacement context can become stale during session replacement.\n\t}\n}\n\nfunction isCommandContext(ctx: ExtensionContext): ctx is ExtensionCommandContext {\n\treturn typeof (ctx as Partial<ExtensionCommandContext>).newSession === \"function\";\n}\n\nfunction safeErrorDetail(error: unknown) {\n\tconst detail = error instanceof Error ? error.message : String(error);\n\tconst normalized =\n\t\t[...detail]\n\t\t\t.map((character) => {\n\t\t\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\t\t\treturn codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? \" \" : character;\n\t\t\t})\n\t\t\t.join(\"\")\n\t\t\t.replace(/\\s+/gu, \" \")\n\t\t\t.trim() || \"unknown error\";\n\tconst characters = [...normalized];\n\treturn characters.length > 500 ? `${characters.slice(0, 499).join(\"\")}\u2026` : normalized;\n}\n", "const PLAN_CONTEXT_MARKER = \"[CODEX-LIKE PLAN MODE ACTIVE]\";\n\nexport function buildPlanModePrompt() {\n\treturn `${PLAN_CONTEXT_MARKER}\n# Plan Mode (Conversational)\n\nYou are in Plan Mode, a Codex-like collaboration mode for producing a decision-complete implementation plan. Chat your way to the plan before finalizing it. A final plan must leave no implementation decisions unresolved.\n\n## Mode rules\n\n- Stay in Plan Mode until a developer or extension explicitly exits it.\n- Treat requests to implement as requests to plan the implementation; do not edit files or carry out the plan.\n- Do not use update_plan/TODO tooling in Plan Mode; Plan Mode is conversational planning, not execution progress tracking.\n- Plan Mode keeps the session's model-visible tool schemas unchanged and enforces a runtime policy allowlist. Non-built-in tools are denied by default and may be allowed only when already active in Pi and explicitly selected by the user at their own risk.\n- Do not perform mutating actions: no edit/write tools, no patching, no formatting that rewrites files, no dependency installation, no commits, no migrations.\n\n## Phase 1 \u2014 Ground in the environment\n\n- Explore first and ask second. Use non-mutating exploration to read files, search, inspect configuration, run read-only checks, and resolve discoverable facts.\n- Before asking the user any question, perform at least one targeted non-mutating exploration pass unless no local environment or repository is available.\n- Do not ask questions that can be answered from repository or system truth. Ask only when multiple plausible choices remain, a needed identifier/context is missing, or the ambiguity is product intent.\n\n## Phase 2 \u2014 Intent chat\n\n- Keep asking until you can clearly state the goal, success criteria, in/out of scope, constraints, current state, and key preferences/tradeoffs.\n- Bias toward questions over guessing: if a high-impact ambiguity remains, do not produce a proposed plan yet.\n- For an unanswered preference or tradeoff, use the recommended option only when it is low risk and record that default as an explicit assumption in the final plan.\n\n## Phase 3 \u2014 Implementation chat\n\n- Once intent is stable, keep asking until the spec is decision-complete: approach, interfaces, data flow, edge cases/failure modes, testing and acceptance criteria, and any migration or compatibility constraints.\n- Use plan_mode_question for important preferences, tradeoffs, or assumption locks that cannot be discovered by non-mutating exploration. Ask 1-3 concise questions with 2-4 meaningful options. Do not include filler options.\n- Treat plan_mode_question and plan_mode_complete as callable when they are listed in the current request's active tools. Do not infer that they are unavailable from earlier modes or conversation history.\n- If a Plan tool call returns an actual error, respond to that error. Do not replace an available structured tool call with prose claiming that the tool is unavailable.\n- If plan_mode_question returns cancelled or ui_unavailable, do not jump straight to a final plan when the missing answer is high impact. Ask one concise plain-text question or proceed only with a clearly stated low-risk assumption.\n\n## Ending each turn\n\nEvery Plan-mode turn that advances or finalizes the plan must end in exactly one of these ways:\n\n- If a material decision remains, use plan_mode_question. If interactive UI is unavailable, ask one concise plain-text question instead.\n- If the implementation plan is decision-complete, call plan_mode_complete alone as your final action. Do not call other tools in the same batch and do not emit a normal assistant response after it.\n\nIf a follow-up asks only for clarification and does not change or challenge the plan, answer it directly, then call plan_mode_complete alone as the final action with the complete unchanged plan so it remains available for implementation.\n\nNever end with prose that merely announces you are about to present, write, or finalize the plan. Submit the actual plan with plan_mode_complete in that turn.\n\n## Completion rule\n\nOnly call plan_mode_complete when the plan leaves no implementation decisions unresolved. Pass the complete plan as Markdown with:\n\n- A clear title\n- A brief summary\n- Important changes to behavior, public APIs, interfaces, or types\n- Test cases and verification scenarios\n- Explicit assumptions and defaults chosen where needed\n\nKeep the plan concise, human and agent digestible, and free of open decisions. Prefer grouped behavior-level changes over file-by-file or symbol-by-symbol inventories. Do not ask \"should I proceed?\"; plan_mode_complete opens the Plan-mode ready flow.\n\nIf the user requests revisions after a completed plan, the next plan_mode_complete call must contain a complete replacement, not a delta. If there is not enough information for a complete replacement, continue planning with plan_mode_question instead of calling plan_mode_complete.`;\n}\n", "import { buildPlanModePrompt } from \"./prompt.js\";\n\nexport const MODE_CONTRACT_MESSAGE_TYPE = \"plan-mode-transition\";\nexport const MODE_CONTRACT_VERSION = 1;\nexport type PlanModeContract = \"plan\" | \"normal\";\n\nconst PLAN_CONTRACT_MARKER = `[PI PLAN MODE CONTRACT v${MODE_CONTRACT_VERSION}: PLAN]`;\nconst NORMAL_CONTRACT_MARKER = `[PI PLAN MODE CONTRACT v${MODE_CONTRACT_VERSION}: NORMAL]`;\nconst NORMAL_CONTRACT = `${NORMAL_CONTRACT_MARKER}\nPlan Mode is no longer active.\nFollow the user's current Normal-mode request and ordinary system instructions.\nEarlier Plan-mode restrictions no longer apply, but retain the planning conversation as context.\nThe visible tool schemas are session capabilities; use only tools appropriate for the current request.`;\n\ninterface ContractMessage {\n\trole?: string;\n\tcustomType?: string;\n\tcontent?: unknown;\n\tdetails?: unknown;\n}\n\nexport function modeContractContent(mode: PlanModeContract) {\n\treturn mode === \"plan\" ? `${PLAN_CONTRACT_MARKER}\\n${buildPlanModePrompt()}` : NORMAL_CONTRACT;\n}\n\nexport function createModeContractMessage(mode: PlanModeContract, timestamp = Date.now()) {\n\treturn {\n\t\trole: \"custom\" as const,\n\t\tcustomType: MODE_CONTRACT_MESSAGE_TYPE,\n\t\tcontent: modeContractContent(mode),\n\t\tdisplay: false,\n\t\tdetails: { version: MODE_CONTRACT_VERSION, mode },\n\t\ttimestamp,\n\t};\n}\n\nexport function modeContractFromMessage(message: unknown): PlanModeContract | undefined {\n\tconst candidate = unwrapMessage(message);\n\tif (candidate.customType !== MODE_CONTRACT_MESSAGE_TYPE) return undefined;\n\tif (candidate.content === modeContractContent(\"plan\")) return \"plan\";\n\tif (candidate.content === modeContractContent(\"normal\")) return \"normal\";\n\treturn undefined;\n}\n\nexport function hasModeContractArtifact(messages: readonly unknown[]) {\n\treturn messages.some(\n\t\t(message) => unwrapMessage(message).customType === MODE_CONTRACT_MESSAGE_TYPE,\n\t);\n}\n\nexport function latestModeContract(messages: readonly unknown[]) {\n\tfor (let index = messages.length - 1; index >= 0; index -= 1) {\n\t\tconst mode = modeContractFromMessage(messages[index]);\n\t\tif (mode) return { index, mode };\n\t}\n\treturn undefined;\n}\n\nexport function reconcileModeContract(messages: unknown[], expected: PlanModeContract) {\n\tconst latest = latestModeContract(messages);\n\tif (latest?.mode === expected) return messages;\n\n\tconst latestContractIndex = findLatestContractArtifactIndex(messages);\n\tconst insertionIndex =\n\t\tlatestContractIndex >= 0 ? latestContractIndex + 1 : leadingSummaryBoundary(messages);\n\treturn [\n\t\t...messages.slice(0, insertionIndex),\n\t\tcreateModeContractMessage(expected, 0),\n\t\t...messages.slice(insertionIndex),\n\t];\n}\n\nfunction findLatestContractArtifactIndex(messages: readonly unknown[]) {\n\tfor (let index = messages.length - 1; index >= 0; index -= 1) {\n\t\tif (unwrapMessage(messages[index]).customType === MODE_CONTRACT_MESSAGE_TYPE) return index;\n\t}\n\treturn -1;\n}\n\nfunction leadingSummaryBoundary(messages: readonly unknown[]) {\n\tlet index = 0;\n\twhile (index < messages.length) {\n\t\tconst role = unwrapMessage(messages[index]).role;\n\t\tif (role !== \"compactionSummary\" && role !== \"branchSummary\") break;\n\t\tindex += 1;\n\t}\n\treturn index;\n}\n\nfunction unwrapMessage(message: unknown): ContractMessage {\n\tconst entry = message as { message?: unknown } | undefined;\n\treturn (entry?.message ?? message ?? {}) as ContractMessage;\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport type { PlanExportDestination } from \"./plan-export.js\";\nimport type { PlanModeState } from \"./state.js\";\n\ntype InteractiveUi = typeof import(\"./interactive-ui.js\");\n\ninterface MenuLifecycle {\n\tsignal: AbortSignal;\n\tisCurrent(): boolean;\n}\n\ninterface PlanActionControllerOptions {\n\tloadInteractiveUi(): Promise<InteractiveUi>;\n\tgetState(): PlanModeState;\n\tcaptureLifecycle(): MenuLifecycle;\n\tstatusText(): string;\n\timplementationOutcome(): string;\n\tgetExportDestination(ctx: ExtensionContext): PlanExportDestination;\n\tshow(ctx: ExtensionContext): void;\n\tfinalize(ctx: ExtensionContext): void;\n\timplementHere(ctx: ExtensionContext): void | Promise<void>;\n\timplementFresh(ctx: ExtensionContext, isCurrent: () => boolean): void | Promise<void>;\n\texportPlan(\n\t\tctx: ExtensionContext,\n\t\tpath: string,\n\t\tsignal: AbortSignal,\n\t\tisCurrent: () => boolean,\n\t): Promise<boolean>;\n\tsettings(ctx: ExtensionContext, signal: AbortSignal, isCurrent: () => boolean): Promise<boolean>;\n\tsave(ctx: ExtensionContext): void;\n\tstay(ctx: ExtensionContext): void;\n\texitReady(ctx: ExtensionContext): void;\n\tclearSaved(ctx: ExtensionContext): void;\n}\n\nexport function createPlanActionController(options: PlanActionControllerOptions) {\n\tconst freshAction = (ctx: ExtensionContext, lifecycle: MenuLifecycle, signal: AbortSignal) =>\n\t\toptions.implementFresh(ctx, () => lifecycle.isCurrent() && !signal.aborted);\n\n\treturn {\n\t\tasync showSaved(ctx: ExtensionContext) {\n\t\t\tconst lifecycle = options.captureLifecycle();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tconst ui = await options.loadInteractiveUi();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tawait ui.showSavedPlanMenu(ctx, {\n\t\t\t\tstatusText: options.statusText(),\n\t\t\t\timplementationOutcome: options.implementationOutcome,\n\t\t\t\tgetExportDestination: () => options.getExportDestination(ctx),\n\t\t\t\tsignal: lifecycle.signal,\n\t\t\t\tisCurrent: lifecycle.isCurrent,\n\t\t\t\tshow: () => options.show(ctx),\n\t\t\t\timplementHere: () => options.implementHere(ctx),\n\t\t\t\timplementFresh: (signal) => freshAction(ctx, lifecycle, signal),\n\t\t\t\texportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),\n\t\t\t\tsettings: (signal) => options.settings(ctx, signal, lifecycle.isCurrent),\n\t\t\t\tclear: () => options.clearSaved(ctx),\n\t\t\t});\n\t\t},\n\t\tasync showCurrent(ctx: ExtensionContext) {\n\t\t\tif (!ctx.hasUI) {\n\t\t\t\tctx.ui.notify(options.statusText(), \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst lifecycle = options.captureLifecycle();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tconst ui = await options.loadInteractiveUi();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tawait ui.showPlanModeMenu(ctx, {\n\t\t\t\tstatusText: options.statusText(),\n\t\t\t\thasReadyPlan: options.getState().latestPlan !== undefined,\n\t\t\t\timplementationOutcome: options.implementationOutcome,\n\t\t\t\tgetExportDestination: () => options.getExportDestination(ctx),\n\t\t\t\t...lifecycle,\n\t\t\t\tshow: () => options.show(ctx),\n\t\t\t\tfinalize: () => options.finalize(ctx),\n\t\t\t\timplementHere: () => options.implementHere(ctx),\n\t\t\t\timplementFresh: (signal) => freshAction(ctx, lifecycle, signal),\n\t\t\t\texportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),\n\t\t\t\tsave: () => options.save(ctx),\n\t\t\t\tstay: () => options.stay(ctx),\n\t\t\t\texit: () => options.exitReady(ctx),\n\t\t\t});\n\t\t},\n\t\tasync showReady(ctx: ExtensionContext) {\n\t\t\tconst lifecycle = options.captureLifecycle();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tconst ui = await options.loadInteractiveUi();\n\t\t\tif (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n\t\t\tawait ui.showReadyPlanMenu(ctx, {\n\t\t\t\t...lifecycle,\n\t\t\t\timplementationOutcome: options.implementationOutcome,\n\t\t\t\tgetExportDestination: () => options.getExportDestination(ctx),\n\t\t\t\timplementHere: () => options.implementHere(ctx),\n\t\t\t\timplementFresh: (signal) => freshAction(ctx, lifecycle, signal),\n\t\t\t\texportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),\n\t\t\t\tsave: () => options.save(ctx),\n\t\t\t\tstay: () => undefined,\n\t\t\t\texit: () => options.exitReady(ctx),\n\t\t\t});\n\t\t},\n\t};\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { exportStoredPlan, planExportDestination } from \"./plan-export.js\";\nimport { configuredPlanExportPath, type PlanModeSettings } from \"./settings.js\";\nimport type { PlanModeState } from \"./state.js\";\n\ninterface PlanExportControllerOptions {\n\tgetState(): PlanModeState;\n\tgetSettings(): PlanModeSettings;\n\tfinishReady(ctx: ExtensionContext): void;\n}\n\nexport function createPlanExportController(options: PlanExportControllerOptions) {\n\treturn {\n\t\texport(\n\t\t\tpath: string | undefined,\n\t\t\tctx: ExtensionContext,\n\t\t\tsignal: AbortSignal,\n\t\t\tisCurrent: () => boolean,\n\t\t) {\n\t\t\tconst state = options.getState();\n\t\t\treturn exportStoredPlan(\n\t\t\t\tstate,\n\t\t\t\tpath,\n\t\t\t\tctx,\n\t\t\t\t{\n\t\t\t\t\tsignal,\n\t\t\t\t\tisCurrent,\n\t\t\t\t\tgetState: options.getState,\n\t\t\t\t\tfinishReady: () => options.finishReady(ctx),\n\t\t\t\t},\n\t\t\t\tconfiguredPlanExportPath(options.getSettings()),\n\t\t\t);\n\t\t},\n\t\tgetDestination(ctx: ExtensionContext) {\n\t\t\treturn planExportDestination(configuredPlanExportPath(options.getSettings()), ctx.cwd);\n\t\t},\n\t};\n}\n", "import type { ExtensionAPI, ExtensionContext, Theme } from \"@earendil-works/pi-coding-agent\";\nimport { stripTerminalSequences, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport type { PlanModeState } from \"./state.js\";\n\nconst STATUS_KEY = \"plan-mode\";\nconst PLAN_WIDGET_KEY = \"plan-mode-plan\";\nconst BIDI_CONTROLS = /[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/gu;\n\nexport function updatePlanModeUi(\n\tctx: ExtensionContext,\n\tstate: PlanModeState,\n\ttoolSummary: () => string,\n) {\n\tctx.ui.setStatus(STATUS_KEY, formatStatus(state));\n\tlet lines: string[] | undefined;\n\tif (state.enabled && state.latestPlan) {\n\t\tlines = [\"Proposed plan ready\", \"Use /plan to implement, save, revise, or exit Plan mode.\"];\n\t} else if (state.enabled) {\n\t\tlines = [\n\t\t\t\"Plan mode: planning\",\n\t\t\ttoolSummary(),\n\t\t\t\"Finish with plan_mode_complete when decision-ready.\",\n\t\t];\n\t} else if (state.savedPlan) {\n\t\tlines = [\"Plan saved for later\", \"Use /plan to show, implement, or clear it.\"];\n\t} else if (state.activeImplementation) {\n\t\tlines = [\"Implementation plan active\", \"Use /plan to show, replace, or clear it.\"];\n\t}\n\n\tpublishPlanModeWidget(ctx, lines);\n}\n\nexport function renderPlanModeWidget(\n\tlines: readonly string[],\n\ttheme: Theme,\n\twidth: number,\n): string[] {\n\tconst renderWidth = Math.max(0, width);\n\treturn [\n\t\ttheme.fg(\"borderMuted\", \"\u2500\".repeat(renderWidth)),\n\t\t...lines.map((line) => truncateToWidth(sanitizePlanModeWidgetLine(line), renderWidth, \"\")),\n\t];\n}\n\nexport function sanitizePlanModeWidgetLine(value: string): string {\n\tlet text = \"\";\n\tfor (const character of stripTerminalSequences(value).replace(BIDI_CONTROLS, \"\")) {\n\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\tconst isControl = codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n\t\ttext += isControl ? \" \" : character;\n\t}\n\treturn text;\n}\n\nexport function clearPlanModeUi(ctx: ExtensionContext) {\n\tctx.ui.setStatus(STATUS_KEY, undefined);\n\tctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);\n}\n\nexport function showStoredPlan(pi: ExtensionAPI, ctx: ExtensionContext, state: PlanModeState) {\n\tconst readyPlan = state.enabled ? state.latestPlan?.trim() : undefined;\n\tconst savedPlan = state.savedPlan?.plan.trim();\n\tif (savedPlan && (ctx.mode === \"print\" || ctx.mode === \"json\")) {\n\t\tthrow new Error(\"Saved plan display is unavailable in print/JSON mode. Use TUI or RPC.\");\n\t}\n\tconst activePlan = state.activeImplementation?.plan.trim();\n\tconst plan = readyPlan ?? savedPlan ?? activePlan;\n\tif (!plan) {\n\t\tctx.ui.notify(\n\t\t\t\"No completed plan is available. Use /plan finalize when planning is complete.\",\n\t\t\t\"info\",\n\t\t);\n\t\treturn;\n\t}\n\tconst title = readyPlan\n\t\t? \"Proposed Plan\"\n\t\t: savedPlan\n\t\t\t? \"Saved Plan\"\n\t\t\t: \"Active Implementation Plan\";\n\tshowPlanModePlan(pi, ctx, title, plan);\n}\n\nexport function showPlanModePlan(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\ttitle: string,\n\tplan: string,\n) {\n\ttry {\n\t\tpi.sendMessage(\n\t\t\t{\n\t\t\t\tcustomType: \"proposed-plan\",\n\t\t\t\tcontent: `**${title}**\\n\\n${plan}`,\n\t\t\t\tdisplay: true,\n\t\t\t},\n\t\t\t{ triggerTurn: false },\n\t\t);\n\t} catch (error: unknown) {\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tctx.ui.notify(`Unable to show completed plan: ${detail}`, \"error\");\n\t}\n}\n\nexport function planModeStatusText(state: PlanModeState, toolSummary: () => string) {\n\tif (state.enabled) {\n\t\tif (state.latestPlan) {\n\t\t\treturn `Plan mode is active and a proposed plan is ready. ${toolSummary()}`;\n\t\t}\n\t\treturn `Plan mode is active. ${toolSummary()} Explore, ask, and finish with plan_mode_complete when decision-ready.`;\n\t}\n\tif (state.savedPlan) return \"A plan is saved for later.\";\n\tif (state.activeImplementation) return \"An implementation plan is active.\";\n\treturn \"Plan mode is off.\";\n}\n\nfunction publishPlanModeWidget(ctx: ExtensionContext, lines: readonly string[] | undefined) {\n\tif (!lines) {\n\t\tctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);\n\t\treturn;\n\t}\n\tif (ctx.mode !== \"tui\") {\n\t\tctx.ui.setWidget(PLAN_WIDGET_KEY, [...lines]);\n\t\treturn;\n\t}\n\n\tconst snapshot = [...lines];\n\tctx.ui.setWidget(PLAN_WIDGET_KEY, (_tui, theme) => ({\n\t\trender: (width) => renderPlanModeWidget(snapshot, theme, width),\n\t\tinvalidate: () => {},\n\t}));\n}\n\nfunction formatStatus(state: PlanModeState) {\n\tif (state.enabled) {\n\t\tif (state.awaitingAction || state.latestPlan) return \"plan ready\";\n\t\treturn \"plan active\";\n\t}\n\tif (state.savedPlan) return \"plan saved\";\n\tif (state.activeImplementation) return \"plan implementing\";\n\treturn undefined;\n}\n", "import { PLAN_MODE_COMPLETE_TOOL_NAME } from \"./completion-tool.js\";\nimport { PLAN_MODE_QUESTION_TOOL_NAME } from \"./question-tool.js\";\nimport { unique } from \"./tool-selection.js\";\n\nexport const REQUIRED_PLAN_MODE_TOOL_NAMES = [\n\tPLAN_MODE_QUESTION_TOOL_NAME,\n\tPLAN_MODE_COMPLETE_TOOL_NAME,\n] as const;\n\nexport function planModeHelperToolsAvailable(toolNames: readonly string[]) {\n\tconst active = new Set(toolNames);\n\treturn REQUIRED_PLAN_MODE_TOOL_NAMES.every((name) => active.has(name));\n}\n\nexport function assertPlanModeHelperToolsAvailable(toolNames: readonly string[]) {\n\tif (planModeHelperToolsAvailable(toolNames)) return;\n\tthrow new Error(\n\t\t\"plan_mode_question and plan_mode_complete are unavailable; include them in the active tool allowlist or leave the restrictive tool mode before starting Plan mode\",\n\t);\n}\n\nexport function withRequiredPlanModeTools(toolNames: string[]) {\n\treturn unique([\n\t\t...withoutRequiredPlanModeTools(toolNames),\n\t\tPLAN_MODE_QUESTION_TOOL_NAME,\n\t\tPLAN_MODE_COMPLETE_TOOL_NAME,\n\t]);\n}\n\nexport function withoutRequiredPlanModeTools(toolNames: string[]) {\n\treturn toolNames.filter(\n\t\t(toolName) =>\n\t\t\ttoolName !== PLAN_MODE_QUESTION_TOOL_NAME && toolName !== PLAN_MODE_COMPLETE_TOOL_NAME,\n\t);\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\n\nexport function savedPlanBlocksNewWorkflow(ctx: ExtensionContext, hasSavedPlan: boolean) {\n\tif (!hasSavedPlan) return false;\n\tconst message =\n\t\t\"A plan is saved for later. Implement or clear it before starting another Plan-mode workflow.\";\n\tif (!ctx.hasUI) throw new Error(message);\n\tctx.ui.notify(message, \"warning\");\n\treturn true;\n}\n\nexport async function preflightSavedPlanImplementation(\n\tctx: ExtensionContext,\n\tisCurrent: () => boolean,\n) {\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") {\n\t\tthrow new Error(\"Saved plan implementation is unavailable in print/JSON mode. Use TUI or RPC.\");\n\t}\n\tconst model = ctx.model;\n\tif (!model) {\n\t\tctx.ui.notify(\"Unable to implement saved plan: no model is selected.\", \"warning\");\n\t\treturn false;\n\t}\n\tlet auth: Awaited<ReturnType<ExtensionContext[\"modelRegistry\"][\"getApiKeyAndHeaders\"]>>;\n\ttry {\n\t\tauth = await ctx.modelRegistry.getApiKeyAndHeaders(model);\n\t} catch (error: unknown) {\n\t\tif (!isCurrent()) return false;\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tctx.ui.notify(`Unable to implement saved plan: ${detail}`, \"error\");\n\t\treturn false;\n\t}\n\tif (!isCurrent()) return false;\n\tif (!auth.ok) {\n\t\tctx.ui.notify(`Unable to implement saved plan: ${auth.error}`, \"warning\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n", "import {\n\tnormalizePlanModeCompletion,\n\tPLAN_MODE_COMPLETE_TOOL_NAME,\n\tplanFromCompletionDetails,\n} from \"./completion-tool.js\";\nimport {\n\tIMPLEMENTATION_PLAN_RETENTIONS,\n\ttype ImplementationPlanRetention,\n\tPLAN_MODE_THINKING_LEVELS,\n\ttype PlanModeFixedThinkingLevel,\n} from \"./settings.js\";\n\nexport type PlanCompletionSource = typeof PLAN_MODE_COMPLETE_TOOL_NAME | \"legacy_proposed_plan\";\n\nexport interface ActiveImplementationPlan {\n\tid: string;\n\tplan: string;\n\tsource: PlanCompletionSource;\n\tstartedAt: number;\n\tretention?: ImplementationPlanRetention;\n}\n\nexport interface SavedPlan {\n\tplan: string;\n\tsource: PlanCompletionSource;\n}\n\nexport interface PlanModeState {\n\tenabled: boolean;\n\tlatestPlan?: string;\n\tlatestPlanSource?: PlanCompletionSource;\n\tawaitingAction: boolean;\n\tsavedPlan?: SavedPlan;\n\tactiveImplementation?: ActiveImplementationPlan;\n\tselectedToolNames?: string[];\n\tselectedToolKeys?: string[];\n\tpreviousThinkingLevel?: PlanModeFixedThinkingLevel;\n\tappliedThinkingLevel?: PlanModeFixedThinkingLevel;\n\tmanualThinkingLevel?: PlanModeFixedThinkingLevel;\n}\n\ntype SessionEntry = {\n\ttype?: string;\n\tcustomType?: string;\n\tdata?: unknown;\n\tmessage?: {\n\t\trole?: string;\n\t\ttoolName?: string;\n\t\tdetails?: unknown;\n\t};\n};\n\nexport function restorePlanModeState(entries: unknown[], stateEntryType: string): PlanModeState {\n\tconst branch = entries as SessionEntry[];\n\tlet stateEntryIndex = -1;\n\tfor (let index = branch.length - 1; index >= 0; index -= 1) {\n\t\tconst candidate = branch[index];\n\t\tif (candidate?.type === \"custom\" && candidate.customType === stateEntryType) {\n\t\t\tstateEntryIndex = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst entry = branch[stateEntryIndex];\n\tif (!isRecord(entry?.data)) return { enabled: false, awaitingAction: false };\n\n\tconst enabled = entry.data.enabled === true;\n\tconst persistedSource = enabled ? planCompletionSource(entry.data.latestPlanSource) : undefined;\n\tconst persistedPlan = enabled ? normalizePersistedPlan(entry.data.latestPlan) : undefined;\n\tconst recoveredPlan =\n\t\tenabled && !persistedPlan ? latestCompletionPlan(branch.slice(stateEntryIndex + 1)) : undefined;\n\tconst latestPlan = persistedPlan ?? recoveredPlan;\n\tconst activeImplementation = enabled\n\t\t? undefined\n\t\t: normalizeActiveImplementation(entry.data.activeImplementation);\n\tconst savedPlan =\n\t\tenabled || activeImplementation ? undefined : normalizeSavedPlan(entry.data.savedPlan);\n\treturn {\n\t\tenabled,\n\t\tlatestPlan,\n\t\tlatestPlanSource: enabled\n\t\t\t? ((persistedPlan ? persistedSource : undefined) ??\n\t\t\t\t(recoveredPlan ? PLAN_MODE_COMPLETE_TOOL_NAME : undefined))\n\t\t\t: undefined,\n\t\tawaitingAction: enabled && latestPlan !== undefined,\n\t\tsavedPlan,\n\t\tactiveImplementation,\n\t\tselectedToolNames: stringArray(entry.data.selectedToolNames),\n\t\tselectedToolKeys: stringArray(entry.data.selectedToolKeys),\n\t\tpreviousThinkingLevel: enabled\n\t\t\t? fixedThinkingLevel(entry.data.previousThinkingLevel)\n\t\t\t: undefined,\n\t\tappliedThinkingLevel: enabled ? fixedThinkingLevel(entry.data.appliedThinkingLevel) : undefined,\n\t\tmanualThinkingLevel: enabled ? fixedThinkingLevel(entry.data.manualThinkingLevel) : undefined,\n\t};\n}\n\nfunction normalizeSavedPlan(value: unknown): SavedPlan | undefined {\n\tif (!isRecord(value)) return undefined;\n\tconst source = planCompletionSource(value.source);\n\tconst normalized = normalizePlanModeCompletion({ plan: value.plan });\n\tif (!source || !normalized.ok) return undefined;\n\treturn { plan: normalized.plan, source };\n}\n\nfunction normalizeActiveImplementation(value: unknown): ActiveImplementationPlan | undefined {\n\tif (!isRecord(value)) return undefined;\n\tconst id =\n\t\ttypeof value.id === \"string\" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value.id)\n\t\t\t? value.id\n\t\t\t: undefined;\n\tconst source = planCompletionSource(value.source);\n\tconst normalized = normalizePlanModeCompletion({ plan: value.plan });\n\tconst startedAt =\n\t\ttypeof value.startedAt === \"number\" &&\n\t\tNumber.isSafeInteger(value.startedAt) &&\n\t\tvalue.startedAt >= 0\n\t\t\t? value.startedAt\n\t\t\t: undefined;\n\tif (!id || !source || !normalized.ok || startedAt === undefined) return undefined;\n\tconst retention = IMPLEMENTATION_PLAN_RETENTIONS.includes(\n\t\tvalue.retention as ImplementationPlanRetention,\n\t)\n\t\t? (value.retention as ImplementationPlanRetention)\n\t\t: \"keep\";\n\treturn { id, plan: normalized.plan, source, startedAt, retention };\n}\n\nfunction normalizePersistedPlan(value: unknown) {\n\tconst normalized = normalizePlanModeCompletion({ plan: value });\n\treturn normalized.ok ? normalized.plan : undefined;\n}\n\nfunction latestCompletionPlan(entries: SessionEntry[]) {\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst message = entries[index]?.message;\n\t\tif (message?.role !== \"toolResult\" || message.toolName !== PLAN_MODE_COMPLETE_TOOL_NAME) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst plan = planFromCompletionDetails(message.details);\n\t\tif (plan) return plan;\n\t}\n\treturn undefined;\n}\n\nfunction planCompletionSource(value: unknown): PlanCompletionSource | undefined {\n\treturn value === PLAN_MODE_COMPLETE_TOOL_NAME || value === \"legacy_proposed_plan\"\n\t\t? value\n\t\t: undefined;\n}\n\nfunction fixedThinkingLevel(value: unknown): PlanModeFixedThinkingLevel | undefined {\n\treturn typeof value === \"string\" &&\n\t\tvalue !== \"inherit\" &&\n\t\tPLAN_MODE_THINKING_LEVELS.includes(value as (typeof PLAN_MODE_THINKING_LEVELS)[number])\n\t\t? (value as PlanModeFixedThinkingLevel)\n\t\t: undefined;\n}\n\nfunction stringArray(value: unknown) {\n\treturn Array.isArray(value) && value.every((item): item is string => typeof item === \"string\")\n\t\t? Array.from(new Set(value))\n\t\t: undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\n\nexport const WORKFLOW_MUTEX_CHANNEL = \"workflow:mutex:v1\";\nexport const AGENT_WORKFLOW_GROUP = \"agent-workflow\";\n\nexport type WorkflowMutexOwner = symbol;\n\ninterface WorkflowMutexAttemptV1 {\n\tsession: object;\n\tgroup: string;\n\tbusy: boolean;\n}\n\nexport class WorkflowMutex {\n\tprivate session: object | undefined;\n\tprivate readonly heldGroups = new Map<string, WorkflowMutexOwner>();\n\tprivate generation = 0;\n\n\tconstructor(private readonly pi: Pick<ExtensionAPI, \"events\">) {\n\t\tpi.events.on(WORKFLOW_MUTEX_CHANNEL, (payload) => {\n\t\t\tthis.answer(payload);\n\t\t});\n\t}\n\n\tbindSession(session: object): void {\n\t\tthis.generation += 1;\n\t\tthis.heldGroups.clear();\n\t\tthis.session = session;\n\t}\n\n\tunbindSession(session: object): void {\n\t\tif (this.session !== session) return;\n\t\tthis.generation += 1;\n\t\tthis.heldGroups.clear();\n\t\tthis.session = undefined;\n\t}\n\n\tacquire(group = AGENT_WORKFLOW_GROUP): WorkflowMutexOwner | undefined {\n\t\tconst session = this.session;\n\t\tconst generation = this.generation;\n\t\tif (!session || this.heldGroups.has(group)) return undefined;\n\n\t\tconst attempt: WorkflowMutexAttemptV1 = { session, group, busy: false };\n\t\ttry {\n\t\t\tthis.pi.events.emit(WORKFLOW_MUTEX_CHANNEL, attempt);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (\n\t\t\tthis.session !== session ||\n\t\t\tthis.generation !== generation ||\n\t\t\tattempt.session !== session ||\n\t\t\tattempt.group !== group ||\n\t\t\tattempt.busy !== false ||\n\t\t\tthis.heldGroups.has(group)\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst owner = Symbol(group);\n\t\tthis.heldGroups.set(group, owner);\n\t\treturn owner;\n\t}\n\n\tisOwner(owner: WorkflowMutexOwner | undefined, group = AGENT_WORKFLOW_GROUP): boolean {\n\t\treturn owner !== undefined && this.heldGroups.get(group) === owner;\n\t}\n\n\trelease(owner: WorkflowMutexOwner | undefined, group = AGENT_WORKFLOW_GROUP): void {\n\t\tif (!this.isOwner(owner, group)) return;\n\t\tthis.heldGroups.delete(group);\n\t}\n\n\tprivate answer(payload: unknown): void {\n\t\ttry {\n\t\t\tif (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) return;\n\t\t\tconst attempt = payload as Partial<WorkflowMutexAttemptV1>;\n\t\t\tif (attempt.session !== this.session) return;\n\t\t\tif (attempt.group !== AGENT_WORKFLOW_GROUP) return;\n\t\t\tif (typeof attempt.busy !== \"boolean\") return;\n\t\t\tif (!this.heldGroups.has(attempt.group)) return;\n\t\t\tattempt.busy = true;\n\t\t} catch {\n\t\t\t// Protocol listeners must ignore unusual objects without interrupting sibling listeners.\n\t\t}\n\t}\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,aAAa;AACtB,SAAS,UAAU,eAAe;;;ACIlC,IAAM,2BAAiE;AAAA,EACtE,EAAE,OAAO,SAAS,OAAO,SAAS,aAAa,2CAA2C;AAAA,EAC1F,EAAE,OAAO,QAAQ,OAAO,QAAQ,aAAa,wCAAwC;AAAA,EACrF,EAAE,OAAO,YAAY,OAAO,YAAY,aAAa,2BAA2B;AAAA,EAChF,EAAE,OAAO,aAAa,OAAO,aAAa,aAAa,wCAAwC;AAAA,EAC/F,EAAE,OAAO,QAAQ,OAAO,QAAQ,aAAa,oCAAoC;AAAA,EACjF,EAAE,OAAO,UAAU,OAAO,UAAU,aAAa,4CAA4C;AAAA,EAC7F,EAAE,OAAO,QAAQ,OAAO,QAAQ,aAAa,+CAA+C;AAAA,EAC5F,EAAE,OAAO,OAAO,OAAO,OAAO,aAAa,+CAA+C;AAAA,EAC1F;AAAA,IACC,OAAO;AAAA,IACP,OAAO;AAAA,IACP,a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