@narumitw/pi-plan-mode 0.58.0 → 0.58.1
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/dist/chunks/{chunk-QHHHBTDO.js → chunk-HF7ZEYIC.js} +29 -111
- package/dist/chunks/chunk-HF7ZEYIC.js.map +7 -0
- package/dist/chunks/{interactive-ui-UNJGC2RQ.js → interactive-ui-UK7IGPOE.js} +13 -41
- package/dist/chunks/interactive-ui-UK7IGPOE.js.map +7 -0
- package/dist/index.ts +25 -82
- package/dist/index.ts.map +2 -2
- package/package.json +50 -51
- package/src/active-implementation-menu.ts +57 -60
- package/src/command.ts +22 -22
- package/src/completion-tool.ts +53 -56
- package/src/extension-runtime.ts +5 -5
- package/src/finalization-request.ts +40 -44
- package/src/fresh-handoff-coordinator.ts +38 -41
- package/src/fresh-implementation.ts +293 -310
- package/src/implementation-models.ts +25 -30
- package/src/implementation-retention.ts +109 -123
- package/src/message-transform.ts +218 -252
- package/src/mode-contract.ts +46 -49
- package/src/plan-action-controller.ts +134 -155
- package/src/plan-action-menus.ts +390 -408
- package/src/plan-export-controller.ts +23 -28
- package/src/plan-export-screen.ts +13 -13
- package/src/plan-export.ts +85 -102
- package/src/plan-launch-menu.ts +119 -119
- package/src/plan-mode.ts +2017 -2098
- package/src/presentation.ts +84 -108
- package/src/prompt.ts +1 -1
- package/src/question-tool.ts +239 -267
- package/src/required-tools.ts +15 -19
- package/src/saved-plan-menu.ts +82 -84
- package/src/saved-plan-preflight.ts +29 -33
- package/src/settings-menu.ts +470 -513
- package/src/settings.ts +393 -452
- package/src/state.ts +167 -198
- package/src/tool-policy.ts +634 -699
- package/src/tool-selection.ts +39 -44
- package/src/workflow-mutex.ts +66 -66
- package/dist/chunks/chunk-QHHHBTDO.js.map +0 -7
- package/dist/chunks/interactive-ui-UNJGC2RQ.js.map +0 -7
package/dist/index.ts.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/plan-mode.ts", "../src/command.ts", "../src/extension-runtime.ts", "../src/finalization-request.ts", "../src/fresh-handoff-coordinator.ts", "../src/fresh-implementation.ts", "../src/prompt.ts", "../src/mode-contract.ts", "../src/state.ts", "../src/plan-action-controller.ts", "../src/plan-export-controller.ts", "../src/presentation.ts", "../src/required-tools.ts", "../src/saved-plan-preflight.ts", "../src/workflow-mutex.ts"],
|
|
4
|
-
"sourcesContent": ["import { randomUUID } from \"node:crypto\";\nimport { watch } from \"node:fs\";\nimport { basename, dirname } from \"node:path\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tInputEvent,\n\tInputSource,\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 { createDeferredFreshHandoffCoordinator } from \"./fresh-handoff-coordinator.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 {\n\tcreatePlanActionController,\n\ttype FreshImplementationTiming,\n} 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} 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 ImplementationPlanRetention,\n\ttype PlanModeSettings,\n\ttype PlanModeSettingsPatch,\n\tplanModeSettingsPath,\n\treadPlanModeSettings,\n\ttype UpdatePlanModeSettingsOptions,\n\tupdatePlanModeSettings,\n} from \"./settings.js\";\nimport {\n\ttype ImplementationRuntimeSelection,\n\ttype PlanCompletionSource,\n\ttype PlanModeState,\n\ttype PlanModeWorkflowToolPolicy,\n\trestorePlanModeState,\n} from \"./state.js\";\nimport {\n\tcanSelectToolInPlanMode,\n\tclassifyPlanModeTool,\n\tfindBlockedCommandSegment,\n\tfindBlockedPowerShellCommandSegment,\n\treadCommand,\n} from \"./tool-policy.js\";\nimport { compareTools, snapshotPlanModeSelectedNames, toolPolicyLabel } 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 RECOVERED_RUNTIME_ADMISSION_INPUT_MESSAGE_TYPE = \"plan-mode-recovered-input\";\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}\ninterface DeferredFreshImplementation {\n\tctx: ExtensionContext;\n\tsourceSession: object;\n\tmenuGeneration: number;\n\tworkflowGeneration: number;\n\tworkflowOwner: WorkflowMutexOwner | undefined;\n\tenabled: boolean;\n\tplan: string;\n\tsource: PlanCompletionSource;\n\tsavedPlan: PlanModeState[\"savedPlan\"];\n\tretention: ImplementationPlanRetention;\n\truntime: ImplementationRuntimeSelection | undefined;\n\tmenuIsCurrent(): boolean;\n}\ninterface PendingWorkflowToolPolicy {\n\tgeneration: number;\n\tmode: \"resolve\" | \"revalidate\";\n}\ntype ImplementationRuntimeApplicationResult = \"ready\" | \"blocked\" | \"stale\";\ninterface ActiveImplementationRuntimeApplication {\n\tsessionManager: ExtensionContext[\"sessionManager\"];\n\tcompletion: Promise<ImplementationRuntimeApplicationResult>;\n\tdrainOnShutdown: boolean;\n\tholdForAdmission: boolean;\n}\ninterface QueuedRuntimeAdmissionInput {\n\tsessionManager: ExtensionContext[\"sessionManager\"];\n\ttext: string;\n\timages?: NonNullable<InputEvent[\"images\"]>;\n\tsource: InputSource;\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 workflowAllowedToolNames: string[] | undefined;\n\tlet pendingWorkflowToolPolicy: PendingWorkflowToolPolicy | undefined;\n\tlet publishedContractMode: PlanModeContract | undefined;\n\tlet modeContractsRelevant = false;\n\tlet readyPresentationIntent: ReadyPresentationIntent | undefined;\n\tlet latestCommandContext: ExtensionCommandContext | undefined;\n\tlet stagedFreshImplementation: DeferredFreshImplementation | undefined;\n\tconst deferredFreshHandoff = createDeferredFreshHandoffCoordinator();\n\tlet nextReadyPresentationNonce = 0;\n\tlet menuGeneration = 0;\n\tlet workflowGeneration = 0;\n\tlet refreshStateBeforeFirstAgentStart = false;\n\tlet activeImplementationRuntimeApplication: ActiveImplementationRuntimeApplication | undefined;\n\tlet pendingRuntimeAdmissionSession: object | undefined;\n\tlet queuedRuntimeAdmissionInputs: QueuedRuntimeAdmissionInput[] = [];\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\t// ExtensionContext.thinkingLevel was added after the supported Pi 0.80.6 floor.\n\t\t// ExtensionAPI has exposed the same runtime value throughout that compatibility range.\n\t\tgetThinkingLevel: () => pi.getThinkingLevel(),\n\t\tgetSettings: () => settings,\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\tif (command === \"settings\") {\n\t\t\t\tif (!ctx.hasUI) {\n\t\t\t\t\tthrow new Error(\"/plan settings requires TUI or RPC mode and is unavailable here.\");\n\t\t\t\t}\n\t\t\t\tconst lifecycle = captureMenuLifecycle();\n\t\t\t\tawait showSettings(ctx, lifecycle.signal, lifecycle.isCurrent);\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\tcancelDeferredFreshImplementation();\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\trefreshStateBeforeFirstAgentStart = event.reason === \"new\";\n\t\tpendingRuntimeAdmissionSession = undefined;\n\t\tqueuedRuntimeAdmissionInputs = [];\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\tpendingWorkflowToolPolicy = 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\t// A new session receives its setup entries after session_start, so its input gate refreshes\n\t\t// them. Resumed and forked sessions already have the intent and must apply it here because\n\t\t// extension-triggered custom-message turns bypass both input and before_agent_start.\n\t\tif (event.reason !== \"new\") await applyPendingImplementationRuntime(ctx);\n\t});\n\n\tpi.on(\"session_before_tree\", (event, ctx) => {\n\t\tif (runtimeAdmissionIsPending(ctx.sessionManager)) {\n\t\t\tif (ctx.hasUI) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Wait for fresh implementation startup to admit the pending prompts before changing branches.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { cancel: true };\n\t\t}\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\", async (_event, ctx) => {\n\t\tcancelDeferredFreshImplementation();\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\tpendingRuntimeAdmissionSession = undefined;\n\t\tqueuedRuntimeAdmissionInputs = [];\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\tawait applyPendingImplementationRuntime(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\tcancelDeferredFreshImplementation();\n\t\tconst shutdownSession = ctx.sessionManager;\n\t\tconst runtimeApplication =\n\t\t\tactiveImplementationRuntimeApplication?.sessionManager === shutdownSession &&\n\t\t\tactiveImplementationRuntimeApplication.drainOnShutdown\n\t\t\t\t? activeImplementationRuntimeApplication\n\t\t\t\t: undefined;\n\t\tconst queuedInputs = takeQueuedRuntimeAdmissionInputs(shutdownSession);\n\t\tfor (const queued of queuedInputs) {\n\t\t\tpi.sendMessage(\n\t\t\t\t{\n\t\t\t\t\tcustomType: RECOVERED_RUNTIME_ADMISSION_INPUT_MESSAGE_TYPE,\n\t\t\t\t\tcontent: runtimeAdmissionInputContent(queued),\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tdetails: { source: queued.source },\n\t\t\t\t},\n\t\t\t\t{ triggerTurn: false },\n\t\t\t);\n\t\t}\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\tpendingRuntimeAdmissionSession = undefined;\n\t\tqueuedRuntimeAdmissionInputs = [];\n\t\tworkflowAllowedToolNames = undefined;\n\t\tpendingWorkflowToolPolicy = undefined;\n\t\timplementationRetention.reset();\n\t\tif (runtimeApplication) await runtimeApplication.completion;\n\t\tif (currentSession !== undefined && currentSession !== shutdownSession) {\n\t\t\tworkflowMutex.unbindSession(shutdownSession);\n\t\t\treturn;\n\t\t}\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, ctx) => {\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 calledTool = toolByName(event.toolName);\n\t\tconst activeToolNames = new Set(safeGetActiveTools());\n\t\tif (!calledTool) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: activeToolNames.has(event.toolName)\n\t\t\t\t\t? `Plan mode blocks tool '${event.toolName}' because its safe policy metadata is unavailable.`\n\t\t\t\t\t: `Plan mode blocks tool '${event.toolName}' because it is not registered or active. Register and activate it before starting the next Plan workflow.`,\n\t\t\t};\n\t\t}\n\t\tif (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 built-in policy is blocked and settings cannot enable it.`,\n\t\t\t};\n\t\t}\n\t\tconst allowedToolNames = new Set(planModePolicyToolNames());\n\t\tif (!activeToolNames.has(event.toolName)) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: allowedToolNames.has(event.toolName)\n\t\t\t\t\t? `Plan mode blocks tool '${event.toolName}' because it was admitted to the active Plan workflow but is currently inactive. Reactivate it to continue without restarting.`\n\t\t\t\t\t: `Plan mode blocks tool '${event.toolName}' because it is registered but inactive. Activate it before starting the next Plan workflow.`,\n\t\t\t};\n\t\t}\n\t\tif (!allowedToolNames.has(event.toolName)) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: workflowDesiredToolNames().has(event.toolName)\n\t\t\t\t\t? `Plan mode blocks tool '${event.toolName}' because it was not available when the active Plan workflow froze its tool policy. Exit Plan mode, then start again after the tool is active.`\n\t\t\t\t\t: `Plan mode blocks tool '${event.toolName}' because it is not selected by the Plan policy. Exit Plan mode, then enable it with /plan tools or defaultPlanTools before starting again.`,\n\t\t\t};\n\t\t}\n\t\tif (event.toolName === \"bash\") {\n\t\t\tconst blocked = findBlockedCommandSegment(\n\t\t\t\treadCommand(event.input),\n\t\t\t\tsettings.safeSubcommands,\n\t\t\t\tctx.cwd,\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 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\tctx.cwd,\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\tresolvePendingWorkflowToolPolicy(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(\"input\", async (event, ctx) => {\n\t\trefreshStateForFirstPrompt(ctx);\n\t\tconst waitsForRuntimeAdmission =\n\t\t\tactiveImplementationRuntimeApplication?.sessionManager === ctx.sessionManager ||\n\t\t\tpendingRuntimeAdmissionSession === ctx.sessionManager;\n\t\tconst queuedInput = waitsForRuntimeAdmission\n\t\t\t? {\n\t\t\t\t\tsessionManager: ctx.sessionManager,\n\t\t\t\t\ttext: event.text,\n\t\t\t\t\t...(event.images ? { images: [...event.images] } : {}),\n\t\t\t\t\tsource: event.source,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tif (queuedInput) queuedRuntimeAdmissionInputs.push(queuedInput);\n\t\tconst result = await applyPendingImplementationRuntime(ctx, true);\n\t\tif (result !== \"ready\") {\n\t\t\tif (result === \"stale\" && queuedInput) removeQueuedRuntimeAdmissionInput(queuedInput);\n\t\t\treturn { action: \"handled\" };\n\t\t}\n\t\tif (queuedInput) return { action: \"handled\" };\n\t});\n\n\tpi.on(\"agent_start\", (_event, ctx) => {\n\t\tif (currentSession !== ctx.sessionManager) return;\n\t\tif (pendingRuntimeAdmissionSession === ctx.sessionManager) {\n\t\t\tpendingRuntimeAdmissionSession = undefined;\n\t\t}\n\t\tconst queuedInputs = takeQueuedRuntimeAdmissionInputs(ctx.sessionManager);\n\t\tfor (const queued of queuedInputs) {\n\t\t\tpi.sendUserMessage(runtimeAdmissionInputContent(queued), {\n\t\t\t\tdeliverAs: \"followUp\",\n\t\t\t\texpandPromptTemplates: queued.source !== \"extension\",\n\t\t\t});\n\t\t}\n\t});\n\n\tpi.on(\"before_agent_start\", (_event, ctx) => {\n\t\trefreshStateForFirstPrompt(ctx);\n\t\tif (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;\n\t\tif (state.latestPlan || state.awaitingAction) {\n\t\t\tcancelDeferredFreshImplementation();\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\tstagedFreshImplementation = 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\tconst request = stagedFreshImplementation;\n\t\t\tstagedFreshImplementation = undefined;\n\t\t\tif (request) armDeferredFreshImplementation(request);\n\t\t} catch (error: unknown) {\n\t\t\tstagedFreshImplementation = undefined;\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\tpendingImplementationRuntime: undefined,\n\t\t\t\tselectedToolNames: candidate.selectedToolNames,\n\t\t\t\tselectedToolKeys: candidate.selectedToolKeys,\n\t\t\t};\n\t\t\tbeginWorkflowToolPolicy();\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\tpendingImplementationRuntime: undefined,\n\t\t\tworkflowToolPolicy: 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\t\trestoredState.pendingImplementationRuntime !== 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\tpendingImplementationRuntime: undefined,\n\t\t\tworkflowToolPolicy: 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(\n\t\tctx: ExtensionContext,\n\t\tmenuIsCurrent: () => boolean,\n\t\truntime: ImplementationRuntimeSelection | undefined,\n\t\ttiming: FreshImplementationTiming,\n\t) {\n\t\tconst retention = configuredImplementationPlanRetention(settings);\n\t\tif (timing === \"immediate\") {\n\t\t\tawait startFreshImplementationFromState(ctx, {\n\t\t\t\tgetState: () => state,\n\t\t\t\tmenuIsCurrent,\n\t\t\t\tretention,\n\t\t\t\tstateEntryType: STATE_ENTRY_TYPE,\n\t\t\t\truntime,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst initialState = state;\n\t\tconst savedPlan = initialState.enabled ? undefined : initialState.savedPlan;\n\t\tconst plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();\n\t\tconst source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;\n\t\tif (!plan || !source || !menuIsCurrent()) return;\n\t\tstagedFreshImplementation = {\n\t\t\tctx,\n\t\t\tsourceSession: ctx.sessionManager,\n\t\t\tmenuGeneration,\n\t\t\tworkflowGeneration,\n\t\t\tworkflowOwner,\n\t\t\tenabled: initialState.enabled,\n\t\t\tplan,\n\t\t\tsource,\n\t\t\tsavedPlan,\n\t\t\tretention,\n\t\t\truntime: runtime\n\t\t\t\t? {\n\t\t\t\t\t\t...(runtime.model ? { model: { ...runtime.model } } : {}),\n\t\t\t\t\t\t...(runtime.thinkingLevel ? { thinkingLevel: runtime.thinkingLevel } : {}),\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t\tmenuIsCurrent,\n\t\t};\n\t}\n\n\tfunction armDeferredFreshImplementation(request: DeferredFreshImplementation) {\n\t\tdeferredFreshHandoff.schedule(\n\t\t\tasync (taskIsCurrent) => {\n\t\t\t\tconst isCurrent = () => taskIsCurrent() && deferredFreshImplementationIsCurrent(request);\n\t\t\t\tif (!isCurrent()) return;\n\t\t\t\tawait startFreshImplementationFromState(request.ctx, {\n\t\t\t\t\tgetState: () => state,\n\t\t\t\t\tmenuIsCurrent: isCurrent,\n\t\t\t\t\tretention: request.retention,\n\t\t\t\t\tstateEntryType: STATE_ENTRY_TYPE,\n\t\t\t\t\truntime: request.runtime,\n\t\t\t\t});\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tif (!deferredFreshImplementationIsCurrent(request)) return;\n\t\t\t\ttry {\n\t\t\t\t\trequest.ctx.ui.notify(\n\t\t\t\t\t\t`Unable to start the deferred fresh implementation: ${terminalErrorDetail(error)}`,\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\t// The source context can become stale while a detached failure is reported.\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t}\n\n\tfunction deferredFreshImplementationIsCurrent(request: DeferredFreshImplementation) {\n\t\tif (\n\t\t\tcurrentSession !== request.sourceSession ||\n\t\t\tmenuGeneration !== request.menuGeneration ||\n\t\t\tworkflowGeneration !== request.workflowGeneration ||\n\t\t\tworkflowOwner !== request.workflowOwner ||\n\t\t\t!request.menuIsCurrent() ||\n\t\t\tstate.enabled !== request.enabled\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\treturn request.enabled\n\t\t\t? workflowMutex.isOwner(request.workflowOwner) &&\n\t\t\t\t\tstate.latestPlan === request.plan &&\n\t\t\t\t\tstate.latestPlanSource === request.source\n\t\t\t: state.savedPlan === request.savedPlan;\n\t}\n\n\tfunction cancelDeferredFreshImplementation() {\n\t\tstagedFreshImplementation = undefined;\n\t\tdeferredFreshHandoff.cancel();\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\tpendingImplementationRuntime: 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\tworkflowToolPolicy: 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\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\trestoreWorkflowToolPolicy(state.workflowToolPolicy);\n\t\t\t\tpublishModeContract(\"plan\", ctx);\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\tconst activeToolNames = new Set(safeGetActiveTools());\n\t\tconst initialSelectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());\n\t\tconst retainsInactiveSelection =\n\t\t\tstate.selectedToolNames !== undefined ||\n\t\t\tstate.selectedToolKeys !== undefined ||\n\t\t\tsettings.defaultPlanTools !== undefined;\n\t\tconst retainedInactiveNames = retainsInactiveSelection\n\t\t\t? initialSelectedNames\n\t\t\t: new Set<string>();\n\t\tconst registeredNames = new Set(tools.map((tool) => tool.name));\n\t\tconst pendingNames = Array.from(retainedInactiveNames).filter(\n\t\t\t(name) => !registeredNames.has(name),\n\t\t);\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\tactiveToolNames.has(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\tconst pending = pendingNames\n\t\t\t\t\t.filter((name) => selectedNames.has(name))\n\t\t\t\t\t.map(terminalToolName);\n\t\t\t\tconst visiblePending = pending.slice(0, 3);\n\t\t\t\tconst pendingSuffix =\n\t\t\t\t\tpending.length > visiblePending.length\n\t\t\t\t\t\t? `, +${pending.length - visiblePending.length} more`\n\t\t\t\t\t\t: \"\";\n\t\t\t\treturn [\n\t\t\t\t\t`Plan policy will allow: ${allowed.length > 0 ? allowed.join(\", \") : \"none\"}.`,\n\t\t\t\t\t...(pending.length > 0\n\t\t\t\t\t\t? [`Pending registration: ${visiblePending.join(\", \")}${pendingSuffix}.`]\n\t\t\t\t\t\t: []),\n\t\t\t\t].join(\" \");\n\t\t\t},\n\t\t\ttools: [\n\t\t\t\t...tools.map((tool) => {\n\t\t\t\t\tconst selectable = canSelectToolInPlanMode(tool);\n\t\t\t\t\tconst active = activeToolNames.has(tool.name);\n\t\t\t\t\tconst retained = retainedInactiveNames.has(tool.name);\n\t\t\t\t\tconst policy = active\n\t\t\t\t\t\t? toolPolicyLabel(tool)\n\t\t\t\t\t\t: retained\n\t\t\t\t\t\t\t? \"not active yet; retained for first-request resolution\"\n\t\t\t\t\t\t\t: \"not active in this Pi session\";\n\t\t\t\t\tconst description = tool.description ?? \"No description available\";\n\t\t\t\t\treturn {\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\tdescription: `${policy} \u00B7 ${description}`,\n\t\t\t\t\t\tsearchText: [policy, description].join(\" \"),\n\t\t\t\t\t\tdisabled: !selectable || !active,\n\t\t\t\t\t\tdisabledReason: !active\n\t\t\t\t\t\t\t? retained\n\t\t\t\t\t\t\t\t? \"Not active yet; retained and resolved before the first request\"\n\t\t\t\t\t\t\t\t: \"Not active in Pi; Plan mode will not activate it\"\n\t\t\t\t\t\t\t: selectable\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: \"Blocked by Plan-mode policy\",\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t\t...pendingNames.map((name) => {\n\t\t\t\t\tconst label = terminalToolName(name);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tlabel,\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"pending registration \u00B7 Retained and resolved before the first Plan request\",\n\t\t\t\t\t\tsearchText: `${label} pending registration retained first Plan request`,\n\t\t\t\t\t\tdisabled: true,\n\t\t\t\t\t\tdisabledReason:\n\t\t\t\t\t\t\t\"Not registered yet; Plan mode will not activate it and will resolve it before the first request\",\n\t\t\t\t\t};\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 = Array.from(\n\t\t\t\t\tnew Set(\n\t\t\t\t\t\tnames.filter((name) => activeToolNames.has(name) || retainedInactiveNames.has(name)),\n\t\t\t\t\t),\n\t\t\t\t);\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: safeGetActiveTools(),\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\tcancelDeferredFreshImplementation();\n\t\tworkflowGeneration += 1;\n\t\tpendingWorkflowToolPolicy = undefined;\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 planModePolicyToolNames() {\n\t\tif (state.enabled) return workflowAllowedToolNames ?? [];\n\t\treturn computePlanModePolicyToolNames();\n\t}\n\n\tfunction workflowDesiredToolNames() {\n\t\tconst policy = state.workflowToolPolicy;\n\t\tif (!state.enabled || !policy) return new Set<string>();\n\t\treturn new Set(\n\t\t\tpolicy.kind === \"automatic\" ? automaticPlanModeToolNames() : (policy.desiredNames ?? []),\n\t\t);\n\t}\n\n\tfunction beginWorkflowToolPolicy() {\n\t\tconst kind = toolPolicySelectionIsExplicit() ? \"explicit\" : \"automatic\";\n\t\tconst desiredNames = desiredPlanModeToolNames();\n\t\tconst allowedNames = resolvePlanModePolicyToolNames(desiredNames);\n\t\tconst policy: PlanModeWorkflowToolPolicy = {\n\t\t\tkind,\n\t\t\t...(kind === \"explicit\" ? { desiredNames } : {}),\n\t\t\tallowedNames,\n\t\t\tresolved: false,\n\t\t};\n\t\tstate = { ...state, workflowToolPolicy: policy };\n\t\tpendingWorkflowToolPolicy = { generation: workflowGeneration, mode: \"resolve\" };\n\t\tworkflowAllowedToolNames = allowedNames;\n\t}\n\n\tfunction resolvePendingWorkflowToolPolicy(ctx: ExtensionContext) {\n\t\tconst pending = pendingWorkflowToolPolicy;\n\t\tif (!pending) return;\n\t\tif (\n\t\t\tpending.generation !== workflowGeneration ||\n\t\t\t!state.enabled ||\n\t\t\t!workflowMutex.isOwner(workflowOwner)\n\t\t) {\n\t\t\tpendingWorkflowToolPolicy = undefined;\n\t\t\treturn;\n\t\t}\n\t\tconst policy = state.workflowToolPolicy;\n\t\tconst expectedResolved = pending.mode === \"revalidate\";\n\t\tif (!policy || policy.resolved !== expectedResolved) {\n\t\t\tpendingWorkflowToolPolicy = undefined;\n\t\t\treturn;\n\t\t}\n\t\tconst allowedNames =\n\t\t\tpending.mode === \"resolve\"\n\t\t\t\t? resolveWorkflowToolPolicy(policy)\n\t\t\t\t: revalidateFrozenWorkflowToolPolicy(policy);\n\t\tconst policyChanged = !policy.resolved || !arrayEquals(policy.allowedNames, allowedNames);\n\t\tworkflowAllowedToolNames = allowedNames;\n\t\tstate = {\n\t\t\t...state,\n\t\t\tworkflowToolPolicy: { ...policy, allowedNames, resolved: true },\n\t\t};\n\t\tpendingWorkflowToolPolicy = undefined;\n\t\tif (policyChanged) persistState();\n\t\tupdateUi(ctx);\n\t}\n\n\tfunction toolPolicySelectionIsExplicit() {\n\t\treturn (\n\t\t\tstate.selectedToolNames !== undefined ||\n\t\t\tstate.selectedToolKeys !== undefined ||\n\t\t\tsettings.defaultPlanTools !== undefined\n\t\t);\n\t}\n\n\tfunction desiredPlanModeToolNames() {\n\t\tconst tools = activePlanPolicyTools();\n\t\treturn Array.from(snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()));\n\t}\n\n\tfunction automaticPlanModeToolNames() {\n\t\treturn Array.from(snapshotPlanModeSelectedNames(activePlanPolicyTools(), {}));\n\t}\n\n\tfunction resolveWorkflowToolPolicy(policy: PlanModeWorkflowToolPolicy) {\n\t\treturn resolvePlanModePolicyToolNames(\n\t\t\tpolicy.kind === \"automatic\" ? automaticPlanModeToolNames() : (policy.desiredNames ?? []),\n\t\t);\n\t}\n\n\tfunction revalidateFrozenWorkflowToolPolicy(policy: PlanModeWorkflowToolPolicy) {\n\t\tconst currentlyAllowed = new Set(\n\t\t\tpolicy.kind === \"automatic\"\n\t\t\t\t? resolvePlanModePolicyToolNames(automaticPlanModeToolNames())\n\t\t\t\t: resolvePlanModePolicyToolNames(policy.allowedNames),\n\t\t);\n\t\treturn policy.allowedNames.filter((name) => currentlyAllowed.has(name));\n\t}\n\n\tfunction restoreWorkflowToolPolicy(policy: PlanModeWorkflowToolPolicy | undefined) {\n\t\tlet nextPolicy: PlanModeWorkflowToolPolicy;\n\t\tif (!policy) {\n\t\t\tconst kind = toolPolicySelectionIsExplicit() ? \"explicit\" : \"automatic\";\n\t\t\tconst desiredNames = desiredPlanModeToolNames();\n\t\t\tnextPolicy = {\n\t\t\t\tkind,\n\t\t\t\t...(kind === \"explicit\" ? { desiredNames } : {}),\n\t\t\t\tallowedNames: resolvePlanModePolicyToolNames(desiredNames),\n\t\t\t\tresolved: true,\n\t\t\t};\n\t\t} else if (policy.resolved) {\n\t\t\tnextPolicy = policy;\n\t\t} else {\n\t\t\tnextPolicy = {\n\t\t\t\t...policy,\n\t\t\t\tallowedNames: resolveWorkflowToolPolicy(policy),\n\t\t\t};\n\t\t}\n\t\tstate = { ...state, workflowToolPolicy: nextPolicy };\n\t\tworkflowAllowedToolNames = nextPolicy.resolved\n\t\t\t? revalidateFrozenWorkflowToolPolicy(nextPolicy)\n\t\t\t: nextPolicy.allowedNames;\n\t\tpendingWorkflowToolPolicy = {\n\t\t\tgeneration: workflowGeneration,\n\t\t\tmode: nextPolicy.resolved ? \"revalidate\" : \"resolve\",\n\t\t};\n\t\treturn !workflowToolPoliciesEqual(policy, nextPolicy);\n\t}\n\n\tfunction workflowToolPoliciesEqual(\n\t\tleft: PlanModeWorkflowToolPolicy | undefined,\n\t\tright: PlanModeWorkflowToolPolicy,\n\t) {\n\t\treturn (\n\t\t\tleft?.kind === right.kind &&\n\t\t\tleft.resolved === right.resolved &&\n\t\t\tarrayEquals(left.allowedNames, right.allowedNames) &&\n\t\t\tarrayEquals(left.desiredNames ?? [], right.desiredNames ?? [])\n\t\t);\n\t}\n\n\tfunction arrayEquals(left: readonly string[], right: readonly string[]) {\n\t\treturn left.length === right.length && left.every((value, index) => value === right[index]);\n\t}\n\n\tfunction computePlanModePolicyToolNames() {\n\t\treturn resolvePlanModePolicyToolNames(desiredPlanModeToolNames());\n\t}\n\n\tfunction resolvePlanModePolicyToolNames(desiredNames: readonly string[]) {\n\t\tconst selectedNames = new Set(desiredNames);\n\t\treturn activePlanPolicyTools()\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(safeGetActiveTools());\n\t\treturn selectableTools().filter((tool) => activeNames.has(tool.name));\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 runtimeAdmissionIsPending(sessionManager: ExtensionContext[\"sessionManager\"]) {\n\t\treturn (\n\t\t\tactiveImplementationRuntimeApplication?.sessionManager === sessionManager ||\n\t\t\tpendingRuntimeAdmissionSession === sessionManager ||\n\t\t\tqueuedRuntimeAdmissionInputs.some((queued) => queued.sessionManager === sessionManager)\n\t\t);\n\t}\n\n\tfunction takeQueuedRuntimeAdmissionInputs(sessionManager: ExtensionContext[\"sessionManager\"]) {\n\t\tconst matching: QueuedRuntimeAdmissionInput[] = [];\n\t\tconst remaining: QueuedRuntimeAdmissionInput[] = [];\n\t\tfor (const queued of queuedRuntimeAdmissionInputs) {\n\t\t\tif (queued.sessionManager === sessionManager) matching.push(queued);\n\t\t\telse remaining.push(queued);\n\t\t}\n\t\tqueuedRuntimeAdmissionInputs = remaining;\n\t\treturn matching;\n\t}\n\n\tfunction removeQueuedRuntimeAdmissionInput(queuedInput: QueuedRuntimeAdmissionInput) {\n\t\tconst index = queuedRuntimeAdmissionInputs.indexOf(queuedInput);\n\t\tif (index >= 0) queuedRuntimeAdmissionInputs.splice(index, 1);\n\t}\n\n\tfunction runtimeAdmissionInputContent(queued: QueuedRuntimeAdmissionInput) {\n\t\treturn queued.images?.length\n\t\t\t? [{ type: \"text\" as const, text: queued.text }, ...queued.images]\n\t\t\t: queued.text;\n\t}\n\n\tfunction refreshStateForFirstPrompt(ctx: ExtensionContext) {\n\t\tif (!refreshStateBeforeFirstAgentStart) return;\n\t\trefreshStateBeforeFirstAgentStart = false;\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\tupdateUi(ctx);\n\t}\n\n\tasync function applyPendingImplementationRuntime(\n\t\tctx: ExtensionContext,\n\t\tholdForAdmission = false,\n\t): Promise<ImplementationRuntimeApplicationResult> {\n\t\tconst session = ctx.sessionManager;\n\t\tconst activeApplication = activeImplementationRuntimeApplication;\n\t\tif (activeApplication?.sessionManager === session) {\n\t\t\tif (holdForAdmission) activeApplication.holdForAdmission = true;\n\t\t\treturn activeApplication.completion;\n\t\t}\n\n\t\tconst intent = state.enabled ? undefined : state.pendingImplementationRuntime;\n\t\tif (!intent) return \"ready\";\n\t\tconst generation = menuGeneration;\n\t\tconst isCurrent = () =>\n\t\t\tcurrentSession === session && generation === menuGeneration && !menuController.signal.aborted;\n\t\tconst notifyCurrent = (message: string) => {\n\t\t\tif (!isCurrent()) return;\n\t\t\ttry {\n\t\t\t\tctx.ui.notify(message, \"warning\");\n\t\t\t} catch {\n\t\t\t\t// The session can become stale while an asynchronous runtime application settles.\n\t\t\t}\n\t\t};\n\t\tlet application!: ActiveImplementationRuntimeApplication;\n\t\tconst completion = Promise.resolve()\n\t\t\t.then(async (): Promise<ImplementationRuntimeApplicationResult> => {\n\t\t\t\tif (!isCurrent()) return \"stale\";\n\t\t\t\tconst pendingState = state;\n\t\t\t\tconst previousThinkingLevel = pi.getThinkingLevel();\n\n\t\t\t\tconst applyThinking = () => {\n\t\t\t\t\tif (!intent.thinkingLevel) return;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpi.setThinkingLevel(intent.thinkingLevel);\n\t\t\t\t\t\tconst effectiveLevel = pi.getThinkingLevel();\n\t\t\t\t\t\tif (effectiveLevel !== intent.thinkingLevel) {\n\t\t\t\t\t\t\tnotifyCurrent(\n\t\t\t\t\t\t\t\t`Implementation thinking ${intent.thinkingLevel} is unsupported by the destination model; Pi is using ${effectiveLevel}.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tnotifyCurrent(\n\t\t\t\t\t\t\t`Implementation thinking ${intent.thinkingLevel} could not be applied: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default will continue.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tif (intent.model) {\n\t\t\t\t\tlet model: ReturnType<ExtensionContext[\"modelRegistry\"][\"find\"]>;\n\t\t\t\t\tlet resolutionFailed = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tmodel = ctx.modelRegistry.find(intent.model.provider, intent.model.modelId);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tnotifyCurrent(\n\t\t\t\t\t\t\t`Implementation model ${terminalModelReference(intent.model)} could not be resolved: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tresolutionFailed = true;\n\t\t\t\t\t\tmodel = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tif (!model && !resolutionFailed) {\n\t\t\t\t\t\tnotifyCurrent(\n\t\t\t\t\t\t\t`Implementation model ${terminalModelReference(intent.model)} is no longer available. The destination default model will continue.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (model) {\n\t\t\t\t\t\tlet authenticated = false;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\t\t\t\tif (!isCurrent()) return \"stale\";\n\t\t\t\t\t\t\tif (auth.ok) authenticated = true;\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tnotifyCurrent(\n\t\t\t\t\t\t\t\t\t`Implementation model ${terminalModelReference(intent.model)} could not be authenticated: ${safeTerminalText(auth.error)}. The destination default model will continue.`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\t\tnotifyCurrent(\n\t\t\t\t\t\t\t\t`Implementation model ${terminalModelReference(intent.model)} could not be authenticated: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!isCurrent()) return \"stale\";\n\t\t\t\t\t\tif (authenticated) {\n\t\t\t\t\t\t\tlet applied = false;\n\t\t\t\t\t\t\tlet applicationFailed = false;\n\t\t\t\t\t\t\tapplication.drainOnShutdown = true;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tapplied = await pi.setModel(model);\n\t\t\t\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\t\t\t\tapplicationFailed = true;\n\t\t\t\t\t\t\t\t\tnotifyCurrent(\n\t\t\t\t\t\t\t\t\t\t`Implementation model ${terminalModelReference(intent.model)} could not be applied: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\tapplication.drainOnShutdown = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!isCurrent()) return \"stale\";\n\t\t\t\t\t\t\tif (!applied && !applicationFailed) {\n\t\t\t\t\t\t\t\tnotifyCurrent(\n\t\t\t\t\t\t\t\t\t`Implementation model ${terminalModelReference(intent.model)} could not be applied after authentication changed. The destination default model will continue.`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!isCurrent()) return \"stale\";\n\t\t\t\tapplyThinking();\n\t\t\t\tif (!isCurrent()) return \"stale\";\n\n\t\t\t\tstate = { ...state, pendingImplementationRuntime: undefined };\n\t\t\t\ttry {\n\t\t\t\t\tpersistState();\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tstate = pendingState;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (pi.getThinkingLevel() !== previousThinkingLevel) {\n\t\t\t\t\t\t\tpi.setThinkingLevel(previousThinkingLevel);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Keep the durable intent pending even if a runtime rollback is unavailable.\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpersistState();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// SessionManager mutates its in-memory branch before a disk append can fail.\n\t\t\t\t\t\t// A best-effort rollback entry keeps that branch aligned with durable pending state.\n\t\t\t\t\t}\n\t\t\t\t\tnotifyCurrent(\n\t\t\t\t\t\t`Unable to apply fresh implementation settings because their one-shot state could not be consumed: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The implementation request was not sent; retry after session persistence is available.`,\n\t\t\t\t\t);\n\t\t\t\t\treturn \"blocked\";\n\t\t\t\t}\n\t\t\t\tif (application.holdForAdmission) pendingRuntimeAdmissionSession = session;\n\t\t\t\treturn \"ready\";\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tif (activeImplementationRuntimeApplication === application) {\n\t\t\t\t\tactiveImplementationRuntimeApplication = undefined;\n\t\t\t\t}\n\t\t\t});\n\t\tapplication = {\n\t\t\tsessionManager: session,\n\t\t\tcompletion,\n\t\t\tdrainOnShutdown: false,\n\t\t\tholdForAdmission,\n\t\t};\n\t\tactiveImplementationRuntimeApplication = application;\n\t\treturn completion;\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 previousPendingWorkflowToolPolicy = pendingWorkflowToolPolicy;\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\tpendingWorkflowToolPolicy = 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\tpendingWorkflowToolPolicy = 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\tconst policyChanged = state.enabled\n\t\t\t\t? restoreWorkflowToolPolicy(state.workflowToolPolicy)\n\t\t\t\t: false;\n\t\t\tif (!state.enabled) {\n\t\t\t\tworkflowAllowedToolNames = undefined;\n\t\t\t\tpendingWorkflowToolPolicy = undefined;\n\t\t\t}\n\t\t\tif (policyChanged) persistState();\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\tpendingWorkflowToolPolicy = previousPendingWorkflowToolPolicy;\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\tpendingWorkflowToolPolicy = 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 terminalToolName(value: string) {\n\t\tconst safe = safeTerminalText(value) || \"(unnamed tool)\";\n\t\treturn safe.length > 120 ? `${safe.slice(0, 119)}\u2026` : safe;\n\t}\n\n\tfunction terminalModelReference(model: { provider: string; modelId: string }) {\n\t\tconst safe = safeTerminalText(`${model.provider}/${model.modelId}`) || \"(unnamed model)\";\n\t\treturn safe.length > 160 ? `${safe.slice(0, 159)}\u2026` : safe;\n\t}\n\n\tfunction terminalErrorDetail(error: unknown) {\n\t\tconst safe = safeTerminalText(error instanceof Error ? error.message : String(error));\n\t\tif (!safe) return \"unknown error\";\n\t\treturn safe.length > 500 ? `${safe.slice(0, 499)}\u2026` : safe;\n\t}\n\n\tfunction safeTerminalText(value: string) {\n\t\treturn [...stripVTControlCharacters(value)]\n\t\t\t.map((character) => {\n\t\t\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\t\t\treturn codePoint <= 0x1f ||\n\t\t\t\t\t(codePoint >= 0x7f && codePoint <= 0x9f) ||\n\t\t\t\t\t(codePoint >= 0x202a && codePoint <= 0x202e) ||\n\t\t\t\t\t(codePoint >= 0x2066 && codePoint <= 0x2069)\n\t\t\t\t\t? \" \"\n\t\t\t\t\t: 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: \"settings\", label: \"settings\", description: \"Open Plan mode settings\" },\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", "export interface DeferredFreshHandoffDependencies {\n\tschedule(callback: () => void): unknown;\n\tcancel(handle: unknown): void;\n}\n\nexport interface DeferredFreshHandoffCoordinator {\n\tschedule(\n\t\trun: (isCurrent: () => boolean) => Promise<void>,\n\t\tonError: (error: unknown) => void,\n\t): void;\n\tcancel(): void;\n}\n\nconst defaultDependencies: DeferredFreshHandoffDependencies = {\n\tschedule: (callback) => setTimeout(callback, 0),\n\tcancel: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n};\n\nexport function createDeferredFreshHandoffCoordinator(\n\tdependencies: DeferredFreshHandoffDependencies = defaultDependencies,\n): DeferredFreshHandoffCoordinator {\n\tlet generation = 0;\n\tlet pending: { generation: number; handle: unknown } | undefined;\n\n\tconst cancel = () => {\n\t\tgeneration += 1;\n\t\tif (!pending) return;\n\t\tdependencies.cancel(pending.handle);\n\t\tpending = undefined;\n\t};\n\n\treturn {\n\t\tschedule(run, onError) {\n\t\t\tcancel();\n\t\t\tconst taskGeneration = generation;\n\t\t\tconst handle = dependencies.schedule(() => {\n\t\t\t\tif (pending?.generation !== taskGeneration || generation !== taskGeneration) return;\n\t\t\t\tpending = undefined;\n\t\t\t\tconst isCurrent = () => generation === taskGeneration;\n\t\t\t\tvoid Promise.resolve()\n\t\t\t\t\t.then(() => run(isCurrent))\n\t\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\t\tif (!isCurrent()) return;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tonError(error);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// Detached error reporting must not create another unhandled rejection.\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t});\n\t\t\tpending = { generation: taskGeneration, handle };\n\t\t},\n\t\tcancel,\n\t};\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { stripVTControlCharacters } from \"node:util\";\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 {\n\ttype ImplementationRuntimeSelection,\n\tisPendingImplementationModelIdentifier,\n\tMAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH,\n\ttype PendingImplementationRuntime,\n\ttype PlanCompletionSource,\n\ttype PlanModeState,\n\trestorePlanModeState,\n} 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\truntime?: ImplementationRuntimeSelection;\n\tisCurrent(): boolean;\n}\n\ninterface FreshImplementationFromStateOptions {\n\tgetState(): PlanModeState;\n\tmenuIsCurrent(): boolean;\n\tretention: ImplementationPlanRetention;\n\tstateEntryType: string;\n\truntime?: ImplementationRuntimeSelection;\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\truntime: options.runtime,\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))) return { kind: \"rejected\" };\n\tif (!request.isCurrent()) return { kind: \"stale\" };\n\n\tconst usesConversationHistory = request.retention === \"clear-on-start\";\n\tconst pendingImplementationRuntime = pendingRuntimeIntent(request.runtime);\n\tconst activeImplementation = usesConversationHistory\n\t\t? undefined\n\t\t: {\n\t\t\t\tid: randomUUID(),\n\t\t\t\tplan: request.plan,\n\t\t\t\tsource: request.source,\n\t\t\t\tstartedAt: Date.now(),\n\t\t\t\tretention: request.retention,\n\t\t\t};\n\tconst destinationState: PlanModeState | undefined =\n\t\tactiveImplementation || pendingImplementationRuntime\n\t\t\t? {\n\t\t\t\t\tenabled: false,\n\t\t\t\t\tawaitingAction: false,\n\t\t\t\t\t...(activeImplementation ? { activeImplementation } : {}),\n\t\t\t\t\t...(pendingImplementationRuntime ? { pendingImplementationRuntime } : {}),\n\t\t\t\t}\n\t\t\t: undefined;\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\tconst reportKickoffFailure = (detail: string) => {\n\t\t\t\t\tkickoffError = detail;\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: ${detail}. 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: ${detail}. 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: ${detail}. 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};\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\treportKickoffFailure(safeErrorDetail(error));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (pendingImplementationRuntime) {\n\t\t\t\t\tconst runtimeStatus = destinationRuntimeConsumptionStatus(\n\t\t\t\t\t\treplacementCtx,\n\t\t\t\t\t\trequest.stateEntryType,\n\t\t\t\t\t);\n\t\t\t\t\tif (runtimeStatus !== \"consumed\") {\n\t\t\t\t\t\treportKickoffFailure(\n\t\t\t\t\t\t\truntimeStatus === \"pending\"\n\t\t\t\t\t\t\t\t? \"fresh implementation settings could not be consumed\"\n\t\t\t\t\t\t\t\t: \"fresh implementation settings could not be verified as consumed\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\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, request: FreshImplementationRequest) {\n\tconst requestedModel = request.runtime?.model;\n\tlet model = ctx.model;\n\tif (requestedModel) {\n\t\tif (\n\t\t\t!isPendingImplementationModelIdentifier(requestedModel.provider) ||\n\t\t\t!isPendingImplementationModelIdentifier(requestedModel.modelId)\n\t\t) {\n\t\t\tnotifyCurrent(\n\t\t\t\tctx,\n\t\t\t\trequest,\n\t\t\t\t`Unable to implement the plan: implementation model provider and ID must each contain 1-${MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH} characters. Choose another model and retry.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t\tconst isCurrentModel =\n\t\t\tctx.model?.provider === requestedModel.provider && ctx.model.id === requestedModel.modelId;\n\t\tif (!isCurrentModel) {\n\t\t\ttry {\n\t\t\t\tmodel = ctx.modelRegistry.find(requestedModel.provider, requestedModel.modelId);\n\t\t\t} catch (error: unknown) {\n\t\t\t\tnotifyCurrent(\n\t\t\t\t\tctx,\n\t\t\t\t\trequest,\n\t\t\t\t\t`Unable to implement the plan: ${safeErrorDetail(error)}`,\n\t\t\t\t\t\"error\",\n\t\t\t\t);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (!model) {\n\t\t\tnotifyCurrent(\n\t\t\t\tctx,\n\t\t\t\trequest,\n\t\t\t\t`Unable to implement the plan: implementation model ${safeModelReference(requestedModel)} is no longer available. Choose another model and retry.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (!model) {\n\t\tnotifyCurrent(ctx, request, \"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\tnotifyCurrent(ctx, request, `Unable to implement the plan: ${safeErrorDetail(error)}`, \"error\");\n\t\treturn false;\n\t}\n\tif (!request.isCurrent()) return false;\n\tif (!auth.ok) {\n\t\tnotifyCurrent(\n\t\t\tctx,\n\t\t\trequest,\n\t\t\trequestedModel\n\t\t\t\t? `Unable to implement the plan with ${safeModelReference(model)}: ${safeErrorDetail(auth.error)}. Choose another model or configure authentication, then retry.`\n\t\t\t\t: `Unable to implement the plan: ${safeErrorDetail(auth.error)}`,\n\t\t\t\"warning\",\n\t\t);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction notifyCurrent(\n\tctx: Pick<ExtensionContext, \"ui\">,\n\trequest: FreshImplementationRequest,\n\tmessage: string,\n\tlevel: \"info\" | \"warning\" | \"error\",\n) {\n\tif (request.isCurrent()) safeNotify(ctx, message, level);\n}\n\nfunction pendingRuntimeIntent(\n\tselection: ImplementationRuntimeSelection | undefined,\n): PendingImplementationRuntime | undefined {\n\tif (!selection?.model && !selection?.thinkingLevel) return undefined;\n\treturn {\n\t\tversion: 1,\n\t\t...(selection.model\n\t\t\t? { model: { provider: selection.model.provider, modelId: selection.model.modelId } }\n\t\t\t: {}),\n\t\t...(selection.thinkingLevel ? { thinkingLevel: selection.thinkingLevel } : {}),\n\t};\n}\n\nfunction safeModelReference(model: { provider: string; id?: string; modelId?: string }) {\n\treturn safeErrorDetail(`${model.provider}/${model.modelId ?? model.id ?? \"unknown\"}`);\n}\n\nfunction destinationRuntimeConsumptionStatus(\n\tctx: ReplacementContext,\n\tstateEntryType: string,\n): \"consumed\" | \"pending\" | \"unavailable\" {\n\ttry {\n\t\treturn restorePlanModeState(ctx.sessionManager.getBranch(), stateEntryType)\n\t\t\t.pendingImplementationRuntime\n\t\t\t? \"pending\"\n\t\t\t: \"consumed\";\n\t} catch {\n\t\treturn \"unavailable\";\n\t}\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[...stripVTControlCharacters(detail)]\n\t\t\t.map((character) => {\n\t\t\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\t\t\treturn codePoint <= 0x1f ||\n\t\t\t\t\t(codePoint >= 0x7f && codePoint <= 0x9f) ||\n\t\t\t\t\t(codePoint >= 0x202a && codePoint <= 0x202e) ||\n\t\t\t\t\t(codePoint >= 0x2066 && codePoint <= 0x2069)\n\t\t\t\t\t? \" \"\n\t\t\t\t\t: 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 {\n\tnormalizePlanModeCompletion,\n\tPLAN_MODE_COMPLETE_TOOL_NAME,\n\tplanFromCompletionDetails,\n} from \"./completion-tool.js\";\nimport {\n\ttype ImplementationModelOverride,\n\tisPendingImplementationModelIdentifier,\n} from \"./implementation-models.js\";\nimport {\n\tIMPLEMENTATION_PLAN_RETENTIONS,\n\ttype ImplementationPlanRetention,\n\tPLAN_MODE_THINKING_LEVELS,\n\ttype PlanModeFixedThinkingLevel,\n} from \"./settings.js\";\n\nexport type { ImplementationModelOverride } from \"./implementation-models.js\";\nexport {\n\tisPendingImplementationModelIdentifier,\n\tMAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH,\n} from \"./implementation-models.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 ImplementationRuntimeSelection {\n\tmodel?: ImplementationModelOverride;\n\tthinkingLevel?: PlanModeFixedThinkingLevel;\n}\n\nexport interface PendingImplementationRuntime extends ImplementationRuntimeSelection {\n\tversion: 1;\n}\n\nexport interface PlanModeWorkflowToolPolicy {\n\tkind: \"automatic\" | \"explicit\";\n\tdesiredNames?: string[];\n\tallowedNames: string[];\n\tresolved: boolean;\n}\n\nexport interface PlanModeState {\n\tenabled: boolean;\n\tlatestPlan?: string;\n\tlatestPlanSource?: PlanCompletionSource;\n\tawaitingAction: boolean;\n\tsavedPlan?: SavedPlan;\n\tactiveImplementation?: ActiveImplementationPlan;\n\tpendingImplementationRuntime?: PendingImplementationRuntime;\n\tselectedToolNames?: string[];\n\tselectedToolKeys?: string[];\n\tworkflowToolPolicy?: PlanModeWorkflowToolPolicy;\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\tconst pendingImplementationRuntime = enabled\n\t\t? undefined\n\t\t: normalizePendingImplementationRuntime(entry.data.pendingImplementationRuntime);\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\tpendingImplementationRuntime,\n\t\tselectedToolNames: stringArray(entry.data.selectedToolNames),\n\t\tselectedToolKeys: stringArray(entry.data.selectedToolKeys),\n\t\tworkflowToolPolicy: enabled\n\t\t\t? normalizeWorkflowToolPolicy(entry.data.workflowToolPolicy)\n\t\t\t: undefined,\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 normalizeWorkflowToolPolicy(value: unknown): PlanModeWorkflowToolPolicy | undefined {\n\tif (value === undefined) return undefined;\n\tconst denied: PlanModeWorkflowToolPolicy = {\n\t\tkind: \"automatic\",\n\t\tallowedNames: [],\n\t\tresolved: true,\n\t};\n\tif (!isRecord(value)) return denied;\n\tconst kind = value.kind === \"automatic\" || value.kind === \"explicit\" ? value.kind : undefined;\n\tconst allowedNames = stringArray(value.allowedNames);\n\tif (!kind || !allowedNames || typeof value.resolved !== \"boolean\") return denied;\n\tif (kind === \"automatic\") {\n\t\treturn { kind, allowedNames, resolved: value.resolved };\n\t}\n\tconst desiredNames = stringArray(value.desiredNames);\n\tif (!desiredNames) return denied;\n\treturn { kind, desiredNames, allowedNames, resolved: value.resolved };\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 normalizePendingImplementationRuntime(\n\tvalue: unknown,\n): PendingImplementationRuntime | undefined {\n\tif (!isRecord(value) || value.version !== 1) return undefined;\n\tif (\n\t\tObject.keys(value).some(\n\t\t\t(key) => key !== \"version\" && key !== \"model\" && key !== \"thinkingLevel\",\n\t\t)\n\t) {\n\t\treturn undefined;\n\t}\n\tlet model: ImplementationModelOverride | undefined;\n\tif (value.model !== undefined) {\n\t\tif (\n\t\t\t!isRecord(value.model) ||\n\t\t\tObject.keys(value.model).some((key) => key !== \"provider\" && key !== \"modelId\")\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (\n\t\t\t!isPendingImplementationModelIdentifier(value.model.provider) ||\n\t\t\t!isPendingImplementationModelIdentifier(value.model.modelId)\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tmodel = { provider: value.model.provider, modelId: value.model.modelId };\n\t}\n\tconst thinkingLevel =\n\t\tvalue.thinkingLevel === undefined ? undefined : fixedThinkingLevel(value.thinkingLevel);\n\tif (value.thinkingLevel !== undefined && !thinkingLevel) return undefined;\n\tif (!model && !thinkingLevel) return undefined;\n\treturn {\n\t\tversion: 1,\n\t\t...(model ? { model } : {}),\n\t\t...(thinkingLevel ? { thinkingLevel } : {}),\n\t};\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 { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport {\n\tfindAvailableImplementationModel,\n\tsnapshotAvailableImplementationModels,\n} from \"./implementation-models.js\";\nimport type { PlanExportDestination } from \"./plan-export.js\";\nimport {\n\tconfiguredImplementationModel,\n\tconfiguredImplementationThinkingLevel,\n\ttype PlanModeFixedThinkingLevel,\n\ttype PlanModeSettings,\n} from \"./settings.js\";\nimport type { ImplementationRuntimeSelection, PlanModeState } from \"./state.js\";\n\ntype InteractiveUi = typeof import(\"./interactive-ui.js\");\n\ninterface MenuLifecycle {\n\tsignal: AbortSignal;\n\tisCurrent(): boolean;\n}\n\nexport type FreshImplementationTiming = \"immediate\" | \"after-settled\";\n\ninterface PlanActionControllerOptions {\n\tloadInteractiveUi(): Promise<InteractiveUi>;\n\tgetState(): PlanModeState;\n\tcaptureLifecycle(): MenuLifecycle;\n\tstatusText(): string;\n\tgetThinkingLevel(): PlanModeFixedThinkingLevel | undefined;\n\tgetSettings(): PlanModeSettings;\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(\n\t\tctx: ExtensionContext,\n\t\tisCurrent: () => boolean,\n\t\truntime: ImplementationRuntimeSelection | undefined,\n\t\ttiming: FreshImplementationTiming,\n\t): 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 configuredDefaults = (): ImplementationRuntimeSelection => {\n\t\tconst settings = options.getSettings();\n\t\tconst model = configuredImplementationModel(settings);\n\t\tconst thinkingLevel = configuredImplementationThinkingLevel(settings);\n\t\treturn {\n\t\t\t...(model ? { model: { ...model } } : {}),\n\t\t\t...(thinkingLevel ? { thinkingLevel } : {}),\n\t\t};\n\t};\n\tconst effectiveDefaults = (ctx: ExtensionContext): ImplementationRuntimeSelection => {\n\t\tconst configured = configuredDefaults();\n\t\tconst availableModel = findAvailableImplementationModel(\n\t\t\tsnapshotAvailableImplementationModels(ctx),\n\t\t\tconfigured.model,\n\t\t);\n\t\tif (configured.model && !availableModel) {\n\t\t\tctx.ui.notify(\n\t\t\t\t\"The configured fresh implementation model is unavailable; using the planning model.\",\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\t\tconst planModel = ctx.model\n\t\t\t? { provider: ctx.model.provider, modelId: ctx.model.id }\n\t\t\t: undefined;\n\t\tconst model = availableModel\n\t\t\t? { provider: availableModel.provider, modelId: availableModel.id }\n\t\t\t: planModel;\n\t\tconst thinkingLevel = configured.thinkingLevel ?? options.getThinkingLevel();\n\t\treturn {\n\t\t\t...(model ? { model } : {}),\n\t\t\t...(thinkingLevel ? { thinkingLevel } : {}),\n\t\t};\n\t};\n\tconst freshAction = (\n\t\tctx: ExtensionContext,\n\t\tlifecycle: MenuLifecycle,\n\t\tsignal: AbortSignal,\n\t\truntime: ImplementationRuntimeSelection | undefined,\n\t\ttiming: FreshImplementationTiming,\n\t) => {\n\t\tif (signal.aborted) return;\n\t\tconst isCurrent =\n\t\t\ttiming === \"after-settled\"\n\t\t\t\t? lifecycle.isCurrent\n\t\t\t\t: () => lifecycle.isCurrent() && !signal.aborted;\n\t\treturn options.implementFresh(ctx, isCurrent, runtime, timing);\n\t};\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) =>\n\t\t\t\t\tfreshAction(ctx, lifecycle, signal, effectiveDefaults(ctx), \"immediate\"),\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\tplanThinkingLevel: options.getThinkingLevel(),\n\t\t\t\timplementationDefaults: configuredDefaults(),\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: (runtime, signal) =>\n\t\t\t\t\tfreshAction(ctx, lifecycle, signal, runtime, \"immediate\"),\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\tplanThinkingLevel: options.getThinkingLevel(),\n\t\t\t\timplementationDefaults: configuredDefaults(),\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: (runtime, signal) =>\n\t\t\t\t\tfreshAction(ctx, lifecycle, signal, runtime, \"after-settled\"),\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 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;AAClC,SAAS,4BAAAC,iCAAgC;;;ACGzC,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,YAAY,OAAO,YAAY,aAAa,0BAA0B;AAAA,EAC/E,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,aAAa;AAAA,EACd;AACD;AAEO,SAAS,sBAAsB,gBAA4D;AACjG,QAAM,SAA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AAE,KAAK;AACvE,WAAO,KAAK,SAAS,MAAM,GAAG,KAAK,MAAM,GAAG,GAAG,CAAC,WAAM;AAAA,EACvD;AAEA,WAAS,oBAAoB,OAAgB;AAC5C,UAAM,OAAO,iBAAiB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpF,QAAI,CAAC,KAAM,QAAO;AAClB,WAAO,KAAK,SAAS,MAAM,GAAG,KAAK,MAAM,GAAG,GAAG,CAAC,WAAM;AAAA,EACvD;AAEA,WAAS,iBAAiB,OAAe;AACxC,WAAO,CAAC,GAAGC,0BAAyB,KAAK,CAAC,EACxC,IAAI,CAAC,cAAc;AACnB,YAAM,YAAY,UAAU,YAAY,CAAC,KAAK;AAC9C,aAAO,aAAa,MAClB,aAAa,OAAQ,aAAa,OAClC,aAAa,QAAU,aAAa,QACpC,aAAa,QAAU,aAAa,OACnC,MACA;AAAA,IACJ,CAAC,EACA,KAAK,EAAE,EACP,KAAK;AAAA,EACR;AACD;",
|
|
4
|
+
"sourcesContent": ["import { randomUUID } from \"node:crypto\";\nimport { watch } from \"node:fs\";\nimport { basename, dirname } from \"node:path\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport type {\n ExtensionAPI,\n ExtensionCommandContext,\n ExtensionContext,\n InputEvent,\n InputSource,\n} from \"@earendil-works/pi-coding-agent\";\nimport { completePlanArguments } from \"./command.js\";\nimport {\n normalizePlanModeCompletion,\n PLAN_MODE_COMPLETE_PARAMS,\n PLAN_MODE_COMPLETE_TOOL_NAME,\n planModeCompleted,\n renderPlanModeCompletion,\n} from \"./completion-tool.js\";\nimport { isStaleExtensionContextError } from \"./extension-runtime.js\";\nimport {\n createFinalizationRequestCoordinator,\n FINALIZE_PLAN_PROMPT,\n type FinalizationRunOutcome,\n RETRY_FINALIZE_PLAN_PROMPT,\n} from \"./finalization-request.js\";\nimport { createDeferredFreshHandoffCoordinator } from \"./fresh-handoff-coordinator.js\";\nimport {\n formatHistoryImplementationPrompt,\n formatImplementationHandoff,\n formatTransferredPlanPrompt,\n startFreshImplementationFromState,\n} from \"./fresh-implementation.js\";\nimport {\n createImplementationRetentionCoordinator,\n implementationRetentionPreview,\n} from \"./implementation-retention.js\";\nimport {\n invalidPlanMessage,\n latestAssistantStopReason,\n latestAssistantText,\n messageTextContent,\n parseProposedPlan,\n} from \"./message-transform.js\";\nimport {\n createModeContractMessage,\n hasModeContractArtifact,\n latestModeContract,\n MODE_CONTRACT_MESSAGE_TYPE,\n type PlanModeContract,\n reconcileModeContract,\n} from \"./mode-contract.js\";\nimport { createPlanActionController, type FreshImplementationTiming } from \"./plan-action-controller.js\";\nimport { createPlanExportController } from \"./plan-export-controller.js\";\nimport {\n clearPlanModeUi,\n planModeStatusText as formatPlanModeStatusText,\n showStoredPlan,\n updatePlanModeUi,\n} from \"./presentation.js\";\nimport {\n answerPlanModeQuestions,\n normalizePlanModeQuestionParams,\n PLAN_MODE_QUESTION_PARAMS,\n PLAN_MODE_QUESTION_TOOL_NAME,\n planModeQuestionCancelled,\n} from \"./question-tool.js\";\nimport { assertPlanModeHelperToolsAvailable, planModeHelperToolsAvailable } from \"./required-tools.js\";\nimport { preflightSavedPlanImplementation, savedPlanBlocksNewWorkflow } from \"./saved-plan-preflight.js\";\nimport {\n awaitPlanModeSettingsWrites,\n configuredImplementationPlanRetention,\n configuredPlanModeToggleShortcut,\n configuredThinkingLevel,\n type ImplementationPlanRetention,\n type PlanModeSettings,\n type PlanModeSettingsPatch,\n planModeSettingsPath,\n readPlanModeSettings,\n type UpdatePlanModeSettingsOptions,\n updatePlanModeSettings,\n} from \"./settings.js\";\nimport {\n type ImplementationRuntimeSelection,\n type PlanCompletionSource,\n type PlanModeState,\n type PlanModeWorkflowToolPolicy,\n restorePlanModeState,\n} from \"./state.js\";\nimport {\n canSelectToolInPlanMode,\n classifyPlanModeTool,\n findBlockedCommandSegment,\n findBlockedPowerShellCommandSegment,\n readCommand,\n} from \"./tool-policy.js\";\nimport { compareTools, snapshotPlanModeSelectedNames, toolPolicyLabel } 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 RECOVERED_RUNTIME_ADMISSION_INPUT_MESSAGE_TYPE = \"plan-mode-recovered-input\";\nconst BLOCKED_MUTATING_TOOLS = new Set([\"edit\", \"write\", \"update_plan\"]);\nconst DEFAULT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\"];\ninterface ReadyPresentationIntent {\n nonce: number;\n plan: string;\n source: PlanCompletionSource;\n}\ninterface DeferredFreshImplementation {\n ctx: ExtensionContext;\n sourceSession: object;\n menuGeneration: number;\n workflowGeneration: number;\n workflowOwner: WorkflowMutexOwner | undefined;\n enabled: boolean;\n plan: string;\n source: PlanCompletionSource;\n savedPlan: PlanModeState[\"savedPlan\"];\n retention: ImplementationPlanRetention;\n runtime: ImplementationRuntimeSelection | undefined;\n menuIsCurrent(): boolean;\n}\ninterface PendingWorkflowToolPolicy {\n generation: number;\n mode: \"resolve\" | \"revalidate\";\n}\ntype ImplementationRuntimeApplicationResult = \"ready\" | \"blocked\" | \"stale\";\ninterface ActiveImplementationRuntimeApplication {\n sessionManager: ExtensionContext[\"sessionManager\"];\n completion: Promise<ImplementationRuntimeApplicationResult>;\n drainOnShutdown: boolean;\n holdForAdmission: boolean;\n}\ninterface QueuedRuntimeAdmissionInput {\n sessionManager: ExtensionContext[\"sessionManager\"];\n text: string;\n images?: NonNullable<InputEvent[\"images\"]>;\n source: InputSource;\n}\ntype InteractiveUi = typeof import(\"./interactive-ui.js\");\n\ninterface PlanModeDependencies {\n readSettings?(): ReturnType<typeof readPlanModeSettings>;\n updateSettings?(\n patch: PlanModeSettingsPatch,\n options?: UpdatePlanModeSettingsOptions,\n ): ReturnType<typeof updatePlanModeSettings>;\n settingsPath?: string;\n loadInteractiveUi?(): 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 const workflowMutex = new WorkflowMutex(pi);\n let workflowOwner: WorkflowMutexOwner | undefined;\n let currentSession: object | undefined;\n let currentSessionContext: ExtensionContext | undefined;\n let interactiveUiPromise: Promise<InteractiveUi> | undefined;\n const loadInteractiveUi = () => {\n if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();\n if (!interactiveUiPromise) {\n interactiveUiPromise = import(\"./interactive-ui.js\").catch((error) => {\n interactiveUiPromise = undefined;\n throw error;\n });\n }\n return interactiveUiPromise;\n };\n const explicitPlanModeSettingsPath = dependencies.settingsPath;\n let state: PlanModeState = { enabled: false, awaitingAction: false };\n let settings: PlanModeSettings = { thinkingLevel: \"inherit\" };\n let toggleShortcut: ReturnType<typeof configuredPlanModeToggleShortcut>;\n const clearPlanModeShortcutHandler = () => {};\n let workflowAllowedToolNames: string[] | undefined;\n let pendingWorkflowToolPolicy: PendingWorkflowToolPolicy | undefined;\n let publishedContractMode: PlanModeContract | undefined;\n let modeContractsRelevant = false;\n let readyPresentationIntent: ReadyPresentationIntent | undefined;\n let latestCommandContext: ExtensionCommandContext | undefined;\n let stagedFreshImplementation: DeferredFreshImplementation | undefined;\n const deferredFreshHandoff = createDeferredFreshHandoffCoordinator();\n let nextReadyPresentationNonce = 0;\n let menuGeneration = 0;\n let workflowGeneration = 0;\n let refreshStateBeforeFirstAgentStart = false;\n let activeImplementationRuntimeApplication: ActiveImplementationRuntimeApplication | undefined;\n let pendingRuntimeAdmissionSession: object | undefined;\n let queuedRuntimeAdmissionInputs: QueuedRuntimeAdmissionInput[] = [];\n let menuController = new AbortController();\n let settingsWatch: ReturnType<typeof watch> | undefined;\n let settingsReloadTimer: ReturnType<typeof setTimeout> | undefined;\n const implementationRetention = createImplementationRetentionCoordinator();\n const finalizationRequest = createFinalizationRequestCoordinator();\n const persistState = () => pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, state);\n const planExports = createPlanExportController({\n getState: () => state,\n getSettings: () => settings,\n finishReady: (ctx) => {\n exitPlanMode(ctx);\n },\n });\n const planActions = createPlanActionController({\n loadInteractiveUi,\n getState: () => state,\n captureLifecycle: captureMenuLifecycle,\n statusText: planStatusText,\n // ExtensionContext.thinkingLevel was added after the supported Pi 0.80.6 floor.\n // ExtensionAPI has exposed the same runtime value throughout that compatibility range.\n getThinkingLevel: () => pi.getThinkingLevel(),\n getSettings: () => settings,\n implementationOutcome,\n getExportDestination: (ctx) => planExports.getDestination(ctx),\n show: (ctx) => showStoredPlan(pi, ctx, state),\n finalize: requestFinalPlan,\n implementHere: startImplementation,\n implementFresh: startFreshImplementation,\n exportPlan: exportPlan,\n settings: showSettings,\n save: savePlanForLater,\n stay: updateUi,\n exitReady: (ctx) => {\n if (exitPlanMode(ctx)) {\n ctx.ui.notify(\"Plan mode disabled. Proposed plan discarded.\", \"info\");\n }\n },\n clearSaved: (ctx) => {\n if (exitPlanMode(ctx)) ctx.ui.notify(\"Saved plan cleared.\", \"info\");\n },\n });\n\n pi.registerTool({\n name: PLAN_MODE_QUESTION_TOOL_NAME,\n label: \"Plan question\",\n description:\n \"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 parameters: PLAN_MODE_QUESTION_PARAMS,\n async execute(_toolCallId, params: unknown, _signal, _onUpdate, ctx) {\n if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {\n return planModeQuestionCancelled(\n [],\n \"plan_mode_inactive\",\n \"Error: plan_mode_question is only available while Plan mode is active.\",\n );\n }\n\n const parsed = normalizePlanModeQuestionParams(params);\n if (!parsed.ok) {\n return planModeQuestionCancelled([], \"invalid_input\", `Error: ${parsed.error}`);\n }\n finalizationRequest.satisfy();\n\n if (!ctx.hasUI) {\n return planModeQuestionCancelled(\n parsed.questions,\n \"ui_unavailable\",\n \"Unable to ask Plan-mode questions because interactive UI is not available.\",\n );\n }\n\n const sessionGeneration = menuGeneration;\n const questionWorkflowGeneration = workflowGeneration;\n const questionOwner = workflowOwner;\n return answerPlanModeQuestions(parsed.questions, ctx, {\n isCurrent: () =>\n sessionGeneration === menuGeneration &&\n questionWorkflowGeneration === workflowGeneration &&\n workflowMutex.isOwner(questionOwner),\n isEnabled: () => state.enabled,\n });\n },\n });\n\n pi.registerTool({\n name: PLAN_MODE_COMPLETE_TOOL_NAME,\n label: \"Complete plan\",\n description:\n \"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 parameters: PLAN_MODE_COMPLETE_PARAMS,\n renderResult: renderPlanModeCompletion,\n async execute(_toolCallId, params: unknown, _signal, _onUpdate, ctx) {\n if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {\n throw new Error(\"plan_mode_complete is only available while Plan mode is active\");\n }\n const parsed = normalizePlanModeCompletion(params);\n if (!parsed.ok) throw new Error(parsed.error);\n\n acceptCompletedPlan(parsed.plan, PLAN_MODE_COMPLETE_TOOL_NAME, ctx);\n return planModeCompleted(parsed.plan);\n },\n });\n\n pi.registerCommand(\"plan\", {\n description: \"Enter or manage Codex-like Plan mode\",\n getArgumentCompletions: completePlanArguments,\n handler: async (args, ctx) => {\n latestCommandContext = ctx;\n const prompt = args.trim();\n const command = prompt.toLowerCase();\n if (command === \"start\") {\n if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled)) return;\n if (state.enabled) {\n ctx.ui.notify(\"Plan mode is already active.\", \"info\");\n return;\n }\n if (enterPlanMode(ctx)) {\n ctx.ui.notify(\"Plan mode enabled. I will explore and plan, but not modify files.\", \"info\");\n }\n return;\n }\n if (command === \"show\") {\n showStoredPlan(pi, ctx, state);\n return;\n }\n if (command === \"finalize\") {\n requestFinalPlan(ctx);\n return;\n }\n if (command === \"implement\") {\n if (!(state.enabled && state.latestPlan?.trim()) && !state.savedPlan?.plan.trim()) {\n ctx.ui.notify(\"No completed plan is available to implement.\", \"warning\");\n return;\n }\n await startImplementation(ctx);\n return;\n }\n if (command === \"save\") {\n savePlanForLater(ctx);\n return;\n }\n if (command === \"settings\") {\n if (!ctx.hasUI) {\n throw new Error(\"/plan settings requires TUI or RPC mode and is unavailable here.\");\n }\n const lifecycle = captureMenuLifecycle();\n await showSettings(ctx, lifecycle.signal, lifecycle.isCurrent);\n return;\n }\n const exportMatch = /^export(?:\\s+([\\s\\S]+))?$/iu.exec(prompt);\n if (exportMatch) {\n const lifecycle = captureMenuLifecycle();\n await exportPlan(ctx, exportMatch[1], lifecycle.signal, lifecycle.isCurrent);\n return;\n }\n if (command === \"exit\" || command === \"off\") {\n const notification = planModeDisableNotification();\n if (exitPlanMode(ctx)) ctx.ui.notify(notification, \"info\");\n return;\n }\n if (command === \"tools\") {\n if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled)) return;\n if (state.enabled) {\n const message =\n \"Plan-mode tools are locked while Planning is active. Exit Plan mode and choose tools before starting again.\";\n if (!ctx.hasUI) throw new Error(message);\n ctx.ui.notify(message, \"warning\");\n return;\n }\n if (!ctx.hasUI) {\n throw new Error(\"/plan tools requires TUI or RPC mode and is unavailable here.\");\n }\n await showLaunchMenu(ctx, \"tools\");\n return;\n }\n if (prompt) {\n if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined && !state.enabled)) return;\n enterPlanModeWithPrompt(prompt, ctx);\n return;\n }\n if (!ctx.hasUI) {\n throw new Error(\n \"The interactive /plan menu is unavailable in print and JSON modes. Use /plan start or /plan <prompt>.\",\n );\n }\n if (!state.enabled) {\n if (state.activeImplementation && ctx.hasUI) {\n await showActivePlanMenu(ctx);\n return;\n }\n if (state.savedPlan) {\n await planActions.showSaved(ctx);\n return;\n }\n await showLaunchMenu(ctx);\n return;\n }\n await planActions.showCurrent(ctx);\n },\n });\n\n const applyPlanModeShortcut = (nextShortcut: ReturnType<typeof configuredPlanModeToggleShortcut>) => {\n if (toggleShortcut && toggleShortcut !== nextShortcut) {\n pi.registerShortcut(toggleShortcut, {\n handler: clearPlanModeShortcutHandler,\n });\n }\n if (!nextShortcut) {\n toggleShortcut = undefined;\n return;\n }\n if (toggleShortcut === nextShortcut) return;\n pi.registerShortcut(nextShortcut, {\n description: \"Toggle Plan mode\",\n handler: (ctx) => {\n togglePlanMode(ctx);\n },\n });\n toggleShortcut = nextShortcut;\n };\n\n const readPlanModeRuntimeSettings = async () => {\n return dependencies.readSettings?.() ?? readPlanModeSettings(explicitPlanModeSettingsPath);\n };\n\n const applyPlanModeSettings = async (\n generation: number,\n ctx: ExtensionContext | undefined,\n showWarnings: boolean,\n ) => {\n const loadedSettings = await readPlanModeRuntimeSettings();\n if (generation !== menuGeneration || menuController.signal.aborted) {\n return undefined;\n }\n settings =\n loadedSettings.kind === \"loaded\"\n ? loadedSettings.settings\n : ({ thinkingLevel: \"inherit\" } satisfies PlanModeSettings);\n applyPlanModeShortcut(configuredPlanModeToggleShortcut(settings));\n if (!ctx || !showWarnings) return loadedSettings;\n if (loadedSettings.kind === \"invalid\") {\n ctx.ui.notify(`pi-plan-mode settings ignored: ${loadedSettings.reason}`, \"warning\");\n }\n if (loadedSettings.notice) {\n ctx.ui.notify(loadedSettings.notice, \"warning\");\n }\n return loadedSettings;\n };\n\n const stopPlanModeSettingsWatch = () => {\n if (settingsReloadTimer) {\n clearTimeout(settingsReloadTimer);\n settingsReloadTimer = undefined;\n }\n settingsWatch?.close();\n settingsWatch = undefined;\n };\n\n const schedulePlanModeSettingsReload = (generation: number) => {\n if (settingsReloadTimer) {\n clearTimeout(settingsReloadTimer);\n settingsReloadTimer = undefined;\n }\n settingsReloadTimer = setTimeout(() => {\n settingsReloadTimer = undefined;\n void applyPlanModeSettings(generation, currentSessionContext, false);\n }, 75);\n };\n\n const startPlanModeSettingsWatch = (generation: number) => {\n stopPlanModeSettingsWatch();\n if (dependencies.readSettings) return;\n const pathToWatch = explicitPlanModeSettingsPath ?? planModeSettingsPath();\n try {\n const directory = dirname(pathToWatch);\n const fileName = basename(pathToWatch);\n const watcher = watch(directory, { persistent: false }, (event, changedFile) => {\n if (event !== \"rename\" && event !== \"change\") return;\n if (!changedFile || changedFile.toString() !== fileName) return;\n schedulePlanModeSettingsReload(generation);\n });\n watcher.on(\"error\", () => {\n stopPlanModeSettingsWatch();\n });\n settingsWatch = watcher;\n } catch {\n stopPlanModeSettingsWatch();\n }\n };\n\n pi.on(\"session_start\", async (event, ctx) => {\n cancelDeferredFreshImplementation();\n const generation = ++menuGeneration;\n finalizationRequest.reset();\n currentSession = ctx.sessionManager;\n currentSessionContext = ctx;\n workflowOwner = undefined;\n workflowMutex.bindSession(ctx.sessionManager);\n refreshStateBeforeFirstAgentStart = event.reason === \"new\";\n pendingRuntimeAdmissionSession = undefined;\n queuedRuntimeAdmissionInputs = [];\n menuController.abort(new DOMException(\"Plan-mode session replaced\", \"AbortError\"));\n menuController = new AbortController();\n readyPresentationIntent = undefined;\n latestCommandContext = undefined;\n workflowAllowedToolNames = undefined;\n pendingWorkflowToolPolicy = undefined;\n implementationRetention.reset();\n settings = { thinkingLevel: \"inherit\" };\n const branch = ctx.sessionManager.getBranch();\n const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);\n restoreModeContractTracking(branch, restoredState);\n state = { enabled: false, awaitingAction: false };\n await applyPlanModeSettings(generation, ctx, true);\n if (generation !== menuGeneration || menuController.signal.aborted) return;\n startPlanModeSettingsWatch(generation);\n if (!installRestoredState(restoredState, ctx)) return;\n implementationRetention.restore(state.activeImplementation);\n updateUi(ctx);\n // A new session receives its setup entries after session_start, so its input gate refreshes\n // them. Resumed and forked sessions already have the intent and must apply it here because\n // extension-triggered custom-message turns bypass both input and before_agent_start.\n if (event.reason !== \"new\") await applyPendingImplementationRuntime(ctx);\n });\n\n pi.on(\"session_before_tree\", (event, ctx) => {\n if (runtimeAdmissionIsPending(ctx.sessionManager)) {\n if (ctx.hasUI) {\n ctx.ui.notify(\n \"Wait for fresh implementation startup to admit the pending prompts before changing branches.\",\n \"warning\",\n );\n }\n return { cancel: true };\n }\n const target = ctx.sessionManager.getEntry(event.preparation.targetId);\n if (target?.type !== \"custom_message\" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {\n return;\n }\n if (ctx.hasUI) {\n ctx.ui.notify(\n \"Plan mode transition markers are internal. Select the adjacent conversation entry instead.\",\n \"warning\",\n );\n }\n return { cancel: true };\n });\n\n pi.on(\"session_tree\", async (_event, ctx) => {\n cancelDeferredFreshImplementation();\n advanceWorkflowGeneration();\n menuGeneration += 1;\n menuController.abort(new DOMException(\"Plan-mode tree branch changed\", \"AbortError\"));\n menuController = new AbortController();\n readyPresentationIntent = undefined;\n latestCommandContext = undefined;\n pendingRuntimeAdmissionSession = undefined;\n queuedRuntimeAdmissionInputs = [];\n implementationRetention.reset();\n const branch = ctx.sessionManager.getBranch();\n const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);\n restoreModeContractTracking(branch, restoredState);\n if (!installRestoredState(restoredState, ctx)) return;\n implementationRetention.restore(state.activeImplementation);\n startPlanModeSettingsWatch(menuGeneration);\n updateUi(ctx);\n await applyPendingImplementationRuntime(ctx);\n });\n\n pi.on(\"thinking_level_select\", (event) => {\n if (!state.enabled || !state.appliedThinkingLevel) return;\n if (event.level !== state.appliedThinkingLevel) {\n state = {\n ...state,\n manualThinkingLevel: event.level,\n previousThinkingLevel: undefined,\n appliedThinkingLevel: undefined,\n };\n persistState();\n }\n });\n\n pi.on(\"session_shutdown\", async (_event, ctx) => {\n cancelDeferredFreshImplementation();\n const shutdownSession = ctx.sessionManager;\n const runtimeApplication =\n activeImplementationRuntimeApplication?.sessionManager === shutdownSession &&\n activeImplementationRuntimeApplication.drainOnShutdown\n ? activeImplementationRuntimeApplication\n : undefined;\n const queuedInputs = takeQueuedRuntimeAdmissionInputs(shutdownSession);\n for (const queued of queuedInputs) {\n pi.sendMessage(\n {\n customType: RECOVERED_RUNTIME_ADMISSION_INPUT_MESSAGE_TYPE,\n content: runtimeAdmissionInputContent(queued),\n display: true,\n details: { source: queued.source },\n },\n { triggerTurn: false },\n );\n }\n finalizationRequest.reset();\n menuGeneration += 1;\n menuController.abort(new DOMException(\"Plan-mode session shut down\", \"AbortError\"));\n readyPresentationIntent = undefined;\n latestCommandContext = undefined;\n refreshStateBeforeFirstAgentStart = false;\n pendingRuntimeAdmissionSession = undefined;\n queuedRuntimeAdmissionInputs = [];\n workflowAllowedToolNames = undefined;\n pendingWorkflowToolPolicy = undefined;\n implementationRetention.reset();\n if (runtimeApplication) await runtimeApplication.completion;\n if (currentSession !== undefined && currentSession !== shutdownSession) {\n workflowMutex.unbindSession(shutdownSession);\n return;\n }\n await awaitPlanModeSettingsWrites(dependencies.settingsPath);\n if (currentSession !== undefined && currentSession !== shutdownSession) {\n workflowMutex.unbindSession(shutdownSession);\n return;\n }\n captureManualThinkingLevel();\n persistState();\n if (state.enabled) restoreThinkingLevel();\n stopPlanModeSettingsWatch();\n clearUi(ctx);\n releaseWorkflowOwner();\n workflowMutex.unbindSession(ctx.sessionManager);\n if (currentSession === ctx.sessionManager) {\n currentSession = undefined;\n currentSessionContext = undefined;\n }\n });\n\n pi.on(\"tool_call\", async (event, ctx) => {\n const requiredHelper =\n event.toolName === PLAN_MODE_QUESTION_TOOL_NAME || event.toolName === PLAN_MODE_COMPLETE_TOOL_NAME;\n if (!state.enabled) {\n if (!requiredHelper) return;\n return {\n block: true,\n reason: `${event.toolName} is only available while Plan mode is active.`,\n };\n }\n if (!workflowMutex.isOwner(workflowOwner)) {\n return {\n block: true,\n reason: `Plan mode blocks tool '${event.toolName}' because workflow ownership is unavailable.`,\n };\n }\n if (BLOCKED_MUTATING_TOOLS.has(event.toolName)) {\n return {\n block: true,\n reason:\n event.toolName === \"update_plan\"\n ? \"Plan mode blocks update_plan because it tracks execution progress rather than conversational planning.\"\n : `Plan mode blocks mutating tool '${event.toolName}'.`,\n };\n }\n if (requiredHelper) return;\n\n const calledTool = toolByName(event.toolName);\n const activeToolNames = new Set(safeGetActiveTools());\n if (!calledTool) {\n return {\n block: true,\n reason: activeToolNames.has(event.toolName)\n ? `Plan mode blocks tool '${event.toolName}' because its safe policy metadata is unavailable.`\n : `Plan mode blocks tool '${event.toolName}' because it is not registered or active. Register and activate it before starting the next Plan workflow.`,\n };\n }\n if (classifyPlanModeTool(calledTool) === \"blocked\") {\n return {\n block: true,\n reason: `Plan mode blocks tool '${event.toolName}' because its built-in policy is blocked and settings cannot enable it.`,\n };\n }\n const allowedToolNames = new Set(planModePolicyToolNames());\n if (!activeToolNames.has(event.toolName)) {\n return {\n block: true,\n reason: allowedToolNames.has(event.toolName)\n ? `Plan mode blocks tool '${event.toolName}' because it was admitted to the active Plan workflow but is currently inactive. Reactivate it to continue without restarting.`\n : `Plan mode blocks tool '${event.toolName}' because it is registered but inactive. Activate it before starting the next Plan workflow.`,\n };\n }\n if (!allowedToolNames.has(event.toolName)) {\n return {\n block: true,\n reason: workflowDesiredToolNames().has(event.toolName)\n ? `Plan mode blocks tool '${event.toolName}' because it was not available when the active Plan workflow froze its tool policy. Exit Plan mode, then start again after the tool is active.`\n : `Plan mode blocks tool '${event.toolName}' because it is not selected by the Plan policy. Exit Plan mode, then enable it with /plan tools or defaultPlanTools before starting again.`,\n };\n }\n if (event.toolName === \"bash\") {\n const blocked = findBlockedCommandSegment(readCommand(event.input), settings.safeSubcommands, ctx.cwd);\n if (blocked !== undefined) {\n return {\n block: true,\n reason: `Plan mode blocks bash commands outside its reviewed inspection policy or containing explicitly unsafe arguments.\\nBlocked command: ${blocked}`,\n };\n }\n }\n if (event.toolName === \"powershell\") {\n const blocked = findBlockedPowerShellCommandSegment(readCommand(event.input), settings.safeSubcommands, ctx.cwd);\n if (blocked !== undefined) {\n return {\n block: true,\n reason: `Plan mode blocks PowerShell commands outside its reviewed inspection policy or containing explicitly unsafe syntax.\\nBlocked command: ${blocked}`,\n };\n }\n }\n });\n\n pi.on(\"message_start\", (event) => {\n if (\n state.enabled &&\n event.message.role === \"user\" &&\n messageTextContent(event.message).trim() === FINALIZE_PLAN_PROMPT\n ) {\n finalizationRequest.request(workflowGeneration);\n }\n });\n\n pi.on(\"context\", async (event, ctx) => {\n resolvePendingWorkflowToolPolicy(ctx);\n const result = implementationRetention.transformContext(event.messages, state);\n if (result.clearActiveImplementationId) {\n clearActiveImplementation(result.clearActiveImplementationId, ctx);\n }\n const messages =\n state.enabled || modeContractsRelevant\n ? reconcileModeContract(result.messages, state.enabled ? \"plan\" : \"normal\")\n : result.messages;\n return { messages: messages as typeof event.messages };\n });\n\n pi.on(\"input\", async (event, ctx) => {\n refreshStateForFirstPrompt(ctx);\n const waitsForRuntimeAdmission =\n activeImplementationRuntimeApplication?.sessionManager === ctx.sessionManager ||\n pendingRuntimeAdmissionSession === ctx.sessionManager;\n const queuedInput = waitsForRuntimeAdmission\n ? {\n sessionManager: ctx.sessionManager,\n text: event.text,\n ...(event.images ? { images: [...event.images] } : {}),\n source: event.source,\n }\n : undefined;\n if (queuedInput) queuedRuntimeAdmissionInputs.push(queuedInput);\n const result = await applyPendingImplementationRuntime(ctx, true);\n if (result !== \"ready\") {\n if (result === \"stale\" && queuedInput) removeQueuedRuntimeAdmissionInput(queuedInput);\n return { action: \"handled\" };\n }\n if (queuedInput) return { action: \"handled\" };\n });\n\n pi.on(\"agent_start\", (_event, ctx) => {\n if (currentSession !== ctx.sessionManager) return;\n if (pendingRuntimeAdmissionSession === ctx.sessionManager) {\n pendingRuntimeAdmissionSession = undefined;\n }\n const queuedInputs = takeQueuedRuntimeAdmissionInputs(ctx.sessionManager);\n for (const queued of queuedInputs) {\n pi.sendUserMessage(runtimeAdmissionInputContent(queued), {\n deliverAs: \"followUp\",\n expandPromptTemplates: queued.source !== \"extension\",\n });\n }\n });\n\n pi.on(\"before_agent_start\", (_event, ctx) => {\n refreshStateForFirstPrompt(ctx);\n if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;\n if (state.latestPlan || state.awaitingAction) {\n cancelDeferredFreshImplementation();\n readyPresentationIntent = undefined;\n state = {\n ...state,\n latestPlan: undefined,\n latestPlanSource: undefined,\n awaitingAction: false,\n };\n persistState();\n updateUi(ctx);\n }\n });\n\n pi.on(\"agent_end\", async (event, ctx) => {\n if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;\n\n const text = latestAssistantText(event.messages);\n const parsedPlan = parseProposedPlan(text);\n if (parsedPlan.kind !== \"valid\") {\n finalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));\n if (parsedPlan.kind !== \"absent\") {\n ctx.ui.notify(invalidPlanMessage(parsedPlan.kind), \"warning\");\n }\n persistState();\n updateUi(ctx);\n return;\n }\n acceptCompletedPlan(parsedPlan.plan, \"legacy_proposed_plan\", ctx);\n });\n\n pi.on(\"agent_settled\", async (_event, ctx) => {\n const settledImplementationId = implementationRetention.implementationSettled(state.activeImplementation);\n if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);\n\n if (finalizationRequest.hasPendingRequest() && state.enabled && workflowMutex.isOwner(workflowOwner)) {\n if (!ctx.isIdle() || ctx.hasPendingMessages()) return;\n const action = finalizationRequest.settle(workflowGeneration);\n if (action === \"retry\") {\n if (sendPlanModeUserMessage(RETRY_FINALIZE_PLAN_PROMPT, ctx)) return;\n finalizationRequest.reset();\n }\n if (action === \"failed\") {\n ctx.ui.notify(\n \"Plan finalization ended twice without a structured question or completed plan. Plan mode remains active; revise the plan or run /plan finalize again.\",\n \"warning\",\n );\n }\n }\n\n const intent = readyPresentationIntent;\n if (!intent || !readyPresentationIsCurrent(intent)) return;\n if (!ctx.isIdle() || ctx.hasPendingMessages()) return;\n\n readyPresentationIntent = undefined;\n stagedFreshImplementation = undefined;\n try {\n if (intent.source === \"legacy_proposed_plan\") {\n pi.sendMessage(\n {\n customType: PROPOSED_PLAN_MESSAGE_TYPE,\n content: `**Proposed Plan**\\n\\n${intent.plan}`,\n display: true,\n },\n { triggerTurn: false },\n );\n }\n if (ctx.hasUI && completedPlanIsCurrent(intent)) {\n await planActions.showReady(latestCommandContext ?? ctx);\n }\n const request = stagedFreshImplementation;\n stagedFreshImplementation = undefined;\n if (request) armDeferredFreshImplementation(request);\n } catch (error: unknown) {\n stagedFreshImplementation = undefined;\n if (!isStaleExtensionContextError(error)) throw error;\n }\n });\n\n function enterPlanMode(\n ctx: ExtensionContext,\n candidate: Pick<PlanModeState, \"selectedToolNames\" | \"selectedToolKeys\"> = state,\n ) {\n if (!state.enabled && !allowModeTransition(ctx, \"start Plan mode\")) return false;\n bindWorkflowSessionIfNeeded(ctx);\n if (state.enabled) return workflowMutex.isOwner(workflowOwner);\n const owner = workflowMutex.acquire();\n if (!owner) return reportWorkflowBusy(ctx);\n workflowOwner = owner;\n\n const previousState = state;\n try {\n assertPlanModeHelperToolsAvailable(safeGetActiveTools());\n if (!publishModeContract(\"plan\", ctx)) {\n releaseWorkflowOwner();\n return false;\n }\n } catch (error: unknown) {\n releaseWorkflowOwner();\n return reportHelperActivationFailure(ctx, error);\n }\n advanceWorkflowGeneration();\n try {\n modeContractsRelevant = true;\n state = {\n ...state,\n enabled: true,\n awaitingAction: false,\n savedPlan: undefined,\n activeImplementation: undefined,\n pendingImplementationRuntime: undefined,\n selectedToolNames: candidate.selectedToolNames,\n selectedToolKeys: candidate.selectedToolKeys,\n };\n beginWorkflowToolPolicy();\n applyPlanThinkingLevel();\n persistState();\n updateUi(ctx);\n return true;\n } catch (error: unknown) {\n rollbackNewActivation(previousState, ctx);\n throw error;\n }\n }\n\n function enterPlanModeWithPrompt(prompt: string, ctx: ExtensionContext) {\n const previousState = state;\n const previousOwner = workflowOwner;\n const wasEnabled = state.enabled;\n if (!enterPlanMode(ctx)) return;\n if (!wasEnabled) {\n ctx.ui.notify(\"Plan mode enabled. I will explore and plan, but not modify files.\", \"info\");\n }\n if (sendPlanModeUserMessage(prompt, ctx)) return;\n if (wasEnabled) return;\n rollbackNewActivation(previousState, ctx, previousOwner);\n }\n\n function exitPlanMode(ctx: ExtensionContext) {\n if (!allowModeTransition(ctx, \"leave or clear Plan mode\")) return false;\n const wasEnabled = state.enabled;\n if ((wasEnabled || modeContractsRelevant) && !publishModeContract(\"normal\", ctx)) {\n return false;\n }\n advanceWorkflowGeneration();\n readyPresentationIntent = undefined;\n workflowAllowedToolNames = undefined;\n state = {\n ...state,\n enabled: false,\n latestPlan: undefined,\n latestPlanSource: undefined,\n awaitingAction: false,\n savedPlan: undefined,\n activeImplementation: undefined,\n pendingImplementationRuntime: undefined,\n workflowToolPolicy: undefined,\n manualThinkingLevel: undefined,\n };\n if (wasEnabled) {\n restoreThinkingLevel();\n state = { ...state, manualThinkingLevel: undefined };\n }\n persistState();\n updateUi(ctx);\n if (wasEnabled) releaseWorkflowOwner();\n return true;\n }\n\n function restoreModeContractTracking(branch: unknown[], restoredState: PlanModeState) {\n publishedContractMode = latestModeContract(branch)?.mode;\n modeContractsRelevant =\n hasModeContractArtifact(branch) ||\n restoredState.enabled ||\n restoredState.savedPlan !== undefined ||\n restoredState.activeImplementation !== undefined ||\n restoredState.pendingImplementationRuntime !== undefined;\n }\n\n function publishModeContract(mode: PlanModeContract, ctx: ExtensionContext) {\n if (publishedContractMode === mode) return true;\n const { role: _role, timestamp: _timestamp, ...message } = createModeContractMessage(mode);\n try {\n pi.sendMessage(message, { triggerTurn: false });\n publishedContractMode = mode;\n modeContractsRelevant = true;\n return true;\n } catch (error: unknown) {\n const detail = safeTerminalText(error instanceof Error ? error.message : String(error));\n const notification = `Unable to publish the ${mode === \"plan\" ? \"Plan\" : \"Normal\"} mode contract: ${detail}`;\n if (!ctx.hasUI) throw new Error(notification, { cause: error });\n ctx.ui.notify(notification, \"error\");\n return false;\n }\n }\n\n function sendPlanModeUserMessage(message: string, ctx: ExtensionContext) {\n try {\n if (ctx.isIdle()) pi.sendUserMessage(message);\n else pi.sendUserMessage(message, { deliverAs: \"followUp\" });\n return true;\n } catch (error: unknown) {\n const detail = safeTerminalText(error instanceof Error ? error.message : String(error));\n ctx.ui.notify(`Unable to send Plan-mode message: ${detail}`, \"error\");\n return false;\n }\n }\n\n function acceptCompletedPlan(plan: string, source: PlanCompletionSource, ctx: ExtensionContext) {\n const normalized = normalizePlanModeCompletion({ plan });\n if (!normalized.ok) {\n ctx.ui.notify(`Proposed plan is not ready: ${normalized.error}.`, \"warning\");\n persistState();\n updateUi(ctx);\n return;\n }\n finalizationRequest.satisfy();\n if (\n state.enabled &&\n state.awaitingAction &&\n state.latestPlan === normalized.plan &&\n state.latestPlanSource === source\n ) {\n return;\n }\n state = {\n ...state,\n latestPlan: normalized.plan,\n latestPlanSource: source,\n awaitingAction: true,\n };\n readyPresentationIntent = {\n nonce: ++nextReadyPresentationNonce,\n plan: normalized.plan,\n source,\n };\n persistState();\n updateUi(ctx);\n }\n\n function completedPlanIsCurrent(intent: ReadyPresentationIntent) {\n return (\n state.enabled &&\n workflowMutex.isOwner(workflowOwner) &&\n state.awaitingAction &&\n state.latestPlan === intent.plan &&\n state.latestPlanSource === intent.source\n );\n }\n\n function readyPresentationIsCurrent(intent: ReadyPresentationIntent) {\n return completedPlanIsCurrent(intent) && readyPresentationIntent?.nonce === intent.nonce;\n }\n\n function togglePlanMode(ctx: ExtensionContext) {\n if (state.enabled) {\n const notification = planModeDisableNotification();\n if (exitPlanMode(ctx)) ctx.ui.notify(notification, \"info\");\n return;\n }\n if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== undefined)) return;\n if (enterPlanMode(ctx)) {\n ctx.ui.notify(\"Plan mode enabled. I will explore and plan, but not modify files.\", \"info\");\n }\n }\n\n function planModeDisableNotification() {\n return state.activeImplementation\n ? \"Active implementation plan cleared.\"\n : state.savedPlan\n ? \"Saved plan cleared.\"\n : state.latestPlan\n ? \"Plan mode disabled. Proposed plan discarded.\"\n : \"Plan mode disabled.\";\n }\n\n function requestFinalPlan(ctx: ExtensionContext) {\n if (!state.enabled) {\n ctx.ui.notify(\"Plan mode is not active. Use /plan first.\", \"warning\");\n return;\n }\n finalizationRequest.request(workflowGeneration);\n if (!sendPlanModeUserMessage(FINALIZE_PLAN_PROMPT, ctx)) finalizationRequest.reset();\n }\n\n function savePlanForLater(ctx: ExtensionContext) {\n const plan = state.enabled ? state.latestPlan?.trim() : undefined;\n if (!plan) {\n const message = \"No completed plan is available to save.\";\n if (!ctx.hasUI) throw new Error(message);\n ctx.ui.notify(message, \"warning\");\n return;\n }\n const source = state.latestPlanSource ?? \"legacy_proposed_plan\";\n if (!allowModeTransition(ctx, \"save the plan and leave Plan mode\")) return;\n\n if (!publishModeContract(\"normal\", ctx)) return;\n advanceWorkflowGeneration();\n readyPresentationIntent = undefined;\n workflowAllowedToolNames = undefined;\n state = {\n ...state,\n enabled: false,\n latestPlan: undefined,\n latestPlanSource: undefined,\n awaitingAction: false,\n savedPlan: { plan, source },\n activeImplementation: undefined,\n pendingImplementationRuntime: undefined,\n workflowToolPolicy: undefined,\n manualThinkingLevel: undefined,\n };\n restoreThinkingLevel();\n state = { ...state, manualThinkingLevel: undefined };\n persistState();\n updateUi(ctx);\n releaseWorkflowOwner();\n ctx.ui.notify(\"Plan saved for later. Plan mode disabled.\", \"info\");\n }\n\n async function startFreshImplementation(\n ctx: ExtensionContext,\n menuIsCurrent: () => boolean,\n runtime: ImplementationRuntimeSelection | undefined,\n timing: FreshImplementationTiming,\n ) {\n const retention = configuredImplementationPlanRetention(settings);\n if (timing === \"immediate\") {\n await startFreshImplementationFromState(ctx, {\n getState: () => state,\n menuIsCurrent,\n retention,\n stateEntryType: STATE_ENTRY_TYPE,\n runtime,\n });\n return;\n }\n\n const initialState = state;\n const savedPlan = initialState.enabled ? undefined : initialState.savedPlan;\n const plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();\n const source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;\n if (!plan || !source || !menuIsCurrent()) return;\n stagedFreshImplementation = {\n ctx,\n sourceSession: ctx.sessionManager,\n menuGeneration,\n workflowGeneration,\n workflowOwner,\n enabled: initialState.enabled,\n plan,\n source,\n savedPlan,\n retention,\n runtime: runtime\n ? {\n ...(runtime.model ? { model: { ...runtime.model } } : {}),\n ...(runtime.thinkingLevel ? { thinkingLevel: runtime.thinkingLevel } : {}),\n }\n : undefined,\n menuIsCurrent,\n };\n }\n\n function armDeferredFreshImplementation(request: DeferredFreshImplementation) {\n deferredFreshHandoff.schedule(\n async (taskIsCurrent) => {\n const isCurrent = () => taskIsCurrent() && deferredFreshImplementationIsCurrent(request);\n if (!isCurrent()) return;\n await startFreshImplementationFromState(request.ctx, {\n getState: () => state,\n menuIsCurrent: isCurrent,\n retention: request.retention,\n stateEntryType: STATE_ENTRY_TYPE,\n runtime: request.runtime,\n });\n },\n (error) => {\n if (!deferredFreshImplementationIsCurrent(request)) return;\n try {\n request.ctx.ui.notify(\n `Unable to start the deferred fresh implementation: ${terminalErrorDetail(error)}`,\n \"error\",\n );\n } catch {\n // The source context can become stale while a detached failure is reported.\n }\n },\n );\n }\n\n function deferredFreshImplementationIsCurrent(request: DeferredFreshImplementation) {\n if (\n currentSession !== request.sourceSession ||\n menuGeneration !== request.menuGeneration ||\n workflowGeneration !== request.workflowGeneration ||\n workflowOwner !== request.workflowOwner ||\n !request.menuIsCurrent() ||\n state.enabled !== request.enabled\n ) {\n return false;\n }\n return request.enabled\n ? workflowMutex.isOwner(request.workflowOwner) &&\n state.latestPlan === request.plan &&\n state.latestPlanSource === request.source\n : state.savedPlan === request.savedPlan;\n }\n\n function cancelDeferredFreshImplementation() {\n stagedFreshImplementation = undefined;\n deferredFreshHandoff.cancel();\n }\n\n async function startImplementation(ctx: ExtensionContext) {\n const savedPlan = state.enabled ? undefined : state.savedPlan;\n const initialPlan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();\n if (!initialPlan) {\n ctx.ui.notify(\"Plan mode disabled. No proposed plan is available to implement.\", \"warning\");\n return;\n }\n if (!allowModeTransition(ctx, \"start plan implementation\")) return;\n if (savedPlan) {\n const sessionGeneration = menuGeneration;\n const planWorkflowGeneration = workflowGeneration;\n const isCurrent = () =>\n sessionGeneration === menuGeneration &&\n planWorkflowGeneration === workflowGeneration &&\n !menuController.signal.aborted &&\n !state.enabled &&\n state.savedPlan === savedPlan;\n if (!(await preflightSavedPlanImplementation(ctx, isCurrent))) return;\n if (!allowModeTransition(ctx, \"start plan implementation\")) return;\n }\n const plan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();\n const source = (state.enabled ? state.latestPlanSource : savedPlan?.source) ?? \"legacy_proposed_plan\";\n if (!plan) return;\n\n const previousState = state;\n const previousIntent = readyPresentationIntent;\n const wasEnabled = state.enabled;\n if (!publishModeContract(\"normal\", ctx)) return;\n advanceWorkflowGeneration();\n const retention = configuredImplementationPlanRetention(settings);\n const usesConversationHistory = retention === \"clear-on-start\";\n readyPresentationIntent = undefined;\n workflowAllowedToolNames = undefined;\n state = {\n ...state,\n enabled: false,\n latestPlan: undefined,\n latestPlanSource: undefined,\n awaitingAction: false,\n savedPlan: undefined,\n pendingImplementationRuntime: undefined,\n activeImplementation: usesConversationHistory\n ? undefined\n : {\n id: randomUUID(),\n plan,\n source,\n startedAt: Date.now(),\n retention,\n },\n workflowToolPolicy: undefined,\n manualThinkingLevel: undefined,\n };\n if (wasEnabled) {\n restoreThinkingLevel();\n state = { ...state, manualThinkingLevel: undefined };\n }\n persistState();\n updateUi(ctx);\n\n const handoff = usesConversationHistory\n ? wasEnabled\n ? formatHistoryImplementationPrompt()\n : formatTransferredPlanPrompt(plan, false)\n : formatImplementationHandoff(plan);\n const sent = sendPlanModeUserMessage(handoff, ctx);\n if (!sent) {\n state = previousState;\n readyPresentationIntent = previousIntent;\n if (wasEnabled) {\n restoreWorkflowToolPolicy(state.workflowToolPolicy);\n publishModeContract(\"plan\", ctx);\n applyPlanThinkingLevel();\n }\n persistState();\n updateUi(ctx);\n return;\n }\n if (wasEnabled) releaseWorkflowOwner();\n }\n\n function clearActiveImplementation(id: string, ctx: ExtensionContext) {\n if (state.activeImplementation?.id !== id) return false;\n advanceWorkflowGeneration();\n state = { ...state, activeImplementation: undefined };\n persistState();\n updateUi(ctx);\n return true;\n }\n\n async function exportPlan(\n ctx: ExtensionContext,\n path: string | undefined,\n signal: AbortSignal,\n isCurrent: () => boolean,\n ) {\n const exitsReadyPlan = state.enabled && Boolean(state.latestPlan?.trim());\n if (exitsReadyPlan && !allowModeTransition(ctx, \"export the ready plan and leave Plan mode\")) {\n return false;\n }\n return planExports.export(path, ctx, signal, () => {\n return isCurrent() && (!exitsReadyPlan || ctx.isIdle());\n });\n }\n\n async function showLaunchMenu(ctx: ExtensionContext, initialScreen: \"main\" | \"tools\" = \"main\") {\n const lifecycle = captureMenuLifecycle();\n if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n const ui = await loadInteractiveUi();\n if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n const tools = selectableTools();\n const activeToolNames = new Set(safeGetActiveTools());\n const initialSelectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());\n const retainsInactiveSelection =\n state.selectedToolNames !== undefined ||\n state.selectedToolKeys !== undefined ||\n settings.defaultPlanTools !== undefined;\n const retainedInactiveNames = retainsInactiveSelection ? initialSelectedNames : new Set<string>();\n const registeredNames = new Set(tools.map((tool) => tool.name));\n const pendingNames = Array.from(retainedInactiveNames).filter((name) => !registeredNames.has(name));\n await ui.showPlanLaunchMenu(ctx, {\n statusText: planModeHelperToolsAvailable(safeGetActiveTools())\n ? \"Status: Off \u2014 visible Plan helpers stay inactive until /plan starts.\"\n : \"Status: Off \u2014 required Plan helpers are unavailable under the active tool policy.\",\n initialScreen,\n getSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),\n toolSummary: (selectedNames) => {\n const allowed = tools\n .filter(\n (tool) => activeToolNames.has(tool.name) && selectedNames.has(tool.name) && canSelectToolInPlanMode(tool),\n )\n .map((tool) => tool.name);\n const pending = pendingNames.filter((name) => selectedNames.has(name)).map(terminalToolName);\n const visiblePending = pending.slice(0, 3);\n const pendingSuffix =\n pending.length > visiblePending.length ? `, +${pending.length - visiblePending.length} more` : \"\";\n return [\n `Plan policy will allow: ${allowed.length > 0 ? allowed.join(\", \") : \"none\"}.`,\n ...(pending.length > 0 ? [`Pending registration: ${visiblePending.join(\", \")}${pendingSuffix}.`] : []),\n ].join(\" \");\n },\n tools: [\n ...tools.map((tool) => {\n const selectable = canSelectToolInPlanMode(tool);\n const active = activeToolNames.has(tool.name);\n const retained = retainedInactiveNames.has(tool.name);\n const policy = active\n ? toolPolicyLabel(tool)\n : retained\n ? \"not active yet; retained for first-request resolution\"\n : \"not active in this Pi session\";\n const description = tool.description ?? \"No description available\";\n return {\n name: tool.name,\n description: `${policy} \u00B7 ${description}`,\n searchText: [policy, description].join(\" \"),\n disabled: !selectable || !active,\n disabledReason: !active\n ? retained\n ? \"Not active yet; retained and resolved before the first request\"\n : \"Not active in Pi; Plan mode will not activate it\"\n : selectable\n ? undefined\n : \"Blocked by Plan-mode policy\",\n };\n }),\n ...pendingNames.map((name) => {\n const label = terminalToolName(name);\n return {\n name,\n label,\n description: \"pending registration \u00B7 Retained and resolved before the first Plan request\",\n searchText: `${label} pending registration retained first Plan request`,\n disabled: true,\n disabledReason:\n \"Not registered yet; Plan mode will not activate it and will resolve it before the first request\",\n };\n }),\n ],\n ...lifecycle,\n start: (signal) => {\n if (signal.aborted || !lifecycle.isCurrent()) return;\n if (enterPlanMode(ctx)) {\n ctx.ui.notify(\"Plan mode enabled. I will explore and plan, but not modify files.\", \"info\");\n }\n },\n startWithTools: (names, signal) => {\n if (signal.aborted || !lifecycle.isCurrent()) return;\n const selectedToolNames = Array.from(\n new Set(names.filter((name) => activeToolNames.has(name) || retainedInactiveNames.has(name))),\n );\n if (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: undefined })) {\n ctx.ui.notify(\"Plan mode enabled with the selected tools.\", \"info\");\n }\n },\n settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),\n });\n }\n\n async function showActivePlanMenu(ctx: ExtensionContext) {\n if (!ctx.hasUI) {\n ctx.ui.notify(planStatusText(), \"info\");\n return;\n }\n const lifecycle = captureMenuLifecycle();\n if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n const ui = await loadInteractiveUi();\n if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n await ui.showActiveImplementationMenu(ctx, {\n statusText: planStatusText(),\n getExportDestination: () => planExports.getDestination(ctx),\n signal: lifecycle.signal,\n isCurrent: lifecycle.isCurrent,\n show: () => showStoredPlan(pi, ctx, state),\n exportPlan: (path, signal) => planExports.export(path, ctx, signal, lifecycle.isCurrent),\n settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),\n startNew: () => {\n if (enterPlanMode(ctx)) {\n ctx.ui.notify(\"Plan mode enabled. I will explore and plan, but not modify files.\", \"info\");\n }\n },\n clear: () => {\n if (exitPlanMode(ctx)) ctx.ui.notify(\"Active implementation plan cleared.\", \"info\");\n },\n });\n }\n\n async function showSettings(ctx: ExtensionContext, signal: AbortSignal, isCurrent: () => boolean) {\n if (!isCurrent() || signal.aborted) return false;\n const ui = await loadInteractiveUi();\n if (!isCurrent() || signal.aborted) return false;\n const result = await ui.showPlanModeSettings(ctx, {\n tools: selectableTools(),\n activeToolNames: safeGetActiveTools(),\n signal,\n isCurrent,\n settingsPath: dependencies.settingsPath,\n updateSettings: dependencies.updateSettings ?? updatePlanModeSettings,\n onSaved: (saved) => {\n if (!isCurrent()) return;\n settings = saved;\n applyPlanModeShortcut(configuredPlanModeToggleShortcut(saved));\n },\n ...(dependencies.readSettings\n ? { readSettings: async () => dependencies.readSettings?.() ?? { kind: \"missing\" } }\n : {}),\n });\n return result.kind === \"closed\" && \"reason\" in result && result.reason === \"close\";\n }\n\n function allowModeTransition(ctx: ExtensionContext, action: string) {\n if (ctx.isIdle()) return true;\n const message = `Cannot ${action} while an agent run is active. Wait for the run to settle, then retry.`;\n if (!ctx.hasUI) throw new Error(message);\n ctx.ui.notify(message, \"warning\");\n return false;\n }\n\n function advanceWorkflowGeneration() {\n cancelDeferredFreshImplementation();\n workflowGeneration += 1;\n pendingWorkflowToolPolicy = undefined;\n finalizationRequest.reset();\n }\n\n function finalizationRunOutcome(messages: unknown): FinalizationRunOutcome {\n const stopReason = latestAssistantStopReason(messages);\n if (stopReason === undefined || stopReason === \"stop\") return \"normal\";\n if (stopReason === \"aborted\") return \"cancelled\";\n return \"error\";\n }\n\n function captureMenuLifecycle() {\n const sessionGeneration = menuGeneration;\n const planWorkflowGeneration = workflowGeneration;\n const owner = workflowOwner;\n const controller = menuController;\n return {\n signal: controller.signal,\n isCurrent: () =>\n sessionGeneration === menuGeneration &&\n planWorkflowGeneration === workflowGeneration &&\n !controller.signal.aborted &&\n (!state.enabled || workflowMutex.isOwner(owner)),\n };\n }\n\n function planModePolicyToolNames() {\n if (state.enabled) return workflowAllowedToolNames ?? [];\n return computePlanModePolicyToolNames();\n }\n\n function workflowDesiredToolNames() {\n const policy = state.workflowToolPolicy;\n if (!state.enabled || !policy) return new Set<string>();\n return new Set(policy.kind === \"automatic\" ? automaticPlanModeToolNames() : (policy.desiredNames ?? []));\n }\n\n function beginWorkflowToolPolicy() {\n const kind = toolPolicySelectionIsExplicit() ? \"explicit\" : \"automatic\";\n const desiredNames = desiredPlanModeToolNames();\n const allowedNames = resolvePlanModePolicyToolNames(desiredNames);\n const policy: PlanModeWorkflowToolPolicy = {\n kind,\n ...(kind === \"explicit\" ? { desiredNames } : {}),\n allowedNames,\n resolved: false,\n };\n state = { ...state, workflowToolPolicy: policy };\n pendingWorkflowToolPolicy = { generation: workflowGeneration, mode: \"resolve\" };\n workflowAllowedToolNames = allowedNames;\n }\n\n function resolvePendingWorkflowToolPolicy(ctx: ExtensionContext) {\n const pending = pendingWorkflowToolPolicy;\n if (!pending) return;\n if (pending.generation !== workflowGeneration || !state.enabled || !workflowMutex.isOwner(workflowOwner)) {\n pendingWorkflowToolPolicy = undefined;\n return;\n }\n const policy = state.workflowToolPolicy;\n const expectedResolved = pending.mode === \"revalidate\";\n if (!policy || policy.resolved !== expectedResolved) {\n pendingWorkflowToolPolicy = undefined;\n return;\n }\n const allowedNames =\n pending.mode === \"resolve\" ? resolveWorkflowToolPolicy(policy) : revalidateFrozenWorkflowToolPolicy(policy);\n const policyChanged = !policy.resolved || !arrayEquals(policy.allowedNames, allowedNames);\n workflowAllowedToolNames = allowedNames;\n state = {\n ...state,\n workflowToolPolicy: { ...policy, allowedNames, resolved: true },\n };\n pendingWorkflowToolPolicy = undefined;\n if (policyChanged) persistState();\n updateUi(ctx);\n }\n\n function toolPolicySelectionIsExplicit() {\n return (\n state.selectedToolNames !== undefined ||\n state.selectedToolKeys !== undefined ||\n settings.defaultPlanTools !== undefined\n );\n }\n\n function desiredPlanModeToolNames() {\n const tools = activePlanPolicyTools();\n return Array.from(snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()));\n }\n\n function automaticPlanModeToolNames() {\n return Array.from(snapshotPlanModeSelectedNames(activePlanPolicyTools(), {}));\n }\n\n function resolveWorkflowToolPolicy(policy: PlanModeWorkflowToolPolicy) {\n return resolvePlanModePolicyToolNames(\n policy.kind === \"automatic\" ? automaticPlanModeToolNames() : (policy.desiredNames ?? []),\n );\n }\n\n function revalidateFrozenWorkflowToolPolicy(policy: PlanModeWorkflowToolPolicy) {\n const currentlyAllowed = new Set(\n policy.kind === \"automatic\"\n ? resolvePlanModePolicyToolNames(automaticPlanModeToolNames())\n : resolvePlanModePolicyToolNames(policy.allowedNames),\n );\n return policy.allowedNames.filter((name) => currentlyAllowed.has(name));\n }\n\n function restoreWorkflowToolPolicy(policy: PlanModeWorkflowToolPolicy | undefined) {\n let nextPolicy: PlanModeWorkflowToolPolicy;\n if (!policy) {\n const kind = toolPolicySelectionIsExplicit() ? \"explicit\" : \"automatic\";\n const desiredNames = desiredPlanModeToolNames();\n nextPolicy = {\n kind,\n ...(kind === \"explicit\" ? { desiredNames } : {}),\n allowedNames: resolvePlanModePolicyToolNames(desiredNames),\n resolved: true,\n };\n } else if (policy.resolved) {\n nextPolicy = policy;\n } else {\n nextPolicy = {\n ...policy,\n allowedNames: resolveWorkflowToolPolicy(policy),\n };\n }\n state = { ...state, workflowToolPolicy: nextPolicy };\n workflowAllowedToolNames = nextPolicy.resolved\n ? revalidateFrozenWorkflowToolPolicy(nextPolicy)\n : nextPolicy.allowedNames;\n pendingWorkflowToolPolicy = {\n generation: workflowGeneration,\n mode: nextPolicy.resolved ? \"revalidate\" : \"resolve\",\n };\n return !workflowToolPoliciesEqual(policy, nextPolicy);\n }\n\n function workflowToolPoliciesEqual(left: PlanModeWorkflowToolPolicy | undefined, right: PlanModeWorkflowToolPolicy) {\n return (\n left?.kind === right.kind &&\n left.resolved === right.resolved &&\n arrayEquals(left.allowedNames, right.allowedNames) &&\n arrayEquals(left.desiredNames ?? [], right.desiredNames ?? [])\n );\n }\n\n function arrayEquals(left: readonly string[], right: readonly string[]) {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n }\n\n function computePlanModePolicyToolNames() {\n return resolvePlanModePolicyToolNames(desiredPlanModeToolNames());\n }\n\n function resolvePlanModePolicyToolNames(desiredNames: readonly string[]) {\n const selectedNames = new Set(desiredNames);\n return activePlanPolicyTools()\n .filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool))\n .map((tool) => tool.name);\n }\n\n function toolSelectionSnapshot() {\n return {\n selectedToolNames: state.selectedToolNames,\n selectedToolKeys: state.selectedToolKeys,\n defaultPlanTools: settings.defaultPlanTools,\n };\n }\n\n function selectableTools() {\n return safeGetAllTools()\n .filter((tool) => tool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME)\n .sort(compareTools);\n }\n\n function activePlanPolicyTools() {\n const activeNames = new Set(safeGetActiveTools());\n return selectableTools().filter((tool) => activeNames.has(tool.name));\n }\n\n function safeGetAllTools() {\n try {\n return pi.getAllTools();\n } catch {\n return [];\n }\n }\n\n function runtimeAdmissionIsPending(sessionManager: ExtensionContext[\"sessionManager\"]) {\n return (\n activeImplementationRuntimeApplication?.sessionManager === sessionManager ||\n pendingRuntimeAdmissionSession === sessionManager ||\n queuedRuntimeAdmissionInputs.some((queued) => queued.sessionManager === sessionManager)\n );\n }\n\n function takeQueuedRuntimeAdmissionInputs(sessionManager: ExtensionContext[\"sessionManager\"]) {\n const matching: QueuedRuntimeAdmissionInput[] = [];\n const remaining: QueuedRuntimeAdmissionInput[] = [];\n for (const queued of queuedRuntimeAdmissionInputs) {\n if (queued.sessionManager === sessionManager) matching.push(queued);\n else remaining.push(queued);\n }\n queuedRuntimeAdmissionInputs = remaining;\n return matching;\n }\n\n function removeQueuedRuntimeAdmissionInput(queuedInput: QueuedRuntimeAdmissionInput) {\n const index = queuedRuntimeAdmissionInputs.indexOf(queuedInput);\n if (index >= 0) queuedRuntimeAdmissionInputs.splice(index, 1);\n }\n\n function runtimeAdmissionInputContent(queued: QueuedRuntimeAdmissionInput) {\n return queued.images?.length ? [{ type: \"text\" as const, text: queued.text }, ...queued.images] : queued.text;\n }\n\n function refreshStateForFirstPrompt(ctx: ExtensionContext) {\n if (!refreshStateBeforeFirstAgentStart) return;\n refreshStateBeforeFirstAgentStart = false;\n implementationRetention.reset();\n const branch = ctx.sessionManager.getBranch();\n const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);\n restoreModeContractTracking(branch, restoredState);\n if (!installRestoredState(restoredState, ctx)) return;\n implementationRetention.restore(state.activeImplementation);\n updateUi(ctx);\n }\n\n async function applyPendingImplementationRuntime(\n ctx: ExtensionContext,\n holdForAdmission = false,\n ): Promise<ImplementationRuntimeApplicationResult> {\n const session = ctx.sessionManager;\n const activeApplication = activeImplementationRuntimeApplication;\n if (activeApplication?.sessionManager === session) {\n if (holdForAdmission) activeApplication.holdForAdmission = true;\n return activeApplication.completion;\n }\n\n const intent = state.enabled ? undefined : state.pendingImplementationRuntime;\n if (!intent) return \"ready\";\n const generation = menuGeneration;\n const isCurrent = () =>\n currentSession === session && generation === menuGeneration && !menuController.signal.aborted;\n const notifyCurrent = (message: string) => {\n if (!isCurrent()) return;\n try {\n ctx.ui.notify(message, \"warning\");\n } catch {\n // The session can become stale while an asynchronous runtime application settles.\n }\n };\n let application!: ActiveImplementationRuntimeApplication;\n const completion = Promise.resolve()\n .then(async (): Promise<ImplementationRuntimeApplicationResult> => {\n if (!isCurrent()) return \"stale\";\n const pendingState = state;\n const previousThinkingLevel = pi.getThinkingLevel();\n\n const applyThinking = () => {\n if (!intent.thinkingLevel) return;\n try {\n pi.setThinkingLevel(intent.thinkingLevel);\n const effectiveLevel = pi.getThinkingLevel();\n if (effectiveLevel !== intent.thinkingLevel) {\n notifyCurrent(\n `Implementation thinking ${intent.thinkingLevel} is unsupported by the destination model; Pi is using ${effectiveLevel}.`,\n );\n }\n } catch (error: unknown) {\n notifyCurrent(\n `Implementation thinking ${intent.thinkingLevel} could not be applied: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default will continue.`,\n );\n }\n };\n\n if (intent.model) {\n let model: ReturnType<ExtensionContext[\"modelRegistry\"][\"find\"]>;\n let resolutionFailed = false;\n try {\n model = ctx.modelRegistry.find(intent.model.provider, intent.model.modelId);\n } catch (error: unknown) {\n notifyCurrent(\n `Implementation model ${terminalModelReference(intent.model)} could not be resolved: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`,\n );\n resolutionFailed = true;\n model = undefined;\n }\n if (!model && !resolutionFailed) {\n notifyCurrent(\n `Implementation model ${terminalModelReference(intent.model)} is no longer available. The destination default model will continue.`,\n );\n }\n if (model) {\n let authenticated = false;\n try {\n const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);\n if (!isCurrent()) return \"stale\";\n if (auth.ok) authenticated = true;\n else {\n notifyCurrent(\n `Implementation model ${terminalModelReference(intent.model)} could not be authenticated: ${safeTerminalText(auth.error)}. The destination default model will continue.`,\n );\n }\n } catch (error: unknown) {\n notifyCurrent(\n `Implementation model ${terminalModelReference(intent.model)} could not be authenticated: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`,\n );\n }\n if (!isCurrent()) return \"stale\";\n if (authenticated) {\n let applied = false;\n let applicationFailed = false;\n application.drainOnShutdown = true;\n try {\n try {\n applied = await pi.setModel(model);\n } catch (error: unknown) {\n applicationFailed = true;\n notifyCurrent(\n `Implementation model ${terminalModelReference(intent.model)} could not be applied: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`,\n );\n }\n } finally {\n application.drainOnShutdown = false;\n }\n if (!isCurrent()) return \"stale\";\n if (!applied && !applicationFailed) {\n notifyCurrent(\n `Implementation model ${terminalModelReference(intent.model)} could not be applied after authentication changed. The destination default model will continue.`,\n );\n }\n }\n }\n }\n if (!isCurrent()) return \"stale\";\n applyThinking();\n if (!isCurrent()) return \"stale\";\n\n state = { ...state, pendingImplementationRuntime: undefined };\n try {\n persistState();\n } catch (error: unknown) {\n state = pendingState;\n try {\n if (pi.getThinkingLevel() !== previousThinkingLevel) {\n pi.setThinkingLevel(previousThinkingLevel);\n }\n } catch {\n // Keep the durable intent pending even if a runtime rollback is unavailable.\n }\n try {\n persistState();\n } catch {\n // SessionManager mutates its in-memory branch before a disk append can fail.\n // A best-effort rollback entry keeps that branch aligned with durable pending state.\n }\n notifyCurrent(\n `Unable to apply fresh implementation settings because their one-shot state could not be consumed: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The implementation request was not sent; retry after session persistence is available.`,\n );\n return \"blocked\";\n }\n if (application.holdForAdmission) pendingRuntimeAdmissionSession = session;\n return \"ready\";\n })\n .finally(() => {\n if (activeImplementationRuntimeApplication === application) {\n activeImplementationRuntimeApplication = undefined;\n }\n });\n application = {\n sessionManager: session,\n completion,\n drainOnShutdown: false,\n holdForAdmission,\n };\n activeImplementationRuntimeApplication = application;\n return completion;\n }\n\n function applyPlanThinkingLevel() {\n if (state.manualThinkingLevel) {\n if (pi.getThinkingLevel() !== state.manualThinkingLevel) {\n pi.setThinkingLevel(state.manualThinkingLevel);\n }\n return;\n }\n const configured = configuredThinkingLevel(settings);\n if (!configured) {\n state = {\n ...state,\n previousThinkingLevel: undefined,\n appliedThinkingLevel: undefined,\n };\n return;\n }\n const current = pi.getThinkingLevel();\n if (!state.appliedThinkingLevel) state.previousThinkingLevel = current;\n if (current !== configured) pi.setThinkingLevel(configured);\n state.appliedThinkingLevel = pi.getThinkingLevel();\n }\n\n function captureManualThinkingLevel() {\n if (!state.appliedThinkingLevel) return;\n const current = pi.getThinkingLevel();\n if (current === state.appliedThinkingLevel) return;\n state = {\n ...state,\n manualThinkingLevel: current,\n previousThinkingLevel: undefined,\n appliedThinkingLevel: undefined,\n };\n }\n\n function restoreThinkingLevel() {\n captureManualThinkingLevel();\n const { appliedThinkingLevel, previousThinkingLevel } = state;\n if (appliedThinkingLevel && previousThinkingLevel && pi.getThinkingLevel() === appliedThinkingLevel) {\n pi.setThinkingLevel(previousThinkingLevel);\n }\n state = { ...state, appliedThinkingLevel: undefined, previousThinkingLevel: undefined };\n }\n\n function safeGetActiveTools() {\n try {\n return pi.getActiveTools();\n } catch {\n return DEFAULT_TOOLS;\n }\n }\n\n function installRestoredState(candidate: PlanModeState, ctx: ExtensionContext) {\n const previousState = state;\n const previousWorkflowAllowedToolNames = workflowAllowedToolNames;\n const previousPendingWorkflowToolPolicy = pendingWorkflowToolPolicy;\n const previousOwner = workflowOwner;\n const wasEnabled = state.enabled;\n if (candidate.enabled && !workflowMutex.isOwner(workflowOwner)) {\n const owner = workflowMutex.acquire();\n if (!owner) {\n state = { enabled: false, awaitingAction: false };\n workflowAllowedToolNames = undefined;\n pendingWorkflowToolPolicy = undefined;\n reportRestoredWorkflowBusy(ctx);\n return false;\n }\n workflowOwner = owner;\n }\n\n try {\n if (candidate.enabled) {\n try {\n assertPlanModeHelperToolsAvailable(safeGetActiveTools());\n } catch {\n state = { enabled: false, awaitingAction: false };\n workflowAllowedToolNames = undefined;\n pendingWorkflowToolPolicy = undefined;\n if (workflowOwner !== previousOwner) {\n workflowMutex.release(workflowOwner);\n workflowOwner = previousOwner;\n }\n reportRestoredHelpersUnavailable(ctx);\n return false;\n }\n }\n if (wasEnabled && !candidate.enabled) {\n readyPresentationIntent = undefined;\n restoreThinkingLevel();\n }\n state = candidate;\n const policyChanged = state.enabled ? restoreWorkflowToolPolicy(state.workflowToolPolicy) : false;\n if (!state.enabled) {\n workflowAllowedToolNames = undefined;\n pendingWorkflowToolPolicy = undefined;\n }\n if (policyChanged) persistState();\n if (state.enabled) applyPlanThinkingLevel();\n else if (wasEnabled) releaseWorkflowOwner();\n return true;\n } catch (error: unknown) {\n try {\n if (!wasEnabled && state.enabled) restoreThinkingLevel();\n } finally {\n state = previousState;\n workflowAllowedToolNames = previousWorkflowAllowedToolNames;\n pendingWorkflowToolPolicy = previousPendingWorkflowToolPolicy;\n if (workflowOwner !== previousOwner) {\n workflowMutex.release(workflowOwner);\n workflowOwner = previousOwner;\n }\n }\n throw error;\n }\n }\n\n function rollbackNewActivation(\n previousState: PlanModeState,\n ctx: ExtensionContext,\n previousOwner?: WorkflowMutexOwner,\n ) {\n const activatedOwner = workflowOwner;\n readyPresentationIntent = undefined;\n try {\n if (state.enabled) {\n publishModeContract(\"normal\", ctx);\n restoreThinkingLevel();\n }\n } finally {\n state = previousState;\n workflowAllowedToolNames = undefined;\n pendingWorkflowToolPolicy = undefined;\n try {\n persistState();\n updateUi(ctx);\n } finally {\n if (activatedOwner !== previousOwner) {\n workflowMutex.release(activatedOwner);\n workflowOwner = previousOwner;\n }\n }\n }\n }\n\n function bindWorkflowSessionIfNeeded(ctx: ExtensionContext) {\n if (currentSession === ctx.sessionManager) return;\n currentSession = ctx.sessionManager;\n workflowOwner = undefined;\n workflowMutex.bindSession(ctx.sessionManager);\n }\n\n function releaseWorkflowOwner() {\n const owner = workflowOwner;\n workflowMutex.release(owner);\n if (!workflowMutex.isOwner(owner)) workflowOwner = undefined;\n }\n\n function reportWorkflowBusy(ctx: ExtensionContext) {\n const message = \"Another workflow is active in this session. End it before starting Plan mode.\";\n if (!ctx.hasUI) throw new Error(message);\n ctx.ui.notify(message, \"warning\");\n return false;\n }\n\n function reportRestoredWorkflowBusy(ctx: ExtensionContext) {\n if (!ctx.hasUI) return;\n ctx.ui.notify(\n \"Plan mode was not restored because another workflow is active in this session. Reload or start Plan mode after it ends.\",\n \"warning\",\n );\n }\n\n function reportRestoredHelpersUnavailable(ctx: ExtensionContext) {\n if (!ctx.hasUI) return;\n ctx.ui.notify(\n \"Plan mode was not restored because its helper tools are unavailable under the active tool policy.\",\n \"warning\",\n );\n }\n\n function reportHelperActivationFailure(ctx: ExtensionContext, error: unknown) {\n const detail = safeTerminalText(error instanceof Error ? error.message : String(error));\n const message = `Cannot start Plan mode: ${detail}.`;\n if (!ctx.hasUI) throw new Error(message, { cause: error });\n ctx.ui.notify(message, \"error\");\n return false;\n }\n\n function updateUi(ctx: ExtensionContext) {\n updatePlanModeUi(ctx, state, formatToolSummary);\n }\n\n function clearUi(ctx: ExtensionContext) {\n clearPlanModeUi(ctx);\n }\n\n function planStatusText() {\n return formatPlanModeStatusText(state, formatToolSummary);\n }\n\n function implementationOutcome() {\n return implementationRetentionPreview(configuredImplementationPlanRetention(settings));\n }\n\n function formatToolSummary() {\n const names = planModePolicyToolNames();\n return `Plan policy allows: ${names.length > 0 ? names.join(\", \") : \"none\"}. Model-visible tools stay unchanged.`;\n }\n\n function toolByName(toolName: string) {\n return safeGetAllTools().find((candidate) => candidate.name === toolName);\n }\n\n function terminalToolName(value: string) {\n const safe = safeTerminalText(value) || \"(unnamed tool)\";\n return safe.length > 120 ? `${safe.slice(0, 119)}\u2026` : safe;\n }\n\n function terminalModelReference(model: { provider: string; modelId: string }) {\n const safe = safeTerminalText(`${model.provider}/${model.modelId}`) || \"(unnamed model)\";\n return safe.length > 160 ? `${safe.slice(0, 159)}\u2026` : safe;\n }\n\n function terminalErrorDetail(error: unknown) {\n const safe = safeTerminalText(error instanceof Error ? error.message : String(error));\n if (!safe) return \"unknown error\";\n return safe.length > 500 ? `${safe.slice(0, 499)}\u2026` : safe;\n }\n\n function safeTerminalText(value: string) {\n return [...stripVTControlCharacters(value)]\n .map((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n return codePoint <= 0x1f ||\n (codePoint >= 0x7f && codePoint <= 0x9f) ||\n (codePoint >= 0x202a && codePoint <= 0x202e) ||\n (codePoint >= 0x2066 && codePoint <= 0x2069)\n ? \" \"\n : character;\n })\n .join(\"\")\n .trim();\n }\n}\n\nexport { completePlanArguments } from \"./command.js\";\nexport {\n extractProposedPlan,\n latestAssistantText,\n parseProposedPlan,\n stripProposedPlanBlocks,\n stripProposedPlanBlocksFromMessage,\n} from \"./message-transform.js\";\nexport {\n createModeContractMessage,\n modeContractContent,\n reconcileModeContract,\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 value: string;\n label: string;\n description?: string;\n}\n\nconst PLAN_COMMAND_COMPLETIONS: readonly CommandArgumentCompletion[] = [\n { value: \"start\", label: \"start\", description: \"Start Plan mode without sending a prompt\" },\n { value: \"show\", label: \"show\", description: \"Show the ready, saved, or active plan\" },\n { value: \"finalize\", label: \"finalize\", description: \"Request a completed plan\" },\n { value: \"implement\", label: \"implement\", description: \"Implement the completed or saved plan\" },\n { value: \"save\", label: \"save\", description: \"Save the completed plan for later\" },\n { value: \"settings\", label: \"settings\", description: \"Open Plan mode settings\" },\n { value: \"export\", label: \"export\", description: \"Export the stored plan to a Markdown file\" },\n { value: \"exit\", label: \"exit\", description: \"Leave Plan mode or clear a saved/active plan\" },\n { value: \"off\", label: \"off\", description: \"Leave Plan mode or clear a saved/active plan\" },\n {\n value: \"tools\",\n label: \"tools\",\n description: \"Choose tools before starting this Plan workflow\",\n },\n];\n\nexport function completePlanArguments(argumentPrefix: string): CommandArgumentCompletion[] | null {\n const prefix = argumentPrefix.trimStart().toLowerCase();\n if (prefix === \"\") return [...PLAN_COMMAND_COMPLETIONS];\n if (/\\s/.test(prefix)) return null;\n\n const matches = PLAN_COMMAND_COMPLETIONS.filter((item) => item.value.startsWith(prefix));\n return matches.length > 0 ? [...matches] : null;\n}\n", "export function isStaleExtensionContextError(error: unknown) {\n return (\n error instanceof Error &&\n (error.message.includes(\"This extension ctx is stale after session replacement or reload\") ||\n error.message.includes(\"Extension context is no longer active\"))\n );\n}\n", "export const FINALIZE_PLAN_PROMPT =\n \"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 \"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 workflowGeneration: number;\n retryCount: number;\n awaitingSettlement: boolean;\n}\n\nexport function createFinalizationRequestCoordinator() {\n let pending: PendingFinalizationRequest | undefined;\n\n return {\n request(workflowGeneration: number) {\n pending = { workflowGeneration, retryCount: 0, awaitingSettlement: false };\n },\n satisfy() {\n pending = undefined;\n },\n observeRunEnd(workflowGeneration: number, outcome: FinalizationRunOutcome) {\n if (!pending || pending.workflowGeneration !== workflowGeneration) return;\n if (outcome !== \"normal\") {\n pending = undefined;\n return;\n }\n pending.awaitingSettlement = true;\n },\n settle(workflowGeneration: number): FinalizationSettlementAction {\n if (!pending || pending.workflowGeneration !== workflowGeneration || !pending.awaitingSettlement) {\n return undefined;\n }\n if (pending.retryCount === 0) {\n pending.retryCount = 1;\n pending.awaitingSettlement = false;\n return \"retry\";\n }\n pending = undefined;\n return \"failed\";\n },\n reset() {\n pending = undefined;\n },\n hasPendingRequest() {\n return pending !== undefined;\n },\n };\n}\n", "export interface DeferredFreshHandoffDependencies {\n schedule(callback: () => void): unknown;\n cancel(handle: unknown): void;\n}\n\nexport interface DeferredFreshHandoffCoordinator {\n schedule(run: (isCurrent: () => boolean) => Promise<void>, onError: (error: unknown) => void): void;\n cancel(): void;\n}\n\nconst defaultDependencies: DeferredFreshHandoffDependencies = {\n schedule: (callback) => setTimeout(callback, 0),\n cancel: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n};\n\nexport function createDeferredFreshHandoffCoordinator(\n dependencies: DeferredFreshHandoffDependencies = defaultDependencies,\n): DeferredFreshHandoffCoordinator {\n let generation = 0;\n let pending: { generation: number; handle: unknown } | undefined;\n\n const cancel = () => {\n generation += 1;\n if (!pending) return;\n dependencies.cancel(pending.handle);\n pending = undefined;\n };\n\n return {\n schedule(run, onError) {\n cancel();\n const taskGeneration = generation;\n const handle = dependencies.schedule(() => {\n if (pending?.generation !== taskGeneration || generation !== taskGeneration) return;\n pending = undefined;\n const isCurrent = () => generation === taskGeneration;\n void Promise.resolve()\n .then(() => run(isCurrent))\n .catch((error: unknown) => {\n if (!isCurrent()) return;\n try {\n onError(error);\n } catch {\n // Detached error reporting must not create another unhandled rejection.\n }\n });\n });\n pending = { generation: taskGeneration, handle };\n },\n cancel,\n };\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { stripVTControlCharacters } from \"node:util\";\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 {\n type ImplementationRuntimeSelection,\n isPendingImplementationModelIdentifier,\n MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH,\n type PendingImplementationRuntime,\n type PlanCompletionSource,\n type PlanModeState,\n restorePlanModeState,\n} from \"./state.js\";\n\ntype NewSessionOptions = Exclude<Parameters<ExtensionCommandContext[\"newSession\"]>[0], undefined>;\ntype ReplacementContext = Parameters<NonNullable<NewSessionOptions[\"withSession\"]>>[0];\n\nexport interface FreshImplementationRequest {\n plan: string;\n source: PlanCompletionSource;\n retention: ImplementationPlanRetention;\n stateEntryType: string;\n runtime?: ImplementationRuntimeSelection;\n isCurrent(): boolean;\n}\n\ninterface FreshImplementationFromStateOptions {\n getState(): PlanModeState;\n menuIsCurrent(): boolean;\n retention: ImplementationPlanRetention;\n stateEntryType: string;\n runtime?: ImplementationRuntimeSelection;\n}\n\nexport type FreshImplementationResult =\n | { kind: \"started\" }\n | { kind: \"cancelled\" }\n | { kind: \"partial\" }\n | { kind: \"rejected\" }\n | { kind: \"stale\" };\n\nexport function formatImplementationHandoff(plan: string) {\n return `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:\\n\\n${plan}`;\n}\n\nexport function formatHistoryImplementationPrompt() {\n return PLAN_HISTORY_IMPLEMENTATION_PROMPT;\n}\n\nexport function formatTransferredPlanPrompt(plan: string, fresh: boolean) {\n const destination = fresh ? \" in a fresh context\" : \"\";\n return `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 ctx: ExtensionContext,\n options: FreshImplementationFromStateOptions,\n) {\n if (!isCommandContext(ctx)) {\n ctx.ui.notify(\n \"Fresh implementation requires the interactive /plan command. Reopen /plan and try again.\",\n \"warning\",\n );\n return { kind: \"rejected\" } as const;\n }\n const initialState = options.getState();\n const savedPlan = initialState.enabled ? undefined : initialState.savedPlan;\n const plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();\n const source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;\n if (!plan || !source) {\n ctx.ui.notify(\"No completed plan is available to implement.\", \"warning\");\n return { kind: \"rejected\" } as const;\n }\n const wasEnabled = initialState.enabled;\n const isCurrent = () => {\n const current = options.getState();\n return (\n options.menuIsCurrent() &&\n current.enabled === wasEnabled &&\n (wasEnabled\n ? current.latestPlan === plan && current.latestPlanSource === source\n : current.savedPlan === savedPlan)\n );\n };\n return startFreshImplementationSession(ctx, {\n plan,\n source,\n retention: options.retention,\n stateEntryType: options.stateEntryType,\n runtime: options.runtime,\n isCurrent,\n });\n}\n\nexport async function startFreshImplementationSession(\n ctx: ExtensionCommandContext,\n request: FreshImplementationRequest,\n): Promise<FreshImplementationResult> {\n if (ctx.mode === \"print\" || ctx.mode === \"json\") {\n throw new Error(\"Fresh plan implementation is unavailable in print/JSON mode. Use TUI or RPC.\");\n }\n\n await ctx.waitForIdle();\n if (!request.isCurrent()) return { kind: \"stale\" };\n if (!(await preflightModel(ctx, request))) return { kind: \"rejected\" };\n if (!request.isCurrent()) return { kind: \"stale\" };\n\n const usesConversationHistory = request.retention === \"clear-on-start\";\n const pendingImplementationRuntime = pendingRuntimeIntent(request.runtime);\n const activeImplementation = usesConversationHistory\n ? undefined\n : {\n id: randomUUID(),\n plan: request.plan,\n source: request.source,\n startedAt: Date.now(),\n retention: request.retention,\n };\n const destinationState: PlanModeState | undefined =\n activeImplementation || pendingImplementationRuntime\n ? {\n enabled: false,\n awaitingAction: false,\n ...(activeImplementation ? { activeImplementation } : {}),\n ...(pendingImplementationRuntime ? { pendingImplementationRuntime } : {}),\n }\n : undefined;\n const handoff = usesConversationHistory\n ? formatTransferredPlanPrompt(request.plan, true)\n : formatImplementationHandoff(request.plan);\n const parentSession = ctx.sessionManager.getSessionFile();\n let setupError: string | undefined;\n let kickoffError: string | undefined;\n\n if (ctx.mode === \"rpc\") safeNotify(ctx, \"Starting fresh implementation session\u2026\", \"info\");\n\n let result: Awaited<ReturnType<ExtensionCommandContext[\"newSession\"]>>;\n try {\n result = await ctx.newSession({\n ...(parentSession ? { parentSession } : {}),\n setup: async (sessionManager) => {\n try {\n const contract = createModeContractMessage(\"normal\");\n sessionManager.appendCustomMessageEntry(\n contract.customType,\n contract.content,\n contract.display,\n contract.details,\n );\n if (destinationState) {\n sessionManager.appendCustomEntry(request.stateEntryType, destinationState);\n }\n } catch (error: unknown) {\n setupError = safeErrorDetail(error);\n }\n },\n withSession: async (replacementCtx) => {\n if (setupError) {\n recoverSetupFailure(replacementCtx, handoff, setupError);\n return;\n }\n const reportKickoffFailure = (detail: string) => {\n kickoffError = detail;\n const recoveredInEditor = usesConversationHistory && safeSetEditorText(replacementCtx, handoff);\n safeNotify(\n replacementCtx,\n usesConversationHistory\n ? recoveredInEditor\n ? `Fresh session created, but implementation did not start: ${detail}. The implementation request is in the editor; submit it or resume the parent planning session.`\n : `Fresh session created, but implementation did not start: ${detail}. The implementation request could not be restored to the editor; resume the parent planning session.`\n : `Fresh session created, but implementation did not start: ${detail}. Send a message to continue, use /plan exit to clear the active plan, or resume the parent planning session.`,\n \"error\",\n );\n };\n try {\n await replacementCtx.sendUserMessage(handoff);\n } catch (error: unknown) {\n reportKickoffFailure(safeErrorDetail(error));\n return;\n }\n if (pendingImplementationRuntime) {\n const runtimeStatus = destinationRuntimeConsumptionStatus(replacementCtx, request.stateEntryType);\n if (runtimeStatus !== \"consumed\") {\n reportKickoffFailure(\n runtimeStatus === \"pending\"\n ? \"fresh implementation settings could not be consumed\"\n : \"fresh implementation settings could not be verified as consumed\",\n );\n return;\n }\n }\n safeNotify(\n replacementCtx,\n \"Fresh implementation session started. Only the approved plan was transferred.\",\n \"info\",\n );\n },\n });\n } catch (error: unknown) {\n safeNotify(\n ctx,\n `Unable to start a fresh implementation session: ${safeErrorDetail(error)}. The source plan remains available; retry or resume the planning session.`,\n \"error\",\n );\n return { kind: \"rejected\" };\n }\n\n if (result.cancelled) {\n safeNotify(ctx, \"Fresh implementation cancelled. The plan remains available.\", \"info\");\n return { kind: \"cancelled\" };\n }\n return setupError || kickoffError ? { kind: \"partial\" } : { kind: \"started\" };\n}\n\nasync function preflightModel(ctx: ExtensionCommandContext, request: FreshImplementationRequest) {\n const requestedModel = request.runtime?.model;\n let model = ctx.model;\n if (requestedModel) {\n if (\n !isPendingImplementationModelIdentifier(requestedModel.provider) ||\n !isPendingImplementationModelIdentifier(requestedModel.modelId)\n ) {\n notifyCurrent(\n ctx,\n request,\n `Unable to implement the plan: implementation model provider and ID must each contain 1-${MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH} characters. Choose another model and retry.`,\n \"warning\",\n );\n return false;\n }\n const isCurrentModel = ctx.model?.provider === requestedModel.provider && ctx.model.id === requestedModel.modelId;\n if (!isCurrentModel) {\n try {\n model = ctx.modelRegistry.find(requestedModel.provider, requestedModel.modelId);\n } catch (error: unknown) {\n notifyCurrent(ctx, request, `Unable to implement the plan: ${safeErrorDetail(error)}`, \"error\");\n return false;\n }\n }\n if (!model) {\n notifyCurrent(\n ctx,\n request,\n `Unable to implement the plan: implementation model ${safeModelReference(requestedModel)} is no longer available. Choose another model and retry.`,\n \"warning\",\n );\n return false;\n }\n }\n if (!model) {\n notifyCurrent(ctx, request, \"Unable to implement the plan: no model is selected.\", \"warning\");\n return false;\n }\n let auth: Awaited<ReturnType<ExtensionCommandContext[\"modelRegistry\"][\"getApiKeyAndHeaders\"]>>;\n try {\n auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);\n } catch (error: unknown) {\n notifyCurrent(ctx, request, `Unable to implement the plan: ${safeErrorDetail(error)}`, \"error\");\n return false;\n }\n if (!request.isCurrent()) return false;\n if (!auth.ok) {\n notifyCurrent(\n ctx,\n request,\n requestedModel\n ? `Unable to implement the plan with ${safeModelReference(model)}: ${safeErrorDetail(auth.error)}. Choose another model or configure authentication, then retry.`\n : `Unable to implement the plan: ${safeErrorDetail(auth.error)}`,\n \"warning\",\n );\n return false;\n }\n return true;\n}\n\nfunction notifyCurrent(\n ctx: Pick<ExtensionContext, \"ui\">,\n request: FreshImplementationRequest,\n message: string,\n level: \"info\" | \"warning\" | \"error\",\n) {\n if (request.isCurrent()) safeNotify(ctx, message, level);\n}\n\nfunction pendingRuntimeIntent(\n selection: ImplementationRuntimeSelection | undefined,\n): PendingImplementationRuntime | undefined {\n if (!selection?.model && !selection?.thinkingLevel) return undefined;\n return {\n version: 1,\n ...(selection.model ? { model: { provider: selection.model.provider, modelId: selection.model.modelId } } : {}),\n ...(selection.thinkingLevel ? { thinkingLevel: selection.thinkingLevel } : {}),\n };\n}\n\nfunction safeModelReference(model: { provider: string; id?: string; modelId?: string }) {\n return safeErrorDetail(`${model.provider}/${model.modelId ?? model.id ?? \"unknown\"}`);\n}\n\nfunction destinationRuntimeConsumptionStatus(\n ctx: ReplacementContext,\n stateEntryType: string,\n): \"consumed\" | \"pending\" | \"unavailable\" {\n try {\n return restorePlanModeState(ctx.sessionManager.getBranch(), stateEntryType).pendingImplementationRuntime\n ? \"pending\"\n : \"consumed\";\n } catch {\n return \"unavailable\";\n }\n}\n\nfunction recoverSetupFailure(ctx: ReplacementContext, handoff: string, setupError: string) {\n const recoveredInEditor = safeSetEditorText(ctx, handoff);\n safeNotify(\n ctx,\n recoveredInEditor\n ? `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 : `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 \"error\",\n );\n}\n\nfunction safeSetEditorText(ctx: Pick<ExtensionContext, \"ui\">, text: string) {\n try {\n ctx.ui.setEditorText(text);\n return true;\n } catch {\n // A replacement context can become stale while Pi reports a partial handoff.\n return false;\n }\n}\n\nfunction safeNotify(ctx: Pick<ExtensionContext, \"ui\">, message: string, level: \"info\" | \"warning\" | \"error\") {\n try {\n ctx.ui.notify(message, level);\n } catch {\n // A source or replacement context can become stale during session replacement.\n }\n}\n\nfunction isCommandContext(ctx: ExtensionContext): ctx is ExtensionCommandContext {\n return typeof (ctx as Partial<ExtensionCommandContext>).newSession === \"function\";\n}\n\nfunction safeErrorDetail(error: unknown) {\n const detail = error instanceof Error ? error.message : String(error);\n const normalized =\n [...stripVTControlCharacters(detail)]\n .map((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n return codePoint <= 0x1f ||\n (codePoint >= 0x7f && codePoint <= 0x9f) ||\n (codePoint >= 0x202a && codePoint <= 0x202e) ||\n (codePoint >= 0x2066 && codePoint <= 0x2069)\n ? \" \"\n : character;\n })\n .join(\"\")\n .replace(/\\s+/gu, \" \")\n .trim() || \"unknown error\";\n const characters = [...normalized];\n return 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 return `${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 role?: string;\n customType?: string;\n content?: unknown;\n details?: unknown;\n}\n\nexport function modeContractContent(mode: PlanModeContract) {\n return mode === \"plan\" ? `${PLAN_CONTRACT_MARKER}\\n${buildPlanModePrompt()}` : NORMAL_CONTRACT;\n}\n\nexport function createModeContractMessage(mode: PlanModeContract, timestamp = Date.now()) {\n return {\n role: \"custom\" as const,\n customType: MODE_CONTRACT_MESSAGE_TYPE,\n content: modeContractContent(mode),\n display: false,\n details: { version: MODE_CONTRACT_VERSION, mode },\n timestamp,\n };\n}\n\nexport function modeContractFromMessage(message: unknown): PlanModeContract | undefined {\n const candidate = unwrapMessage(message);\n if (candidate.customType !== MODE_CONTRACT_MESSAGE_TYPE) return undefined;\n if (candidate.content === modeContractContent(\"plan\")) return \"plan\";\n if (candidate.content === modeContractContent(\"normal\")) return \"normal\";\n return undefined;\n}\n\nexport function hasModeContractArtifact(messages: readonly unknown[]) {\n return messages.some((message) => unwrapMessage(message).customType === MODE_CONTRACT_MESSAGE_TYPE);\n}\n\nexport function latestModeContract(messages: readonly unknown[]) {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const mode = modeContractFromMessage(messages[index]);\n if (mode) return { index, mode };\n }\n return undefined;\n}\n\nexport function reconcileModeContract(messages: unknown[], expected: PlanModeContract) {\n const latest = latestModeContract(messages);\n if (latest?.mode === expected) return messages;\n\n const latestContractIndex = findLatestContractArtifactIndex(messages);\n const insertionIndex = latestContractIndex >= 0 ? latestContractIndex + 1 : leadingSummaryBoundary(messages);\n return [\n ...messages.slice(0, insertionIndex),\n createModeContractMessage(expected, 0),\n ...messages.slice(insertionIndex),\n ];\n}\n\nfunction findLatestContractArtifactIndex(messages: readonly unknown[]) {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (unwrapMessage(messages[index]).customType === MODE_CONTRACT_MESSAGE_TYPE) return index;\n }\n return -1;\n}\n\nfunction leadingSummaryBoundary(messages: readonly unknown[]) {\n let index = unwrapMessage(messages[0]).role === \"system\" ? 1 : 0;\n while (index < messages.length) {\n const role = unwrapMessage(messages[index]).role;\n if (role !== \"compactionSummary\" && role !== \"branchSummary\") break;\n index += 1;\n }\n return index;\n}\n\nfunction unwrapMessage(message: unknown): ContractMessage {\n const entry = message as { message?: unknown } | undefined;\n return (entry?.message ?? message ?? {}) as ContractMessage;\n}\n", "import {\n normalizePlanModeCompletion,\n PLAN_MODE_COMPLETE_TOOL_NAME,\n planFromCompletionDetails,\n} from \"./completion-tool.js\";\nimport { type ImplementationModelOverride, isPendingImplementationModelIdentifier } from \"./implementation-models.js\";\nimport {\n IMPLEMENTATION_PLAN_RETENTIONS,\n type ImplementationPlanRetention,\n PLAN_MODE_THINKING_LEVELS,\n type PlanModeFixedThinkingLevel,\n} from \"./settings.js\";\n\nexport type { ImplementationModelOverride } from \"./implementation-models.js\";\nexport {\n isPendingImplementationModelIdentifier,\n MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH,\n} from \"./implementation-models.js\";\n\nexport type PlanCompletionSource = typeof PLAN_MODE_COMPLETE_TOOL_NAME | \"legacy_proposed_plan\";\n\nexport interface ActiveImplementationPlan {\n id: string;\n plan: string;\n source: PlanCompletionSource;\n startedAt: number;\n retention?: ImplementationPlanRetention;\n}\n\nexport interface SavedPlan {\n plan: string;\n source: PlanCompletionSource;\n}\n\nexport interface ImplementationRuntimeSelection {\n model?: ImplementationModelOverride;\n thinkingLevel?: PlanModeFixedThinkingLevel;\n}\n\nexport interface PendingImplementationRuntime extends ImplementationRuntimeSelection {\n version: 1;\n}\n\nexport interface PlanModeWorkflowToolPolicy {\n kind: \"automatic\" | \"explicit\";\n desiredNames?: string[];\n allowedNames: string[];\n resolved: boolean;\n}\n\nexport interface PlanModeState {\n enabled: boolean;\n latestPlan?: string;\n latestPlanSource?: PlanCompletionSource;\n awaitingAction: boolean;\n savedPlan?: SavedPlan;\n activeImplementation?: ActiveImplementationPlan;\n pendingImplementationRuntime?: PendingImplementationRuntime;\n selectedToolNames?: string[];\n selectedToolKeys?: string[];\n workflowToolPolicy?: PlanModeWorkflowToolPolicy;\n previousThinkingLevel?: PlanModeFixedThinkingLevel;\n appliedThinkingLevel?: PlanModeFixedThinkingLevel;\n manualThinkingLevel?: PlanModeFixedThinkingLevel;\n}\n\ntype SessionEntry = {\n type?: string;\n customType?: string;\n data?: unknown;\n message?: {\n role?: string;\n toolName?: string;\n details?: unknown;\n };\n};\n\nexport function restorePlanModeState(entries: unknown[], stateEntryType: string): PlanModeState {\n const branch = entries as SessionEntry[];\n let stateEntryIndex = -1;\n for (let index = branch.length - 1; index >= 0; index -= 1) {\n const candidate = branch[index];\n if (candidate?.type === \"custom\" && candidate.customType === stateEntryType) {\n stateEntryIndex = index;\n break;\n }\n }\n const entry = branch[stateEntryIndex];\n if (!isRecord(entry?.data)) return { enabled: false, awaitingAction: false };\n\n const enabled = entry.data.enabled === true;\n const persistedSource = enabled ? planCompletionSource(entry.data.latestPlanSource) : undefined;\n const persistedPlan = enabled ? normalizePersistedPlan(entry.data.latestPlan) : undefined;\n const recoveredPlan = enabled && !persistedPlan ? latestCompletionPlan(branch.slice(stateEntryIndex + 1)) : undefined;\n const latestPlan = persistedPlan ?? recoveredPlan;\n const activeImplementation = enabled ? undefined : normalizeActiveImplementation(entry.data.activeImplementation);\n const savedPlan = enabled || activeImplementation ? undefined : normalizeSavedPlan(entry.data.savedPlan);\n const pendingImplementationRuntime = enabled\n ? undefined\n : normalizePendingImplementationRuntime(entry.data.pendingImplementationRuntime);\n return {\n enabled,\n latestPlan,\n latestPlanSource: enabled\n ? ((persistedPlan ? persistedSource : undefined) ?? (recoveredPlan ? PLAN_MODE_COMPLETE_TOOL_NAME : undefined))\n : undefined,\n awaitingAction: enabled && latestPlan !== undefined,\n savedPlan,\n activeImplementation,\n pendingImplementationRuntime,\n selectedToolNames: stringArray(entry.data.selectedToolNames),\n selectedToolKeys: stringArray(entry.data.selectedToolKeys),\n workflowToolPolicy: enabled ? normalizeWorkflowToolPolicy(entry.data.workflowToolPolicy) : undefined,\n previousThinkingLevel: enabled ? fixedThinkingLevel(entry.data.previousThinkingLevel) : undefined,\n appliedThinkingLevel: enabled ? fixedThinkingLevel(entry.data.appliedThinkingLevel) : undefined,\n manualThinkingLevel: enabled ? fixedThinkingLevel(entry.data.manualThinkingLevel) : undefined,\n };\n}\n\nfunction normalizeWorkflowToolPolicy(value: unknown): PlanModeWorkflowToolPolicy | undefined {\n if (value === undefined) return undefined;\n const denied: PlanModeWorkflowToolPolicy = {\n kind: \"automatic\",\n allowedNames: [],\n resolved: true,\n };\n if (!isRecord(value)) return denied;\n const kind = value.kind === \"automatic\" || value.kind === \"explicit\" ? value.kind : undefined;\n const allowedNames = stringArray(value.allowedNames);\n if (!kind || !allowedNames || typeof value.resolved !== \"boolean\") return denied;\n if (kind === \"automatic\") {\n return { kind, allowedNames, resolved: value.resolved };\n }\n const desiredNames = stringArray(value.desiredNames);\n if (!desiredNames) return denied;\n return { kind, desiredNames, allowedNames, resolved: value.resolved };\n}\n\nfunction normalizeSavedPlan(value: unknown): SavedPlan | undefined {\n if (!isRecord(value)) return undefined;\n const source = planCompletionSource(value.source);\n const normalized = normalizePlanModeCompletion({ plan: value.plan });\n if (!source || !normalized.ok) return undefined;\n return { plan: normalized.plan, source };\n}\n\nfunction normalizePendingImplementationRuntime(value: unknown): PendingImplementationRuntime | undefined {\n if (!isRecord(value) || value.version !== 1) return undefined;\n if (Object.keys(value).some((key) => key !== \"version\" && key !== \"model\" && key !== \"thinkingLevel\")) {\n return undefined;\n }\n let model: ImplementationModelOverride | undefined;\n if (value.model !== undefined) {\n if (!isRecord(value.model) || Object.keys(value.model).some((key) => key !== \"provider\" && key !== \"modelId\")) {\n return undefined;\n }\n if (\n !isPendingImplementationModelIdentifier(value.model.provider) ||\n !isPendingImplementationModelIdentifier(value.model.modelId)\n ) {\n return undefined;\n }\n model = { provider: value.model.provider, modelId: value.model.modelId };\n }\n const thinkingLevel = value.thinkingLevel === undefined ? undefined : fixedThinkingLevel(value.thinkingLevel);\n if (value.thinkingLevel !== undefined && !thinkingLevel) return undefined;\n if (!model && !thinkingLevel) return undefined;\n return {\n version: 1,\n ...(model ? { model } : {}),\n ...(thinkingLevel ? { thinkingLevel } : {}),\n };\n}\n\nfunction normalizeActiveImplementation(value: unknown): ActiveImplementationPlan | undefined {\n if (!isRecord(value)) return undefined;\n const id = typeof value.id === \"string\" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value.id) ? value.id : undefined;\n const source = planCompletionSource(value.source);\n const normalized = normalizePlanModeCompletion({ plan: value.plan });\n const startedAt =\n typeof value.startedAt === \"number\" && Number.isSafeInteger(value.startedAt) && value.startedAt >= 0\n ? value.startedAt\n : undefined;\n if (!id || !source || !normalized.ok || startedAt === undefined) return undefined;\n const retention = IMPLEMENTATION_PLAN_RETENTIONS.includes(value.retention as ImplementationPlanRetention)\n ? (value.retention as ImplementationPlanRetention)\n : \"keep\";\n return { id, plan: normalized.plan, source, startedAt, retention };\n}\n\nfunction normalizePersistedPlan(value: unknown) {\n const normalized = normalizePlanModeCompletion({ plan: value });\n return normalized.ok ? normalized.plan : undefined;\n}\n\nfunction latestCompletionPlan(entries: SessionEntry[]) {\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const message = entries[index]?.message;\n if (message?.role !== \"toolResult\" || message.toolName !== PLAN_MODE_COMPLETE_TOOL_NAME) {\n continue;\n }\n const plan = planFromCompletionDetails(message.details);\n if (plan) return plan;\n }\n return undefined;\n}\n\nfunction planCompletionSource(value: unknown): PlanCompletionSource | undefined {\n return value === PLAN_MODE_COMPLETE_TOOL_NAME || value === \"legacy_proposed_plan\" ? value : undefined;\n}\n\nfunction fixedThinkingLevel(value: unknown): PlanModeFixedThinkingLevel | undefined {\n return typeof value === \"string\" &&\n value !== \"inherit\" &&\n PLAN_MODE_THINKING_LEVELS.includes(value as (typeof PLAN_MODE_THINKING_LEVELS)[number])\n ? (value as PlanModeFixedThinkingLevel)\n : undefined;\n}\n\nfunction stringArray(value: unknown) {\n return Array.isArray(value) && value.every((item): item is string => typeof item === \"string\")\n ? Array.from(new Set(value))\n : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport { findAvailableImplementationModel, snapshotAvailableImplementationModels } from \"./implementation-models.js\";\nimport type { PlanExportDestination } from \"./plan-export.js\";\nimport {\n configuredImplementationModel,\n configuredImplementationThinkingLevel,\n type PlanModeFixedThinkingLevel,\n type PlanModeSettings,\n} from \"./settings.js\";\nimport type { ImplementationRuntimeSelection, PlanModeState } from \"./state.js\";\n\ntype InteractiveUi = typeof import(\"./interactive-ui.js\");\n\ninterface MenuLifecycle {\n signal: AbortSignal;\n isCurrent(): boolean;\n}\n\nexport type FreshImplementationTiming = \"immediate\" | \"after-settled\";\n\ninterface PlanActionControllerOptions {\n loadInteractiveUi(): Promise<InteractiveUi>;\n getState(): PlanModeState;\n captureLifecycle(): MenuLifecycle;\n statusText(): string;\n getThinkingLevel(): PlanModeFixedThinkingLevel | undefined;\n getSettings(): PlanModeSettings;\n implementationOutcome(): string;\n getExportDestination(ctx: ExtensionContext): PlanExportDestination;\n show(ctx: ExtensionContext): void;\n finalize(ctx: ExtensionContext): void;\n implementHere(ctx: ExtensionContext): void | Promise<void>;\n implementFresh(\n ctx: ExtensionContext,\n isCurrent: () => boolean,\n runtime: ImplementationRuntimeSelection | undefined,\n timing: FreshImplementationTiming,\n ): void | Promise<void>;\n exportPlan(ctx: ExtensionContext, path: string, signal: AbortSignal, isCurrent: () => boolean): Promise<boolean>;\n settings(ctx: ExtensionContext, signal: AbortSignal, isCurrent: () => boolean): Promise<boolean>;\n save(ctx: ExtensionContext): void;\n stay(ctx: ExtensionContext): void;\n exitReady(ctx: ExtensionContext): void;\n clearSaved(ctx: ExtensionContext): void;\n}\n\nexport function createPlanActionController(options: PlanActionControllerOptions) {\n const configuredDefaults = (): ImplementationRuntimeSelection => {\n const settings = options.getSettings();\n const model = configuredImplementationModel(settings);\n const thinkingLevel = configuredImplementationThinkingLevel(settings);\n return {\n ...(model ? { model: { ...model } } : {}),\n ...(thinkingLevel ? { thinkingLevel } : {}),\n };\n };\n const effectiveDefaults = (ctx: ExtensionContext): ImplementationRuntimeSelection => {\n const configured = configuredDefaults();\n const availableModel = findAvailableImplementationModel(\n snapshotAvailableImplementationModels(ctx),\n configured.model,\n );\n if (configured.model && !availableModel) {\n ctx.ui.notify(\"The configured fresh implementation model is unavailable; using the planning model.\", \"warning\");\n }\n const planModel = ctx.model ? { provider: ctx.model.provider, modelId: ctx.model.id } : undefined;\n const model = availableModel ? { provider: availableModel.provider, modelId: availableModel.id } : planModel;\n const thinkingLevel = configured.thinkingLevel ?? options.getThinkingLevel();\n return {\n ...(model ? { model } : {}),\n ...(thinkingLevel ? { thinkingLevel } : {}),\n };\n };\n const freshAction = (\n ctx: ExtensionContext,\n lifecycle: MenuLifecycle,\n signal: AbortSignal,\n runtime: ImplementationRuntimeSelection | undefined,\n timing: FreshImplementationTiming,\n ) => {\n if (signal.aborted) return;\n const isCurrent = timing === \"after-settled\" ? lifecycle.isCurrent : () => lifecycle.isCurrent() && !signal.aborted;\n return options.implementFresh(ctx, isCurrent, runtime, timing);\n };\n\n return {\n async showSaved(ctx: ExtensionContext) {\n const lifecycle = options.captureLifecycle();\n if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n const ui = await options.loadInteractiveUi();\n if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n await ui.showSavedPlanMenu(ctx, {\n statusText: options.statusText(),\n implementationOutcome: options.implementationOutcome,\n getExportDestination: () => options.getExportDestination(ctx),\n signal: lifecycle.signal,\n isCurrent: lifecycle.isCurrent,\n show: () => options.show(ctx),\n implementHere: () => options.implementHere(ctx),\n implementFresh: (signal) => freshAction(ctx, lifecycle, signal, effectiveDefaults(ctx), \"immediate\"),\n exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),\n settings: (signal) => options.settings(ctx, signal, lifecycle.isCurrent),\n clear: () => options.clearSaved(ctx),\n });\n },\n async showCurrent(ctx: ExtensionContext) {\n if (!ctx.hasUI) {\n ctx.ui.notify(options.statusText(), \"info\");\n return;\n }\n const lifecycle = options.captureLifecycle();\n if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n const ui = await options.loadInteractiveUi();\n if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n await ui.showPlanModeMenu(ctx, {\n statusText: options.statusText(),\n planThinkingLevel: options.getThinkingLevel(),\n implementationDefaults: configuredDefaults(),\n hasReadyPlan: options.getState().latestPlan !== undefined,\n implementationOutcome: options.implementationOutcome,\n getExportDestination: () => options.getExportDestination(ctx),\n ...lifecycle,\n show: () => options.show(ctx),\n finalize: () => options.finalize(ctx),\n implementHere: () => options.implementHere(ctx),\n implementFresh: (runtime, signal) => freshAction(ctx, lifecycle, signal, runtime, \"immediate\"),\n exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),\n save: () => options.save(ctx),\n stay: () => options.stay(ctx),\n exit: () => options.exitReady(ctx),\n });\n },\n async showReady(ctx: ExtensionContext) {\n const lifecycle = options.captureLifecycle();\n if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n const ui = await options.loadInteractiveUi();\n if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;\n await ui.showReadyPlanMenu(ctx, {\n ...lifecycle,\n planThinkingLevel: options.getThinkingLevel(),\n implementationDefaults: configuredDefaults(),\n implementationOutcome: options.implementationOutcome,\n getExportDestination: () => options.getExportDestination(ctx),\n implementHere: () => options.implementHere(ctx),\n implementFresh: (runtime, signal) => freshAction(ctx, lifecycle, signal, runtime, \"after-settled\"),\n exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),\n save: () => options.save(ctx),\n stay: () => undefined,\n exit: () => options.exitReady(ctx),\n });\n },\n };\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 getState(): PlanModeState;\n getSettings(): PlanModeSettings;\n finishReady(ctx: ExtensionContext): void;\n}\n\nexport function createPlanExportController(options: PlanExportControllerOptions) {\n return {\n export(path: string | undefined, ctx: ExtensionContext, signal: AbortSignal, isCurrent: () => boolean) {\n const state = options.getState();\n return exportStoredPlan(\n state,\n path,\n ctx,\n {\n signal,\n isCurrent,\n getState: options.getState,\n finishReady: () => options.finishReady(ctx),\n },\n configuredPlanExportPath(options.getSettings()),\n );\n },\n getDestination(ctx: ExtensionContext) {\n return planExportDestination(configuredPlanExportPath(options.getSettings()), ctx.cwd);\n },\n };\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(ctx: ExtensionContext, state: PlanModeState, toolSummary: () => string) {\n ctx.ui.setStatus(STATUS_KEY, formatStatus(state));\n let lines: string[] | undefined;\n if (state.enabled && state.latestPlan) {\n lines = [\"Proposed plan ready\", \"Use /plan to implement, save, revise, or exit Plan mode.\"];\n } else if (state.enabled) {\n lines = [\"Plan mode: planning\", toolSummary(), \"Finish with plan_mode_complete when decision-ready.\"];\n } else if (state.savedPlan) {\n lines = [\"Plan saved for later\", \"Use /plan to show, implement, or clear it.\"];\n } else if (state.activeImplementation) {\n lines = [\"Implementation plan active\", \"Use /plan to show, replace, or clear it.\"];\n }\n\n publishPlanModeWidget(ctx, lines);\n}\n\nexport function renderPlanModeWidget(lines: readonly string[], theme: Theme, width: number): string[] {\n const renderWidth = Math.max(0, width);\n return [\n theme.fg(\"borderMuted\", \"\u2500\".repeat(renderWidth)),\n ...lines.map((line) => truncateToWidth(sanitizePlanModeWidgetLine(line), renderWidth, \"\")),\n ];\n}\n\nexport function sanitizePlanModeWidgetLine(value: string): string {\n let text = \"\";\n for (const character of stripTerminalSequences(value).replace(BIDI_CONTROLS, \"\")) {\n const codePoint = character.codePointAt(0) ?? 0;\n const isControl = codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);\n text += isControl ? \" \" : character;\n }\n return text;\n}\n\nexport function clearPlanModeUi(ctx: ExtensionContext) {\n ctx.ui.setStatus(STATUS_KEY, undefined);\n ctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);\n}\n\nexport function showStoredPlan(pi: ExtensionAPI, ctx: ExtensionContext, state: PlanModeState) {\n const readyPlan = state.enabled ? state.latestPlan?.trim() : undefined;\n const savedPlan = state.savedPlan?.plan.trim();\n if (savedPlan && (ctx.mode === \"print\" || ctx.mode === \"json\")) {\n throw new Error(\"Saved plan display is unavailable in print/JSON mode. Use TUI or RPC.\");\n }\n const activePlan = state.activeImplementation?.plan.trim();\n const plan = readyPlan ?? savedPlan ?? activePlan;\n if (!plan) {\n ctx.ui.notify(\"No completed plan is available. Use /plan finalize when planning is complete.\", \"info\");\n return;\n }\n const title = readyPlan ? \"Proposed Plan\" : savedPlan ? \"Saved Plan\" : \"Active Implementation Plan\";\n showPlanModePlan(pi, ctx, title, plan);\n}\n\nexport function showPlanModePlan(pi: ExtensionAPI, ctx: ExtensionContext, title: string, plan: string) {\n try {\n pi.sendMessage(\n {\n customType: \"proposed-plan\",\n content: `**${title}**\\n\\n${plan}`,\n display: true,\n },\n { triggerTurn: false },\n );\n } catch (error: unknown) {\n const detail = error instanceof Error ? error.message : String(error);\n ctx.ui.notify(`Unable to show completed plan: ${detail}`, \"error\");\n }\n}\n\nexport function planModeStatusText(state: PlanModeState, toolSummary: () => string) {\n if (state.enabled) {\n if (state.latestPlan) {\n return `Plan mode is active and a proposed plan is ready. ${toolSummary()}`;\n }\n return `Plan mode is active. ${toolSummary()} Explore, ask, and finish with plan_mode_complete when decision-ready.`;\n }\n if (state.savedPlan) return \"A plan is saved for later.\";\n if (state.activeImplementation) return \"An implementation plan is active.\";\n return \"Plan mode is off.\";\n}\n\nfunction publishPlanModeWidget(ctx: ExtensionContext, lines: readonly string[] | undefined) {\n if (!lines) {\n ctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);\n return;\n }\n if (ctx.mode !== \"tui\") {\n ctx.ui.setWidget(PLAN_WIDGET_KEY, [...lines]);\n return;\n }\n\n const snapshot = [...lines];\n ctx.ui.setWidget(PLAN_WIDGET_KEY, (_tui, theme) => ({\n render: (width) => renderPlanModeWidget(snapshot, theme, width),\n invalidate: () => {},\n }));\n}\n\nfunction formatStatus(state: PlanModeState) {\n if (state.enabled) {\n if (state.awaitingAction || state.latestPlan) return \"plan ready\";\n return \"plan active\";\n }\n if (state.savedPlan) return \"plan saved\";\n if (state.activeImplementation) return \"plan implementing\";\n return 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 = [PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME] as const;\n\nexport function planModeHelperToolsAvailable(toolNames: readonly string[]) {\n const active = new Set(toolNames);\n return REQUIRED_PLAN_MODE_TOOL_NAMES.every((name) => active.has(name));\n}\n\nexport function assertPlanModeHelperToolsAvailable(toolNames: readonly string[]) {\n if (planModeHelperToolsAvailable(toolNames)) return;\n throw new Error(\n \"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 );\n}\n\nexport function withRequiredPlanModeTools(toolNames: string[]) {\n return unique([\n ...withoutRequiredPlanModeTools(toolNames),\n PLAN_MODE_QUESTION_TOOL_NAME,\n PLAN_MODE_COMPLETE_TOOL_NAME,\n ]);\n}\n\nexport function withoutRequiredPlanModeTools(toolNames: string[]) {\n return toolNames.filter(\n (toolName) => toolName !== PLAN_MODE_QUESTION_TOOL_NAME && toolName !== PLAN_MODE_COMPLETE_TOOL_NAME,\n );\n}\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\n\nexport function savedPlanBlocksNewWorkflow(ctx: ExtensionContext, hasSavedPlan: boolean) {\n if (!hasSavedPlan) return false;\n const message = \"A plan is saved for later. Implement or clear it before starting another Plan-mode workflow.\";\n if (!ctx.hasUI) throw new Error(message);\n ctx.ui.notify(message, \"warning\");\n return true;\n}\n\nexport async function preflightSavedPlanImplementation(ctx: ExtensionContext, isCurrent: () => boolean) {\n if (ctx.mode === \"print\" || ctx.mode === \"json\") {\n throw new Error(\"Saved plan implementation is unavailable in print/JSON mode. Use TUI or RPC.\");\n }\n const model = ctx.model;\n if (!model) {\n ctx.ui.notify(\"Unable to implement saved plan: no model is selected.\", \"warning\");\n return false;\n }\n let auth: Awaited<ReturnType<ExtensionContext[\"modelRegistry\"][\"getApiKeyAndHeaders\"]>>;\n try {\n auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);\n } catch (error: unknown) {\n if (!isCurrent()) return false;\n const detail = error instanceof Error ? error.message : String(error);\n ctx.ui.notify(`Unable to implement saved plan: ${detail}`, \"error\");\n return false;\n }\n if (!isCurrent()) return false;\n if (!auth.ok) {\n ctx.ui.notify(`Unable to implement saved plan: ${auth.error}`, \"warning\");\n return false;\n }\n return true;\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 session: object;\n group: string;\n busy: boolean;\n}\n\nexport class WorkflowMutex {\n private session: object | undefined;\n private readonly heldGroups = new Map<string, WorkflowMutexOwner>();\n private generation = 0;\n\n constructor(private readonly pi: Pick<ExtensionAPI, \"events\">) {\n pi.events.on(WORKFLOW_MUTEX_CHANNEL, (payload) => {\n this.answer(payload);\n });\n }\n\n bindSession(session: object): void {\n this.generation += 1;\n this.heldGroups.clear();\n this.session = session;\n }\n\n unbindSession(session: object): void {\n if (this.session !== session) return;\n this.generation += 1;\n this.heldGroups.clear();\n this.session = undefined;\n }\n\n acquire(group = AGENT_WORKFLOW_GROUP): WorkflowMutexOwner | undefined {\n const session = this.session;\n const generation = this.generation;\n if (!session || this.heldGroups.has(group)) return undefined;\n\n const attempt: WorkflowMutexAttemptV1 = { session, group, busy: false };\n try {\n this.pi.events.emit(WORKFLOW_MUTEX_CHANNEL, attempt);\n } catch {\n return undefined;\n }\n if (\n this.session !== session ||\n this.generation !== generation ||\n attempt.session !== session ||\n attempt.group !== group ||\n attempt.busy !== false ||\n this.heldGroups.has(group)\n ) {\n return undefined;\n }\n\n const owner = Symbol(group);\n this.heldGroups.set(group, owner);\n return owner;\n }\n\n isOwner(owner: WorkflowMutexOwner | undefined, group = AGENT_WORKFLOW_GROUP): boolean {\n return owner !== undefined && this.heldGroups.get(group) === owner;\n }\n\n release(owner: WorkflowMutexOwner | undefined, group = AGENT_WORKFLOW_GROUP): void {\n if (!this.isOwner(owner, group)) return;\n this.heldGroups.delete(group);\n }\n\n private answer(payload: unknown): void {\n try {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) return;\n const attempt = payload as Partial<WorkflowMutexAttemptV1>;\n if (attempt.session !== this.session) return;\n if (attempt.group !== AGENT_WORKFLOW_GROUP) return;\n if (typeof attempt.busy !== \"boolean\") return;\n if (!this.heldGroups.has(attempt.group)) return;\n attempt.busy = true;\n } catch {\n // Protocol listeners must ignore unusual objects without interrupting sibling listeners.\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,aAAa;AACtB,SAAS,UAAU,eAAe;AAClC,SAAS,4BAAAC,iCAAgC;;;ACGzC,IAAM,2BAAiE;AAAA,EACrE,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,YAAY,OAAO,YAA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