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AAmB,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAO,GAC/G,OAAO,CAAC;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAC;QAAC,YAAY,CAAC,EAAE,kBAAkB,CAAA;KAAE,CAAC,CAiL5G;IAED;;OAEG;IACH,yBAAyB,IAAI,KAAK,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAepE;IAED,OAAO,CAAC,uBAAuB;IAW/B;;OAEG;IACH,eAAe,IAAI,YAAY,CA2C9B;IAED,eAAe,IAAI,YAAY,GAAG,SAAS,CA4C1C;IAED;;;;OAIG;IACG,YAAY,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAiBvD;IAMD;;;;OAIG;IACH,oBAAoB,IAAI,MAAM,GAAG,SAAS,CAsBzC;IAMD;;OAEG;IACH,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAE/C;IAED;;OAEG;IACH,IAAI,eAAe,IAAI,eAAe,GAAG,SAAS,CAEjD;CACD","sourcesContent":["/**\n * AgentSession - Core abstraction for agent lifecycle and session management.\n *\n * This class is shared between all run modes (interactive, print, rpc).\n * It encapsulates:\n * - Agent state access\n * - Event subscription with automatic session persistence\n * - Model and thinking level management\n * - Compaction (manual and auto)\n * - Bash execution\n * - Session switching and branching\n *\n * Modes use this class and add their own I/O layer on top.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport type {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tContextCacheDiagnostics,\n\tThinkingLevel,\n} from \"@apholdings/jensen-agent-core\";\nimport type { AssistantMessage, ImageContent, Message, Model, TextContent } from \"@apholdings/jensen-ai\";\nimport {\n\tisContextOverflow,\n\tmodelsAreEqual,\n\tresetApiProviders,\n\tsupportsXhigh,\n\tvalidateChatCompletionsTranscript,\n\tvalidateResponsesTranscript,\n} from \"@apholdings/jensen-ai\";\nimport { getDocsPath } from \"../config.js\";\nimport { theme } from \"../modes/interactive/theme/theme.js\";\nimport { stripFrontmatter } from \"../utils/frontmatter.js\";\nimport { sleep } from \"../utils/sleep.js\";\nimport { type BashResult, executeBash as executeBashCommand, executeBashWithOperations } from \"./bash-executor.js\";\nimport { createBtwNextTurnMessage, getBtwNoteFromMessage } from \"./btw-command.js\";\nimport type { CavemanLevel } from \"./caveman-command.js\";\nimport {\n\ttype CompactionResult,\n\tcalculateContextTokens,\n\tcollectEntriesForBranchSummary,\n\tcompact,\n\tcreateDeterministicCompactionDetails,\n\testimateContextTokens,\n\tgenerateBranchSummary,\n\tprepareCompaction,\n\tshouldCompact,\n} from \"./compaction/index.js\";\nimport {\n\ttype ContextGovernor,\n\tcreateMissionContextCheckpoint,\n\ttype EvidenceArchive,\n\ttype FindingRecord,\n\ttype MissionContextCheckpoint,\n} from \"./context-runtime/index.js\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.js\";\nimport {\n\tbuildDelegatedWorkSummary,\n\ttype DelegatedTask,\n\ttype DelegatedWorkSummary,\n\textractDelegatedTasks,\n\tgetRecentDelegatedTasks,\n\tmergeDelegatedTask,\n\treconcileDelegatedResult,\n} from \"./delegated-work.js\";\nimport { exportSessionToHtml, type ToolHtmlRenderer } from \"./export-html/index.js\";\nimport { createToolHtmlRenderer } from \"./export-html/tool-renderer.js\";\nimport {\n\ttype ContextUsage,\n\ttype ExtensionCommandContextActions,\n\ttype ExtensionContext,\n\ttype ExtensionErrorListener,\n\tExtensionRunner,\n\ttype ExtensionUIContext,\n\ttype InputSource,\n\ttype MessageEndEvent,\n\ttype MessageStartEvent,\n\ttype MessageUpdateEvent,\n\ttype SessionBeforeCompactResult,\n\ttype SessionBeforeForkResult,\n\ttype SessionBeforeSwitchResult,\n\ttype SessionBeforeTreeResult,\n\ttype ShutdownHandler,\n\ttype ToolDefinition,\n\ttype ToolExecutionEndEvent,\n\ttype ToolExecutionStartEvent,\n\ttype ToolExecutionUpdateEvent,\n\ttype ToolInfo,\n\ttype TreePreparation,\n\ttype TurnEndEvent,\n\ttype TurnStartEvent,\n\twrapRegisteredTools,\n} from \"./extensions/index.js\";\nimport {\n\tclearMemoryItems,\n\tdeleteMemoryItem,\n\tgetMemoryItem,\n\ttype MemoryHistorySnapshot,\n\ttype MemoryItem,\n\tupsertMemoryItems,\n} from \"./memory.js\";\nimport {\n\tbuildStructuredMemoryCompareData,\n\tbuildStructuredMemoryHistoryData,\n\ttype StructuredMemoryCompareData,\n\ttype StructuredMemoryHistoryData,\n} from \"./memory-snapshot-contract.js\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.js\";\nimport type { ModelRegistry } from \"./model-registry.js\";\nimport { expandPromptTemplate, type PromptTemplate } from \"./prompt-templates.js\";\nimport type { MissionDefinitionInput } from \"./reliability/mission-contract-factory.js\";\nimport type { MissionRuntime } from \"./reliability/mission-runtime.js\";\nimport { ReliabilitySessionController } from \"./reliability/session-controller.js\";\nimport { createWorkspaceVerificationExecutor } from \"./reliability/workspace-verification.js\";\nimport type { ResourceExtensionPaths, ResourceLoader } from \"./resource-loader.js\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tMemorySnapshotResolution,\n\tSessionManager,\n} from \"./session-manager.js\";\nimport { getLatestCompactionEntry } from \"./session-manager.js\";\nimport type { SettingsManager } from \"./settings-manager.js\";\nimport { BUILTIN_SLASH_COMMANDS, type SlashCommandInfo, type SlashCommandLocation } from \"./slash-commands.js\";\nimport { buildSystemPromptRegions } from \"./system-prompt.js\";\nimport { TodoEngine } from \"./todo/index.js\";\nimport type { BashOperations } from \"./tools/bash.js\";\nimport { createAllTools } from \"./tools/index.js\";\nimport { createMemoryWriteTool } from \"./tools/memory-write.js\";\nimport { createRetrieveEvidenceTool } from \"./tools/retrieve-evidence.js\";\nimport {\n\tcreateTaskCreateTool,\n\tcreateTaskGetTool,\n\tcreateTaskListTool,\n\tcreateTaskUpdateTool,\n\ttype Task,\n} from \"./tools/task-tools.js\";\nimport { TodoLoopGuard } from \"./tools/todo-loop-guard.js\";\nimport { createTodoReadTool } from \"./tools/todo-read.js\";\nimport { createTodoUpdateTool } from \"./tools/todo-update.js\";\nimport { createPerTurnLock, createTodoWriteTool, type TodoItem } from \"./tools/todo-write.js\";\nimport {\n\tbuildUltraplanPlannerTask,\n\tbuildUltraplanRevisionTask,\n\tformatUltraplanArtifact,\n\tparseUltraplanArtifactData,\n\tparseUltraplanArtifactFromText,\n\tSESSION_ULTRAPLAN_CUSTOM_TYPE,\n\tselectUltraplanApplySteps,\n\ttype UltraplanArtifact,\n\ttype UltraplanRunResult,\n} from \"./ultraplan.js\";\nimport { buildWorkingContext, type WorkingContext } from \"./working-context.js\";\n\n// ============================================================================\n// Caveman Safety Protections (exported for test reference)\n// ============================================================================\n\nexport const CAVEMAN_SAFETY_PROTECTIONS = [\n\t\"Tool calls, tool arguments, tool results, and command output\",\n\t\"JSON, YAML, XML, frontmatter, schemas, or any machine-parsed envelopes\",\n\t\"details.results and all result fields used for parent validation\",\n\t\"Task, planner, slice, handoff, run, and verification state\",\n\t\"Code, file paths, URLs, commit hashes, CLI commands, and exact error messages\",\n\t\"Security confirmations, destructive action confirmations, and ordered procedures\",\n\t\"Delegated evidence from reviewer, security, pentester, and librarian agents\",\n] as const;\n\n// ============================================================================\n// Skill Block Parsing\n// ============================================================================\n\n/** Parsed skill block from a user message */\nexport interface ParsedSkillBlock {\n\tname: string;\n\tlocation: string;\n\tcontent: string;\n\tuserMessage: string | undefined;\n}\n\n/**\n * Parse a skill block from message text.\n * Returns null if the text doesn't contain a skill block.\n */\nexport function parseSkillBlock(text: string): ParsedSkillBlock | null {\n\tconst match = text.match(/^<skill name=\"([^\"]+)\" location=\"([^\"]+)\">\\n([\\s\\S]*?)\\n<\\/skill>(?:\\n\\n([\\s\\S]+))?$/);\n\tif (!match) return null;\n\treturn {\n\t\tname: match[1],\n\t\tlocation: match[2],\n\t\tcontent: match[3],\n\t\tuserMessage: match[4]?.trim() || undefined,\n\t};\n}\n\n/** Session-specific events that extend the core AgentEvent */\nexport type AgentSessionEvent =\n\t| AgentEvent\n\t| { type: \"auto_compaction_start\"; reason: \"threshold\" | \"overflow\" }\n\t| {\n\t\t\ttype: \"auto_compaction_end\";\n\t\t\tresult: CompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\terrorMessage?: string;\n\t  }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string }\n\t| { type: \"auto_fallback\"; model: Model<any>; fallbackModel: Model<any>; reason: string }\n\t| { type: \"todo_update\"; todos: Array<{ content: string; activeForm: string; status: string }> }\n\t| { type: \"memory_update\"; items: MemoryItem[] }\n\t| { type: \"task_update\"; tasks: Task[] }\n\t| { type: \"notification\"; kind: string; message: string };\n\n/** Listener function for agent session events */\nexport type AgentSessionEventListener = (event: AgentSessionEvent) => void;\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface AgentSessionConfig {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tcwd: string;\n\t/** Models to cycle through with Ctrl+P (from --models flag) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\t/** Fallback models to try if the primary model fails */\n\tfallbackModels?: Model<any>[];\n\t/** Resource loader for skills, prompts, themes, context files, system prompt */\n\tresourceLoader: ResourceLoader;\n\t/** SDK custom tools registered outside extensions */\n\tcustomTools?: ToolDefinition[];\n\t/** Model registry for API key resolution and model discovery */\n\tmodelRegistry: ModelRegistry;\n\t/** Initial active built-in tool names. Default: [read, bash, edit, write] */\n\tinitialActiveToolNames?: string[];\n\t/** Override base tools (useful for custom runtimes). */\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\t/** Cold evidence archive for the model-facing retrieve_evidence capability. */\n\tevidenceArchive?: EvidenceArchive;\n\t/** Context Governor for provider-overflow recovery wiring. */\n\tcontextGovernor?: ContextGovernor;\n\t/** Enable brief-only output contract for this session. Default: false */\n\tbriefOnly?: boolean;\n\t/** Enable Caveman output compression for this session. Default: \"off\" */\n\tcavemanLevel?: CavemanLevel;\n\t/** Mutable ref used by Agent to access the current ExtensionRunner */\n\textensionRunnerRef?: { current?: ExtensionRunner };\n}\n\nexport interface ExtensionBindings {\n\tuiContext?: ExtensionUIContext;\n\tcommandContextActions?: ExtensionCommandContextActions;\n\tshutdownHandler?: ShutdownHandler;\n\tonError?: ExtensionErrorListener;\n}\n\n/** Options for AgentSession.prompt() */\nexport interface PromptOptions {\n\t/** Whether to expand file-based prompt templates (default: true) */\n\texpandPromptTemplates?: boolean;\n\t/** Image attachments */\n\timages?: ImageContent[];\n\t/** When streaming, how to queue the message: \"steer\" (interrupt) or \"followUp\" (wait). Required if streaming. */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n\t/** Source of input for extension input event handlers. Defaults to \"interactive\". */\n\tsource?: InputSource;\n}\n\n/** Result from cycleModel() */\nexport interface ModelCycleResult {\n\tmodel: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n\t/** Whether cycling through scoped models (--models flag) or all available */\n\tisScoped: boolean;\n}\n\n/** Session statistics for /session command */\nexport interface SessionStats {\n\tsessionFile: string | undefined;\n\tsessionId: string;\n\tuserMessages: number;\n\tassistantMessages: number;\n\ttoolCalls: number;\n\ttoolResults: number;\n\ttotalMessages: number;\n\ttokens: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n\tcost: number;\n\t/** Metadata-only diagnostics for the latest provider request. Prompt content is never included. */\n\tcontextCache?: ContextCacheDiagnostics;\n}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Standard thinking levels */\nconst THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\n/** Bounded provider-overflow recovery attempts (Phase P). */\nconst MAX_OVERFLOW_RECOVERY_ATTEMPTS = 3;\n\n/** Thinking levels including xhigh (for supported models) */\nconst THINKING_LEVELS_WITH_XHIGH: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\"];\n\ninterface UltraplanSubagentTool {\n\texecute(\n\t\ttoolCallId: string,\n\t\tparams: { agent: string; task: string; agentScope?: \"user\" | \"project\" | \"both\" },\n\t\tsignal: AbortSignal | undefined,\n\t\tonUpdate: undefined,\n\t\tctx: ExtensionContext,\n\t): Promise<{ content: Array<{ type: \"text\"; text: string }>; isError?: boolean }>;\n}\n\nconst NO_OP_EXTENSION_UI_CONTEXT: ExtensionUIContext = {\n\tselect: async () => undefined,\n\tconfirm: async () => false,\n\tinput: async () => undefined,\n\tnotify: () => {},\n\tonTerminalInput: () => () => {},\n\tsetStatus: () => {},\n\tsetWorkingMessage: () => {},\n\tsetWidget: (() => {}) as ExtensionUIContext[\"setWidget\"],\n\tsetFooter: () => {},\n\tsetHeader: () => {},\n\tsetTitle: () => {},\n\tcustom: async () => undefined as never,\n\tpasteToEditor: () => {},\n\tsetEditorText: () => {},\n\tgetEditorText: () => \"\",\n\teditor: async () => undefined,\n\tsetEditorComponent: () => {},\n\tget theme() {\n\t\treturn theme;\n\t},\n\tgetAllThemes: () => [],\n\tgetTheme: () => undefined,\n\tsetTheme: () => ({ success: false, error: \"UI unavailable\" }),\n\tgetToolsExpanded: () => false,\n\tsetToolsExpanded: () => {},\n};\n\n// ============================================================================\n// AgentSession Class\n// ============================================================================\n\nexport class AgentSession {\n\treadonly agent: Agent;\n\treadonly sessionManager: SessionManager;\n\treadonly settingsManager: SettingsManager;\n\n\tprivate _scopedModels: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\tprivate _fallbackModels: Model<any>[];\n\tprivate _fallbackIndex = -1;\n\n\t// Event subscription state\n\tprivate _unsubscribeAgent?: () => void;\n\tprivate _eventListeners: AgentSessionEventListener[] = [];\n\tprivate _agentEventQueue: Promise<void> = Promise.resolve();\n\n\t/** Tracks pending steering messages for UI display. Removed when delivered. */\n\tprivate _steeringMessages: string[] = [];\n\t/** Tracks pending follow-up messages for UI display. Removed when delivered. */\n\tprivate _followUpMessages: string[] = [];\n\t/** Messages queued to be included with the next user prompt as context (\"asides\"). */\n\tprivate _pendingNextTurnMessages: CustomMessage[] = [];\n\n\t// Compaction state\n\tprivate _compactionAbortController: AbortController | undefined = undefined;\n\tprivate _autoCompactionAbortController: AbortController | undefined = undefined;\n\tprivate _overflowRecoveryCount = 0;\n\n\t// Branch summarization state\n\tprivate _branchSummaryAbortController: AbortController | undefined = undefined;\n\n\t// Retry state\n\tprivate _retryAbortController: AbortController | undefined = undefined;\n\tprivate _retryAttempt = 0;\n\tprivate _retryPromise: Promise<void> | undefined = undefined;\n\tprivate _retryResolve: (() => void) | undefined = undefined;\n\n\t// Bash execution state\n\tprivate _bashAbortController: AbortController | undefined = undefined;\n\tprivate _pendingBashMessages: BashExecutionMessage[] = [];\n\n\t// Todo state\n\tprivate _todos: TodoItem[] = [];\n\tprivate _todoRevision = 0;\n\tprivate _todoLoopGuard = new TodoLoopGuard();\n\tprivate _todoPerTurnLock = createPerTurnLock();\n\tprivate _todoReadSnapshot: { revision: number; timestamp: number } | null = null;\n\tprivate _todoUpdateRejectionState = { count: 0 };\n\tprivate _todoEngine!: TodoEngine;\n\tprivate _memoryItems: MemoryItem[] = [];\n\tprivate _delegatedTasks: DelegatedTask[] = [];\n\tprivate _tasks: Task[] = [];\n\n\t// Reliability Kernel (2.2.0): active for normal agent sessions by default.\n\tprivate _reliability: ReliabilitySessionController | undefined = undefined;\n\n\t// Extension system\n\tprivate _extensionRunner: ExtensionRunner | undefined = undefined;\n\tprivate _turnIndex = 0;\n\n\tprivate _resourceLoader: ResourceLoader;\n\tprivate _customTools: ToolDefinition[];\n\tprivate _baseToolRegistry: Map<string, AgentTool> = new Map();\n\tprivate _cwd: string;\n\tprivate _extensionRunnerRef?: { current?: ExtensionRunner };\n\tprivate _initialActiveToolNames?: string[];\n\tprivate _baseToolsOverride?: Record<string, AgentTool>;\n\tprivate _evidenceArchive?: EvidenceArchive;\n\tprivate _extensionUIContext?: ExtensionUIContext;\n\tprivate _extensionCommandContextActions?: ExtensionCommandContextActions;\n\tprivate _extensionShutdownHandler?: ShutdownHandler;\n\tprivate _extensionErrorListener?: ExtensionErrorListener;\n\tprivate _extensionErrorUnsubscriber?: () => void;\n\tprivate _contextGovernor?: ContextGovernor;\n\n\t// Model registry for API key resolution\n\tprivate _modelRegistry: ModelRegistry;\n\n\t// Tool registry for extension getTools/setTools\n\tprivate _toolRegistry: Map<string, AgentTool> = new Map();\n\tprivate _toolPromptSnippets: Map<string, string> = new Map();\n\tprivate _toolPromptGuidelines: Map<string, string[]> = new Map();\n\n\t// Base system prompt (without extension appends) - used to apply fresh appends each turn\n\tprivate _baseSystemPrompt = \"\";\n\tprivate _baseDynamicPrompt = \"\";\n\tprivate _briefOnly = false;\n\tprivate _cavemanLevel: CavemanLevel = \"off\";\n\n\tconstructor(config: AgentSessionConfig) {\n\t\tthis.agent = config.agent;\n\t\tthis.sessionManager = config.sessionManager;\n\t\tthis.settingsManager = config.settingsManager;\n\t\tthis._scopedModels = config.scopedModels ?? [];\n\t\tthis._fallbackModels = config.fallbackModels ?? [];\n\t\tthis._resourceLoader = config.resourceLoader;\n\t\tthis._customTools = config.customTools ?? [];\n\t\tthis._cwd = config.cwd;\n\t\tthis._modelRegistry = config.modelRegistry;\n\t\tthis._extensionRunnerRef = config.extensionRunnerRef;\n\t\tthis._initialActiveToolNames = config.initialActiveToolNames;\n\t\tthis._briefOnly = config.briefOnly ?? false;\n\t\tthis._cavemanLevel = config.cavemanLevel ?? \"off\";\n\t\tthis._baseToolsOverride = config.baseToolsOverride;\n\t\tthis._evidenceArchive = config.evidenceArchive;\n\t\tthis._contextGovernor = config.contextGovernor;\n\n\t\t// Reliability Kernel (2.2.0): initialize before tool hooks so the bridge is\n\t\t// authoritative for every tool call and turn end. Restores a persisted\n\t\t// mission on resume, otherwise starts in governance mode.\n\t\tthis._reliability = new ReliabilitySessionController({\n\t\t\tcwd: this._cwd,\n\t\t\tsessionManager: this.sessionManager,\n\t\t\tverificationExecutor: createWorkspaceVerificationExecutor({ cwd: this._cwd }),\n\t\t\tgetTools: () => this.agent.state.tools,\n\t\t});\n\n\t\t// Always subscribe to agent events for internal handling\n\t\t// (session persistence, extensions, auto-compaction, retry logic)\n\t\tthis._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);\n\t\tthis._installAgentToolHooks();\n\t\tthis._installReliabilityTurnEndHook();\n\n\t\tconst restoredContext = this.sessionManager.buildSessionContext();\n\t\tthis._todos = restoredContext.todos as TodoItem[];\n\t\tthis._resetTodoEngine();\n\t\tthis._memoryItems = restoredContext.memoryItems;\n\t\tthis._tasks = this.sessionManager.getLatestSessionTasks();\n\n\t\tthis._buildRuntime({\n\t\t\tactiveToolNames: this._initialActiveToolNames,\n\t\t\tincludeAllExtensionTools: true,\n\t\t});\n\t}\n\n\t/** Model registry for API key resolution and model discovery */\n\tget modelRegistry(): ModelRegistry {\n\t\treturn this._modelRegistry;\n\t}\n\n\t/**\n\t * Install tool hooks once on the Agent instance.\n\t *\n\t * The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the\n\t * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt\n\t * registered tool execution to the extension context. Tool call and tool result interception now\n\t * happens here instead of in wrappers.\n\t */\n\tprivate _installAgentToolHooks(): void {\n\t\tthis.agent.setBeforeToolCall(async ({ toolCall, args }) => {\n\t\t\t// Reliability Kernel (2.2.0): validate the requested action against the\n\t\t\t// tool registry and mission policy before execution. Invalid actions are\n\t\t\t// blocked and returned as structured failures to the model.\n\t\t\tconst reliability = this._reliability;\n\t\t\tif (reliability) {\n\t\t\t\tconst decision = await reliability.beforeToolCall(toolCall);\n\t\t\t\tif (decision.block) {\n\t\t\t\t\treturn { block: true, reason: decision.reason };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst runner = this._extensionRunner;\n\t\t\tif (!runner?.hasHandlers(\"tool_call\")) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\tawait this._agentEventQueue;\n\n\t\t\ttry {\n\t\t\t\treturn await runner.emitToolCall({\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof Error) {\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t\tthrow new Error(`Extension failed, blocking execution: ${String(err)}`);\n\t\t\t}\n\t\t});\n\n\t\tthis.agent.setAfterToolCall(async ({ toolCall, args, result, isError }) => {\n\t\t\t// Reliability Kernel (2.2.0): record the observed real tool outcome as\n\t\t\t// authoritative evidence before any extension override is applied.\n\t\t\tthis._reliability?.afterToolCall(toolCall, isError);\n\n\t\t\tif (toolCall.name === \"todo_write\" && !isError) {\n\t\t\t\tconst details = result.details as Record<string, unknown> | undefined;\n\t\t\t\tif (details?.changed === true || details?.todoWriteAlreadyApplied === true) {\n\t\t\t\t\tthis._todoPerTurnLock.setLockedForCurrentTurn();\n\t\t\t\t\tthis.setActiveToolsByName(this.getActiveToolNames().filter((name) => name !== \"todo_write\"));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst runner = this._extensionRunner;\n\t\t\tif (!runner?.hasHandlers(\"tool_result\")) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\tconst hookResult = await runner.emitToolResult({\n\t\t\t\ttype: \"tool_result\",\n\t\t\t\ttoolName: toolCall.name,\n\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t\tcontent: result.content,\n\t\t\t\tdetails: isError ? undefined : result.details,\n\t\t\t\tisError,\n\t\t\t});\n\n\t\t\tif (!hookResult || isError) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tcontent: hookResult.content,\n\t\t\t\tdetails: hookResult.details,\n\t\t\t};\n\t\t});\n\t}\n\n\t/**\n\t * Install the Reliability Kernel turn-end hook.\n\t *\n\t * When a mission is active, \"the model finished its turn without further tool\n\t * calls\" is routed through the Completion Gate. A rejected finalization keeps\n\t * the run alive with a structured FINALIZATION_REJECTED message so the model\n\t * gets another bounded turn.\n\t */\n\tprivate _installReliabilityTurnEndHook(): void {\n\t\tthis.agent.setOnTurnEnd(async () => {\n\t\t\tif (!this._reliability) return undefined;\n\t\t\tconst result = await this._reliability.onTurnEnd();\n\t\t\treturn result.continue ? { continue: true, message: result.message } : { continue: false };\n\t\t});\n\t}\n\n\t// =========================================================================\n\t// Reliability Kernel public API\n\t// =========================================================================\n\n\t/** Whether the Reliability Kernel has an active (or restored) mission. */\n\tget reliabilityActive(): boolean {\n\t\treturn this._reliability?.isActive ?? false;\n\t}\n\n\t/** Active mission id, if any. */\n\tget missionId(): string | undefined {\n\t\treturn this._reliability?.missionId;\n\t}\n\n\t/** Active mission phase, if any. */\n\tget reliabilityPhase(): ReliabilitySessionController[\"phase\"] {\n\t\treturn this._reliability?.phase;\n\t}\n\n\t/** Read-only access to the active MissionRuntime (for tooling/tests). */\n\tget reliabilityRuntime(): MissionRuntime | undefined {\n\t\treturn this._reliability?.runtime;\n\t}\n\n\t/** True when a persisted reliability document failed to deserialize (kept intact). */\n\tget corruptReliabilityState(): boolean {\n\t\treturn this._reliability?.corruptPersistedState ?? false;\n\t}\n\n\t/** Current acceptance-criterion view for the active mission. */\n\tgetReliabilityCriteria(): ReturnType<ReliabilitySessionController[\"criterionView\"]> {\n\t\treturn this._reliability?.criterionView() ?? [];\n\t}\n\n\t/** Compact authoritative mission state for model context, if active. */\n\tgetMissionSummary(): string | undefined {\n\t\treturn this._reliability?.summarizeForModel();\n\t}\n\n\t/**\n\t * Build a durable-projection mission context checkpoint (L2 warm memory).\n\t *\n\t * This is a bounded, deterministic projection over already-durable state —\n\t * the Reliability Kernel mission (objective/constraints/criteria/failures),\n\t * session memory, todos, tasks, and latest compaction file operations. It is\n\t * used by the Context Governor to rehydrate operational state across a\n\t * rollover and never carries completion authority.\n\t */\n\tbuildMissionContextCheckpoint(\n\t\tevidenceRefs: { evidenceId: string; summary: string }[] = [],\n\t): MissionContextCheckpoint | undefined {\n\t\tconst runtime = this._reliability?.runtime;\n\t\tconst missionId = this._reliability?.missionId ?? this.sessionManager.getSessionId();\n\t\tif (!missionId) return undefined;\n\n\t\tconst constraints: string[] = [];\n\t\tif (runtime) {\n\t\t\tfor (const c of runtime.constraints) constraints.push(`${c.id}: ${c.statement}`);\n\t\t}\n\n\t\tconst completedSteps: string[] = [];\n\t\tconst pendingSteps: string[] = [];\n\t\tfor (const todo of this._todos) {\n\t\t\tconst text = todo.status === \"in_progress\" ? todo.activeForm : todo.content;\n\t\t\tif (todo.status === \"completed\") completedSteps.push(todo.content);\n\t\t\telse pendingSteps.push(text);\n\t\t}\n\n\t\tconst nextActions: string[] = [];\n\t\tfor (const task of this._tasks) {\n\t\t\tif (task.status === \"in_progress\") nextActions.push(task.activeForm ?? task.subject);\n\t\t\telse if (task.status === \"pending\") nextActions.push(task.subject);\n\t\t}\n\n\t\t// Bounded: keep the checkpoint compact by construction.\n\t\tconst findings: FindingRecord[] = this._memoryItems.slice(0, 24).map((item) => ({\n\t\t\tsubject: item.key,\n\t\t\tdetail: item.value,\n\t\t}));\n\n\t\tconst activeFiles = this._latestCompactionFileLists();\n\n\t\tconst blockers: string[] = [];\n\t\tif (runtime) {\n\t\t\tfor (const failure of runtime.failures.slice(-8)) {\n\t\t\t\tif (failure.category === \"CONTEXT_REQUIRED\" || failure.category === \"FINALIZATION_REJECTED\") {\n\t\t\t\t\tblockers.push(failure.message);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn createMissionContextCheckpoint(missionId, {\n\t\t\tobjective: runtime?.goal ?? this.getMissionSummary() ?? \"\",\n\t\t\tconstraints,\n\t\t\tdecisions: [],\n\t\t\tplan: \"\",\n\t\t\tcompletedSteps,\n\t\t\tpendingSteps,\n\t\t\tactiveFiles,\n\t\t\tfindings,\n\t\t\tevidenceRefs: evidenceRefs.slice(-24),\n\t\t\ttestState: {},\n\t\t\tblockers,\n\t\t\tnextActions: nextActions.slice(0, 12),\n\t\t});\n\t}\n\n\tprivate _latestCompactionFileLists(): string[] {\n\t\tconst branch = this.sessionManager.getBranch();\n\t\tconst latest = getLatestCompactionEntry(branch);\n\t\tif (!latest) return [];\n\t\tconst details = latest.details as { readFiles?: string[]; modifiedFiles?: string[] } | undefined;\n\t\tconst files = new Set<string>();\n\t\tfor (const f of details?.readFiles ?? []) files.add(f);\n\t\tfor (const f of details?.modifiedFiles ?? []) files.add(f);\n\t\treturn [...files].slice(0, 64);\n\t}\n\n\t/** Start (or replace) the governed mission for this session. */\n\tstartMission(definition: MissionDefinitionInput): void {\n\t\tthis._reliability?.startMission(definition);\n\t\tthis._applyReliabilityContext();\n\t}\n\n\t/** Inject the current authoritative mission state into the next model turn. */\n\tprivate _applyReliabilityContext(): void {\n\t\tif (this._reliability?.isActive) {\n\t\t\tthis.agent.setDynamicPrompt(this._reliability.summarizeForModel());\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Event Subscription\n\t// =========================================================================\n\n\t/** Emit an event to all listeners */\n\tprivate _emit(event: AgentSessionEvent): void {\n\t\tfor (const l of this._eventListeners) {\n\t\t\tl(event);\n\t\t}\n\t}\n\n\t// Track last assistant message for auto-compaction check\n\tprivate _lastAssistantMessage: AssistantMessage | undefined = undefined;\n\n\t/** Internal handler for agent events - shared by subscribe and reconnect */\n\tprivate _handleAgentEvent = (event: AgentEvent): void => {\n\t\t// Create retry promise synchronously before queueing async processing.\n\t\t// Agent.emit() calls this handler synchronously, and prompt() calls waitForRetry()\n\t\t// as soon as agent.prompt() resolves. If _retryPromise is created only inside\n\t\t// _processAgentEvent, slow earlier queued events can delay agent_end processing\n\t\t// and waitForRetry() can miss the in-flight retry.\n\t\tthis._createRetryPromiseForAgentEnd(event);\n\n\t\tthis._agentEventQueue = this._agentEventQueue.then(\n\t\t\t() => this._processAgentEvent(event),\n\t\t\t() => this._processAgentEvent(event),\n\t\t);\n\n\t\t// Keep queue alive if an event handler fails\n\t\tthis._agentEventQueue.catch(() => {});\n\t};\n\n\tprivate _createRetryPromiseForAgentEnd(event: AgentEvent): void {\n\t\tif (event.type !== \"agent_end\" || this._retryPromise) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst settings = this.settingsManager.getRetrySettings();\n\t\tif (!settings.enabled) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst lastAssistant = this._findLastAssistantInMessages(event.messages);\n\t\tif (!lastAssistant || !this._isRetryableError(lastAssistant)) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._retryPromise = new Promise((resolve) => {\n\t\t\tthis._retryResolve = resolve;\n\t\t});\n\t}\n\n\tprivate _findLastAssistantInMessages(messages: AgentMessage[]): AssistantMessage | undefined {\n\t\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\t\tconst message = messages[i];\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\treturn message as AssistantMessage;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async _processAgentEvent(event: AgentEvent): Promise<void> {\n\t\t// When a user message starts, check if it's from either queue and remove it BEFORE emitting\n\t\t// This ensures the UI sees the updated queue state\n\t\tif (event.type === \"message_start\" && event.message.role === \"user\") {\n\t\t\tthis._overflowRecoveryCount = 0;\n\t\t\tconst messageText = this._getUserMessageText(event.message);\n\t\t\tif (messageText) {\n\t\t\t\t// Check steering queue first\n\t\t\t\tconst steeringIndex = this._steeringMessages.indexOf(messageText);\n\t\t\t\tif (steeringIndex !== -1) {\n\t\t\t\t\tthis._steeringMessages.splice(steeringIndex, 1);\n\t\t\t\t} else {\n\t\t\t\t\t// Check follow-up queue\n\t\t\t\t\tconst followUpIndex = this._followUpMessages.indexOf(messageText);\n\t\t\t\t\tif (followUpIndex !== -1) {\n\t\t\t\t\t\tthis._followUpMessages.splice(followUpIndex, 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Emit to extensions first\n\t\tawait this._emitExtensionEvent(event);\n\t\tthis._updateDelegatedWorkState(event);\n\n\t\t// Notify all listeners\n\t\tthis._emit(event);\n\n\t\t// Handle session persistence\n\t\tif (event.type === \"message_end\") {\n\t\t\tif (event.message.role === \"user\") {\n\t\t\t\tthis._todoLoopGuard.resetOnNewUserMessage();\n\t\t\t\tthis._todoUpdateRejectionState.count = 0;\n\t\t\t\tthis._todoPerTurnLock.currentTurn++;\n\t\t\t\tthis._todoPerTurnLock.lockedUntil = -1;\n\t\t\t\tthis._todoPerTurnLock.reservedUntil = -1;\n\t\t\t}\n\t\t\t// Check if this is a custom message from extensions\n\t\t\tif (event.message.role === \"custom\") {\n\t\t\t\t// Persist as CustomMessageEntry\n\t\t\t\tthis.sessionManager.appendCustomMessageEntry(\n\t\t\t\t\tevent.message.customType,\n\t\t\t\t\tevent.message.content,\n\t\t\t\t\tevent.message.display,\n\t\t\t\t\tevent.message.details,\n\t\t\t\t);\n\t\t\t} else if (\n\t\t\t\tevent.message.role === \"user\" ||\n\t\t\t\tevent.message.role === \"assistant\" ||\n\t\t\t\tevent.message.role === \"toolResult\"\n\t\t\t) {\n\t\t\t\t// Regular LLM message - persist as SessionMessageEntry\n\t\t\t\tthis.sessionManager.appendMessage(event.message);\n\t\t\t}\n\t\t\t// Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere\n\n\t\t\t// Track assistant message for auto-compaction (checked on agent_end)\n\t\t\tif (event.message.role === \"assistant\") {\n\t\t\t\tthis._lastAssistantMessage = event.message;\n\n\t\t\t\tconst assistantMsg = event.message as AssistantMessage;\n\t\t\t\tif (assistantMsg.stopReason !== \"error\") {\n\t\t\t\t\tthis._overflowRecoveryCount = 0;\n\n\t\t\t\t\t// Feed authoritative provider usage back into the governor for\n\t\t\t\t\t// deterministic conservative calibration (only ever raises the\n\t\t\t\t\t// estimate, never lowers it).\n\t\t\t\t\tconst governor = this._contextGovernor;\n\t\t\t\t\tconst diagnostics = governor?.lastDiagnostics;\n\t\t\t\t\tif (governor && diagnostics && assistantMsg.usage) {\n\t\t\t\t\t\tconst observed = assistantMsg.usage.input + assistantMsg.usage.cacheRead;\n\t\t\t\t\t\tif (observed > 0 && diagnostics.inputTokensAfter > 0) {\n\t\t\t\t\t\t\tgovernor.observeProviderUsage(diagnostics.inputTokensAfter, observed);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Reset retry counter immediately on successful assistant response\n\t\t\t\t// This prevents accumulation across multiple LLM calls within a turn\n\t\t\t\tif (assistantMsg.stopReason !== \"error\" && this._retryAttempt > 0) {\n\t\t\t\t\tthis._emit({\n\t\t\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\t\t});\n\t\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\t\tthis._resolveRetry();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Final wire-payload validation after every context transformation.\n\t\t\t// Runs on the exact serialized message array just before network transport.\n\t\t\t// Invalid transcripts fail locally with INVALID_TOOL_TRANSCRIPT and produce\n\t\t\t// zero network requests, without automatic retry.\n\t\t\tif (event.message.role === \"assistant\" || event.message.role === \"toolResult\") {\n\t\t\t\tconst model = this.agent.state.model;\n\t\t\t\tif (model) {\n\t\t\t\t\tconst history = this.agent.state.messages as Message[];\n\t\t\t\t\tconst useResponses =\n\t\t\t\t\t\tmodel.api === \"openai-responses\" ||\n\t\t\t\t\t\tmodel.api === \"azure-openai-responses\" ||\n\t\t\t\t\t\tmodel.api === \"openai-codex-responses\";\n\t\t\t\t\tconst result = useResponses\n\t\t\t\t\t\t? validateResponsesTranscript(history, model.provider, model.id)\n\t\t\t\t\t\t: validateChatCompletionsTranscript(history, model.provider, model.id);\n\t\t\t\t\tif (\"code\" in result) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`INVALID_TOOL_TRANSCRIPT: protocol=${result.protocol}, ` +\n\t\t\t\t\t\t\t\t`missingToolCallIds=[${result.missingToolCallIds.join(\", \")}], ` +\n\t\t\t\t\t\t\t\t`duplicateToolCallIds=[${result.duplicateToolCallIds.join(\", \")}], ` +\n\t\t\t\t\t\t\t\t`orphanToolResultIds=[${result.orphanToolResultIds.join(\", \")}], ` +\n\t\t\t\t\t\t\t\t`duplicateCallIds=[${result.duplicateCallIds.join(\", \")}], ` +\n\t\t\t\t\t\t\t\t`provider=${result.provider}, model=${result.model}, messageIndex=${result.messageIndex}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check auto-retry and auto-compaction after agent completes\n\t\tif (event.type === \"agent_end\" && this._lastAssistantMessage) {\n\t\t\tconst msg = this._lastAssistantMessage;\n\t\t\tthis._lastAssistantMessage = undefined;\n\n\t\t\t// Check for retryable errors first (overloaded, rate limit, server errors)\n\t\t\tif (this._isRetryableError(msg)) {\n\t\t\t\tconst didRetry = await this._handleRetryableError(msg);\n\t\t\t\tif (didRetry) return; // Retry was initiated, don't proceed to compaction\n\t\t\t} else if (msg.stopReason === \"error\" && msg.errorMessage) {\n\t\t\t\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t\t\t\tif (!isContextOverflow(msg, contextWindow)) {\n\t\t\t\t\tconst didFallback = await this._handleFallback(msg, msg.errorMessage);\n\t\t\t\t\tif (didFallback) return;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait this._checkCompaction(msg);\n\t\t}\n\t}\n\n\t/** Resolve the pending retry promise */\n\tprivate _resolveRetry(): void {\n\t\tif (this._retryResolve) {\n\t\t\tthis._retryResolve();\n\t\t\tthis._retryResolve = undefined;\n\t\t\tthis._retryPromise = undefined;\n\t\t}\n\t}\n\n\t/** Extract text content from a message */\n\tprivate _getUserMessageText(message: Message): string {\n\t\tif (message.role !== \"user\") return \"\";\n\t\tconst content = message.content;\n\t\tif (typeof content === \"string\") return content;\n\t\tconst textBlocks = content.filter((c) => c.type === \"text\");\n\t\treturn textBlocks.map((c) => (c as TextContent).text).join(\"\");\n\t}\n\n\t/** Find the last assistant message in agent state (including aborted ones) */\n\tprivate _findLastAssistantMessage(): AssistantMessage | undefined {\n\t\tconst messages = this.agent.state.messages;\n\t\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\t\tconst msg = messages[i];\n\t\t\tif (msg.role === \"assistant\") {\n\t\t\t\treturn msg as AssistantMessage;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/** Emit extension events based on agent events */\n\tprivate async _emitExtensionEvent(event: AgentEvent): Promise<void> {\n\t\tif (!this._extensionRunner) return;\n\n\t\tif (event.type === \"agent_start\") {\n\t\t\tthis._turnIndex = 0;\n\t\t\tawait this._extensionRunner.emit({ type: \"agent_start\" });\n\t\t} else if (event.type === \"agent_end\") {\n\t\t\tawait this._extensionRunner.emit({ type: \"agent_end\", messages: event.messages });\n\t\t} else if (event.type === \"turn_start\") {\n\t\t\tconst extensionEvent: TurnStartEvent = {\n\t\t\t\ttype: \"turn_start\",\n\t\t\t\tturnIndex: this._turnIndex,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t};\n\t\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\t} else if (event.type === \"turn_end\") {\n\t\t\tconst extensionEvent: TurnEndEvent = {\n\t\t\t\ttype: \"turn_end\",\n\t\t\t\tturnIndex: this._turnIndex,\n\t\t\t\tmessage: event.message,\n\t\t\t\ttoolResults: event.toolResults,\n\t\t\t};\n\t\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\t\tthis._turnIndex++;\n\t\t} else if (event.type === \"message_start\") {\n\t\t\tconst extensionEvent: MessageStartEvent = {\n\t\t\t\ttype: \"message_start\",\n\t\t\t\tmessage: event.message,\n\t\t\t};\n\t\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\t} else if (event.type === \"message_update\") {\n\t\t\tconst extensionEvent: MessageUpdateEvent = {\n\t\t\t\ttype: \"message_update\",\n\t\t\t\tmessage: event.message,\n\t\t\t\tassistantMessageEvent: event.assistantMessageEvent,\n\t\t\t};\n\t\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\t} else if (event.type === \"message_end\") {\n\t\t\tconst extensionEvent: MessageEndEvent = {\n\t\t\t\ttype: \"message_end\",\n\t\t\t\tmessage: event.message,\n\t\t\t};\n\t\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\t} else if (event.type === \"tool_execution_start\") {\n\t\t\tconst extensionEvent: ToolExecutionStartEvent = {\n\t\t\t\ttype: \"tool_execution_start\",\n\t\t\t\ttoolCallId: event.toolCallId,\n\t\t\t\ttoolName: event.toolName,\n\t\t\t\targs: event.args,\n\t\t\t};\n\t\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\t} else if (event.type === \"tool_execution_update\") {\n\t\t\tconst extensionEvent: ToolExecutionUpdateEvent = {\n\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\ttoolCallId: event.toolCallId,\n\t\t\t\ttoolName: event.toolName,\n\t\t\t\targs: event.args,\n\t\t\t\tpartialResult: event.partialResult,\n\t\t\t};\n\t\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\t} else if (event.type === \"tool_execution_end\") {\n\t\t\tif (event.toolName === \"todo_write\") {\n\t\t\t\tconst details = event.result.details as Record<string, unknown> | undefined;\n\n\t\t\t\tif (details?.changed) {\n\t\t\t\t\t// Successful state-mutating todo_write — hide from future provider\n\t\t\t\t\t// requests for the rest of this user turn.\n\t\t\t\t\tthis._todoPerTurnLock.setLockedForCurrentTurn();\n\t\t\t\t\tconst activeNames = this.getActiveToolNames().filter((n) => n !== \"todo_write\");\n\t\t\t\t\tthis.setActiveToolsByName(activeNames);\n\t\t\t\t} else if (details?.todoWriteAlreadyApplied) {\n\t\t\t\t\t// First duplicate rejection — keep todo_write hidden for the rest of\n\t\t\t\t\t// the turn so the provider cannot call it again.\n\t\t\t\t\tthis._todoPerTurnLock.setLockedForCurrentTurn();\n\t\t\t\t\tconst activeNames = this.getActiveToolNames().filter((n) => n !== \"todo_write\");\n\t\t\t\t\tthis.setActiveToolsByName(activeNames);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!event.isError && event.toolName !== \"todo_write\" && event.toolName !== \"todo_read\") {\n\t\t\t\tthis._todoLoopGuard.resetOnNonTodoToolSuccess(event.toolName);\n\t\t\t\tthis._todoEngine.recordProgress();\n\t\t\t}\n\t\t\tconst extensionEvent: ToolExecutionEndEvent = {\n\t\t\t\ttype: \"tool_execution_end\",\n\t\t\t\ttoolCallId: event.toolCallId,\n\t\t\t\ttoolName: event.toolName,\n\t\t\t\tresult: event.result,\n\t\t\t\tisError: event.isError,\n\t\t\t};\n\t\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\t}\n\t}\n\n\tprivate _updateDelegatedWorkState(event: AgentEvent): void {\n\t\tif (event.type === \"tool_execution_start\") {\n\t\t\tconst tasks = extractDelegatedTasks({\n\t\t\t\ttype: \"tool_call\",\n\t\t\t\ttoolCallId: event.toolCallId,\n\t\t\t\ttoolName: event.toolName,\n\t\t\t\tinput: typeof event.args === \"object\" && event.args !== null ? event.args : {},\n\t\t\t});\n\t\t\tfor (const task of tasks) {\n\t\t\t\tthis._delegatedTasks = mergeDelegatedTask(this._delegatedTasks, task);\n\t\t\t}\n\n\t\t\t// Operator state discipline advisory: warn if delegating without visible task/todo state\n\t\t\tif (event.toolName === \"subagent\") {\n\t\t\t\tconst hasVisibleState = this._tasks.length > 0 || this._todos.length > 0;\n\t\t\t\tif (!hasVisibleState) {\n\t\t\t\t\tthis._emit({\n\t\t\t\t\t\ttype: \"notification\",\n\t\t\t\t\t\tkind: \"operator_discipline_advisory\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Delegating without visible task or todo state. Consider creating tracking entries before delegating.\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (\n\t\t\t(event.type !== \"tool_execution_update\" && event.type !== \"tool_execution_end\") ||\n\t\t\tevent.toolName !== \"subagent\"\n\t\t) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst matchingTasks = this._delegatedTasks.filter((task) => task.toolCallId === event.toolCallId);\n\t\tif (matchingTasks.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst resultPayload = event.type === \"tool_execution_end\" ? event.result : event.partialResult;\n\t\tconst toolResult = {\n\t\t\trole: \"toolResult\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\tcontent:\n\t\t\t\tresultPayload && typeof resultPayload === \"object\" && Array.isArray(resultPayload.content)\n\t\t\t\t\t? resultPayload.content\n\t\t\t\t\t: [],\n\t\t\tdetails: resultPayload && typeof resultPayload === \"object\" ? resultPayload.details : undefined,\n\t\t\tisError: event.type === \"tool_execution_end\" ? event.isError : false,\n\t\t\ttimestamp: Date.now(),\n\t\t} as const;\n\n\t\tthis._delegatedTasks = reconcileDelegatedResult(this._delegatedTasks, toolResult);\n\t}\n\n\t/**\n\t * Subscribe to agent events.\n\t * Session persistence is handled internally (saves messages on message_end).\n\t * Multiple listeners can be added. Returns unsubscribe function for this listener.\n\t */\n\tsubscribe(listener: AgentSessionEventListener): () => void {\n\t\tthis._eventListeners.push(listener);\n\n\t\t// Return unsubscribe function for this specific listener\n\t\treturn () => {\n\t\t\tconst index = this._eventListeners.indexOf(listener);\n\t\t\tif (index !== -1) {\n\t\t\t\tthis._eventListeners.splice(index, 1);\n\t\t\t}\n\t\t};\n\t}\n\n\t/**\n\t * Temporarily disconnect from agent events.\n\t * User listeners are preserved and will receive events again after resubscribe().\n\t * Used internally during operations that need to pause event processing.\n\t */\n\tprivate _disconnectFromAgent(): void {\n\t\tif (this._unsubscribeAgent) {\n\t\t\tthis._unsubscribeAgent();\n\t\t\tthis._unsubscribeAgent = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Reconnect to agent events after _disconnectFromAgent().\n\t * Preserves all existing listeners.\n\t */\n\tprivate _reconnectToAgent(): void {\n\t\tif (this._unsubscribeAgent) return; // Already connected\n\t\tthis._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);\n\t}\n\n\t/**\n\t * Remove all listeners and disconnect from agent.\n\t * Call this when completely done with the session.\n\t */\n\tdispose(): void {\n\t\tthis._disconnectFromAgent();\n\t\tthis._eventListeners = [];\n\t}\n\n\t// =========================================================================\n\t// Read-only State Access\n\t// =========================================================================\n\n\t/** Full agent state */\n\tget state(): AgentState {\n\t\treturn this.agent.state;\n\t}\n\n\t/** Current model (may be undefined if not yet selected) */\n\tget model(): Model<any> | undefined {\n\t\treturn this.agent.state.model;\n\t}\n\n\t/** Current thinking level */\n\tget thinkingLevel(): ThinkingLevel {\n\t\treturn this.agent.state.thinkingLevel;\n\t}\n\n\t/** Whether agent is currently streaming a response */\n\tget isStreaming(): boolean {\n\t\treturn this.agent.state.isStreaming;\n\t}\n\n\t/** Current effective system prompt (includes any per-turn extension modifications) */\n\tget systemPrompt(): string {\n\t\tconst { systemPrompt, dynamicPrompt } = this.agent.state;\n\t\treturn dynamicPrompt ? `${systemPrompt}\\n\\n${dynamicPrompt}` : systemPrompt;\n\t}\n\n\t/** Current retry attempt (0 if not retrying) */\n\tget retryAttempt(): number {\n\t\treturn this._retryAttempt;\n\t}\n\n\t/** Whether the brief-only output contract is enabled for this session runtime. */\n\tget briefOnly(): boolean {\n\t\treturn this._briefOnly;\n\t}\n\n\t/** Current Caveman output compression level for this session runtime. */\n\tget cavemanLevel(): CavemanLevel {\n\t\treturn this._cavemanLevel;\n\t}\n\n\t/** Pending /btw guidance notes that will be injected on the next turn only. */\n\tgetPendingByTheWayNotes(): readonly string[] {\n\t\treturn this._pendingNextTurnMessages\n\t\t\t.map((message) => getBtwNoteFromMessage(message))\n\t\t\t.filter((note): note is string => note !== undefined);\n\t}\n\n\t/**\n\t * Get the names of currently active tools.\n\t * Returns the names of tools currently set on the agent.\n\t */\n\tgetActiveToolNames(): string[] {\n\t\treturn this.agent.state.tools.map((t) => t.name);\n\t}\n\n\t/**\n\t * Get all configured tools with name, description, and parameter schema.\n\t */\n\tgetAllTools(): ToolInfo[] {\n\t\treturn Array.from(this._toolRegistry.values()).map((t) => ({\n\t\t\tname: t.name,\n\t\t\tdescription: t.description,\n\t\t\tparameters: t.parameters,\n\t\t}));\n\t}\n\n\t/**\n\t * Set active tools by name.\n\t * Only tools in the registry can be enabled. Unknown tool names are ignored.\n\t * Also rebuilds the system prompt to reflect the new tool set.\n\t * Changes take effect on the next agent turn.\n\t */\n\tsetActiveToolsByName(toolNames: string[]): void {\n\t\tconst tools: AgentTool[] = [];\n\t\tconst validToolNames: string[] = [];\n\t\tfor (const name of toolNames) {\n\t\t\tconst tool = this._toolRegistry.get(name);\n\t\t\tif (tool) {\n\t\t\t\ttools.push(tool);\n\t\t\t\tvalidToolNames.push(name);\n\t\t\t}\n\t\t}\n\t\tthis.agent.setTools(tools);\n\n\t\t// Rebuild base system prompt with new tool set\n\t\tthis._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);\n\t\tthis._applyBaseSystemPrompt();\n\t}\n\n\t/**\n\t * Get the current todo list.\n\t * Returns the session's todo state for UI rendering.\n\t */\n\tgetTodos(): ReadonlyArray<TodoItem> {\n\t\treturn this._todos;\n\t}\n\n\t/**\n\t * Live TODO subsystem diagnostics (progress epoch, snapshot/ledger counts,\n\t * loop-chain state). Read-only, used by operability surfaces.\n\t */\n\tgetTodoDiagnostics() {\n\t\treturn this._todoEngine.getDiagnostics();\n\t}\n\n\tprivate _resetTodoEngine(): void {\n\t\tthis._todoEngine = new TodoEngine(`session:${this.sessionManager.getSessionId()}`, {}, Date.now, {\n\t\t\tload: () => this.sessionManager.getLatestTodoEngineState(),\n\t\t\tsave: (state) => {\n\t\t\t\tthis.sessionManager.appendTodoEngineState(state);\n\t\t\t},\n\t\t});\n\t\tthis._todoRevision = this._todoEngine.getCurrentRevision();\n\t\tif (this._todoRevision === 0 && this._todos.length > 0) {\n\t\t\tthis._todoEngine.recordState(0, this._todos);\n\t\t}\n\t}\n\n\t/**\n\t * Get the current todo revision number.\n\t * Increments on every non-no-op todo_write or todo_update mutation.\n\t */\n\tget todoRevision(): number {\n\t\treturn this._todoRevision;\n\t}\n\n\tgetDelegatedTasks(): readonly DelegatedTask[] {\n\t\treturn this._delegatedTasks;\n\t}\n\n\tgetDelegatedWorkSummary(): DelegatedWorkSummary {\n\t\treturn buildDelegatedWorkSummary(this._delegatedTasks);\n\t}\n\n\tgetRecentDelegatedTasks(limit = 3): readonly DelegatedTask[] {\n\t\treturn getRecentDelegatedTasks(this._delegatedTasks, { limit });\n\t}\n\n\t/**\n\t * Internal: Set todos and emit update event.\n\t * Called by the todo_write tool to update session state.\n\t */\n\tprivate _setTodos(todos: TodoItem[]): void {\n\t\t// Ensure all todos have IDs before persisting\n\t\tconst withIds: {\n\t\t\tid: string;\n\t\t\tcontent: string;\n\t\t\tactiveForm: string;\n\t\t\tstatus: \"pending\" | \"in_progress\" | \"completed\";\n\t\t}[] = todos.map((t) => ({\n\t\t\tid: t.id || crypto.randomUUID(),\n\t\t\tcontent: t.content,\n\t\t\tactiveForm: t.activeForm,\n\t\t\tstatus: t.status,\n\t\t}));\n\t\tthis._todos = withIds;\n\t\tthis._todoRevision++;\n\t\tthis._todoEngine.recordState(this._todoRevision, this._todos);\n\t\t// Invalidate read snapshot - external revision changed, any cached read is stale\n\t\tthis._todoReadSnapshot = null;\n\t\tthis.sessionManager.appendSessionTodos(withIds);\n\t\tthis._emit({ type: \"todo_update\", todos: this._todos });\n\t}\n\n\tgetMemoryItems(): readonly MemoryItem[] {\n\t\treturn this._memoryItems;\n\t}\n\n\tprivate _setMemoryItems(items: MemoryItem[]): void {\n\t\tthis._memoryItems = items;\n\t\tthis.sessionManager.appendSessionMemory(items);\n\t\tthis._emit({ type: \"memory_update\", items: this._memoryItems });\n\t}\n\n\tsetMemoryItem(key: string, value: string): MemoryItem[] {\n\t\tconst next = upsertMemoryItems(this._memoryItems, key, value, new Date().toISOString());\n\t\tthis._setMemoryItems(next);\n\t\treturn next;\n\t}\n\n\tclearMemory(): MemoryItem[] {\n\t\tconst next = clearMemoryItems();\n\t\tthis._setMemoryItems(next);\n\t\treturn next;\n\t}\n\n\tdeleteMemoryItem(key: string): MemoryItem[] {\n\t\tconst next = deleteMemoryItem(this._memoryItems, key);\n\t\tthis._setMemoryItems(next);\n\t\treturn next;\n\t}\n\n\tgetMemoryItem(key: string): MemoryItem | undefined {\n\t\treturn getMemoryItem(this._memoryItems, key);\n\t}\n\n\t/**\n\t * Get the current task list.\n\t */\n\tgetTasks(): ReadonlyArray<Task> {\n\t\treturn this._tasks;\n\t}\n\n\t/**\n\t * Internal: Set tasks, persist, and emit update event.\n\t */\n\tprivate _setTasks(tasks: Task[]): void {\n\t\tthis._tasks = tasks;\n\t\tthis.sessionManager.appendSessionTasks(tasks);\n\t\tthis._emit({ type: \"task_update\", tasks: this._tasks });\n\t}\n\n\t/**\n\t * Get memory history as a timeline of snapshots.\n\t * Delegates to SessionManager.getMemoryHistory() which walks the current branch.\n\t *\n\t * History is derived from persisted session entries with customType === \"session_memory\".\n\t * Because persistence is snapshot-based, each snapshot contains the complete memory\n\t * state at that point, not individual add/update/delete events.\n\t */\n\tgetMemoryHistory(): readonly MemoryHistorySnapshot[] {\n\t\treturn this.sessionManager.getMemoryHistory();\n\t}\n\n\t/**\n\t * Get the structured memory history payload used by RPC history consumers.\n\t *\n\t * This stays current-branch-only and snapshot-based because it delegates to the\n\t * same persisted snapshot backend as getMemoryHistory().\n\t */\n\tgetStructuredMemoryHistory(): StructuredMemoryHistoryData {\n\t\treturn buildStructuredMemoryHistoryData(this);\n\t}\n\n\t/**\n\t * Compare memory snapshots using the shared structured contract used by RPC.\n\t *\n\t * - Omit selectors for adjacent latest-vs-previous comparison.\n\t * - Provide both baseline and target selectors for explicit comparison.\n\t * - Throws if only one selector is provided, matching the RPC command contract.\n\t */\n\tcompareMemorySnapshots(options?: { baseline?: string; target?: string }): StructuredMemoryCompareData {\n\t\tconst hasBaseline = options?.baseline !== undefined;\n\t\tconst hasTarget = options?.target !== undefined;\n\t\tif (hasBaseline !== hasTarget) {\n\t\t\tthrow new Error(\"Provide both baseline and target selectors, or neither for adjacent comparison.\");\n\t\t}\n\t\treturn buildStructuredMemoryCompareData(\n\t\t\tthis,\n\t\t\thasBaseline ? { baseline: options!.baseline!, target: options!.target! } : undefined,\n\t\t);\n\t}\n\n\t/**\n\t * Resolve a memory snapshot by entry ID within the current branch history.\n\t * Delegates to SessionManager.findMemorySnapshotById().\n\t *\n\t * @param id - The entry ID of the snapshot to find\n\t * @returns The snapshot with that ID, or undefined if not found in current branch\n\t */\n\tfindMemorySnapshotById(id: string): MemoryHistorySnapshot | undefined {\n\t\treturn this.sessionManager.findMemorySnapshotById(id);\n\t}\n\n\t/**\n\t * Strictly resolve a snapshot selector string against current-branch history.\n\t * Delegates to SessionManager.resolveMemorySnapshotSelector().\n\t *\n\t * Resolution order:\n\t * 1. Exact full entryId match (always wins)\n\t * 2. Exact short-ID match (first 8 chars of an entryId)\n\t * 3. Strict unique prefix match — prefix must resolve to exactly one snapshot\n\t *\n\t * Supports optional surrounding brackets copied from /memory history output: [abcd1234]\n\t *\n\t * @param input - Raw selector string (may include surrounding brackets)\n\t * @returns Resolution result with snapshot or error details\n\t */\n\tresolveMemorySnapshotSelector(input: string): MemorySnapshotResolution {\n\t\treturn this.sessionManager.resolveMemorySnapshotSelector(input);\n\t}\n\n\t/**\n\t * Get the integrated working context surface.\n\t *\n\t * Returns a real-time snapshot of three state sources:\n\t * - memory: persisted session memory (current-branch snapshot-based)\n\t * - todo: persisted todo/plan state (current-branch snapshot-based)\n\t * - delegatedWork: live current-process delegated subagent state (NOT persisted)\n\t *\n\t * This reuses the same structured payload exposed via RPC `get_working_context`\n\t * and displayed in the interactive working-context panel.\n\t *\n\t * Honesty contract:\n\t * - `memory.isPersisted: true` and `todo.isPersisted: true` — snapshot-backed session state\n\t * - `delegatedWork.isPersisted: false` — live runtime state only, resets on session switch/resume\n\t *\n\t * @returns The current working context snapshot\n\t */\n\tgetWorkingContext(): WorkingContext {\n\t\treturn buildWorkingContext({\n\t\t\tmemoryItems: this.getMemoryItems(),\n\t\t\ttodos: this.getTodos(),\n\t\t\ttasks: this.getTasks(),\n\t\t\tdelegatedWorkSummary: this.getDelegatedWorkSummary(),\n\t\t});\n\t}\n\n\tgetLatestUltraplanPlan(): UltraplanArtifact | undefined {\n\t\tconst branch = this.sessionManager.getBranch();\n\t\tfor (let i = branch.length - 1; i >= 0; i--) {\n\t\t\tconst entry = branch[i];\n\t\t\tif (entry.type === \"custom\" && entry.customType === SESSION_ULTRAPLAN_CUSTOM_TYPE) {\n\t\t\t\treturn parseUltraplanArtifactData(entry.data);\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate _createUltraplanExecutionContext(): ExtensionContext {\n\t\treturn (\n\t\t\tthis._extensionRunner?.createContext() ?? {\n\t\t\t\tui: NO_OP_EXTENSION_UI_CONTEXT,\n\t\t\t\thasUI: false,\n\t\t\t\tcwd: this._cwd,\n\t\t\t\tsessionManager: this.sessionManager,\n\t\t\t\tmodelRegistry: this._modelRegistry,\n\t\t\t\tmodel: this.model,\n\t\t\t\tisIdle: () => !this.isStreaming,\n\t\t\t\tabort: () => {\n\t\t\t\t\tvoid this.abort();\n\t\t\t\t},\n\t\t\t\thasPendingMessages: () => this.pendingMessageCount > 0,\n\t\t\t\tshutdown: () => {\n\t\t\t\t\tthis._extensionShutdownHandler?.();\n\t\t\t\t},\n\t\t\t\tgetContextUsage: () => this.getContextUsage(),\n\t\t\t\tcompact: (options?: {\n\t\t\t\t\tcustomInstructions?: string;\n\t\t\t\t\tonComplete?: (result: CompactionResult) => void;\n\t\t\t\t\tonError?: (error: Error) => void;\n\t\t\t\t}) => {\n\t\t\t\t\tvoid (async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await this.compact(options?.customInstructions);\n\t\t\t\t\t\t\toptions?.onComplete?.(result);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\t\t\toptions?.onError?.(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t\tgetSystemPrompt: () => this.systemPrompt,\n\t\t\t\tgetActiveMissionId: () => this.missionId,\n\t\t\t}\n\t\t);\n\t}\n\n\tasync runUltraplan(objective: string): Promise<UltraplanRunResult> {\n\t\tconst trimmedObjective = objective.trim();\n\t\tif (trimmedObjective.length === 0) {\n\t\t\tthrow new Error(\"Ultraplan requires a non-empty objective.\");\n\t\t}\n\n\t\tconst subagentTool = [\n\t\t\t...(this._extensionRunner?.getAllRegisteredTools().map((tool) => tool.definition) ?? []),\n\t\t\t...this._customTools,\n\t\t].find((tool) => tool.name === \"subagent\") as UltraplanSubagentTool | undefined;\n\t\tif (!subagentTool) {\n\t\t\tthrow new Error(\"Ultraplan requires the local subagent tool to be available.\");\n\t\t}\n\n\t\tconst result = await subagentTool.execute(\n\t\t\t`ultraplan_${Date.now()}`,\n\t\t\t{\n\t\t\t\tagent: \"planner\",\n\t\t\t\ttask: buildUltraplanPlannerTask({\n\t\t\t\t\tobjective: trimmedObjective,\n\t\t\t\t\tmemoryItems: this.getMemoryItems(),\n\t\t\t\t\ttodos: this.getTodos(),\n\t\t\t\t}),\n\t\t\t\tagentScope: \"user\",\n\t\t\t},\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\tthis._createUltraplanExecutionContext(),\n\t\t);\n\t\tif (result.isError) {\n\t\t\tconst errorText = result.content.find((entry) => entry.type === \"text\")?.text ?? \"Ultraplan failed.\";\n\t\t\tthrow new Error(errorText);\n\t\t}\n\n\t\tconst plannerOutput = result.content.find((entry) => entry.type === \"text\")?.text?.trim();\n\t\tif (!plannerOutput) {\n\t\t\tthrow new Error(\"Planner returned no Ultraplan output.\");\n\t\t}\n\n\t\tconst artifact = parseUltraplanArtifactFromText(plannerOutput);\n\t\tthis.sessionManager.appendCustomEntry(SESSION_ULTRAPLAN_CUSTOM_TYPE, artifact);\n\n\t\treturn {\n\t\t\tartifact,\n\t\t\tdisplayText: `${formatUltraplanArtifact(artifact)}\\n\\nPersisted as session-owned Ultraplan state on the current branch.`,\n\t\t\trawPlannerOutput: plannerOutput,\n\t\t};\n\t}\n\n\t/**\n\t * Revise the latest persisted Ultraplan plan based on a revision instruction.\n\t *\n\t * Reads the existing plan artifact and passes it to the planner along with\n\t * the revision instruction. The revised result is persisted as a new latest\n\t * artifact. Apply remains separate and manual.\n\t *\n\t * @param instruction - Revision instruction to guide the planner\n\t * @returns Revised plan artifact and display text\n\t * @throws Error if no persisted Ultraplan plan exists or planner tool unavailable\n\t */\n\tasync runUltraplanRevise(instruction: string): Promise<UltraplanRunResult> {\n\t\tconst trimmedInstruction = instruction.trim();\n\t\tif (trimmedInstruction.length === 0) {\n\t\t\tthrow new Error(\"Ultraplan revision requires a non-empty instruction.\");\n\t\t}\n\n\t\tconst existingArtifact = this.getLatestUltraplanPlan();\n\t\tif (!existingArtifact) {\n\t\t\tthrow new Error(\"No persisted Ultraplan plan found. Run /ultraplan <objective> first.\");\n\t\t}\n\n\t\tconst subagentTool = [\n\t\t\t...(this._extensionRunner?.getAllRegisteredTools().map((tool) => tool.definition) ?? []),\n\t\t\t...this._customTools,\n\t\t].find((tool) => tool.name === \"subagent\") as UltraplanSubagentTool | undefined;\n\t\tif (!subagentTool) {\n\t\t\tthrow new Error(\"Ultraplan requires the local subagent tool to be available.\");\n\t\t}\n\n\t\tconst result = await subagentTool.execute(\n\t\t\t`ultraplan_revise_${Date.now()}`,\n\t\t\t{\n\t\t\t\tagent: \"planner\",\n\t\t\t\ttask: buildUltraplanRevisionTask({\n\t\t\t\t\tinstruction: trimmedInstruction,\n\t\t\t\t\texistingArtifact,\n\t\t\t\t\tmemoryItems: this.getMemoryItems(),\n\t\t\t\t\ttodos: this.getTodos(),\n\t\t\t\t}),\n\t\t\t\tagentScope: \"user\",\n\t\t\t},\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\tthis._createUltraplanExecutionContext(),\n\t\t);\n\t\tif (result.isError) {\n\t\t\tconst errorText = result.content.find((entry) => entry.type === \"text\")?.text ?? \"Ultraplan revision failed.\";\n\t\t\tthrow new Error(errorText);\n\t\t}\n\n\t\tconst plannerOutput = result.content.find((entry) => entry.type === \"text\")?.text?.trim();\n\t\tif (!plannerOutput) {\n\t\t\tthrow new Error(\"Planner returned no Ultraplan output.\");\n\t\t}\n\n\t\tconst artifact = parseUltraplanArtifactFromText(plannerOutput);\n\t\tthis.sessionManager.appendCustomEntry(SESSION_ULTRAPLAN_CUSTOM_TYPE, artifact);\n\n\t\treturn {\n\t\t\tartifact,\n\t\t\tdisplayText:\n\t\t\t\t`${formatUltraplanArtifact(artifact)}\\n\\n` +\n\t\t\t\t\"Persisted as a new latest session-owned Ultraplan state on the current branch. \" +\n\t\t\t\t\"Prior plan artifacts remain preserved separately. Apply remains manual; no execution has started.\",\n\t\t\trawPlannerOutput: plannerOutput,\n\t\t};\n\t}\n\n\t/**\n\t * Apply the latest persisted Ultraplan plan to session-owned todo state.\n\t *\n\t * This materializes plan output into persisted todo state only.\n\t * The original Ultraplan artifact remains intact and no execution starts.\n\t *\n\t * @returns Result with applied todos and clear applied-not-executed messaging\n\t * @throws Error if no persisted Ultraplan plan exists\n\t */\n\tapplyUltraplan(): {\n\t\tapplied: TodoItem[];\n\t\tdisplayText: string;\n\t} {\n\t\tconst artifact = this.getLatestUltraplanPlan();\n\t\tif (!artifact) {\n\t\t\tthrow new Error(\"No persisted Ultraplan plan found. Run /ultraplan <objective> first.\");\n\t\t}\n\n\t\tconst selection = selectUltraplanApplySteps(artifact);\n\t\tif (selection.steps.length === 0) {\n\t\t\treturn {\n\t\t\t\tapplied: [],\n\t\t\t\tdisplayText:\n\t\t\t\t\t\"Ultraplan plan found, but it contains no applicable actionable steps.\\n\\n\" +\n\t\t\t\t\t\"The plan artifact is preserved separately. Apply did not start execution.\",\n\t\t\t};\n\t\t}\n\n\t\tconst existingTodoContents = new Set(this._todos.map((todo) => todo.content));\n\t\tconst newTodos: TodoItem[] = selection.steps\n\t\t\t.filter((step) => !existingTodoContents.has(step))\n\t\t\t.map((step) => ({\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\tcontent: step,\n\t\t\t\tactiveForm: step,\n\t\t\t\tstatus: \"pending\" as const,\n\t\t\t}));\n\n\t\tif (newTodos.length === 0) {\n\t\t\treturn {\n\t\t\t\tapplied: [],\n\t\t\t\tdisplayText:\n\t\t\t\t\t\"Ultraplan plan is already represented in session todo state.\\n\\n\" +\n\t\t\t\t\t\"The plan artifact remains preserved separately. Apply did not start execution.\",\n\t\t\t};\n\t\t}\n\n\t\tconst mergedTodos = [...this._todos, ...newTodos];\n\t\tthis._setTodos(mergedTodos);\n\n\t\tconst sourceLabel =\n\t\t\tselection.source === \"actionable_next_steps\"\n\t\t\t\t? \"actionable next steps\"\n\t\t\t\t: selection.source === \"first_phase_steps\"\n\t\t\t\t\t? \"first phase steps\"\n\t\t\t\t\t: \"plan steps\";\n\n\t\treturn {\n\t\t\tapplied: newTodos,\n\t\t\tdisplayText:\n\t\t\t\t`Applied ${newTodos.length} Ultraplan step(s) from the latest persisted plan into session todo state.\\n` +\n\t\t\t\t`Source: ${sourceLabel}. Todo total: ${mergedTodos.length}.\\n\\n` +\n\t\t\t\t\"The Ultraplan artifact remains preserved separately as plan state. Apply did not start execution.\",\n\t\t};\n\t}\n\n\t/** Whether compaction or branch summarization is currently running */\n\tget isCompacting(): boolean {\n\t\treturn (\n\t\t\tthis._autoCompactionAbortController !== undefined ||\n\t\t\tthis._compactionAbortController !== undefined ||\n\t\t\tthis._branchSummaryAbortController !== undefined\n\t\t);\n\t}\n\n\t/** All messages including custom types like BashExecutionMessage */\n\tget messages(): AgentMessage[] {\n\t\treturn this.agent.state.messages;\n\t}\n\n\t/** Current steering mode */\n\tget steeringMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.agent.getSteeringMode();\n\t}\n\n\t/** Current follow-up mode */\n\tget followUpMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.agent.getFollowUpMode();\n\t}\n\n\t/** Current session file path, or undefined if sessions are disabled */\n\tget sessionFile(): string | undefined {\n\t\treturn this.sessionManager.getSessionFile();\n\t}\n\n\t/** Current session ID */\n\tget sessionId(): string {\n\t\treturn this.sessionManager.getSessionId();\n\t}\n\n\t/** Current session display name, if set */\n\tget sessionName(): string | undefined {\n\t\treturn this.sessionManager.getSessionName();\n\t}\n\n\t/** Scoped models for cycling (from --models flag) */\n\tget scopedModels(): ReadonlyArray<{ model: Model<any>; thinkingLevel?: ThinkingLevel }> {\n\t\treturn this._scopedModels;\n\t}\n\n\t/** Update scoped models for cycling */\n\tsetScopedModels(scopedModels: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>): void {\n\t\tthis._scopedModels = scopedModels;\n\t}\n\n\t/** Enable or disable the brief-only output contract for this session runtime. */\n\tsetBriefOnly(enabled: boolean): void {\n\t\tif (this._briefOnly === enabled) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._briefOnly = enabled;\n\t\tthis._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());\n\t\tthis._applyBaseSystemPrompt();\n\t}\n\n\t/** Set the Caveman output compression level for this session runtime. */\n\tsetCavemanLevel(level: CavemanLevel): void {\n\t\tif (this._cavemanLevel === level) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._cavemanLevel = level;\n\t\tthis._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());\n\t\tthis._applyBaseSystemPrompt();\n\t}\n\n\tqueueByTheWay(note: string): void {\n\t\tthis._pendingNextTurnMessages.push({\n\t\t\trole: \"custom\",\n\t\t\t...createBtwNextTurnMessage(note),\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\t}\n\n\t/** File-based prompt templates */\n\tget promptTemplates(): ReadonlyArray<PromptTemplate> {\n\t\treturn this._resourceLoader.getPrompts().prompts;\n\t}\n\n\tprivate _normalizePromptSnippet(text: string | undefined): string | undefined {\n\t\tif (!text) return undefined;\n\t\tconst oneLine = text\n\t\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t\t.replace(/\\s+/g, \" \")\n\t\t\t.trim();\n\t\treturn oneLine.length > 0 ? oneLine : undefined;\n\t}\n\n\tprivate _normalizePromptGuidelines(guidelines: string[] | undefined): string[] {\n\t\tif (!guidelines || guidelines.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst unique = new Set<string>();\n\t\tfor (const guideline of guidelines) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\tunique.add(normalized);\n\t\t\t}\n\t\t}\n\t\treturn Array.from(unique);\n\t}\n\n\tprivate _augmentCompactionSummary(summary: string): string {\n\t\tconst memorySection =\n\t\t\tthis._memoryItems.length > 0\n\t\t\t\t? `\\n\\n## Active Session Memory\\n${this._memoryItems.map((item) => `- ${item.key}: ${item.value}`).join(\"\\n\")}`\n\t\t\t\t: \"\";\n\t\tconst todoSection =\n\t\t\tthis._todos.length > 0\n\t\t\t\t? `\\n\\n## Active Todo State\\n${this._todos.map((todo) => `- [${todo.status}] ${todo.status === \"in_progress\" ? todo.activeForm : todo.content}`).join(\"\\n\")}`\n\t\t\t\t: \"\";\n\t\treturn `${summary}${memorySection}${todoSection}`;\n\t}\n\n\tprivate async _finalizeCompaction(options: {\n\t\tsummary: string;\n\t\tfirstKeptEntryId: string;\n\t\ttokensBefore: number;\n\t\tdetails: unknown;\n\t\tfromExtension: boolean;\n\t}): Promise<{ result: CompactionResult; savedCompactionEntry: CompactionEntry | undefined }> {\n\t\tconst { summary, firstKeptEntryId, tokensBefore, details, fromExtension } = options;\n\t\tconst persistedSummary = this._augmentCompactionSummary(summary);\n\n\t\tthis.sessionManager.appendCompaction(persistedSummary, firstKeptEntryId, tokensBefore, details, fromExtension);\n\t\tconst newEntries = this.sessionManager.getEntries();\n\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\tthis.agent.replaceMessages(sessionContext.messages);\n\n\t\tconst savedCompactionEntry = newEntries.find((e) => e.type === \"compaction\" && e.summary === persistedSummary) as\n\t\t\t| CompactionEntry\n\t\t\t| undefined;\n\n\t\tif (this._extensionRunner && savedCompactionEntry) {\n\t\t\tawait this._extensionRunner.emit({\n\t\t\t\ttype: \"session_compact\",\n\t\t\t\tcompactionEntry: savedCompactionEntry,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t}\n\n\t\treturn {\n\t\t\tresult: {\n\t\t\t\tsummary: persistedSummary,\n\t\t\t\tfirstKeptEntryId,\n\t\t\t\ttokensBefore,\n\t\t\t\tdetails,\n\t\t\t},\n\t\t\tsavedCompactionEntry,\n\t\t};\n\t}\n\n\tprivate _getBriefOnlyPromptGuidelines(): string[] {\n\t\tif (!this._briefOnly) {\n\t\t\treturn [];\n\t\t}\n\n\t\treturn [\n\t\t\t\"Brief-only mode is enabled for this session.\",\n\t\t\t\"Suppress ordinary assistant prose.\",\n\t\t\t\"Do not emit assistant narration, summaries, or conversational filler unless it is necessary for honest error reporting or operational transparency.\",\n\t\t\t\"Do not hide tool activity, approvals, warnings, errors, or other security-relevant execution details.\",\n\t\t\t\"User-visible brief updates may be delivered separately by the runtime; avoid duplicating them in assistant prose.\",\n\t\t];\n\t}\n\n\tprivate _getCavemanPromptGuidelines(): string[] {\n\t\tif (this._cavemanLevel === \"off\") {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst safetyExclusions = [\n\t\t\t\"CRITICAL SAFETY - NEVER compress, omit, modify, or summarize the following under any circumstances:\",\n\t\t\t\"  - Tool calls, tool arguments, tool results, and command output\",\n\t\t\t\"  - JSON, YAML, XML, frontmatter, schemas, or any machine-parsed envelopes\",\n\t\t\t\"  - details.results and all result fields used for parent validation\",\n\t\t\t\"  - Task, planner, slice, handoff, run, and verification state\",\n\t\t\t\"  - Code, file paths, URLs, commit hashes, CLI commands, and exact error messages\",\n\t\t\t\"  - Security confirmations, destructive action confirmations, and ordered procedures\",\n\t\t\t\"  - Delegated evidence from reviewer, security, pentester, and librarian agents\",\n\t\t\t\"These global native rules cannot be weakened by project-local configuration or skills.\",\n\t\t\t\"Delegated narrative summaries are acceptable only for prose, never for structured results.\",\n\t\t\t\"Preserve the user's original language in all modes. Do not change language, terminology, or phrasing used by the user.\",\n\t\t];\n\n\t\tif (this._cavemanLevel === \"lite\") {\n\t\t\treturn [\n\t\t\t\t\"Caveman Lite output compression is active for this session. Use professional complete sentences that remove filler words, hedging language, and unnecessary elaboration. Present each step clearly and concisely while maintaining natural prose flow.\",\n\t\t\t\t...safetyExclusions,\n\t\t\t];\n\t\t}\n\n\t\tif (this._cavemanLevel === \"full\") {\n\t\t\treturn [\n\t\t\t\t\"Caveman Full output compression is active for this session. Use tighter phrasing. Favor sentence fragments only where meaning remains unambiguous. Eliminate redundant words and softening phrases.\",\n\t\t\t\t...safetyExclusions,\n\t\t\t];\n\t\t}\n\n\t\t// \"ultra\"\n\t\treturn [\n\t\t\t\"Caveman Ultra output compression is active for this session. Use only simple, non-risky answers with minimal prose. MANDATORY: For warnings, destructive actions/confirmations, ambiguity, ordered or multi-step procedures, or repeated questions, you MUST automatically fall back to clear, complete prose. Never use keyword-level output for these situations.\",\n\t\t\t...safetyExclusions,\n\t\t];\n\t}\n\n\tprivate _rebuildSystemPrompt(toolNames: string[]): string {\n\t\tconst validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));\n\t\tconst toolSnippets: Record<string, string> = {};\n\t\tconst promptGuidelines: string[] = [];\n\t\tfor (const name of validToolNames) {\n\t\t\tconst snippet = this._toolPromptSnippets.get(name);\n\t\t\tif (snippet) {\n\t\t\t\ttoolSnippets[name] = snippet;\n\t\t\t}\n\n\t\t\tconst toolGuidelines = this._toolPromptGuidelines.get(name);\n\t\t\tif (toolGuidelines) {\n\t\t\t\tpromptGuidelines.push(...toolGuidelines);\n\t\t\t}\n\t\t}\n\t\tpromptGuidelines.push(...this._getBriefOnlyPromptGuidelines());\n\t\tpromptGuidelines.push(...this._getCavemanPromptGuidelines());\n\n\t\tconst loaderSystemPrompt = this._resourceLoader.getSystemPrompt();\n\t\tconst loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();\n\t\tconst appendSystemPrompt =\n\t\t\tloaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join(\"\\n\\n\") : undefined;\n\t\tconst loadedSkills = this._resourceLoader.getSkills().skills;\n\t\tconst loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;\n\n\t\tconst regions = buildSystemPromptRegions({\n\t\t\tcwd: this._cwd,\n\t\t\tskills: loadedSkills,\n\t\t\tcontextFiles: loadedContextFiles,\n\t\t\tcustomPrompt: loaderSystemPrompt,\n\t\t\tappendSystemPrompt,\n\t\t\tselectedTools: validToolNames,\n\t\t\ttoolSnippets,\n\t\t\tpromptGuidelines,\n\t\t});\n\t\tthis._baseDynamicPrompt = regions.dynamicSuffix;\n\t\treturn regions.stablePrefix;\n\t}\n\n\tprivate _applyBaseSystemPrompt(): void {\n\t\tthis.agent.setSystemPrompt(this._baseSystemPrompt);\n\t\tthis.agent.setDynamicPrompt(this._baseDynamicPrompt);\n\t}\n\n\tprivate _getCompleteBaseSystemPrompt(): string {\n\t\treturn this._baseDynamicPrompt\n\t\t\t? `${this._baseSystemPrompt}\\n\\n${this._baseDynamicPrompt}`\n\t\t\t: this._baseSystemPrompt;\n\t}\n\n\t// =========================================================================\n\t// Prompting\n\t// =========================================================================\n\n\t/**\n\t * Send a prompt to the agent.\n\t * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming\n\t * - Expands file-based prompt templates by default\n\t * - During streaming, queues via steer() or followUp() based on streamingBehavior option\n\t * - Validates model and API key before sending (when not streaming)\n\t * @throws Error if streaming and no streamingBehavior specified\n\t * @throws Error if no model selected or no API key available (when not streaming)\n\t */\n\tasync prompt(text: string, options?: PromptOptions): Promise<void> {\n\t\tconst expandPromptTemplates = options?.expandPromptTemplates ?? true;\n\n\t\t// Handle extension commands first (execute immediately, even during streaming)\n\t\t// Extension commands manage their own LLM interaction via pi.sendMessage()\n\t\tif (expandPromptTemplates && text.startsWith(\"/\")) {\n\t\t\tconst handled = await this._tryExecuteExtensionCommand(text);\n\t\t\tif (handled) {\n\t\t\t\t// Extension command executed, no prompt to send\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Emit input event for extension interception (before skill/template expansion)\n\t\tlet currentText = text;\n\t\tlet currentImages = options?.images;\n\t\tif (this._extensionRunner?.hasHandlers(\"input\")) {\n\t\t\tconst inputResult = await this._extensionRunner.emitInput(\n\t\t\t\tcurrentText,\n\t\t\t\tcurrentImages,\n\t\t\t\toptions?.source ?? \"interactive\",\n\t\t\t);\n\t\t\tif (inputResult.action === \"handled\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (inputResult.action === \"transform\") {\n\t\t\t\tcurrentText = inputResult.text;\n\t\t\t\tcurrentImages = inputResult.images ?? currentImages;\n\t\t\t}\n\t\t}\n\n\t\t// Expand skill commands (/skill:name args) and prompt templates (/template args)\n\t\tlet expandedText = currentText;\n\t\tif (expandPromptTemplates) {\n\t\t\texpandedText = this._expandSkillCommand(expandedText);\n\t\t\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\t\t}\n\n\t\t// If streaming, queue via steer() or followUp() based on option\n\t\tif (this.isStreaming) {\n\t\t\tif (!options?.streamingBehavior) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (options.streamingBehavior === \"followUp\") {\n\t\t\t\tawait this._queueFollowUp(expandedText, currentImages);\n\t\t\t} else {\n\t\t\t\tawait this._queueSteer(expandedText, currentImages);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Flush any pending bash messages before the new prompt\n\t\tthis._flushPendingBashMessages();\n\n\t\t// Validate model\n\t\tif (!this.model) {\n\t\t\tthrow new Error(\n\t\t\t\t\"No model selected.\\n\\n\" +\n\t\t\t\t\t`Use /login or set an API key environment variable. See ${join(getDocsPath(), \"providers.md\")}\\n\\n` +\n\t\t\t\t\t\"Then use /model to select a model.\",\n\t\t\t);\n\t\t}\n\n\t\t// Validate API key\n\t\tlet apiKey = await this._modelRegistry.getApiKey(this.model);\n\t\tif (!apiKey) {\n\t\t\tlet fallbackSuccess = false;\n\t\t\twhile (!apiKey && this._fallbackIndex < this._fallbackModels.length - 1) {\n\t\t\t\tthis._fallbackIndex++;\n\t\t\t\tconst fallbackModel = this._fallbackModels[this._fallbackIndex];\n\t\t\t\tapiKey = await this._modelRegistry.getApiKey(fallbackModel);\n\t\t\t\tif (apiKey) {\n\t\t\t\t\tthis._emit({\n\t\t\t\t\t\ttype: \"auto_fallback\",\n\t\t\t\t\t\tmodel: this.model,\n\t\t\t\t\t\tfallbackModel,\n\t\t\t\t\t\treason: \"Missing API key for primary model\",\n\t\t\t\t\t});\n\t\t\t\t\tawait this.setModel(fallbackModel);\n\t\t\t\t\tfallbackSuccess = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!fallbackSuccess && !apiKey) {\n\t\t\t\tconst isOAuth = this._modelRegistry.isUsingOAuth(this.model);\n\t\t\t\tif (isOAuth) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Authentication failed for \"${this.model.provider}\". ` +\n\t\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t\t`Run '/login ${this.model.provider}' to re-authenticate.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No API key found for ${this.model.provider}.\\n\\n` +\n\t\t\t\t\t\t`Use /login or set an API key environment variable. See ${join(getDocsPath(), \"providers.md\")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Check if we need to compact before sending (catches aborted responses)\n\t\tconst lastAssistant = this._findLastAssistantMessage();\n\t\tif (lastAssistant) {\n\t\t\tawait this._checkCompaction(lastAssistant, false);\n\t\t}\n\n\t\t// Build messages array (custom message if any, then user message)\n\t\tconst messages: AgentMessage[] = [];\n\n\t\t// Add user message\n\t\tconst userContent: (TextContent | ImageContent)[] = [{ type: \"text\", text: expandedText }];\n\t\tif (currentImages) {\n\t\t\tuserContent.push(...currentImages);\n\t\t}\n\t\tmessages.push({\n\t\t\trole: \"user\",\n\t\t\tcontent: userContent,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\n\t\t// Inject any pending \"nextTurn\" messages as context alongside the user message\n\t\tfor (const msg of this._pendingNextTurnMessages) {\n\t\t\tmessages.push(msg);\n\t\t}\n\t\tthis._pendingNextTurnMessages = [];\n\n\t\t// Emit before_agent_start extension event\n\t\tif (this._extensionRunner) {\n\t\t\tconst result = await this._extensionRunner.emitBeforeAgentStart(\n\t\t\t\texpandedText,\n\t\t\t\tcurrentImages,\n\t\t\t\tthis._getCompleteBaseSystemPrompt(),\n\t\t\t);\n\t\t\t// Add all custom messages from extensions\n\t\t\tif (result?.messages) {\n\t\t\t\tfor (const msg of result.messages) {\n\t\t\t\t\tmessages.push({\n\t\t\t\t\t\trole: \"custom\",\n\t\t\t\t\t\tcustomType: msg.customType,\n\t\t\t\t\t\tcontent: msg.content,\n\t\t\t\t\t\tdisplay: msg.display,\n\t\t\t\t\t\tdetails: msg.details,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Apply extension-modified system prompt, or reset to base\n\t\t\tif (result?.systemPrompt && result.systemPrompt !== this._getCompleteBaseSystemPrompt()) {\n\t\t\t\tthis.agent.setSystemPrompt(result.systemPrompt);\n\t\t\t\tthis.agent.setDynamicPrompt(undefined);\n\t\t\t} else {\n\t\t\t\t// Ensure we're using the base prompt (in case previous turn had modifications)\n\t\t\t\tthis._applyBaseSystemPrompt();\n\t\t\t}\n\t\t}\n\n\t\tthis._todoLoopGuard.resetOnNewUserMessage();\n\t\tthis._todoUpdateRejectionState.count = 0;\n\t\tthis._todoPerTurnLock.currentTurn++;\n\t\tthis._todoPerTurnLock.lockedUntil = -1;\n\t\tthis._todoPerTurnLock.reservedUntil = -1;\n\t\tif (this._toolRegistry.has(\"todo_write\") && !this.getActiveToolNames().includes(\"todo_write\")) {\n\t\t\tthis.setActiveToolsByName([...this.getActiveToolNames(), \"todo_write\"]);\n\t\t}\n\n\t\t// Reliability Kernel: reset per-run finalization budget and inject the\n\t\t// authoritative mission state into this turn's context.\n\t\tthis._reliability?.resetRun();\n\t\tthis._applyReliabilityContext();\n\n\t\tawait this.agent.prompt(messages);\n\t\tawait this.waitForRetry();\n\t}\n\n\t/**\n\t * Try to execute an extension command. Returns true if command was found and executed.\n\t */\n\tprivate async _tryExecuteExtensionCommand(text: string): Promise<boolean> {\n\t\tif (!this._extensionRunner) return false;\n\n\t\t// Parse command name and args\n\t\tconst spaceIndex = text.indexOf(\" \");\n\t\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\t\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\n\t\tconst command = this._extensionRunner.getCommand(commandName);\n\t\tif (!command) return false;\n\n\t\t// Get command context from extension runner (includes session control methods)\n\t\tconst ctx = this._extensionRunner.createCommandContext();\n\n\t\ttry {\n\t\t\tawait command.handler(args, ctx);\n\t\t\treturn true;\n\t\t} catch (err) {\n\t\t\t// Emit error via extension runner\n\t\t\tthis._extensionRunner.emitError({\n\t\t\t\textensionPath: `command:${commandName}`,\n\t\t\t\tevent: \"command\",\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/**\n\t * Expand skill commands (/skill:name args) to their full content.\n\t * Returns the expanded text, or the original text if not a skill command or skill not found.\n\t * Emits errors via extension runner if file read fails.\n\t */\n\tprivate _expandSkillCommand(text: string): string {\n\t\tif (!text.startsWith(\"/skill:\")) return text;\n\n\t\tconst spaceIndex = text.indexOf(\" \");\n\t\tconst skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);\n\t\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1).trim();\n\n\t\tconst skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);\n\t\tif (!skill) return text; // Unknown skill, pass through\n\n\t\ttry {\n\t\t\tconst content = readFileSync(skill.filePath, \"utf-8\");\n\t\t\tconst body = stripFrontmatter(content).trim();\n\t\t\tconst skillBlock = `<skill name=\"${skill.name}\" location=\"${skill.filePath}\">\\nReferences are relative to ${skill.baseDir}.\\n\\n${body}\\n</skill>`;\n\t\t\treturn args ? `${skillBlock}\\n\\n${args}` : skillBlock;\n\t\t} catch (err) {\n\t\t\t// Emit error like extension commands do\n\t\t\tthis._extensionRunner?.emitError({\n\t\t\t\textensionPath: skill.filePath,\n\t\t\t\tevent: \"skill_expansion\",\n\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t});\n\t\t\treturn text; // Return original on error\n\t\t}\n\t}\n\n\t/**\n\t * Queue a steering message while the agent is running.\n\t * Delivered after the current assistant turn finishes executing its tool calls,\n\t * before the next LLM call.\n\t * Expands skill commands and prompt templates. Errors on extension commands.\n\t * @param images Optional image attachments to include with the message\n\t * @throws Error if text is an extension command\n\t */\n\tasync steer(text: string, images?: ImageContent[]): Promise<void> {\n\t\t// Check for extension commands (cannot be queued)\n\t\tif (text.startsWith(\"/\")) {\n\t\t\tthis._throwIfExtensionCommand(text);\n\t\t}\n\n\t\t// Expand skill commands and prompt templates\n\t\tlet expandedText = this._expandSkillCommand(text);\n\t\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\t\tawait this._queueSteer(expandedText, images);\n\t}\n\n\t/**\n\t * Queue a follow-up message to be processed after the agent finishes.\n\t * Delivered only when agent has no more tool calls or steering messages.\n\t * Expands skill commands and prompt templates. Errors on extension commands.\n\t * @param images Optional image attachments to include with the message\n\t * @throws Error if text is an extension command\n\t */\n\tasync followUp(text: string, images?: ImageContent[]): Promise<void> {\n\t\t// Check for extension commands (cannot be queued)\n\t\tif (text.startsWith(\"/\")) {\n\t\t\tthis._throwIfExtensionCommand(text);\n\t\t}\n\n\t\t// Expand skill commands and prompt templates\n\t\tlet expandedText = this._expandSkillCommand(text);\n\t\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\t\tawait this._queueFollowUp(expandedText, images);\n\t}\n\n\t/**\n\t * Internal: Queue a steering message (already expanded, no extension command check).\n\t */\n\tprivate async _queueSteer(text: string, images?: ImageContent[]): Promise<void> {\n\t\tthis._steeringMessages.push(text);\n\t\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text }];\n\t\tif (images) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\tthis.agent.steer({\n\t\t\trole: \"user\",\n\t\t\tcontent,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\t}\n\n\t/**\n\t * Internal: Queue a follow-up message (already expanded, no extension command check).\n\t */\n\tprivate async _queueFollowUp(text: string, images?: ImageContent[]): Promise<void> {\n\t\tthis._followUpMessages.push(text);\n\t\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text }];\n\t\tif (images) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\tthis.agent.followUp({\n\t\t\trole: \"user\",\n\t\t\tcontent,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\t}\n\n\t/**\n\t * Throw an error if the text is an extension command.\n\t */\n\tprivate _throwIfExtensionCommand(text: string): void {\n\t\tif (!this._extensionRunner) return;\n\n\t\tconst spaceIndex = text.indexOf(\" \");\n\t\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\t\tconst command = this._extensionRunner.getCommand(commandName);\n\n\t\tif (command) {\n\t\t\tthrow new Error(\n\t\t\t\t`Extension command \"/${commandName}\" cannot be queued. Use prompt() or execute the command when not streaming.`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Send a custom message to the session. Creates a CustomMessageEntry.\n\t *\n\t * Handles three cases:\n\t * - Streaming: queues message, processed when loop pulls from queue\n\t * - Not streaming + triggerTurn: appends to state/session, starts new turn\n\t * - Not streaming + no trigger: appends to state/session, no turn\n\t *\n\t * @param message Custom message with customType, content, display, details\n\t * @param options.triggerTurn If true and not streaming, triggers a new LLM turn\n\t * @param options.deliverAs Delivery mode: \"steer\", \"followUp\", or \"nextTurn\"\n\t */\n\tasync sendCustomMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n\t): Promise<void> {\n\t\tconst appMessage = {\n\t\t\trole: \"custom\" as const,\n\t\t\tcustomType: message.customType,\n\t\t\tcontent: message.content,\n\t\t\tdisplay: message.display,\n\t\t\tdetails: message.details,\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies CustomMessage<T>;\n\t\tif (options?.deliverAs === \"nextTurn\") {\n\t\t\tthis._pendingNextTurnMessages.push(appMessage);\n\t\t} else if (this.isStreaming) {\n\t\t\tif (options?.deliverAs === \"followUp\") {\n\t\t\t\tthis.agent.followUp(appMessage);\n\t\t\t} else {\n\t\t\t\tthis.agent.steer(appMessage);\n\t\t\t}\n\t\t} else if (options?.triggerTurn) {\n\t\t\tawait this.agent.prompt(appMessage);\n\t\t} else {\n\t\t\tthis.agent.appendMessage(appMessage);\n\t\t\tthis.sessionManager.appendCustomMessageEntry(\n\t\t\t\tmessage.customType,\n\t\t\t\tmessage.content,\n\t\t\t\tmessage.display,\n\t\t\t\tmessage.details,\n\t\t\t);\n\t\t\tthis._emit({ type: \"message_start\", message: appMessage });\n\t\t\tthis._emit({ type: \"message_end\", message: appMessage });\n\t\t}\n\t}\n\n\t/**\n\t * Send a user message to the agent. Always triggers a turn.\n\t * When the agent is streaming, use deliverAs to specify how to queue the message.\n\t *\n\t * @param content User message content (string or content array)\n\t * @param options.deliverAs Delivery mode when streaming: \"steer\" or \"followUp\"\n\t */\n\tasync sendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): Promise<void> {\n\t\t// Normalize content to text string + optional images\n\t\tlet text: string;\n\t\tlet images: ImageContent[] | undefined;\n\n\t\tif (typeof content === \"string\") {\n\t\t\ttext = content;\n\t\t} else {\n\t\t\tconst textParts: string[] = [];\n\t\t\timages = [];\n\t\t\tfor (const part of content) {\n\t\t\t\tif (part.type === \"text\") {\n\t\t\t\t\ttextParts.push(part.text);\n\t\t\t\t} else {\n\t\t\t\t\timages.push(part);\n\t\t\t\t}\n\t\t\t}\n\t\t\ttext = textParts.join(\"\\n\");\n\t\t\tif (images.length === 0) images = undefined;\n\t\t}\n\n\t\t// Use prompt() with expandPromptTemplates: false to skip command handling and template expansion\n\t\tawait this.prompt(text, {\n\t\t\texpandPromptTemplates: false,\n\t\t\tstreamingBehavior: options?.deliverAs,\n\t\t\timages,\n\t\t\tsource: \"extension\",\n\t\t});\n\t}\n\n\t/**\n\t * Clear all queued messages and return them.\n\t * Useful for restoring to editor when user aborts.\n\t * @returns Object with steering and followUp arrays\n\t */\n\tclearQueue(): { steering: string[]; followUp: string[] } {\n\t\tconst steering = [...this._steeringMessages];\n\t\tconst followUp = [...this._followUpMessages];\n\t\tthis._steeringMessages = [];\n\t\tthis._followUpMessages = [];\n\t\tthis.agent.clearAllQueues();\n\t\treturn { steering, followUp };\n\t}\n\n\t/** Number of pending messages (includes both steering and follow-up) */\n\tget pendingMessageCount(): number {\n\t\treturn this._steeringMessages.length + this._followUpMessages.length;\n\t}\n\n\t/** Get pending steering messages (read-only) */\n\tgetSteeringMessages(): readonly string[] {\n\t\treturn this._steeringMessages;\n\t}\n\n\t/** Get pending follow-up messages (read-only) */\n\tgetFollowUpMessages(): readonly string[] {\n\t\treturn this._followUpMessages;\n\t}\n\n\tget resourceLoader(): ResourceLoader {\n\t\treturn this._resourceLoader;\n\t}\n\n\t/**\n\t * Abort current operation and wait for agent to become idle.\n\t */\n\tasync abort(): Promise<void> {\n\t\tthis.abortRetry();\n\t\tthis.agent.abort();\n\t\tawait this.agent.waitForIdle();\n\t}\n\n\t/**\n\t * Start a new session, optionally with initial messages and parent tracking.\n\t * Clears all messages and starts a new session.\n\t * Listeners are preserved and will continue receiving events.\n\t * @param options.parentSession - Optional parent session path for tracking\n\t * @param options.setup - Optional callback to initialize session (e.g., append messages)\n\t * @returns true if completed, false if cancelled by extension\n\t */\n\tasync newSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t}): Promise<boolean> {\n\t\tconst previousSessionFile = this.sessionFile;\n\n\t\t// Emit session_before_switch event with reason \"new\" (can be cancelled)\n\t\tif (this._extensionRunner?.hasHandlers(\"session_before_switch\")) {\n\t\t\tconst result = (await this._extensionRunner.emit({\n\t\t\t\ttype: \"session_before_switch\",\n\t\t\t\treason: \"new\",\n\t\t\t})) as SessionBeforeSwitchResult | undefined;\n\n\t\t\tif (result?.cancel) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tthis._disconnectFromAgent();\n\t\tawait this.abort();\n\t\tthis.agent.reset();\n\t\tthis.sessionManager.newSession({ parentSession: options?.parentSession });\n\t\tthis.agent.sessionId = this.sessionManager.getSessionId();\n\t\tthis._steeringMessages = [];\n\t\tthis._followUpMessages = [];\n\t\tthis._pendingNextTurnMessages = [];\n\t\tthis._todos = [];\n\t\tthis._todoRevision = 0;\n\t\tthis._resetTodoEngine();\n\t\tthis._todoReadSnapshot = null;\n\t\tthis._todoUpdateRejectionState.count = 0;\n\t\tthis._todoPerTurnLock.currentTurn = 0;\n\t\tthis._todoPerTurnLock.lockedUntil = -1;\n\t\tthis._todoPerTurnLock.reservedUntil = -1;\n\t\tthis._memoryItems = [];\n\t\tthis._delegatedTasks = [];\n\t\tthis._tasks = [];\n\t\tthis._cavemanLevel = \"off\";\n\t\tthis._briefOnly = false;\n\n\t\tthis._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());\n\t\tthis._applyBaseSystemPrompt();\n\n\t\tthis.sessionManager.appendThinkingLevelChange(this.thinkingLevel);\n\t\tthis._emit({ type: \"todo_update\", todos: this._todos });\n\t\tthis._emit({ type: \"memory_update\", items: this._memoryItems });\n\n\t\t// Run setup callback if provided (e.g., to append initial messages)\n\t\tif (options?.setup) {\n\t\t\tawait options.setup(this.sessionManager);\n\t\t\t// Sync agent state with session manager after setup\n\t\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\t\tthis.agent.replaceMessages(sessionContext.messages);\n\t\t}\n\n\t\tthis._reconnectToAgent();\n\n\t\t// Emit session_switch event with reason \"new\" to extensions\n\t\tif (this._extensionRunner) {\n\t\t\tawait this._extensionRunner.emit({\n\t\t\t\ttype: \"session_switch\",\n\t\t\t\treason: \"new\",\n\t\t\t\tpreviousSessionFile,\n\t\t\t});\n\t\t}\n\n\t\t// Emit session event to custom tools\n\t\treturn true;\n\t}\n\n\t// =========================================================================\n\t// Model Management\n\t// =========================================================================\n\n\tprivate async _emitModelSelect(\n\t\tnextModel: Model<any>,\n\t\tpreviousModel: Model<any> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\",\n\t): Promise<void> {\n\t\tif (!this._extensionRunner) return;\n\t\tif (modelsAreEqual(previousModel, nextModel)) return;\n\t\tawait this._extensionRunner.emit({\n\t\t\ttype: \"model_select\",\n\t\t\tmodel: nextModel,\n\t\t\tpreviousModel,\n\t\t\tsource,\n\t\t});\n\t}\n\n\t/**\n\t * Set model directly.\n\t * Validates API key, saves to session and settings.\n\t * @throws Error if no API key available for the model\n\t */\n\tasync setModel(model: Model<any>): Promise<void> {\n\t\tconst apiKey = await this._modelRegistry.getApiKey(model);\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(`No API key for ${model.provider}/${model.id}`);\n\t\t}\n\n\t\tconst previousModel = this.model;\n\t\tconst thinkingLevel = this._getThinkingLevelForModelSwitch();\n\t\tthis.agent.setModel(model);\n\t\tthis.sessionManager.appendModelChange(model.provider, model.id);\n\t\tthis.settingsManager.setDefaultModelAndProvider(model.provider, model.id);\n\n\t\t// Re-clamp thinking level for new model's capabilities\n\t\tthis.setThinkingLevel(thinkingLevel);\n\n\t\tawait this._emitModelSelect(model, previousModel, \"set\");\n\t}\n\n\t/**\n\t * Cycle to next/previous model.\n\t * Uses scoped models (from --models flag) if available, otherwise all available models.\n\t * @param direction - \"forward\" (default) or \"backward\"\n\t * @returns The new model info, or undefined if only one model available\n\t */\n\tasync cycleModel(direction: \"forward\" | \"backward\" = \"forward\"): Promise<ModelCycleResult | undefined> {\n\t\tif (this._scopedModels.length > 0) {\n\t\t\treturn this._cycleScopedModel(direction);\n\t\t}\n\t\treturn this._cycleAvailableModel(direction);\n\t}\n\n\tprivate async _getScopedModelsWithApiKey(): Promise<Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>> {\n\t\tconst apiKeysByProvider = new Map<string, string | undefined>();\n\t\tconst result: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }> = [];\n\n\t\tfor (const scoped of this._scopedModels) {\n\t\t\tconst provider = scoped.model.provider;\n\t\t\tlet apiKey: string | undefined;\n\t\t\tif (apiKeysByProvider.has(provider)) {\n\t\t\t\tapiKey = apiKeysByProvider.get(provider);\n\t\t\t} else {\n\t\t\t\tapiKey = await this._modelRegistry.getApiKeyForProvider(provider);\n\t\t\t\tapiKeysByProvider.set(provider, apiKey);\n\t\t\t}\n\n\t\t\tif (apiKey) {\n\t\t\t\tresult.push(scoped);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate async _cycleScopedModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\t\tconst scopedModels = await this._getScopedModelsWithApiKey();\n\t\tif (scopedModels.length <= 1) return undefined;\n\n\t\tconst currentModel = this.model;\n\t\tlet currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));\n\n\t\tif (currentIndex === -1) currentIndex = 0;\n\t\tconst len = scopedModels.length;\n\t\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\t\tconst next = scopedModels[nextIndex];\n\t\tconst thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);\n\n\t\t// Apply model\n\t\tthis.agent.setModel(next.model);\n\t\tthis.sessionManager.appendModelChange(next.model.provider, next.model.id);\n\t\tthis.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);\n\n\t\t// Apply thinking level.\n\t\t// - Explicit scoped model thinking level overrides current session level\n\t\t// - Undefined scoped model thinking level inherits the current session preference\n\t\t// setThinkingLevel clamps to model capabilities.\n\t\tthis.setThinkingLevel(thinkingLevel);\n\n\t\tawait this._emitModelSelect(next.model, currentModel, \"cycle\");\n\n\t\treturn { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };\n\t}\n\n\tprivate async _cycleAvailableModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\t\tconst availableModels = await this._modelRegistry.getAvailable();\n\t\tif (availableModels.length <= 1) return undefined;\n\n\t\tconst currentModel = this.model;\n\t\tlet currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));\n\n\t\tif (currentIndex === -1) currentIndex = 0;\n\t\tconst len = availableModels.length;\n\t\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\t\tconst nextModel = availableModels[nextIndex];\n\n\t\tconst apiKey = await this._modelRegistry.getApiKey(nextModel);\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(`No API key for ${nextModel.provider}/${nextModel.id}`);\n\t\t}\n\n\t\tconst thinkingLevel = this._getThinkingLevelForModelSwitch();\n\t\tthis.agent.setModel(nextModel);\n\t\tthis.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\t\tthis.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);\n\n\t\t// Re-clamp thinking level for new model's capabilities\n\t\tthis.setThinkingLevel(thinkingLevel);\n\n\t\tawait this._emitModelSelect(nextModel, currentModel, \"cycle\");\n\n\t\treturn { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };\n\t}\n\n\t// =========================================================================\n\t// Thinking Level Management\n\t// =========================================================================\n\n\t/**\n\t * Set thinking level.\n\t * Clamps to model capabilities based on available thinking levels.\n\t * Saves to session and settings only if the level actually changes.\n\t */\n\tsetThinkingLevel(level: ThinkingLevel): void {\n\t\tconst availableLevels = this.getAvailableThinkingLevels();\n\t\tconst effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);\n\n\t\t// Only persist if actually changing\n\t\tconst isChanging = effectiveLevel !== this.agent.state.thinkingLevel;\n\n\t\tthis.agent.setThinkingLevel(effectiveLevel);\n\n\t\tif (isChanging) {\n\t\t\tthis.sessionManager.appendThinkingLevelChange(effectiveLevel);\n\t\t\tif (this.supportsThinking() || effectiveLevel !== \"off\") {\n\t\t\t\tthis.settingsManager.setDefaultThinkingLevel(effectiveLevel);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Cycle to next thinking level.\n\t * @returns New level, or undefined if model doesn't support thinking\n\t */\n\tcycleThinkingLevel(): ThinkingLevel | undefined {\n\t\tif (!this.supportsThinking()) return undefined;\n\n\t\tconst levels = this.getAvailableThinkingLevels();\n\t\tconst currentIndex = levels.indexOf(this.thinkingLevel);\n\t\tconst nextIndex = (currentIndex + 1) % levels.length;\n\t\tconst nextLevel = levels[nextIndex];\n\n\t\tthis.setThinkingLevel(nextLevel);\n\t\treturn nextLevel;\n\t}\n\n\t/**\n\t * Get available thinking levels for current model.\n\t * The provider will clamp to what the specific model supports internally.\n\t */\n\tgetAvailableThinkingLevels(): ThinkingLevel[] {\n\t\tif (!this.supportsThinking()) return [\"off\"];\n\t\treturn this.supportsXhighThinking() ? THINKING_LEVELS_WITH_XHIGH : THINKING_LEVELS;\n\t}\n\n\t/**\n\t * Check if current model supports xhigh thinking level.\n\t */\n\tsupportsXhighThinking(): boolean {\n\t\treturn this.model ? supportsXhigh(this.model) : false;\n\t}\n\n\t/**\n\t * Check if current model supports thinking/reasoning.\n\t */\n\tsupportsThinking(): boolean {\n\t\treturn !!this.model?.reasoning;\n\t}\n\n\tprivate _getThinkingLevelForModelSwitch(explicitLevel?: ThinkingLevel): ThinkingLevel {\n\t\tif (explicitLevel !== undefined) {\n\t\t\treturn explicitLevel;\n\t\t}\n\t\tif (!this.supportsThinking()) {\n\t\t\treturn this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t\t}\n\t\treturn this.thinkingLevel;\n\t}\n\n\tprivate _clampThinkingLevel(level: ThinkingLevel, availableLevels: ThinkingLevel[]): ThinkingLevel {\n\t\tconst ordered = THINKING_LEVELS_WITH_XHIGH;\n\t\tconst available = new Set(availableLevels);\n\t\tconst requestedIndex = ordered.indexOf(level);\n\t\tif (requestedIndex === -1) {\n\t\t\treturn availableLevels[0] ?? \"off\";\n\t\t}\n\t\tfor (let i = requestedIndex; i < ordered.length; i++) {\n\t\t\tconst candidate = ordered[i];\n\t\t\tif (available.has(candidate)) return candidate;\n\t\t}\n\t\tfor (let i = requestedIndex - 1; i >= 0; i--) {\n\t\t\tconst candidate = ordered[i];\n\t\t\tif (available.has(candidate)) return candidate;\n\t\t}\n\t\treturn availableLevels[0] ?? \"off\";\n\t}\n\n\t// =========================================================================\n\t// Queue Mode Management\n\t// =========================================================================\n\n\t/**\n\t * Set steering message mode.\n\t * Saves to settings.\n\t */\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void {\n\t\tthis.agent.setSteeringMode(mode);\n\t\tthis.settingsManager.setSteeringMode(mode);\n\t}\n\n\t/**\n\t * Set follow-up message mode.\n\t * Saves to settings.\n\t */\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void {\n\t\tthis.agent.setFollowUpMode(mode);\n\t\tthis.settingsManager.setFollowUpMode(mode);\n\t}\n\n\t// =========================================================================\n\t// Compaction\n\t// =========================================================================\n\n\t/**\n\t * Manually compact the session context.\n\t * Aborts current agent operation first.\n\t * @param customInstructions Optional instructions for the compaction summary\n\t */\n\tasync compact(customInstructions?: string): Promise<CompactionResult> {\n\t\tthis._disconnectFromAgent();\n\t\tawait this.abort();\n\t\tthis._compactionAbortController = new AbortController();\n\n\t\ttry {\n\t\t\tif (!this.model) {\n\t\t\t\tthrow new Error(\"No model selected\");\n\t\t\t}\n\n\t\t\tconst apiKey = await this._modelRegistry.getApiKey(this.model);\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(`No API key for ${this.model.provider}`);\n\t\t\t}\n\n\t\t\tconst pathEntries = this.sessionManager.getBranch();\n\t\t\tconst settings = this.settingsManager.getCompactionSettings();\n\n\t\t\tconst preparation = prepareCompaction(pathEntries, settings);\n\t\t\tif (!preparation) {\n\t\t\t\t// Check why we can't compact\n\t\t\t\tconst lastEntry = pathEntries[pathEntries.length - 1];\n\t\t\t\tif (lastEntry?.type === \"compaction\") {\n\t\t\t\t\tthrow new Error(\"Already compacted\");\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Nothing to compact (session too small)\");\n\t\t\t}\n\n\t\t\tlet extensionCompaction: CompactionResult | undefined;\n\t\t\tlet fromExtension = false;\n\n\t\t\tif (this._extensionRunner?.hasHandlers(\"session_before_compact\")) {\n\t\t\t\tconst result = (await this._extensionRunner.emit({\n\t\t\t\t\ttype: \"session_before_compact\",\n\t\t\t\t\tpreparation,\n\t\t\t\t\tbranchEntries: pathEntries,\n\t\t\t\t\tcustomInstructions,\n\t\t\t\t\tsignal: this._compactionAbortController.signal,\n\t\t\t\t})) as SessionBeforeCompactResult | undefined;\n\n\t\t\t\tif (result?.cancel) {\n\t\t\t\t\tthrow new Error(\"Compaction cancelled\");\n\t\t\t\t}\n\n\t\t\t\tif (result?.compaction) {\n\t\t\t\t\textensionCompaction = result.compaction;\n\t\t\t\t\tfromExtension = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet summary: string;\n\t\t\tlet firstKeptEntryId: string;\n\t\t\tlet tokensBefore: number;\n\t\t\tlet details: unknown;\n\n\t\t\tif (extensionCompaction) {\n\t\t\t\t// Extension provided compaction content\n\t\t\t\tsummary = extensionCompaction.summary;\n\t\t\t\tfirstKeptEntryId = extensionCompaction.firstKeptEntryId;\n\t\t\t\ttokensBefore = extensionCompaction.tokensBefore;\n\t\t\t\tdetails = extensionCompaction.details;\n\t\t\t} else {\n\t\t\t\t// Generate compaction result\n\t\t\t\tconst result = await compact(\n\t\t\t\t\tpreparation,\n\t\t\t\t\tthis.model,\n\t\t\t\t\tapiKey,\n\t\t\t\t\tcustomInstructions,\n\t\t\t\t\tthis._compactionAbortController.signal,\n\t\t\t\t);\n\t\t\t\tsummary = result.summary;\n\t\t\t\tfirstKeptEntryId = result.firstKeptEntryId;\n\t\t\t\ttokensBefore = result.tokensBefore;\n\t\t\t\tdetails = result.details;\n\t\t\t}\n\n\t\t\tif (this._compactionAbortController.signal.aborted) {\n\t\t\t\tthrow new Error(\"Compaction cancelled\");\n\t\t\t}\n\t\t\tdetails = createDeterministicCompactionDetails(preparation, details);\n\n\t\t\tconst { result } = await this._finalizeCompaction({\n\t\t\t\tsummary,\n\t\t\t\tfirstKeptEntryId,\n\t\t\t\ttokensBefore,\n\t\t\t\tdetails,\n\t\t\t\tfromExtension,\n\t\t\t});\n\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tthis._compactionAbortController = undefined;\n\t\t\tthis._reconnectToAgent();\n\t\t}\n\t}\n\n\t/**\n\t * Cancel in-progress compaction (manual or auto).\n\t */\n\tabortCompaction(): void {\n\t\tthis._compactionAbortController?.abort();\n\t\tthis._autoCompactionAbortController?.abort();\n\t}\n\n\t/**\n\t * Cancel in-progress branch summarization.\n\t */\n\tabortBranchSummary(): void {\n\t\tthis._branchSummaryAbortController?.abort();\n\t}\n\n\t/**\n\t * Check if compaction is needed and run it.\n\t * Called after agent_end and before prompt submission.\n\t *\n\t * Two cases:\n\t * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry\n\t * 2. Threshold: Context over threshold, compact, NO auto-retry (user continues manually)\n\t *\n\t * @param assistantMessage The assistant message to check\n\t * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true\n\t */\n\tprivate async _checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {\n\t\tconst settings = this.settingsManager.getCompactionSettings();\n\t\tif (!settings.enabled) return;\n\n\t\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\t\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\t\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t\t// Skip overflow check if the message came from a different model.\n\t\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t\t// shouldn't trigger compaction for the new model.\n\t\tconst sameModel =\n\t\t\tthis.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\n\n\t\t// Skip compaction checks if this assistant message is older than the latest\n\t\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t\t// from retriggering compaction on the first prompt after compaction.\n\t\tconst compactionEntry = getLatestCompactionEntry(this.sessionManager.getBranch());\n\t\tconst assistantIsFromBeforeCompaction =\n\t\t\tcompactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();\n\t\tif (assistantIsFromBeforeCompaction) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Case 1: Overflow - LLM returned context overflow error\n\t\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\t\tif (this._overflowRecoveryCount >= MAX_OVERFLOW_RECOVERY_ATTEMPTS) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"auto_compaction_end\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t`Context overflow recovery failed after ${MAX_OVERFLOW_RECOVERY_ATTEMPTS} verified compact-and-retry attempts. ` +\n\t\t\t\t\t\t\"The working set still exceeds the provider's effective context. Reduce tools, shrink the system prompt, or configure a larger context window.\",\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Wire the provider disagreement into the Context Governor's adaptive\n\t\t\t// safety: the next preflight govern applies a stricter budget and a\n\t\t\t// deterministic forced reduction, so the retry is genuinely smaller.\n\t\t\tconst governor = this._contextGovernor;\n\t\t\tconst diagnostics = governor?.lastDiagnostics;\n\t\t\tif (governor) {\n\t\t\t\tgovernor.recordOverflow({\n\t\t\t\t\tconfiguredContextWindow: contextWindow,\n\t\t\t\t\testimatedInputTokens:\n\t\t\t\t\t\tdiagnostics?.inputTokensAfter ?? estimateContextTokens(this.agent.state.messages).tokens,\n\t\t\t\t\treservedOutputTokens: diagnostics?.capability.reservedOutputTokens ?? 0,\n\t\t\t\t\tsafetyReserveTokens: diagnostics?.capability.safetyReserveTokens ?? 0,\n\t\t\t\t\taccountingMode: governor.getTokenAccountingMode(),\n\t\t\t\t\tproviderError: assistantMessage.errorMessage,\n\t\t\t\t\tobservedInputTokens:\n\t\t\t\t\t\tassistantMessage.usage && assistantMessage.usage.input + assistantMessage.usage.cacheRead > 0\n\t\t\t\t\t\t\t? assistantMessage.usage.input + assistantMessage.usage.cacheRead\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\tobservedContextWindow: contextWindow,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis._overflowRecoveryCount += 1;\n\t\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t\t// but we don't want it in context for the retry)\n\t\t\tconst messages = this.agent.state.messages;\n\t\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\t\tthis.agent.replaceMessages(messages.slice(0, -1));\n\t\t\t}\n\t\t\tawait this._runAutoCompaction(\"overflow\", true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Case 2: Threshold - context is getting large\n\t\t// For error messages (no usage data), estimate from last successful response.\n\t\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\t\tlet contextTokens: number;\n\t\tif (assistantMessage.stopReason === \"error\") {\n\t\t\tconst messages = this.agent.state.messages;\n\t\t\tconst estimate = estimateContextTokens(messages);\n\t\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t\t// trigger compaction right after one just finished.\n\t\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionEntry &&\n\t\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcontextTokens = estimate.tokens;\n\t\t} else {\n\t\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t\t}\n\t\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\t\tawait this._runAutoCompaction(\"threshold\", false);\n\t\t}\n\t}\n\n\t/**\n\t * Internal: Run auto-compaction with events.\n\t */\n\tprivate async _runAutoCompaction(reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void> {\n\t\tconst settings = this.settingsManager.getCompactionSettings();\n\n\t\tthis._emit({ type: \"auto_compaction_start\", reason });\n\t\tthis._autoCompactionAbortController = new AbortController();\n\n\t\ttry {\n\t\t\tif (!this.model) {\n\t\t\t\tthis._emit({ type: \"auto_compaction_end\", result: undefined, aborted: false, willRetry: false });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst apiKey = await this._modelRegistry.getApiKey(this.model);\n\t\t\tif (!apiKey) {\n\t\t\t\tthis._emit({ type: \"auto_compaction_end\", result: undefined, aborted: false, willRetry: false });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst pathEntries = this.sessionManager.getBranch();\n\n\t\t\tconst preparation = prepareCompaction(pathEntries, settings);\n\t\t\tif (!preparation) {\n\t\t\t\tthis._emit({ type: \"auto_compaction_end\", result: undefined, aborted: false, willRetry: false });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet extensionCompaction: CompactionResult | undefined;\n\t\t\tlet fromExtension = false;\n\n\t\t\tif (this._extensionRunner?.hasHandlers(\"session_before_compact\")) {\n\t\t\t\tconst extensionResult = (await this._extensionRunner.emit({\n\t\t\t\t\ttype: \"session_before_compact\",\n\t\t\t\t\tpreparation,\n\t\t\t\t\tbranchEntries: pathEntries,\n\t\t\t\t\tcustomInstructions: undefined,\n\t\t\t\t\tsignal: this._autoCompactionAbortController.signal,\n\t\t\t\t})) as SessionBeforeCompactResult | undefined;\n\n\t\t\t\tif (extensionResult?.cancel) {\n\t\t\t\t\tthis._emit({ type: \"auto_compaction_end\", result: undefined, aborted: true, willRetry: false });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (extensionResult?.compaction) {\n\t\t\t\t\textensionCompaction = extensionResult.compaction;\n\t\t\t\t\tfromExtension = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet summary: string;\n\t\t\tlet firstKeptEntryId: string;\n\t\t\tlet tokensBefore: number;\n\t\t\tlet details: unknown;\n\n\t\t\tif (extensionCompaction) {\n\t\t\t\t// Extension provided compaction content\n\t\t\t\tsummary = extensionCompaction.summary;\n\t\t\t\tfirstKeptEntryId = extensionCompaction.firstKeptEntryId;\n\t\t\t\ttokensBefore = extensionCompaction.tokensBefore;\n\t\t\t\tdetails = extensionCompaction.details;\n\t\t\t} else {\n\t\t\t\t// Generate compaction result\n\t\t\t\tconst compactResult = await compact(\n\t\t\t\t\tpreparation,\n\t\t\t\t\tthis.model,\n\t\t\t\t\tapiKey,\n\t\t\t\t\tundefined,\n\t\t\t\t\tthis._autoCompactionAbortController.signal,\n\t\t\t\t);\n\t\t\t\tsummary = compactResult.summary;\n\t\t\t\tfirstKeptEntryId = compactResult.firstKeptEntryId;\n\t\t\t\ttokensBefore = compactResult.tokensBefore;\n\t\t\t\tdetails = compactResult.details;\n\t\t\t}\n\n\t\t\tif (this._autoCompactionAbortController.signal.aborted) {\n\t\t\t\tthis._emit({ type: \"auto_compaction_end\", result: undefined, aborted: true, willRetry: false });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdetails = createDeterministicCompactionDetails(preparation, details);\n\n\t\t\tconst { result } = await this._finalizeCompaction({\n\t\t\t\tsummary,\n\t\t\t\tfirstKeptEntryId,\n\t\t\t\ttokensBefore,\n\t\t\t\tdetails,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t\tthis._emit({ type: \"auto_compaction_end\", result, aborted: false, willRetry });\n\n\t\t\tif (willRetry) {\n\t\t\t\tconst messages = this.agent.state.messages;\n\t\t\t\tconst lastMsg = messages[messages.length - 1];\n\t\t\t\tif (lastMsg?.role === \"assistant\" && (lastMsg as AssistantMessage).stopReason === \"error\") {\n\t\t\t\t\tthis.agent.replaceMessages(messages.slice(0, -1));\n\t\t\t\t}\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.agent.continue().catch(() => {});\n\t\t\t\t}, 100);\n\t\t\t} else if (this.agent.hasQueuedMessages()) {\n\t\t\t\t// Auto-compaction can complete while follow-up/steering/custom messages are waiting.\n\t\t\t\t// Kick the loop so queued messages are actually delivered.\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.agent.continue().catch(() => {});\n\t\t\t\t}, 100);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_compaction_end\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\terrorMessage:\n\t\t\t\t\treason === \"overflow\"\n\t\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t\t});\n\t\t} finally {\n\t\t\tthis._autoCompactionAbortController = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Toggle auto-compaction setting.\n\t */\n\tsetAutoCompactionEnabled(enabled: boolean): void {\n\t\tthis.settingsManager.setCompactionEnabled(enabled);\n\t}\n\n\t/** Whether auto-compaction is enabled */\n\tget autoCompactionEnabled(): boolean {\n\t\treturn this.settingsManager.getCompactionEnabled();\n\t}\n\n\tasync bindExtensions(bindings: ExtensionBindings): Promise<void> {\n\t\tif (bindings.uiContext !== undefined) {\n\t\t\tthis._extensionUIContext = bindings.uiContext;\n\t\t}\n\t\tif (bindings.commandContextActions !== undefined) {\n\t\t\tthis._extensionCommandContextActions = bindings.commandContextActions;\n\t\t}\n\t\tif (bindings.shutdownHandler !== undefined) {\n\t\t\tthis._extensionShutdownHandler = bindings.shutdownHandler;\n\t\t}\n\t\tif (bindings.onError !== undefined) {\n\t\t\tthis._extensionErrorListener = bindings.onError;\n\t\t}\n\n\t\tif (this._extensionRunner) {\n\t\t\tthis._applyExtensionBindings(this._extensionRunner);\n\t\t\tawait this._extensionRunner.emit({ type: \"session_start\" });\n\t\t\tawait this.extendResourcesFromExtensions(\"startup\");\n\t\t}\n\t}\n\n\tprivate async extendResourcesFromExtensions(reason: \"startup\" | \"reload\"): Promise<void> {\n\t\tif (!this._extensionRunner?.hasHandlers(\"resources_discover\")) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(\n\t\t\tthis._cwd,\n\t\t\treason,\n\t\t);\n\n\t\tif (skillPaths.length === 0 && promptPaths.length === 0 && themePaths.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst extensionPaths: ResourceExtensionPaths = {\n\t\t\tskillPaths: this.buildExtensionResourcePaths(skillPaths),\n\t\t\tpromptPaths: this.buildExtensionResourcePaths(promptPaths),\n\t\t\tthemePaths: this.buildExtensionResourcePaths(themePaths),\n\t\t};\n\n\t\tthis._resourceLoader.extendResources(extensionPaths);\n\t\tthis._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());\n\t\tthis._applyBaseSystemPrompt();\n\t}\n\n\tprivate buildExtensionResourcePaths(entries: Array<{ path: string; extensionPath: string }>): Array<{\n\t\tpath: string;\n\t\tmetadata: { source: string; scope: \"temporary\"; origin: \"top-level\"; baseDir?: string };\n\t}> {\n\t\treturn entries.map((entry) => {\n\t\t\tconst source = this.getExtensionSourceLabel(entry.extensionPath);\n\t\t\tconst baseDir = entry.extensionPath.startsWith(\"<\") ? undefined : dirname(entry.extensionPath);\n\t\t\treturn {\n\t\t\t\tpath: entry.path,\n\t\t\t\tmetadata: {\n\t\t\t\t\tsource,\n\t\t\t\t\tscope: \"temporary\",\n\t\t\t\t\torigin: \"top-level\",\n\t\t\t\t\tbaseDir,\n\t\t\t\t},\n\t\t\t};\n\t\t});\n\t}\n\n\tprivate getExtensionSourceLabel(extensionPath: string): string {\n\t\tif (extensionPath.startsWith(\"<\")) {\n\t\t\treturn `extension:${extensionPath.replace(/[<>]/g, \"\")}`;\n\t\t}\n\t\tconst base = basename(extensionPath);\n\t\tconst name = base.replace(/\\.(ts|js)$/, \"\");\n\t\treturn `extension:${name}`;\n\t}\n\n\tprivate _applyExtensionBindings(runner: ExtensionRunner): void {\n\t\trunner.setUIContext(this._extensionUIContext);\n\t\trunner.bindCommandContext(this._extensionCommandContextActions);\n\n\t\tthis._extensionErrorUnsubscriber?.();\n\t\tthis._extensionErrorUnsubscriber = this._extensionErrorListener\n\t\t\t? runner.onError(this._extensionErrorListener)\n\t\t\t: undefined;\n\t}\n\n\tprivate _refreshCurrentModelFromRegistry(): void {\n\t\tconst currentModel = this.model;\n\t\tif (!currentModel) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst refreshedModel = this._modelRegistry.find(currentModel.provider, currentModel.id);\n\t\tif (!refreshedModel || refreshedModel === currentModel) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.agent.setModel(refreshedModel);\n\t}\n\n\tprivate _bindExtensionCore(runner: ExtensionRunner): void {\n\t\tconst normalizeLocation = (source: string): SlashCommandLocation | undefined => {\n\t\t\tif (source === \"user\" || source === \"project\" || source === \"path\") {\n\t\t\t\treturn source;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t};\n\n\t\tconst reservedBuiltins = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name));\n\n\t\tconst getCommands = (): SlashCommandInfo[] => {\n\t\t\tconst extensionCommands: SlashCommandInfo[] = runner\n\t\t\t\t.getRegisteredCommandsWithPaths()\n\t\t\t\t.filter(({ command }) => !reservedBuiltins.has(command.name))\n\t\t\t\t.map(({ command, extensionPath }) => ({\n\t\t\t\t\tname: command.name,\n\t\t\t\t\tdescription: command.description,\n\t\t\t\t\tsource: \"extension\",\n\t\t\t\t\tpath: extensionPath,\n\t\t\t\t}));\n\n\t\t\tconst templates: SlashCommandInfo[] = this.promptTemplates.map((template) => ({\n\t\t\t\tname: template.name,\n\t\t\t\tdescription: template.description,\n\t\t\t\tsource: \"prompt\",\n\t\t\t\tlocation: normalizeLocation(template.source),\n\t\t\t\tpath: template.filePath,\n\t\t\t}));\n\n\t\t\tconst skills: SlashCommandInfo[] = this._resourceLoader.getSkills().skills.map((skill) => ({\n\t\t\t\tname: `skill:${skill.name}`,\n\t\t\t\tdescription: skill.description,\n\t\t\t\tsource: \"skill\",\n\t\t\t\tlocation: normalizeLocation(skill.source),\n\t\t\t\tpath: skill.filePath,\n\t\t\t}));\n\n\t\t\treturn [...extensionCommands, ...templates, ...skills];\n\t\t};\n\n\t\trunner.bindCore(\n\t\t\t{\n\t\t\t\tsendMessage: (message, options) => {\n\t\t\t\t\tthis.sendCustomMessage(message, options).catch((err) => {\n\t\t\t\t\t\trunner.emitError({\n\t\t\t\t\t\t\textensionPath: \"<runtime>\",\n\t\t\t\t\t\t\tevent: \"send_message\",\n\t\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tsendUserMessage: (content, options) => {\n\t\t\t\t\tthis.sendUserMessage(content, options).catch((err) => {\n\t\t\t\t\t\trunner.emitError({\n\t\t\t\t\t\t\textensionPath: \"<runtime>\",\n\t\t\t\t\t\t\tevent: \"send_user_message\",\n\t\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tappendEntry: (customType, data) => {\n\t\t\t\t\tthis.sessionManager.appendCustomEntry(customType, data);\n\t\t\t\t},\n\t\t\t\tsetSessionName: (name) => {\n\t\t\t\t\tthis.sessionManager.appendSessionInfo(name);\n\t\t\t\t},\n\t\t\t\tgetSessionName: () => {\n\t\t\t\t\treturn this.sessionManager.getSessionName();\n\t\t\t\t},\n\t\t\t\tsetLabel: (entryId, label) => {\n\t\t\t\t\tthis.sessionManager.appendLabelChange(entryId, label);\n\t\t\t\t},\n\t\t\t\tgetActiveTools: () => this.getActiveToolNames(),\n\t\t\t\tgetAllTools: () => this.getAllTools(),\n\t\t\t\tsetActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),\n\t\t\t\trefreshTools: () => this._refreshToolRegistry(),\n\t\t\t\tgetCommands,\n\t\t\t\tsetModel: async (model) => {\n\t\t\t\t\tconst key = await this.modelRegistry.getApiKey(model);\n\t\t\t\t\tif (!key) return false;\n\t\t\t\t\tawait this.setModel(model);\n\t\t\t\t\treturn true;\n\t\t\t\t},\n\t\t\t\tgetThinkingLevel: () => this.thinkingLevel,\n\t\t\t\tsetThinkingLevel: (level) => this.setThinkingLevel(level),\n\t\t\t},\n\t\t\t{\n\t\t\t\tgetModel: () => this.model,\n\t\t\t\tisIdle: () => !this.isStreaming,\n\t\t\t\tabort: () => this.abort(),\n\t\t\t\thasPendingMessages: () => this.pendingMessageCount > 0,\n\t\t\t\tshutdown: () => {\n\t\t\t\t\tthis._extensionShutdownHandler?.();\n\t\t\t\t},\n\t\t\t\tgetContextUsage: () => this.getContextUsage(),\n\t\t\t\tcompact: (options) => {\n\t\t\t\t\tvoid (async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await this.compact(options?.customInstructions);\n\t\t\t\t\t\t\toptions?.onComplete?.(result);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\t\t\toptions?.onError?.(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t\tgetSystemPrompt: () => this.systemPrompt,\n\t\t\t\tgetActiveMissionId: () => this.missionId,\n\t\t\t},\n\t\t\t{\n\t\t\t\tregisterProvider: (name, config) => {\n\t\t\t\t\tthis._modelRegistry.registerProvider(name, config);\n\t\t\t\t\tthis._refreshCurrentModelFromRegistry();\n\t\t\t\t},\n\t\t\t\tunregisterProvider: (name) => {\n\t\t\t\t\tthis._modelRegistry.unregisterProvider(name);\n\t\t\t\t\tthis._refreshCurrentModelFromRegistry();\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\n\tprivate _refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void {\n\t\tconst previousRegistryNames = new Set(this._toolRegistry.keys());\n\t\tconst previousActiveToolNames = this.getActiveToolNames();\n\n\t\tconst registeredTools = this._extensionRunner?.getAllRegisteredTools() ?? [];\n\t\tconst allCustomTools = [\n\t\t\t...registeredTools,\n\t\t\t...this._customTools.map((def) => ({ definition: def, extensionPath: \"<sdk>\" })),\n\t\t];\n\t\tthis._toolPromptSnippets = new Map(\n\t\t\tallCustomTools\n\t\t\t\t.map((registeredTool) => {\n\t\t\t\t\tconst snippet = this._normalizePromptSnippet(registeredTool.definition.promptSnippet);\n\t\t\t\t\treturn snippet ? ([registeredTool.definition.name, snippet] as const) : undefined;\n\t\t\t\t})\n\t\t\t\t.filter((entry): entry is readonly [string, string] => entry !== undefined),\n\t\t);\n\t\tthis._toolPromptGuidelines = new Map(\n\t\t\tallCustomTools\n\t\t\t\t.map((registeredTool) => {\n\t\t\t\t\tconst guidelines = this._normalizePromptGuidelines(registeredTool.definition.promptGuidelines);\n\t\t\t\t\treturn guidelines.length > 0 ? ([registeredTool.definition.name, guidelines] as const) : undefined;\n\t\t\t\t})\n\t\t\t\t.filter((entry): entry is readonly [string, string[]] => entry !== undefined),\n\t\t);\n\t\tconst wrappedExtensionTools = this._extensionRunner\n\t\t\t? wrapRegisteredTools(allCustomTools, this._extensionRunner)\n\t\t\t: [];\n\n\t\tconst toolRegistry = new Map(this._baseToolRegistry);\n\t\tfor (const tool of wrappedExtensionTools as AgentTool[]) {\n\t\t\ttoolRegistry.set(tool.name, tool);\n\t\t}\n\t\tthis._toolRegistry = toolRegistry;\n\n\t\tconst nextActiveToolNames = options?.activeToolNames\n\t\t\t? [...options.activeToolNames]\n\t\t\t: [...previousActiveToolNames];\n\n\t\tif (options?.includeAllExtensionTools) {\n\t\t\tfor (const tool of wrappedExtensionTools) {\n\t\t\t\tnextActiveToolNames.push(tool.name);\n\t\t\t}\n\t\t} else if (!options?.activeToolNames) {\n\t\t\tfor (const toolName of this._toolRegistry.keys()) {\n\t\t\t\tif (!previousRegistryNames.has(toolName)) {\n\t\t\t\t\tnextActiveToolNames.push(toolName);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.setActiveToolsByName([...new Set(nextActiveToolNames)]);\n\t}\n\n\tprivate _buildRuntime(options: {\n\t\tactiveToolNames?: string[];\n\t\tflagValues?: Map<string, boolean | string>;\n\t\tincludeAllExtensionTools?: boolean;\n\t}): void {\n\t\tconst autoResizeImages = this.settingsManager.getImageAutoResize();\n\t\tconst shellCommandPrefix = this.settingsManager.getShellCommandPrefix();\n\t\tconst baseTools = this._baseToolsOverride\n\t\t\t? this._baseToolsOverride\n\t\t\t: createAllTools(this._cwd, {\n\t\t\t\t\tread: { autoResizeImages },\n\t\t\t\t\tbash: { commandPrefix: shellCommandPrefix },\n\t\t\t\t});\n\n\t\tthis._baseToolRegistry = new Map(Object.entries(baseTools).map(([name, tool]) => [name, tool as AgentTool]));\n\n\t\t// Create todo_write, todo_read, and todo_update tools with session callbacks\n\t\tconst todoWriteTool = createTodoWriteTool(\n\t\t\t() => this._todos,\n\t\t\t(todos) => this._setTodos(todos),\n\t\t\tthis._todoLoopGuard,\n\t\t\t() => this._todoRevision,\n\t\t\tthis._todoPerTurnLock,\n\t\t);\n\t\tconst todoReadTool = createTodoReadTool(\n\t\t\t() => this._todos,\n\t\t\t() => this._todoRevision,\n\t\t\t{\n\t\t\t\tonRead: () => {\n\t\t\t\t\tthis._todoReadSnapshot = {\n\t\t\t\t\t\trevision: this._todoRevision,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t};\n\t\t\t\t\tthis._todoUpdateRejectionState.count = 0;\n\t\t\t\t},\n\t\t\t},\n\t\t\tthis._todoEngine,\n\t\t);\n\t\tconst todoUpdateTool = createTodoUpdateTool(\n\t\t\t() => this._todos,\n\t\t\t(todos) => this._setTodos(todos),\n\t\t\t() => this._todoRevision,\n\t\t\tthis._todoLoopGuard,\n\t\t\t{\n\t\t\t\tgetSnapshot: () => this._todoReadSnapshot,\n\t\t\t\tinvalidateSnapshot: () => {\n\t\t\t\t\tthis._todoReadSnapshot = null;\n\t\t\t\t},\n\t\t\t},\n\t\t\tthis._todoUpdateRejectionState,\n\t\t\tthis._todoEngine,\n\t\t);\n\t\tthis._baseToolRegistry.set(\"todo_write\", todoWriteTool as unknown as AgentTool);\n\t\tthis._baseToolRegistry.set(\"todo_read\", todoReadTool as unknown as AgentTool);\n\t\tthis._baseToolRegistry.set(\"todo_update\", todoUpdateTool as unknown as AgentTool);\n\n\t\tconst memoryWriteTool = createMemoryWriteTool({\n\t\t\tset: (key, value) => this.setMemoryItem(key, value),\n\t\t\tclear: () => this.clearMemory(),\n\t\t});\n\t\tthis._baseToolRegistry.set(\"memory_write\", memoryWriteTool as unknown as AgentTool);\n\n\t\t// Model-facing evidence rehydration (2.5.0 extension). Retrieves bounded,\n\t\t// integrity-verified pages of cold evidence by id. Read-only; does not\n\t\t// move completion authority. Registered only when a session archive is\n\t\t// provided (the SDK always provides one for governed sessions).\n\t\tif (this._evidenceArchive) {\n\t\t\tconst retrieveEvidenceTool = createRetrieveEvidenceTool(this._evidenceArchive);\n\t\t\tthis._baseToolRegistry.set(\"retrieve_evidence\", retrieveEvidenceTool as unknown as AgentTool);\n\t\t}\n\n\t\t// Create task tools with session callbacks\n\t\tconst taskCreateTool = createTaskCreateTool(\n\t\t\t() => this._tasks,\n\t\t\t(tasks) => this._setTasks(tasks),\n\t\t);\n\t\tconst taskListTool = createTaskListTool(\n\t\t\t() => this._tasks,\n\t\t\t(tasks) => this._setTasks(tasks),\n\t\t);\n\t\tconst taskGetTool = createTaskGetTool(\n\t\t\t() => this._tasks,\n\t\t\t(tasks) => this._setTasks(tasks),\n\t\t);\n\t\tconst taskUpdateTool = createTaskUpdateTool(\n\t\t\t() => this._tasks,\n\t\t\t(tasks) => this._setTasks(tasks),\n\t\t);\n\t\tthis._baseToolRegistry.set(\"task_create\", taskCreateTool as unknown as AgentTool);\n\t\tthis._baseToolRegistry.set(\"task_list\", taskListTool as unknown as AgentTool);\n\t\tthis._baseToolRegistry.set(\"task_get\", taskGetTool as unknown as AgentTool);\n\t\tthis._baseToolRegistry.set(\"task_update\", taskUpdateTool as unknown as AgentTool);\n\n\t\tconst extensionsResult = this._resourceLoader.getExtensions();\n\t\tif (options.flagValues) {\n\t\t\tfor (const [name, value] of options.flagValues) {\n\t\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\t}\n\t\t}\n\n\t\tconst hasExtensions = extensionsResult.extensions.length > 0;\n\t\tconst hasCustomTools = this._customTools.length > 0;\n\t\tthis._extensionRunner =\n\t\t\thasExtensions || hasCustomTools\n\t\t\t\t? new ExtensionRunner(\n\t\t\t\t\t\textensionsResult.extensions,\n\t\t\t\t\t\textensionsResult.runtime,\n\t\t\t\t\t\tthis._cwd,\n\t\t\t\t\t\tthis.sessionManager,\n\t\t\t\t\t\tthis._modelRegistry,\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\tif (this._extensionRunnerRef) {\n\t\t\tthis._extensionRunnerRef.current = this._extensionRunner;\n\t\t}\n\t\tif (this._extensionRunner) {\n\t\t\tthis._bindExtensionCore(this._extensionRunner);\n\t\t\tthis._applyExtensionBindings(this._extensionRunner);\n\t\t}\n\n\t\tconst defaultActiveToolNames = this._baseToolsOverride\n\t\t\t? Object.keys(this._baseToolsOverride)\n\t\t\t: [\n\t\t\t\t\t\"read\",\n\t\t\t\t\t\"bash\",\n\t\t\t\t\t\"edit\",\n\t\t\t\t\t\"write\",\n\t\t\t\t\t\"todo_write\",\n\t\t\t\t\t\"todo_read\",\n\t\t\t\t\t\"todo_update\",\n\t\t\t\t\t\"memory_write\",\n\t\t\t\t\t\"retrieve_evidence\",\n\t\t\t\t\t\"web_search\",\n\t\t\t\t\t\"web_fetch\",\n\t\t\t\t\t\"deep_research\",\n\t\t\t\t\t\"web_research_status\",\n\t\t\t\t];\n\t\tconst baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;\n\t\tthis._refreshToolRegistry({\n\t\t\tactiveToolNames: baseActiveToolNames,\n\t\t\tincludeAllExtensionTools: options.includeAllExtensionTools,\n\t\t});\n\t}\n\n\tasync reload(): Promise<void> {\n\t\tconst previousFlagValues = this._extensionRunner?.getFlagValues();\n\t\tawait this._extensionRunner?.emit({ type: \"session_shutdown\" });\n\t\tthis.settingsManager.reload();\n\t\tresetApiProviders();\n\t\tawait this._resourceLoader.reload();\n\t\tthis._buildRuntime({\n\t\t\tactiveToolNames: this.getActiveToolNames(),\n\t\t\tflagValues: previousFlagValues,\n\t\t\tincludeAllExtensionTools: true,\n\t\t});\n\n\t\tconst hasBindings =\n\t\t\tthis._extensionUIContext ||\n\t\t\tthis._extensionCommandContextActions ||\n\t\t\tthis._extensionShutdownHandler ||\n\t\t\tthis._extensionErrorListener;\n\t\tif (this._extensionRunner && hasBindings) {\n\t\t\tawait this._extensionRunner.emit({ type: \"session_start\" });\n\t\t\tawait this.extendResourcesFromExtensions(\"reload\");\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Auto-Retry\n\t// =========================================================================\n\n\t/**\n\t * Check if an error is retryable (overloaded, rate limit, server errors).\n\t * Context overflow errors are NOT retryable (handled by compaction instead).\n\t * Transcript structure errors are NOT retryable (same payload would fail again).\n\t */\n\tprivate _isRetryableError(message: AssistantMessage): boolean {\n\t\tif (message.stopReason !== \"error\" || !message.errorMessage) return false;\n\n\t\t// Context overflow is handled by compaction, not retry\n\t\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t\tif (isContextOverflow(message, contextWindow)) return false;\n\n\t\tconst err = message.errorMessage;\n\n\t\t// Non-retryable transcript errors: deterministic failures from invalid tool call/result structure\n\t\t// These fail with 400 and the same payload would produce the same error again\n\t\tif (\n\t\t\t/INVALID_TOOL_TRANSCRIPT/i.test(err) ||\n\t\t\t/must be followed by tool messages/i.test(err) ||\n\t\t\t/invalid_request_error/i.test(err) ||\n\t\t\t/Invalid parameter/i.test(err)\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Match: overloaded_error, provider returned error, rate limit, 429, 500, 502, 503, 504, service unavailable, network/connection errors, fetch failed, terminated, retry delay exceeded\n\t\treturn /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|timed? out|timeout|terminated|retry delay/i.test(\n\t\t\terr,\n\t\t);\n\t}\n\n\t/**\n\t * Handle retryable errors with exponential backoff.\n\t * @returns true if retry was initiated, false if max retries exceeded or disabled\n\t */\n\tprivate async _handleRetryableError(message: AssistantMessage): Promise<boolean> {\n\t\tconst settings = this.settingsManager.getRetrySettings();\n\t\tif (!settings.enabled) {\n\t\t\tthis._resolveRetry();\n\t\t\treturn false;\n\t\t}\n\n\t\t// Retry promise is created synchronously in _handleAgentEvent for agent_end.\n\t\t// Keep a defensive fallback here in case a future refactor bypasses that path.\n\t\tif (!this._retryPromise) {\n\t\t\tthis._retryPromise = new Promise((resolve) => {\n\t\t\t\tthis._retryResolve = resolve;\n\t\t\t});\n\t\t}\n\n\t\tthis._retryAttempt++;\n\n\t\tif (this._retryAttempt > settings.maxRetries) {\n\t\t\t// Try fallback before completely failing\n\t\t\tif (this._fallbackModels.length > 0 && this._fallbackIndex < this._fallbackModels.length - 1) {\n\t\t\t\tconst didFallback = await this._handleFallback(message, message.errorMessage || \"Max retries exceeded\");\n\t\t\t\tif (didFallback) {\n\t\t\t\t\tthis._resolveRetry(); // Resolve so waitForRetry() completes\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Max retries exceeded, emit final failure and reset\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: false,\n\t\t\t\tattempt: this._retryAttempt - 1,\n\t\t\t\tfinalError: message.errorMessage,\n\t\t\t});\n\t\t\tthis._retryAttempt = 0;\n\t\t\tthis._resolveRetry(); // Resolve so waitForRetry() completes\n\t\t\treturn false;\n\t\t}\n\n\t\tconst delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);\n\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_start\",\n\t\t\tattempt: this._retryAttempt,\n\t\t\tmaxAttempts: settings.maxRetries,\n\t\t\tdelayMs,\n\t\t\terrorMessage: message.errorMessage || \"Unknown error\",\n\t\t});\n\n\t\t// Remove error message from agent state (keep in session for history)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.replaceMessages(messages.slice(0, -1));\n\t\t}\n\n\t\t// Wait with exponential backoff (abortable)\n\t\tthis._retryAbortController = new AbortController();\n\t\ttry {\n\t\t\tawait sleep(delayMs, this._retryAbortController.signal);\n\t\t} catch {\n\t\t\t// Aborted during sleep - emit end event so UI can clean up\n\t\t\tconst attempt = this._retryAttempt;\n\t\t\tthis._retryAttempt = 0;\n\t\t\tthis._retryAbortController = undefined;\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: false,\n\t\t\t\tattempt,\n\t\t\t\tfinalError: \"Retry cancelled\",\n\t\t\t});\n\t\t\tthis._resolveRetry();\n\t\t\treturn false;\n\t\t}\n\t\tthis._retryAbortController = undefined;\n\n\t\t// Retry via continue() - use setTimeout to break out of event handler chain\n\t\tsetTimeout(() => {\n\t\t\tthis.agent.continue().catch(() => {\n\t\t\t\t// Retry failed - will be caught by next agent_end\n\t\t\t});\n\t\t}, 0);\n\n\t\treturn true;\n\t}\n\n\tprivate async _handleFallback(message: AssistantMessage, reason: string): Promise<boolean> {\n\t\tif (this._fallbackIndex >= this._fallbackModels.length - 1) {\n\t\t\treturn false; // Exhausted\n\t\t}\n\n\t\tthis._fallbackIndex++;\n\t\tconst fallbackModel = this._fallbackModels[this._fallbackIndex];\n\n\t\t// Ensure api key exists for fallback\n\t\tconst apiKey = await this._modelRegistry.getApiKey(fallbackModel);\n\t\tif (!apiKey) {\n\t\t\t// API key missing, try next fallback immediately recursively\n\t\t\treturn this._handleFallback(message, `${reason} (Skipped ${fallbackModel.id}: missing API key)`);\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"auto_fallback\",\n\t\t\tmodel: this.model!,\n\t\t\tfallbackModel: fallbackModel,\n\t\t\treason,\n\t\t});\n\n\t\t// Switch model\n\t\tawait this.setModel(fallbackModel);\n\n\t\t// Remove error message from agent state (keep in session for history)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.replaceMessages(messages.slice(0, -1));\n\t\t}\n\n\t\t// We reset the retry attempt for the new model\n\t\tthis._retryAttempt = 0;\n\n\t\t// Restart via continue()\n\t\tsetTimeout(() => {\n\t\t\tthis.agent.continue().catch(() => {});\n\t\t}, 0);\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Cancel in-progress retry.\n\t */\n\tabortRetry(): void {\n\t\tthis._retryAbortController?.abort();\n\t\t// Note: _retryAttempt is reset in the catch block of _autoRetry\n\t\tthis._resolveRetry();\n\t}\n\n\t/**\n\t * Wait for any in-progress retry to complete.\n\t * Returns immediately if no retry is in progress.\n\t */\n\tprivate async waitForRetry(): Promise<void> {\n\t\tif (this._retryPromise) {\n\t\t\tawait this._retryPromise;\n\t\t}\n\t}\n\n\t/** Whether auto-retry is currently in progress */\n\tget isRetrying(): boolean {\n\t\treturn this._retryPromise !== undefined;\n\t}\n\n\t/** Whether auto-retry is enabled */\n\tget autoRetryEnabled(): boolean {\n\t\treturn this.settingsManager.getRetryEnabled();\n\t}\n\n\t/**\n\t * Toggle auto-retry setting.\n\t */\n\tsetAutoRetryEnabled(enabled: boolean): void {\n\t\tthis.settingsManager.setRetryEnabled(enabled);\n\t}\n\n\t// =========================================================================\n\t// Bash Execution\n\t// =========================================================================\n\n\t/**\n\t * Execute a bash command.\n\t * Adds result to agent context and session.\n\t * @param command The bash command to execute\n\t * @param onChunk Optional streaming callback for output\n\t * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)\n\t * @param options.operations Custom BashOperations for remote execution\n\t */\n\tasync executeBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string) => void,\n\t\toptions?: { excludeFromContext?: boolean; operations?: BashOperations },\n\t): Promise<BashResult> {\n\t\tthis._bashAbortController = new AbortController();\n\n\t\t// Apply command prefix if configured (e.g., \"shopt -s expand_aliases\" for alias support)\n\t\tconst prefix = this.settingsManager.getShellCommandPrefix();\n\t\tconst resolvedCommand = prefix ? `${prefix}\\n${command}` : command;\n\n\t\ttry {\n\t\t\tconst result = options?.operations\n\t\t\t\t? await executeBashWithOperations(resolvedCommand, process.cwd(), options.operations, {\n\t\t\t\t\t\tonChunk,\n\t\t\t\t\t\tsignal: this._bashAbortController.signal,\n\t\t\t\t\t})\n\t\t\t\t: await executeBashCommand(resolvedCommand, {\n\t\t\t\t\t\tonChunk,\n\t\t\t\t\t\tsignal: this._bashAbortController.signal,\n\t\t\t\t\t});\n\n\t\t\tthis.recordBashResult(command, result, options);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tthis._bashAbortController = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Record a bash execution result in session history.\n\t * Used by executeBash and by extensions that handle bash execution themselves.\n\t */\n\trecordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {\n\t\tconst bashMessage: BashExecutionMessage = {\n\t\t\trole: \"bashExecution\",\n\t\t\tcommand,\n\t\t\toutput: result.output,\n\t\t\texitCode: result.exitCode,\n\t\t\tcancelled: result.cancelled,\n\t\t\ttruncated: result.truncated,\n\t\t\tfullOutputPath: result.fullOutputPath,\n\t\t\ttimestamp: Date.now(),\n\t\t\texcludeFromContext: options?.excludeFromContext,\n\t\t};\n\n\t\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\t\tif (this.isStreaming) {\n\t\t\t// Queue for later - will be flushed on agent_end\n\t\t\tthis._pendingBashMessages.push(bashMessage);\n\t\t} else {\n\t\t\t// Add to agent state immediately\n\t\t\tthis.agent.appendMessage(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.sessionManager.appendMessage(bashMessage);\n\t\t}\n\t}\n\n\t/**\n\t * Cancel running bash command.\n\t */\n\tabortBash(): void {\n\t\tthis._bashAbortController?.abort();\n\t}\n\n\t/** Whether a bash command is currently running */\n\tget isBashRunning(): boolean {\n\t\treturn this._bashAbortController !== undefined;\n\t}\n\n\t/** Whether there are pending bash messages waiting to be flushed */\n\tget hasPendingBashMessages(): boolean {\n\t\treturn this._pendingBashMessages.length > 0;\n\t}\n\n\t/**\n\t * Flush pending bash messages to agent state and session.\n\t * Called after agent turn completes to maintain proper message ordering.\n\t */\n\tprivate _flushPendingBashMessages(): void {\n\t\tif (this._pendingBashMessages.length === 0) return;\n\n\t\tfor (const bashMessage of this._pendingBashMessages) {\n\t\t\t// Add to agent state\n\t\t\tthis.agent.appendMessage(bashMessage);\n\n\t\t\t// Save to session\n\t\t\tthis.sessionManager.appendMessage(bashMessage);\n\t\t}\n\n\t\tthis._pendingBashMessages = [];\n\t}\n\n\t// =========================================================================\n\t// Session Management\n\t// =========================================================================\n\n\t/**\n\t * Switch to a different session file.\n\t * Aborts current operation, loads messages, restores model/thinking.\n\t * Listeners are preserved and will continue receiving events.\n\t * @returns true if switch completed, false if cancelled by extension\n\t */\n\tasync switchSession(sessionPath: string): Promise<boolean> {\n\t\tconst previousSessionFile = this.sessionManager.getSessionFile();\n\n\t\t// Emit session_before_switch event (can be cancelled)\n\t\tif (this._extensionRunner?.hasHandlers(\"session_before_switch\")) {\n\t\t\tconst result = (await this._extensionRunner.emit({\n\t\t\t\ttype: \"session_before_switch\",\n\t\t\t\treason: \"resume\",\n\t\t\t\ttargetSessionFile: sessionPath,\n\t\t\t})) as SessionBeforeSwitchResult | undefined;\n\n\t\t\tif (result?.cancel) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tthis._disconnectFromAgent();\n\t\tawait this.abort();\n\t\tthis._steeringMessages = [];\n\t\tthis._followUpMessages = [];\n\t\tthis._pendingNextTurnMessages = [];\n\t\tthis._cavemanLevel = \"off\";\n\t\tthis._briefOnly = false;\n\n\t\t// Set new session\n\t\tthis.sessionManager.setSessionFile(sessionPath);\n\t\tthis.agent.sessionId = this.sessionManager.getSessionId();\n\n\t\t// Reload messages\n\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\tthis._todos = sessionContext.todos as TodoItem[];\n\t\tthis._resetTodoEngine();\n\t\tthis._todoRevision = this._todoEngine.getCurrentRevision();\n\t\tthis._todoReadSnapshot = null;\n\t\tthis._todoUpdateRejectionState.count = 0;\n\t\tthis._todoPerTurnLock.currentTurn = 0;\n\t\tthis._todoPerTurnLock.lockedUntil = -1;\n\t\tthis._todoPerTurnLock.reservedUntil = -1;\n\t\tthis._memoryItems = sessionContext.memoryItems;\n\t\tthis._delegatedTasks = [];\n\t\tthis._tasks = this.sessionManager.getLatestSessionTasks();\n\n\t\t// Rebuild system prompt after caveman/brief reset\n\t\tthis._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());\n\t\tthis._emit({ type: \"todo_update\", todos: this._todos });\n\t\tthis._emit({ type: \"memory_update\", items: this._memoryItems });\n\t\tthis._emit({ type: \"task_update\", tasks: this._tasks });\n\n\t\t// Emit session_switch event to extensions\n\t\tif (this._extensionRunner) {\n\t\t\tawait this._extensionRunner.emit({\n\t\t\t\ttype: \"session_switch\",\n\t\t\t\treason: \"resume\",\n\t\t\t\tpreviousSessionFile,\n\t\t\t});\n\t\t}\n\n\t\t// Emit session event to custom tools\n\n\t\tthis.agent.replaceMessages(sessionContext.messages);\n\n\t\t// Apply rebuilt system prompt after message restoration\n\t\tthis._applyBaseSystemPrompt();\n\n\t\t// Restore model if saved\n\t\tif (sessionContext.model) {\n\t\t\tconst previousModel = this.model;\n\t\t\tconst availableModels = await this._modelRegistry.getAvailable();\n\t\t\tconst match = availableModels.find(\n\t\t\t\t(m) => m.provider === sessionContext.model!.provider && m.id === sessionContext.model!.modelId,\n\t\t\t);\n\t\t\tif (match) {\n\t\t\t\tthis.agent.setModel(match);\n\t\t\t\tawait this._emitModelSelect(match, previousModel, \"restore\");\n\t\t\t}\n\t\t}\n\n\t\tconst hasThinkingEntry = this.sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\t\tconst defaultThinkingLevel = this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\n\t\tif (hasThinkingEntry) {\n\t\t\t// Restore thinking level if saved (setThinkingLevel clamps to model capabilities)\n\t\t\tthis.setThinkingLevel(sessionContext.thinkingLevel as ThinkingLevel);\n\t\t} else {\n\t\t\tconst availableLevels = this.getAvailableThinkingLevels();\n\t\t\tconst effectiveLevel = availableLevels.includes(defaultThinkingLevel)\n\t\t\t\t? defaultThinkingLevel\n\t\t\t\t: this._clampThinkingLevel(defaultThinkingLevel, availableLevels);\n\t\t\tthis.agent.setThinkingLevel(effectiveLevel);\n\t\t\tthis.sessionManager.appendThinkingLevelChange(effectiveLevel);\n\t\t}\n\n\t\tthis._reconnectToAgent();\n\t\treturn true;\n\t}\n\n\t/**\n\t * Set a display name for the current session.\n\t */\n\tsetSessionName(name: string): void {\n\t\tthis.sessionManager.appendSessionInfo(name);\n\t}\n\n\t/**\n\t * Create a fork from a specific entry.\n\t * Emits before_fork/fork session events to extensions.\n\t *\n\t * @param entryId ID of the entry to fork from\n\t * @returns Object with:\n\t *   - selectedText: The text of the selected user message (for editor pre-fill)\n\t *   - cancelled: True if an extension cancelled the fork\n\t */\n\tasync fork(entryId: string): Promise<{ selectedText: string; cancelled: boolean }> {\n\t\tconst previousSessionFile = this.sessionFile;\n\t\tconst selectedEntry = this.sessionManager.getEntry(entryId);\n\n\t\tif (!selectedEntry || selectedEntry.type !== \"message\" || selectedEntry.message.role !== \"user\") {\n\t\t\tthrow new Error(\"Invalid entry ID for forking\");\n\t\t}\n\n\t\tconst selectedText = this._extractUserMessageText(selectedEntry.message.content);\n\n\t\tlet skipConversationRestore = false;\n\n\t\t// Emit session_before_fork event (can be cancelled)\n\t\tif (this._extensionRunner?.hasHandlers(\"session_before_fork\")) {\n\t\t\tconst result = (await this._extensionRunner.emit({\n\t\t\t\ttype: \"session_before_fork\",\n\t\t\t\tentryId,\n\t\t\t})) as SessionBeforeForkResult | undefined;\n\n\t\t\tif (result?.cancel) {\n\t\t\t\treturn { selectedText, cancelled: true };\n\t\t\t}\n\t\t\tskipConversationRestore = result?.skipConversationRestore ?? false;\n\t\t}\n\n\t\t// Clear pending messages (bound to old session state)\n\t\tthis._pendingNextTurnMessages = [];\n\t\tthis._cavemanLevel = \"off\";\n\t\tthis._briefOnly = false;\n\n\t\tif (!selectedEntry.parentId) {\n\t\t\tthis.sessionManager.newSession({ parentSession: previousSessionFile });\n\t\t} else {\n\t\t\tthis.sessionManager.createBranchedSession(selectedEntry.parentId);\n\t\t}\n\t\tthis.agent.sessionId = this.sessionManager.getSessionId();\n\n\t\t// Reload messages from entries (works for both file and in-memory mode)\n\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\n\t\t// Rebuild system prompt after caveman/brief reset\n\t\tthis._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());\n\n\t\t// Emit session_fork event to extensions (after fork completes)\n\t\tif (this._extensionRunner) {\n\t\t\tawait this._extensionRunner.emit({\n\t\t\t\ttype: \"session_fork\",\n\t\t\t\tpreviousSessionFile,\n\t\t\t});\n\t\t}\n\n\t\t// Emit session event to custom tools (with reason \"fork\")\n\n\t\tif (!skipConversationRestore) {\n\t\t\tthis.agent.replaceMessages(sessionContext.messages);\n\t\t\tthis._applyBaseSystemPrompt();\n\t\t}\n\n\t\treturn { selectedText, cancelled: false };\n\t}\n\n\t// =========================================================================\n\t// Tree Navigation\n\t// =========================================================================\n\n\t/**\n\t * Navigate to a different node in the session tree.\n\t * Unlike fork() which creates a new session file, this stays in the same file.\n\t *\n\t * @param targetId The entry ID to navigate to\n\t * @param options.summarize Whether user wants to summarize abandoned branch\n\t * @param options.customInstructions Custom instructions for summarizer\n\t * @param options.replaceInstructions If true, customInstructions replaces the default prompt\n\t * @param options.label Label to attach to the branch summary entry\n\t * @returns Result with editorText (if user message) and cancelled status\n\t */\n\tasync navigateTree(\n\t\ttargetId: string,\n\t\toptions: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string } = {},\n\t): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {\n\t\tconst oldLeafId = this.sessionManager.getLeafId();\n\n\t\t// No-op if already at target\n\t\tif (targetId === oldLeafId) {\n\t\t\treturn { cancelled: false };\n\t\t}\n\n\t\t// Model required for summarization\n\t\tif (options.summarize && !this.model) {\n\t\t\tthrow new Error(\"No model available for summarization\");\n\t\t}\n\n\t\tconst targetEntry = this.sessionManager.getEntry(targetId);\n\t\tif (!targetEntry) {\n\t\t\tthrow new Error(`Entry ${targetId} not found`);\n\t\t}\n\n\t\t// Collect entries to summarize (from old leaf to common ancestor)\n\t\tconst { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(\n\t\t\tthis.sessionManager,\n\t\t\toldLeafId,\n\t\t\ttargetId,\n\t\t);\n\n\t\t// Prepare event data - mutable so extensions can override\n\t\tlet customInstructions = options.customInstructions;\n\t\tlet replaceInstructions = options.replaceInstructions;\n\t\tlet label = options.label;\n\n\t\tconst preparation: TreePreparation = {\n\t\t\ttargetId,\n\t\t\toldLeafId,\n\t\t\tcommonAncestorId,\n\t\t\tentriesToSummarize,\n\t\t\tuserWantsSummary: options.summarize ?? false,\n\t\t\tcustomInstructions,\n\t\t\treplaceInstructions,\n\t\t\tlabel,\n\t\t};\n\n\t\t// Set up abort controller for summarization\n\t\tthis._branchSummaryAbortController = new AbortController();\n\t\tlet extensionSummary: { summary: string; details?: unknown } | undefined;\n\t\tlet fromExtension = false;\n\n\t\t// Emit session_before_tree event\n\t\tif (this._extensionRunner?.hasHandlers(\"session_before_tree\")) {\n\t\t\tconst result = (await this._extensionRunner.emit({\n\t\t\t\ttype: \"session_before_tree\",\n\t\t\t\tpreparation,\n\t\t\t\tsignal: this._branchSummaryAbortController.signal,\n\t\t\t})) as SessionBeforeTreeResult | undefined;\n\n\t\t\tif (result?.cancel) {\n\t\t\t\treturn { cancelled: true };\n\t\t\t}\n\n\t\t\tif (result?.summary && options.summarize) {\n\t\t\t\textensionSummary = result.summary;\n\t\t\t\tfromExtension = true;\n\t\t\t}\n\n\t\t\t// Allow extensions to override instructions and label\n\t\t\tif (result?.customInstructions !== undefined) {\n\t\t\t\tcustomInstructions = result.customInstructions;\n\t\t\t}\n\t\t\tif (result?.replaceInstructions !== undefined) {\n\t\t\t\treplaceInstructions = result.replaceInstructions;\n\t\t\t}\n\t\t\tif (result?.label !== undefined) {\n\t\t\t\tlabel = result.label;\n\t\t\t}\n\t\t}\n\n\t\t// Run default summarizer if needed\n\t\tlet summaryText: string | undefined;\n\t\tlet summaryDetails: unknown;\n\t\tif (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {\n\t\t\tconst model = this.model!;\n\t\t\tconst apiKey = await this._modelRegistry.getApiKey(model);\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(`No API key for ${model.provider}`);\n\t\t\t}\n\t\t\tconst branchSummarySettings = this.settingsManager.getBranchSummarySettings();\n\t\t\tconst result = await generateBranchSummary(entriesToSummarize, {\n\t\t\t\tmodel,\n\t\t\t\tapiKey,\n\t\t\t\tsignal: this._branchSummaryAbortController.signal,\n\t\t\t\tcustomInstructions,\n\t\t\t\treplaceInstructions,\n\t\t\t\treserveTokens: branchSummarySettings.reserveTokens,\n\t\t\t});\n\t\t\tthis._branchSummaryAbortController = undefined;\n\t\t\tif (result.aborted) {\n\t\t\t\treturn { cancelled: true, aborted: true };\n\t\t\t}\n\t\t\tif (result.error) {\n\t\t\t\tthrow new Error(result.error);\n\t\t\t}\n\t\t\tsummaryText = result.summary;\n\t\t\tsummaryDetails = {\n\t\t\t\treadFiles: result.readFiles || [],\n\t\t\t\tmodifiedFiles: result.modifiedFiles || [],\n\t\t\t};\n\t\t} else if (extensionSummary) {\n\t\t\tsummaryText = extensionSummary.summary;\n\t\t\tsummaryDetails = extensionSummary.details;\n\t\t}\n\n\t\t// Determine the new leaf position based on target type\n\t\tlet newLeafId: string | null;\n\t\tlet editorText: string | undefined;\n\n\t\tif (targetEntry.type === \"message\" && targetEntry.message.role === \"user\") {\n\t\t\t// User message: leaf = parent (null if root), text goes to editor\n\t\t\tnewLeafId = targetEntry.parentId;\n\t\t\teditorText = this._extractUserMessageText(targetEntry.message.content);\n\t\t} else if (targetEntry.type === \"custom_message\") {\n\t\t\t// Custom message: leaf = parent (null if root), text goes to editor\n\t\t\tnewLeafId = targetEntry.parentId;\n\t\t\teditorText =\n\t\t\t\ttypeof targetEntry.content === \"string\"\n\t\t\t\t\t? targetEntry.content\n\t\t\t\t\t: targetEntry.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t} else {\n\t\t\t// Non-user message: leaf = selected node\n\t\t\tnewLeafId = targetId;\n\t\t}\n\n\t\t// Switch leaf (with or without summary)\n\t\t// Summary is attached at the navigation target position (newLeafId), not the old branch\n\t\tlet summaryEntry: BranchSummaryEntry | undefined;\n\t\tif (summaryText) {\n\t\t\t// Create summary at target position (can be null for root)\n\t\t\tconst summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);\n\t\t\tsummaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;\n\n\t\t\t// Attach label to the summary entry\n\t\t\tif (label) {\n\t\t\t\tthis.sessionManager.appendLabelChange(summaryId, label);\n\t\t\t}\n\t\t} else if (newLeafId === null) {\n\t\t\t// No summary, navigating to root - reset leaf\n\t\t\tthis.sessionManager.resetLeaf();\n\t\t} else {\n\t\t\t// No summary, navigating to non-root\n\t\t\tthis.sessionManager.branch(newLeafId);\n\t\t}\n\n\t\t// Attach label to target entry when not summarizing (no summary entry to label)\n\t\tif (label && !summaryText) {\n\t\t\tthis.sessionManager.appendLabelChange(targetId, label);\n\t\t}\n\n\t\t// Update agent state\n\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\tthis.agent.replaceMessages(sessionContext.messages);\n\n\t\t// Emit session_tree event\n\t\tif (this._extensionRunner) {\n\t\t\tawait this._extensionRunner.emit({\n\t\t\t\ttype: \"session_tree\",\n\t\t\t\tnewLeafId: this.sessionManager.getLeafId(),\n\t\t\t\toldLeafId,\n\t\t\t\tsummaryEntry,\n\t\t\t\tfromExtension: summaryText ? fromExtension : undefined,\n\t\t\t});\n\t\t}\n\n\t\t// Emit to custom tools\n\n\t\tthis._branchSummaryAbortController = undefined;\n\t\treturn { editorText, cancelled: false, summaryEntry };\n\t}\n\n\t/**\n\t * Get all user messages from session for fork selector.\n\t */\n\tgetUserMessagesForForking(): Array<{ entryId: string; text: string }> {\n\t\tconst entries = this.sessionManager.getEntries();\n\t\tconst result: Array<{ entryId: string; text: string }> = [];\n\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.type !== \"message\") continue;\n\t\t\tif (entry.message.role !== \"user\") continue;\n\n\t\t\tconst text = this._extractUserMessageText(entry.message.content);\n\t\t\tif (text) {\n\t\t\t\tresult.push({ entryId: entry.id, text });\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate _extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {\n\t\tif (typeof content === \"string\") return content;\n\t\tif (Array.isArray(content)) {\n\t\t\treturn content\n\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t}\n\t\treturn \"\";\n\t}\n\n\t/**\n\t * Get session statistics.\n\t */\n\tgetSessionStats(): SessionStats {\n\t\tconst state = this.state;\n\t\tconst userMessages = state.messages.filter((m) => m.role === \"user\").length;\n\t\tconst assistantMessages = state.messages.filter((m) => m.role === \"assistant\").length;\n\t\tconst toolResults = state.messages.filter((m) => m.role === \"toolResult\").length;\n\n\t\tlet toolCalls = 0;\n\t\tlet totalInput = 0;\n\t\tlet totalOutput = 0;\n\t\tlet totalCacheRead = 0;\n\t\tlet totalCacheWrite = 0;\n\t\tlet totalCost = 0;\n\n\t\tfor (const message of state.messages) {\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\ttoolCalls += assistantMsg.content.filter((c) => c.type === \"toolCall\").length;\n\t\t\t\ttotalInput += assistantMsg.usage.input;\n\t\t\t\ttotalOutput += assistantMsg.usage.output;\n\t\t\t\ttotalCacheRead += assistantMsg.usage.cacheRead;\n\t\t\t\ttotalCacheWrite += assistantMsg.usage.cacheWrite;\n\t\t\t\ttotalCost += assistantMsg.usage.cost.total;\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tsessionFile: this.sessionFile,\n\t\t\tsessionId: this.sessionId,\n\t\t\tuserMessages,\n\t\t\tassistantMessages,\n\t\t\ttoolCalls,\n\t\t\ttoolResults,\n\t\t\ttotalMessages: state.messages.length,\n\t\t\ttokens: {\n\t\t\t\tinput: totalInput,\n\t\t\t\toutput: totalOutput,\n\t\t\t\tcacheRead: totalCacheRead,\n\t\t\t\tcacheWrite: totalCacheWrite,\n\t\t\t\ttotal: totalInput + totalOutput + totalCacheRead + totalCacheWrite,\n\t\t\t},\n\t\t\tcost: totalCost,\n\t\t\tcontextCache: state.contextCache,\n\t\t};\n\t}\n\n\tgetContextUsage(): ContextUsage | undefined {\n\t\tconst model = this.model;\n\t\tif (!model) return undefined;\n\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return undefined;\n\n\t\t// After compaction, the last assistant usage reflects pre-compaction context size.\n\t\t// We can only trust usage from an assistant that responded after the latest compaction.\n\t\t// If no such assistant exists, context token count is unknown until the next LLM response.\n\t\tconst branchEntries = this.sessionManager.getBranch();\n\t\tconst latestCompaction = getLatestCompactionEntry(branchEntries);\n\n\t\tif (latestCompaction) {\n\t\t\t// Check if there's a valid assistant usage after the compaction boundary\n\t\t\tconst compactionIndex = branchEntries.lastIndexOf(latestCompaction);\n\t\t\tlet hasPostCompactionUsage = false;\n\t\t\tfor (let i = branchEntries.length - 1; i > compactionIndex; i--) {\n\t\t\t\tconst entry = branchEntries[i];\n\t\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\tconst assistant = entry.message;\n\t\t\t\t\tif (assistant.stopReason !== \"aborted\" && assistant.stopReason !== \"error\") {\n\t\t\t\t\t\tconst contextTokens = calculateContextTokens(assistant.usage);\n\t\t\t\t\t\tif (contextTokens > 0) {\n\t\t\t\t\t\t\thasPostCompactionUsage = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!hasPostCompactionUsage) {\n\t\t\t\treturn { tokens: null, contextWindow, percent: null };\n\t\t\t}\n\t\t}\n\n\t\tconst estimate = estimateContextTokens(this.messages);\n\t\tconst percent = (estimate.tokens / contextWindow) * 100;\n\n\t\treturn {\n\t\t\ttokens: estimate.tokens,\n\t\t\tcontextWindow,\n\t\t\tpercent,\n\t\t};\n\t}\n\n\t/**\n\t * Export session to HTML.\n\t * @param outputPath Optional output path (defaults to session directory)\n\t * @returns Path to exported file\n\t */\n\tasync exportToHtml(outputPath?: string): Promise<string> {\n\t\tconst themeName = this.settingsManager.getTheme();\n\n\t\t// Create tool renderer if we have an extension runner (for custom tool HTML rendering)\n\t\tlet toolRenderer: ToolHtmlRenderer | undefined;\n\t\tif (this._extensionRunner) {\n\t\t\ttoolRenderer = createToolHtmlRenderer({\n\t\t\t\tgetToolDefinition: (name) => this._extensionRunner!.getToolDefinition(name),\n\t\t\t\ttheme,\n\t\t\t});\n\t\t}\n\n\t\treturn await exportSessionToHtml(this.sessionManager, this.state, {\n\t\t\toutputPath,\n\t\t\tthemeName,\n\t\t\ttoolRenderer,\n\t\t});\n\t}\n\n\t// =========================================================================\n\t// Utilities\n\t// =========================================================================\n\n\t/**\n\t * Get text content of last assistant message.\n\t * Useful for /copy command.\n\t * @returns Text content, or undefined if no assistant message exists\n\t */\n\tgetLastAssistantText(): string | undefined {\n\t\tconst lastAssistant = this.messages\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.find((m) => {\n\t\t\t\tif (m.role !== \"assistant\") return false;\n\t\t\t\tconst msg = m as AssistantMessage;\n\t\t\t\t// Skip aborted messages with no content\n\t\t\t\tif (msg.stopReason === \"aborted\" && msg.content.length === 0) return false;\n\t\t\t\treturn true;\n\t\t\t});\n\n\t\tif (!lastAssistant) return undefined;\n\n\t\tlet text = \"\";\n\t\tfor (const content of (lastAssistant as AssistantMessage).content) {\n\t\t\tif (content.type === \"text\") {\n\t\t\t\ttext += content.text;\n\t\t\t}\n\t\t}\n\n\t\treturn text.trim() || undefined;\n\t}\n\n\t// =========================================================================\n\t// Extension System\n\t// =========================================================================\n\n\t/**\n\t * Check if extensions have handlers for a specific event type.\n\t */\n\thasExtensionHandlers(eventType: string): boolean {\n\t\treturn this._extensionRunner?.hasHandlers(eventType) ?? false;\n\t}\n\n\t/**\n\t * Get the extension runner (for setting UI context and error handlers).\n\t */\n\tget extensionRunner(): ExtensionRunner | undefined {\n\t\treturn this._extensionRunner;\n\t}\n}\n"]}