@mariozechner/pi-coding-agent 0.32.1 → 0.32.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.32.2] - 2026-01-03
4
+
5
+ ### Added
6
+
7
+ - `$ARGUMENTS` syntax for custom slash commands as alternative to `$@` for all arguments joined. Aligns with patterns used by Claude, Codex, and OpenCode. Both syntaxes remain fully supported. ([#418](https://github.com/badlogic/pi-mono/pull/418) by [@skuridin](https://github.com/skuridin))
8
+
9
+ ### Changed
10
+
11
+ - **Slash commands and hook commands now work during streaming**: Previously, using a slash command or hook command while the agent was streaming would crash with "Agent is already processing". Now:
12
+ - Hook commands execute immediately (they manage their own LLM interaction via `pi.sendMessage()`)
13
+ - File-based slash commands are expanded and queued via steer/followUp
14
+ - `steer()` and `followUp()` now expand file-based slash commands and error on hook commands (hook commands cannot be queued)
15
+ - `prompt()` accepts new `streamingBehavior` option (`"steer"` or `"followUp"`) to specify queueing behavior during streaming
16
+ - RPC `prompt` command now accepts optional `streamingBehavior` field
17
+ ([#420](https://github.com/badlogic/pi-mono/issues/420))
18
+
19
+ ### Fixed
20
+
21
+ - Slash command argument substitution now processes positional arguments (`$1`, `$2`, etc.) before all-arguments (`$@`, `$ARGUMENTS`) to prevent recursive substitution when argument values contain dollar-digit patterns like `$100`. ([#418](https://github.com/badlogic/pi-mono/pull/418) by [@skuridin](https://github.com/skuridin))
22
+
3
23
  ## [0.32.1] - 2026-01-03
4
24
 
5
25
  ### Added
package/README.md CHANGED
@@ -647,7 +647,7 @@ Create a React component named $1 with features: $@
647
647
 
648
648
  Usage: `/component Button "onClick handler" "disabled support"`
649
649
  - `$1` = `Button`
650
- - `$@` = all arguments joined
650
+ - `$@` or `$ARGUMENTS` = all arguments joined (`Button onClick handler disabled support`)
651
651
 
652
652
  **Namespacing:** Subdirectories create prefixes. `.pi/commands/frontend/component.md` → `/component (project:frontend)`
653
653
 
@@ -71,6 +71,8 @@ export interface PromptOptions {
71
71
  expandSlashCommands?: boolean;
72
72
  /** Image attachments */
73
73
  images?: ImageContent[];
74
+ /** When streaming, how to queue the message: "steer" (interrupt) or "followUp" (wait). Required if streaming. */
75
+ streamingBehavior?: "steer" | "followUp";
74
76
  }
75
77
  /** Result from cycleModel() */
76
78
  export interface ModelCycleResult {
@@ -189,23 +191,35 @@ export declare class AgentSession {
189
191
  get fileCommands(): ReadonlyArray<FileSlashCommand>;
190
192
  /**
191
193
  * Send a prompt to the agent.
192
- * - Validates model and API key before sending
193
- * - Handles hook commands (registered via pi.registerCommand)
194
+ * - Handles hook commands (registered via pi.registerCommand) immediately, even during streaming
194
195
  * - Expands file-based slash commands by default
195
- * @throws Error if no model selected or no API key available
196
+ * - During streaming, queues via steer() or followUp() based on streamingBehavior option
197
+ * - Validates model and API key before sending (when not streaming)
198
+ * @throws Error if streaming and no streamingBehavior specified
199
+ * @throws Error if no model selected or no API key available (when not streaming)
196
200
  */
197
201
  prompt(text: string, options?: PromptOptions): Promise<void>;
198
202
  private _tryExecuteHookCommand;
199
203
  /**
200
204
  * Queue a steering message to interrupt the agent mid-run.
201
205
  * Delivered after current tool execution, skips remaining tools.
206
+ * Expands file-based slash commands. Errors on hook commands.
207
+ * @throws Error if text is a hook command
202
208
  */
203
209
  steer(text: string): Promise<void>;
204
210
  /**
205
211
  * Queue a follow-up message to be processed after the agent finishes.
206
212
  * Delivered only when agent has no more tool calls or steering messages.
213
+ * Expands file-based slash commands. Errors on hook commands.
214
+ * @throws Error if text is a hook command
207
215
  */
208
216
  followUp(text: string): Promise<void>;
217
+ private _queueSteer;
218
+ private _queueFollowUp;
219
+ /**
220
+ * Throw an error if the text is a hook command.
221
+ */
222
+ private _throwIfHookCommand;
209
223
  /**
210
224
  * Send a hook message to the session. Creates a CustomMessageEntry.
211
225
  *
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session.d.ts","sourceRoot":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AAE,CAAC,CAqJ5G;IAED;;OAEG;IACH,2BAA2B,IAAI,KAAK,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAetE;IAED,OAAO,CAAC,uBAAuB;IAW/B;;OAEG;IACH,eAAe,IAAI,YAAY,CA0C9B;IAED;;;;OAIG;IACH,YAAY,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,CAGxC;IAMD;;;;OAIG;IACH,oBAAoB,IAAI,MAAM,GAAG,SAAS,CAsBzC;IAMD;;OAEG;IACH,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAE1C;IAED;;OAEG;IACH,IAAI,UAAU,IAAI,UAAU,GAAG,SAAS,CAEvC;IAED;;OAEG;IACH,IAAI,WAAW,IAAI,gBAAgB,EAAE,CAEpC;IAED;;;OAGG;IACG,0BAA0B,CAC/B,MAAM,EAAE,sBAAsB,CAAC,QAAQ,CAAC,EACxC,mBAAmB,CAAC,EAAE,MAAM,GAAG,SAAS,GACtC,OAAO,CAAC,IAAI,CAAC,CAwBf;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 type { Agent, AgentEvent, AgentMessage, AgentState, ThinkingLevel } from \"@mariozechner/pi-agent-core\";\nimport type { AssistantMessage, ImageContent, Message, Model, TextContent } from \"@mariozechner/pi-ai\";\nimport { isContextOverflow, modelsAreEqual, supportsXhigh } from \"@mariozechner/pi-ai\";\nimport { getAuthPath } from \"../config.js\";\nimport { type BashResult, executeBash as executeBashCommand } from \"./bash-executor.js\";\nimport {\n\ttype CompactionResult,\n\tcalculateContextTokens,\n\tcollectEntriesForBranchSummary,\n\tcompact,\n\tgenerateBranchSummary,\n\tprepareCompaction,\n\tshouldCompact,\n} from \"./compaction/index.js\";\nimport type { CustomToolContext, CustomToolSessionEvent, LoadedCustomTool } from \"./custom-tools/index.js\";\nimport { exportSessionToHtml } from \"./export-html/index.js\";\nimport type {\n\tHookRunner,\n\tSessionBeforeBranchResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tTreePreparation,\n\tTurnEndEvent,\n\tTurnStartEvent,\n} from \"./hooks/index.js\";\nimport type { BashExecutionMessage, HookMessage } from \"./messages.js\";\nimport type { ModelRegistry } from \"./model-registry.js\";\nimport type { BranchSummaryEntry, CompactionEntry, NewSessionOptions, SessionManager } from \"./session-manager.js\";\nimport type { SettingsManager, SkillsSettings } from \"./settings-manager.js\";\nimport { expandSlashCommand, type FileSlashCommand } from \"./slash-commands.js\";\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| { type: \"auto_compaction_end\"; result: CompactionResult | undefined; aborted: boolean; willRetry: boolean }\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\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\t/** Models to cycle through with Ctrl+P (from --models flag) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel: ThinkingLevel }>;\n\t/** File-based slash commands for expansion */\n\tfileCommands?: FileSlashCommand[];\n\t/** Hook runner (created in main.ts with wrapped tools) */\n\thookRunner?: HookRunner;\n\t/** Custom tools for session lifecycle events */\n\tcustomTools?: LoadedCustomTool[];\n\tskillsSettings?: Required<SkillsSettings>;\n\t/** Model registry for API key resolution and model discovery */\n\tmodelRegistry: ModelRegistry;\n}\n\n/** Options for AgentSession.prompt() */\nexport interface PromptOptions {\n\t/** Whether to expand file-based slash commands (default: true) */\n\texpandSlashCommands?: boolean;\n\t/** Image attachments */\n\timages?: ImageContent[];\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}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Standard thinking levels */\nconst THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\n/** Thinking levels including xhigh (for supported models) */\nconst THINKING_LEVELS_WITH_XHIGH: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\"];\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 _fileCommands: FileSlashCommand[];\n\n\t// Event subscription state\n\tprivate _unsubscribeAgent?: () => void;\n\tprivate _eventListeners: AgentSessionEventListener[] = [];\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\n\t// Compaction state\n\tprivate _compactionAbortController: AbortController | undefined = undefined;\n\tprivate _autoCompactionAbortController: AbortController | undefined = undefined;\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// Hook system\n\tprivate _hookRunner: HookRunner | undefined = undefined;\n\tprivate _turnIndex = 0;\n\n\t// Custom tools for session lifecycle\n\tprivate _customTools: LoadedCustomTool[] = [];\n\n\tprivate _skillsSettings: Required<SkillsSettings> | undefined;\n\n\t// Model registry for API key resolution\n\tprivate _modelRegistry: ModelRegistry;\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._fileCommands = config.fileCommands ?? [];\n\t\tthis._hookRunner = config.hookRunner;\n\t\tthis._customTools = config.customTools ?? [];\n\t\tthis._skillsSettings = config.skillsSettings;\n\t\tthis._modelRegistry = config.modelRegistry;\n\n\t\t// Always subscribe to agent events for internal handling\n\t\t// (session persistence, hooks, auto-compaction, retry logic)\n\t\tthis._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);\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// 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 = async (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\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 hooks first\n\t\tawait this._emitHookEvent(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\t// Check if this is a hook message\n\t\t\tif (event.message.role === \"hookMessage\") {\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\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 (this._retryAttempt > 0) {\n\t\t\t\t// Previous retry succeeded - emit success event and reset counter\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\t});\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\t// Resolve the retry promise so waitForRetry() completes\n\t\t\t\tthis._resolveRetry();\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 hook events based on agent events */\n\tprivate async _emitHookEvent(event: AgentEvent): Promise<void> {\n\t\tif (!this._hookRunner) return;\n\n\t\tif (event.type === \"agent_start\") {\n\t\t\tthis._turnIndex = 0;\n\t\t\tawait this._hookRunner.emit({ type: \"agent_start\" });\n\t\t} else if (event.type === \"agent_end\") {\n\t\t\tawait this._hookRunner.emit({ type: \"agent_end\", messages: event.messages });\n\t\t} else if (event.type === \"turn_start\") {\n\t\t\tconst hookEvent: 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._hookRunner.emit(hookEvent);\n\t\t} else if (event.type === \"turn_end\") {\n\t\t\tconst hookEvent: 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._hookRunner.emit(hookEvent);\n\t\t\tthis._turnIndex++;\n\t\t}\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/** Whether auto-compaction is currently running */\n\tget isCompacting(): boolean {\n\t\treturn this._autoCompactionAbortController !== undefined || this._compactionAbortController !== undefined;\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/** 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/** File-based slash commands */\n\tget fileCommands(): ReadonlyArray<FileSlashCommand> {\n\t\treturn this._fileCommands;\n\t}\n\n\t// =========================================================================\n\t// Prompting\n\t// =========================================================================\n\n\t/**\n\t * Send a prompt to the agent.\n\t * - Validates model and API key before sending\n\t * - Handles hook commands (registered via pi.registerCommand)\n\t * - Expands file-based slash commands by default\n\t * @throws Error if no model selected or no API key available\n\t */\n\tasync prompt(text: string, options?: PromptOptions): Promise<void> {\n\t\tif (this.isStreaming) {\n\t\t\tthrow new Error(\"Agent is already processing. Use steer() or followUp() to queue messages during streaming.\");\n\t\t}\n\n\t\t// Flush any pending bash messages before the new prompt\n\t\tthis._flushPendingBashMessages();\n\n\t\tconst expandCommands = options?.expandSlashCommands ?? true;\n\n\t\t// Handle hook commands first (if enabled and text is a slash command)\n\t\tif (expandCommands && text.startsWith(\"/\")) {\n\t\t\tconst handled = await this._tryExecuteHookCommand(text);\n\t\t\tif (handled) {\n\t\t\t\t// Hook command executed, no prompt to send\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\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, set an API key environment variable, or create ${getAuthPath()}\\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\tconst apiKey = await this._modelRegistry.getApiKey(this.model);\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(\n\t\t\t\t`No API key found for ${this.model.provider}.\\n\\n` +\n\t\t\t\t\t`Use /login, set an API key environment variable, or create ${getAuthPath()}`,\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// Expand file-based slash commands if requested\n\t\tconst expandedText = expandCommands ? expandSlashCommand(text, [...this._fileCommands]) : text;\n\n\t\t// Build messages array (hook 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 (options?.images) {\n\t\t\tuserContent.push(...options.images);\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// Emit before_agent_start hook event\n\t\tif (this._hookRunner) {\n\t\t\tconst result = await this._hookRunner.emitBeforeAgentStart(expandedText, options?.images);\n\t\t\tif (result?.message) {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"hookMessage\",\n\t\t\t\t\tcustomType: result.message.customType,\n\t\t\t\t\tcontent: result.message.content,\n\t\t\t\t\tdisplay: result.message.display,\n\t\t\t\t\tdetails: result.message.details,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tawait this.agent.prompt(messages);\n\t\tawait this.waitForRetry();\n\t}\n\n\t/**\n\t * Try to execute a hook command. Returns true if command was found and executed.\n\t */\n\tprivate async _tryExecuteHookCommand(text: string): Promise<boolean> {\n\t\tif (!this._hookRunner) 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._hookRunner.getCommand(commandName);\n\t\tif (!command) return false;\n\n\t\t// Get command context from hook runner (includes session control methods)\n\t\tconst ctx = this._hookRunner.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 hook runner\n\t\t\tthis._hookRunner.emitError({\n\t\t\t\thookPath: `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 * Queue a steering message to interrupt the agent mid-run.\n\t * Delivered after current tool execution, skips remaining tools.\n\t */\n\tasync steer(text: string): Promise<void> {\n\t\tthis._steeringMessages.push(text);\n\t\tthis.agent.steer({\n\t\t\trole: \"user\",\n\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\ttimestamp: Date.now(),\n\t\t});\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 */\n\tasync followUp(text: string): Promise<void> {\n\t\tthis._followUpMessages.push(text);\n\t\tthis.agent.followUp({\n\t\t\trole: \"user\",\n\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\t}\n\n\t/**\n\t * Send a hook 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 Hook 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 When streaming, use \"steer\" (default) for immediate or \"followUp\" to wait\n\t */\n\tasync sendHookMessage<T = unknown>(\n\t\tmessage: Pick<HookMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" },\n\t): Promise<void> {\n\t\tconst appMessage = {\n\t\t\trole: \"hookMessage\" 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 HookMessage<T>;\n\t\tif (this.isStreaming) {\n\t\t\t// Queue for processing by agent loop\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\t// Send as prompt - agent loop will emit message events\n\t\t\tawait this.agent.prompt(appMessage);\n\t\t} else {\n\t\t\t// Just append to agent state and session, no turn\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}\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 skillsSettings(): Required<SkillsSettings> | undefined {\n\t\treturn this._skillsSettings;\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 - Optional initial messages and parent session path\n\t * @returns true if completed, false if cancelled by hook\n\t */\n\tasync newSession(options?: NewSessionOptions): 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._hookRunner?.hasHandlers(\"session_before_switch\")) {\n\t\t\tconst result = (await this._hookRunner.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(options);\n\t\tthis._steeringMessages = [];\n\t\tthis._followUpMessages = [];\n\t\tthis._reconnectToAgent();\n\n\t\t// Emit session_switch event with reason \"new\" to hooks\n\t\tif (this._hookRunner) {\n\t\t\tawait this._hookRunner.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\tawait this.emitCustomToolSessionEvent(\"switch\", previousSessionFile);\n\t\treturn true;\n\t}\n\n\t// =========================================================================\n\t// Model Management\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\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(this.thinkingLevel);\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 _cycleScopedModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\t\tif (this._scopedModels.length <= 1) return undefined;\n\n\t\tconst currentModel = this.model;\n\t\tlet currentIndex = this._scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));\n\n\t\tif (currentIndex === -1) currentIndex = 0;\n\t\tconst len = this._scopedModels.length;\n\t\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\t\tconst next = this._scopedModels[nextIndex];\n\n\t\t// Validate API key\n\t\tconst apiKey = await this._modelRegistry.getApiKey(next.model);\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(`No API key for ${next.model.provider}/${next.model.id}`);\n\t\t}\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 (setThinkingLevel clamps to model capabilities)\n\t\tthis.setThinkingLevel(next.thinkingLevel);\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\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(this.thinkingLevel);\n\n\t\treturn { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };\n\t}\n\n\t/**\n\t * Get all available models with valid API keys.\n\t */\n\tasync getAvailableModels(): Promise<Model<any>[]> {\n\t\treturn this._modelRegistry.getAvailable();\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: \"off\" if no reasoning, \"high\" if xhigh unsupported.\n\t * Saves to session and settings.\n\t */\n\tsetThinkingLevel(level: ThinkingLevel): void {\n\t\tlet effectiveLevel = level;\n\t\tif (!this.supportsThinking()) {\n\t\t\teffectiveLevel = \"off\";\n\t\t} else if (level === \"xhigh\" && !this.supportsXhighThinking()) {\n\t\t\teffectiveLevel = \"high\";\n\t\t}\n\t\tthis.agent.setThinkingLevel(effectiveLevel);\n\t\tthis.sessionManager.appendThinkingLevelChange(effectiveLevel);\n\t\tthis.settingsManager.setDefaultThinkingLevel(effectiveLevel);\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 */\n\tgetAvailableThinkingLevels(): ThinkingLevel[] {\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\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 hookCompaction: CompactionResult | undefined;\n\t\t\tlet fromHook = false;\n\n\t\t\tif (this._hookRunner?.hasHandlers(\"session_before_compact\")) {\n\t\t\t\tconst result = (await this._hookRunner.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\thookCompaction = result.compaction;\n\t\t\t\t\tfromHook = 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 (hookCompaction) {\n\t\t\t\t// Hook provided compaction content\n\t\t\t\tsummary = hookCompaction.summary;\n\t\t\t\tfirstKeptEntryId = hookCompaction.firstKeptEntryId;\n\t\t\t\ttokensBefore = hookCompaction.tokensBefore;\n\t\t\t\tdetails = hookCompaction.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\n\t\t\tthis.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook);\n\t\t\tconst newEntries = this.sessionManager.getEntries();\n\t\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\t\tthis.agent.replaceMessages(sessionContext.messages);\n\n\t\t\t// Get the saved compaction entry for the hook\n\t\t\tconst savedCompactionEntry = newEntries.find((e) => e.type === \"compaction\" && e.summary === summary) as\n\t\t\t\t| CompactionEntry\n\t\t\t\t| undefined;\n\n\t\t\tif (this._hookRunner && savedCompactionEntry) {\n\t\t\t\tawait this._hookRunner.emit({\n\t\t\t\t\ttype: \"session_compact\",\n\t\t\t\t\tcompactionEntry: savedCompactionEntry,\n\t\t\t\t\tfromHook,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tsummary,\n\t\t\t\tfirstKeptEntryId,\n\t\t\t\ttokensBefore,\n\t\t\t\tdetails,\n\t\t\t};\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// Case 1: Overflow - LLM returned context overflow error\n\t\tif (isContextOverflow(assistantMessage, contextWindow)) {\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 - turn succeeded but context is getting large\n\t\t// Skip if this was an error (non-overflow errors don't have usage data)\n\t\tif (assistantMessage.stopReason === \"error\") return;\n\n\t\tconst contextTokens = calculateContextTokens(assistantMessage.usage);\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 hookCompaction: CompactionResult | undefined;\n\t\t\tlet fromHook = false;\n\n\t\t\tif (this._hookRunner?.hasHandlers(\"session_before_compact\")) {\n\t\t\t\tconst hookResult = (await this._hookRunner.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 (hookResult?.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 (hookResult?.compaction) {\n\t\t\t\t\thookCompaction = hookResult.compaction;\n\t\t\t\t\tfromHook = 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 (hookCompaction) {\n\t\t\t\t// Hook provided compaction content\n\t\t\t\tsummary = hookCompaction.summary;\n\t\t\t\tfirstKeptEntryId = hookCompaction.firstKeptEntryId;\n\t\t\t\ttokensBefore = hookCompaction.tokensBefore;\n\t\t\t\tdetails = hookCompaction.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\n\t\t\tthis.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook);\n\t\t\tconst newEntries = this.sessionManager.getEntries();\n\t\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\t\tthis.agent.replaceMessages(sessionContext.messages);\n\n\t\t\t// Get the saved compaction entry for the hook\n\t\t\tconst savedCompactionEntry = newEntries.find((e) => e.type === \"compaction\" && e.summary === summary) as\n\t\t\t\t| CompactionEntry\n\t\t\t\t| undefined;\n\n\t\t\tif (this._hookRunner && savedCompactionEntry) {\n\t\t\t\tawait this._hookRunner.emit({\n\t\t\t\t\ttype: \"session_compact\",\n\t\t\t\t\tcompactionEntry: savedCompactionEntry,\n\t\t\t\t\tfromHook,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst result: CompactionResult = {\n\t\t\t\tsummary,\n\t\t\t\tfirstKeptEntryId,\n\t\t\t\ttokensBefore,\n\t\t\t\tdetails,\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}\n\t\t} catch (error) {\n\t\t\tthis._emit({ type: \"auto_compaction_end\", result: undefined, aborted: false, willRetry: false });\n\n\t\t\tif (reason === \"overflow\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Context overflow: ${error instanceof Error ? error.message : \"compaction failed\"}. Your input may be too large for the context window.`,\n\t\t\t\t);\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\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 */\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\t\t// Match: overloaded_error, rate limit, 429, 500, 502, 503, 504, service unavailable, connection error\n\t\treturn /overloaded|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server error|internal error|connection.?error/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) return false;\n\n\t\tthis._retryAttempt++;\n\n\t\t// Create retry promise on first attempt so waitForRetry() can await it\n\t\tif (this._retryAttempt === 1 && !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\tif (this._retryAttempt > settings.maxRetries) {\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 this._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\t/**\n\t * Sleep helper that respects abort signal.\n\t */\n\tprivate _sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (signal?.aborted) {\n\t\t\t\treject(new Error(\"Aborted\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst timeout = setTimeout(resolve, ms);\n\n\t\t\tsignal?.addEventListener(\"abort\", () => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new Error(\"Aborted\"));\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Cancel in-progress retry.\n\t */\n\tabortRetry(): void {\n\t\tthis._retryAbortController?.abort();\n\t\tthis._retryAttempt = 0;\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 */\n\tasync executeBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string) => void,\n\t\toptions?: { excludeFromContext?: boolean },\n\t): Promise<BashResult> {\n\t\tthis._bashAbortController = new AbortController();\n\n\t\ttry {\n\t\t\tconst result = await executeBashCommand(command, {\n\t\t\t\tonChunk,\n\t\t\t\tsignal: this._bashAbortController.signal,\n\t\t\t});\n\n\t\t\t// Create and save message\n\t\t\tconst bashMessage: BashExecutionMessage = {\n\t\t\t\trole: \"bashExecution\",\n\t\t\t\tcommand,\n\t\t\t\toutput: result.output,\n\t\t\t\texitCode: result.exitCode,\n\t\t\t\tcancelled: result.cancelled,\n\t\t\t\ttruncated: result.truncated,\n\t\t\t\tfullOutputPath: result.fullOutputPath,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\texcludeFromContext: options?.excludeFromContext,\n\t\t\t};\n\n\t\t\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\t\t\tif (this.isStreaming) {\n\t\t\t\t// Queue for later - will be flushed on agent_end\n\t\t\t\tthis._pendingBashMessages.push(bashMessage);\n\t\t\t} else {\n\t\t\t\t// Add to agent state immediately\n\t\t\t\tthis.agent.appendMessage(bashMessage);\n\n\t\t\t\t// Save to session\n\t\t\t\tthis.sessionManager.appendMessage(bashMessage);\n\t\t\t}\n\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 * 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 hook\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._hookRunner?.hasHandlers(\"session_before_switch\")) {\n\t\t\tconst result = (await this._hookRunner.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\n\t\t// Set new session\n\t\tthis.sessionManager.setSessionFile(sessionPath);\n\n\t\t// Reload messages\n\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\n\t\t// Emit session_switch event to hooks\n\t\tif (this._hookRunner) {\n\t\t\tawait this._hookRunner.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\t\tawait this.emitCustomToolSessionEvent(\"switch\", previousSessionFile);\n\n\t\tthis.agent.replaceMessages(sessionContext.messages);\n\n\t\t// Restore model if saved\n\t\tif (sessionContext.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}\n\t\t}\n\n\t\t// Restore thinking level if saved (setThinkingLevel clamps to model capabilities)\n\t\tif (sessionContext.thinkingLevel) {\n\t\t\tthis.setThinkingLevel(sessionContext.thinkingLevel as ThinkingLevel);\n\t\t}\n\n\t\tthis._reconnectToAgent();\n\t\treturn true;\n\t}\n\n\t/**\n\t * Create a branch from a specific entry.\n\t * Emits before_branch/branch session events to hooks.\n\t *\n\t * @param entryId ID of the entry to branch 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 a hook cancelled the branch\n\t */\n\tasync branch(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 branching\");\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_branch event (can be cancelled)\n\t\tif (this._hookRunner?.hasHandlers(\"session_before_branch\")) {\n\t\t\tconst result = (await this._hookRunner.emit({\n\t\t\t\ttype: \"session_before_branch\",\n\t\t\t\tentryId,\n\t\t\t})) as SessionBeforeBranchResult | 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\tif (!selectedEntry.parentId) {\n\t\t\tthis.sessionManager.newSession();\n\t\t} else {\n\t\t\tthis.sessionManager.createBranchedSession(selectedEntry.parentId);\n\t\t}\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// Emit session_branch event to hooks (after branch completes)\n\t\tif (this._hookRunner) {\n\t\t\tawait this._hookRunner.emit({\n\t\t\t\ttype: \"session_branch\",\n\t\t\t\tpreviousSessionFile,\n\t\t\t});\n\t\t}\n\n\t\t// Emit session event to custom tools (with reason \"branch\")\n\t\tawait this.emitCustomToolSessionEvent(\"branch\", previousSessionFile);\n\n\t\tif (!skipConversationRestore) {\n\t\t\tthis.agent.replaceMessages(sessionContext.messages);\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 branch() 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 * @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 } = {},\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\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};\n\n\t\t// Set up abort controller for summarization\n\t\tthis._branchSummaryAbortController = new AbortController();\n\t\tlet hookSummary: { summary: string; details?: unknown } | undefined;\n\t\tlet fromHook = false;\n\n\t\t// Emit session_before_tree event\n\t\tif (this._hookRunner?.hasHandlers(\"session_before_tree\")) {\n\t\t\tconst result = (await this._hookRunner.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\thookSummary = result.summary;\n\t\t\t\tfromHook = true;\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 && !hookSummary) {\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: options.customInstructions,\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 (hookSummary) {\n\t\t\tsummaryText = hookSummary.summary;\n\t\t\tsummaryDetails = hookSummary.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, fromHook);\n\t\t\tsummaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;\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// 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._hookRunner) {\n\t\t\tawait this._hookRunner.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\tfromHook: summaryText ? fromHook : undefined,\n\t\t\t});\n\t\t}\n\n\t\t// Emit to custom tools\n\t\tawait this.emitCustomToolSessionEvent(\"tree\", this.sessionFile);\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 branch selector.\n\t */\n\tgetUserMessagesForBranching(): 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};\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\texportToHtml(outputPath?: string): string {\n\t\tconst themeName = this.settingsManager.getTheme();\n\t\treturn exportSessionToHtml(this.sessionManager, this.state, { outputPath, themeName });\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// Hook System\n\t// =========================================================================\n\n\t/**\n\t * Check if hooks have handlers for a specific event type.\n\t */\n\thasHookHandlers(eventType: string): boolean {\n\t\treturn this._hookRunner?.hasHandlers(eventType) ?? false;\n\t}\n\n\t/**\n\t * Get the hook runner (for setting UI context and error handlers).\n\t */\n\tget hookRunner(): HookRunner | undefined {\n\t\treturn this._hookRunner;\n\t}\n\n\t/**\n\t * Get custom tools (for setting UI context in modes).\n\t */\n\tget customTools(): LoadedCustomTool[] {\n\t\treturn this._customTools;\n\t}\n\n\t/**\n\t * Emit session event to all custom tools.\n\t * Called on session switch, branch, tree navigation, and shutdown.\n\t */\n\tasync emitCustomToolSessionEvent(\n\t\treason: CustomToolSessionEvent[\"reason\"],\n\t\tpreviousSessionFile?: string | undefined,\n\t): Promise<void> {\n\t\tif (!this._customTools) return;\n\n\t\tconst event: CustomToolSessionEvent = { reason, previousSessionFile };\n\t\tconst ctx: CustomToolContext = {\n\t\t\tsessionManager: this.sessionManager,\n\t\t\tmodelRegistry: this._modelRegistry,\n\t\t\tmodel: this.agent.state.model,\n\t\t\tisIdle: () => !this.isStreaming,\n\t\t\thasPendingMessages: () => this.pendingMessageCount > 0,\n\t\t\tabort: () => {\n\t\t\t\tthis.abort();\n\t\t\t},\n\t\t};\n\n\t\tfor (const { tool } of this._customTools) {\n\t\t\tif (tool.onSession) {\n\t\t\t\ttry {\n\t\t\t\t\tawait tool.onSession(event, ctx);\n\t\t\t\t} catch (_err) {\n\t\t\t\t\t// Silently ignore tool errors during session events\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"agent-session.d.ts","sourceRoot":"","sources":["../../src/core/agent-session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC9G,OAAO,KAAK,EAAoB,YAAY,EAAW,KAAK,EAAe,MAAM,qBAAqB,CAAC;AAGvG,OAAO,EAAE,KAAK,UAAU,EAAqC,MAAM,oBAAoB,CAAC;AACxF,OAAO,EACN,KAAK,gBAAgB,EAOrB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAqB,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE3G,OAAO,KAAK,EACX,UAAU,EAQV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAwB,WAAW,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,kBAAkB,EAAmB,iBAAiB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACnH,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC7E,OAAO,EAAsB,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEhF,8DAA8D;AAC9D,MAAM,MAAM,iBAAiB,GAC1B,UAAU,GACV;IAAE,IAAI,EAAE,uBAAuB,CAAC;IAAC,MAAM,EAAE,WA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AC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,YAAY,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,OAAO,CAAA;KAAE,CAAC,CAkDnF;IAMD;;;;;;;;OAQG;IACG,YAAY,CACjB,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,kBAAkB,CAAC,EAAE,MAAM,CAAA;KAAO,GAChE,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,CAqJ5G;IAED;;OAEG;IACH,2BAA2B,IAAI,KAAK,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAetE;IAED,OAAO,CAAC,uBAAuB;IAW/B;;OAEG;IACH,eAAe,IAAI,YAAY,CA0C9B;IAED;;;;OAIG;IACH,YAAY,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,CAGxC;IAMD;;;;OAIG;IACH,oBAAoB,IAAI,MAAM,GAAG,SAAS,CAsBzC;IAMD;;OAEG;IACH,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAE1C;IAED;;OAEG;IACH,IAAI,UAAU,IAAI,UAAU,GAAG,SAAS,CAEvC;IAED;;OAEG;IACH,IAAI,WAAW,IAAI,gBAAgB,EAAE,CAEpC;IAED;;;OAGG;IACG,0BAA0B,CAC/B,MAAM,EAAE,sBAAsB,CAAC,QAAQ,CAAC,EACxC,mBAAmB,CAAC,EAAE,MAAM,GAAG,SAAS,GACtC,OAAO,CAAC,IAAI,CAAC,CAwBf;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 type { Agent, AgentEvent, AgentMessage, AgentState, ThinkingLevel } from \"@mariozechner/pi-agent-core\";\nimport type { AssistantMessage, ImageContent, Message, Model, TextContent } from \"@mariozechner/pi-ai\";\nimport { isContextOverflow, modelsAreEqual, supportsXhigh } from \"@mariozechner/pi-ai\";\nimport { getAuthPath } from \"../config.js\";\nimport { type BashResult, executeBash as executeBashCommand } from \"./bash-executor.js\";\nimport {\n\ttype CompactionResult,\n\tcalculateContextTokens,\n\tcollectEntriesForBranchSummary,\n\tcompact,\n\tgenerateBranchSummary,\n\tprepareCompaction,\n\tshouldCompact,\n} from \"./compaction/index.js\";\nimport type { CustomToolContext, CustomToolSessionEvent, LoadedCustomTool } from \"./custom-tools/index.js\";\nimport { exportSessionToHtml } from \"./export-html/index.js\";\nimport type {\n\tHookRunner,\n\tSessionBeforeBranchResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tTreePreparation,\n\tTurnEndEvent,\n\tTurnStartEvent,\n} from \"./hooks/index.js\";\nimport type { BashExecutionMessage, HookMessage } from \"./messages.js\";\nimport type { ModelRegistry } from \"./model-registry.js\";\nimport type { BranchSummaryEntry, CompactionEntry, NewSessionOptions, SessionManager } from \"./session-manager.js\";\nimport type { SettingsManager, SkillsSettings } from \"./settings-manager.js\";\nimport { expandSlashCommand, type FileSlashCommand } from \"./slash-commands.js\";\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| { type: \"auto_compaction_end\"; result: CompactionResult | undefined; aborted: boolean; willRetry: boolean }\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\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\t/** Models to cycle through with Ctrl+P (from --models flag) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel: ThinkingLevel }>;\n\t/** File-based slash commands for expansion */\n\tfileCommands?: FileSlashCommand[];\n\t/** Hook runner (created in main.ts with wrapped tools) */\n\thookRunner?: HookRunner;\n\t/** Custom tools for session lifecycle events */\n\tcustomTools?: LoadedCustomTool[];\n\tskillsSettings?: Required<SkillsSettings>;\n\t/** Model registry for API key resolution and model discovery */\n\tmodelRegistry: ModelRegistry;\n}\n\n/** Options for AgentSession.prompt() */\nexport interface PromptOptions {\n\t/** Whether to expand file-based slash commands (default: true) */\n\texpandSlashCommands?: 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}\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}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Standard thinking levels */\nconst THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\n/** Thinking levels including xhigh (for supported models) */\nconst THINKING_LEVELS_WITH_XHIGH: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\"];\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 _fileCommands: FileSlashCommand[];\n\n\t// Event subscription state\n\tprivate _unsubscribeAgent?: () => void;\n\tprivate _eventListeners: AgentSessionEventListener[] = [];\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\n\t// Compaction state\n\tprivate _compactionAbortController: AbortController | undefined = undefined;\n\tprivate _autoCompactionAbortController: AbortController | undefined = undefined;\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// Hook system\n\tprivate _hookRunner: HookRunner | undefined = undefined;\n\tprivate _turnIndex = 0;\n\n\t// Custom tools for session lifecycle\n\tprivate _customTools: LoadedCustomTool[] = [];\n\n\tprivate _skillsSettings: Required<SkillsSettings> | undefined;\n\n\t// Model registry for API key resolution\n\tprivate _modelRegistry: ModelRegistry;\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._fileCommands = config.fileCommands ?? [];\n\t\tthis._hookRunner = config.hookRunner;\n\t\tthis._customTools = config.customTools ?? [];\n\t\tthis._skillsSettings = config.skillsSettings;\n\t\tthis._modelRegistry = config.modelRegistry;\n\n\t\t// Always subscribe to agent events for internal handling\n\t\t// (session persistence, hooks, auto-compaction, retry logic)\n\t\tthis._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);\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// 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 = async (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\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 hooks first\n\t\tawait this._emitHookEvent(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\t// Check if this is a hook message\n\t\t\tif (event.message.role === \"hookMessage\") {\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\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 (this._retryAttempt > 0) {\n\t\t\t\t// Previous retry succeeded - emit success event and reset counter\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\t});\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\t// Resolve the retry promise so waitForRetry() completes\n\t\t\t\tthis._resolveRetry();\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 hook events based on agent events */\n\tprivate async _emitHookEvent(event: AgentEvent): Promise<void> {\n\t\tif (!this._hookRunner) return;\n\n\t\tif (event.type === \"agent_start\") {\n\t\t\tthis._turnIndex = 0;\n\t\t\tawait this._hookRunner.emit({ type: \"agent_start\" });\n\t\t} else if (event.type === \"agent_end\") {\n\t\t\tawait this._hookRunner.emit({ type: \"agent_end\", messages: event.messages });\n\t\t} else if (event.type === \"turn_start\") {\n\t\t\tconst hookEvent: 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._hookRunner.emit(hookEvent);\n\t\t} else if (event.type === \"turn_end\") {\n\t\t\tconst hookEvent: 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._hookRunner.emit(hookEvent);\n\t\t\tthis._turnIndex++;\n\t\t}\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/** Whether auto-compaction is currently running */\n\tget isCompacting(): boolean {\n\t\treturn this._autoCompactionAbortController !== undefined || this._compactionAbortController !== undefined;\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/** 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/** File-based slash commands */\n\tget fileCommands(): ReadonlyArray<FileSlashCommand> {\n\t\treturn this._fileCommands;\n\t}\n\n\t// =========================================================================\n\t// Prompting\n\t// =========================================================================\n\n\t/**\n\t * Send a prompt to the agent.\n\t * - Handles hook commands (registered via pi.registerCommand) immediately, even during streaming\n\t * - Expands file-based slash commands 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 expandCommands = options?.expandSlashCommands ?? true;\n\n\t\t// Handle hook commands first (execute immediately, even during streaming)\n\t\t// Hook commands manage their own LLM interaction via pi.sendMessage()\n\t\tif (expandCommands && text.startsWith(\"/\")) {\n\t\t\tconst handled = await this._tryExecuteHookCommand(text);\n\t\t\tif (handled) {\n\t\t\t\t// Hook command executed, no prompt to send\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Expand file-based slash commands if requested\n\t\tconst expandedText = expandCommands ? expandSlashCommand(text, [...this._fileCommands]) : text;\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);\n\t\t\t} else {\n\t\t\t\tawait this._queueSteer(expandedText);\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, set an API key environment variable, or create ${getAuthPath()}\\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\tconst apiKey = await this._modelRegistry.getApiKey(this.model);\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(\n\t\t\t\t`No API key found for ${this.model.provider}.\\n\\n` +\n\t\t\t\t\t`Use /login, set an API key environment variable, or create ${getAuthPath()}`,\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 (hook 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 (options?.images) {\n\t\t\tuserContent.push(...options.images);\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// Emit before_agent_start hook event\n\t\tif (this._hookRunner) {\n\t\t\tconst result = await this._hookRunner.emitBeforeAgentStart(expandedText, options?.images);\n\t\t\tif (result?.message) {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"hookMessage\",\n\t\t\t\t\tcustomType: result.message.customType,\n\t\t\t\t\tcontent: result.message.content,\n\t\t\t\t\tdisplay: result.message.display,\n\t\t\t\t\tdetails: result.message.details,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tawait this.agent.prompt(messages);\n\t\tawait this.waitForRetry();\n\t}\n\n\t/**\n\t * Try to execute a hook command. Returns true if command was found and executed.\n\t */\n\tprivate async _tryExecuteHookCommand(text: string): Promise<boolean> {\n\t\tif (!this._hookRunner) 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._hookRunner.getCommand(commandName);\n\t\tif (!command) return false;\n\n\t\t// Get command context from hook runner (includes session control methods)\n\t\tconst ctx = this._hookRunner.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 hook runner\n\t\t\tthis._hookRunner.emitError({\n\t\t\t\thookPath: `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 * Queue a steering message to interrupt the agent mid-run.\n\t * Delivered after current tool execution, skips remaining tools.\n\t * Expands file-based slash commands. Errors on hook commands.\n\t * @throws Error if text is a hook command\n\t */\n\tasync steer(text: string): Promise<void> {\n\t\t// Check for hook commands (cannot be queued)\n\t\tif (text.startsWith(\"/\")) {\n\t\t\tthis._throwIfHookCommand(text);\n\t\t}\n\n\t\t// Expand file-based slash commands\n\t\tconst expandedText = expandSlashCommand(text, [...this._fileCommands]);\n\n\t\tawait this._queueSteer(expandedText);\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 file-based slash commands. Errors on hook commands.\n\t * @throws Error if text is a hook command\n\t */\n\tasync followUp(text: string): Promise<void> {\n\t\t// Check for hook commands (cannot be queued)\n\t\tif (text.startsWith(\"/\")) {\n\t\t\tthis._throwIfHookCommand(text);\n\t\t}\n\n\t\t// Expand file-based slash commands\n\t\tconst expandedText = expandSlashCommand(text, [...this._fileCommands]);\n\n\t\tawait this._queueFollowUp(expandedText);\n\t}\n\n\t/**\n\t * Internal: Queue a steering message (already expanded, no hook command check).\n\t */\n\tprivate async _queueSteer(text: string): Promise<void> {\n\t\tthis._steeringMessages.push(text);\n\t\tthis.agent.steer({\n\t\t\trole: \"user\",\n\t\t\tcontent: [{ type: \"text\", text }],\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 hook command check).\n\t */\n\tprivate async _queueFollowUp(text: string): Promise<void> {\n\t\tthis._followUpMessages.push(text);\n\t\tthis.agent.followUp({\n\t\t\trole: \"user\",\n\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\t}\n\n\t/**\n\t * Throw an error if the text is a hook command.\n\t */\n\tprivate _throwIfHookCommand(text: string): void {\n\t\tif (!this._hookRunner) 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._hookRunner.getCommand(commandName);\n\n\t\tif (command) {\n\t\t\tthrow new Error(\n\t\t\t\t`Hook 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 hook 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 Hook 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 When streaming, use \"steer\" (default) for immediate or \"followUp\" to wait\n\t */\n\tasync sendHookMessage<T = unknown>(\n\t\tmessage: Pick<HookMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" },\n\t): Promise<void> {\n\t\tconst appMessage = {\n\t\t\trole: \"hookMessage\" 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 HookMessage<T>;\n\t\tif (this.isStreaming) {\n\t\t\t// Queue for processing by agent loop\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\t// Send as prompt - agent loop will emit message events\n\t\t\tawait this.agent.prompt(appMessage);\n\t\t} else {\n\t\t\t// Just append to agent state and session, no turn\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}\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 skillsSettings(): Required<SkillsSettings> | undefined {\n\t\treturn this._skillsSettings;\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 - Optional initial messages and parent session path\n\t * @returns true if completed, false if cancelled by hook\n\t */\n\tasync newSession(options?: NewSessionOptions): 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._hookRunner?.hasHandlers(\"session_before_switch\")) {\n\t\t\tconst result = (await this._hookRunner.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(options);\n\t\tthis._steeringMessages = [];\n\t\tthis._followUpMessages = [];\n\t\tthis._reconnectToAgent();\n\n\t\t// Emit session_switch event with reason \"new\" to hooks\n\t\tif (this._hookRunner) {\n\t\t\tawait this._hookRunner.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\tawait this.emitCustomToolSessionEvent(\"switch\", previousSessionFile);\n\t\treturn true;\n\t}\n\n\t// =========================================================================\n\t// Model Management\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\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(this.thinkingLevel);\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 _cycleScopedModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\t\tif (this._scopedModels.length <= 1) return undefined;\n\n\t\tconst currentModel = this.model;\n\t\tlet currentIndex = this._scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));\n\n\t\tif (currentIndex === -1) currentIndex = 0;\n\t\tconst len = this._scopedModels.length;\n\t\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\t\tconst next = this._scopedModels[nextIndex];\n\n\t\t// Validate API key\n\t\tconst apiKey = await this._modelRegistry.getApiKey(next.model);\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(`No API key for ${next.model.provider}/${next.model.id}`);\n\t\t}\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 (setThinkingLevel clamps to model capabilities)\n\t\tthis.setThinkingLevel(next.thinkingLevel);\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\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(this.thinkingLevel);\n\n\t\treturn { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };\n\t}\n\n\t/**\n\t * Get all available models with valid API keys.\n\t */\n\tasync getAvailableModels(): Promise<Model<any>[]> {\n\t\treturn this._modelRegistry.getAvailable();\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: \"off\" if no reasoning, \"high\" if xhigh unsupported.\n\t * Saves to session and settings.\n\t */\n\tsetThinkingLevel(level: ThinkingLevel): void {\n\t\tlet effectiveLevel = level;\n\t\tif (!this.supportsThinking()) {\n\t\t\teffectiveLevel = \"off\";\n\t\t} else if (level === \"xhigh\" && !this.supportsXhighThinking()) {\n\t\t\teffectiveLevel = \"high\";\n\t\t}\n\t\tthis.agent.setThinkingLevel(effectiveLevel);\n\t\tthis.sessionManager.appendThinkingLevelChange(effectiveLevel);\n\t\tthis.settingsManager.setDefaultThinkingLevel(effectiveLevel);\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 */\n\tgetAvailableThinkingLevels(): ThinkingLevel[] {\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\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 hookCompaction: CompactionResult | undefined;\n\t\t\tlet fromHook = false;\n\n\t\t\tif (this._hookRunner?.hasHandlers(\"session_before_compact\")) {\n\t\t\t\tconst result = (await this._hookRunner.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\thookCompaction = result.compaction;\n\t\t\t\t\tfromHook = 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 (hookCompaction) {\n\t\t\t\t// Hook provided compaction content\n\t\t\t\tsummary = hookCompaction.summary;\n\t\t\t\tfirstKeptEntryId = hookCompaction.firstKeptEntryId;\n\t\t\t\ttokensBefore = hookCompaction.tokensBefore;\n\t\t\t\tdetails = hookCompaction.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\n\t\t\tthis.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook);\n\t\t\tconst newEntries = this.sessionManager.getEntries();\n\t\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\t\tthis.agent.replaceMessages(sessionContext.messages);\n\n\t\t\t// Get the saved compaction entry for the hook\n\t\t\tconst savedCompactionEntry = newEntries.find((e) => e.type === \"compaction\" && e.summary === summary) as\n\t\t\t\t| CompactionEntry\n\t\t\t\t| undefined;\n\n\t\t\tif (this._hookRunner && savedCompactionEntry) {\n\t\t\t\tawait this._hookRunner.emit({\n\t\t\t\t\ttype: \"session_compact\",\n\t\t\t\t\tcompactionEntry: savedCompactionEntry,\n\t\t\t\t\tfromHook,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tsummary,\n\t\t\t\tfirstKeptEntryId,\n\t\t\t\ttokensBefore,\n\t\t\t\tdetails,\n\t\t\t};\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// Case 1: Overflow - LLM returned context overflow error\n\t\tif (isContextOverflow(assistantMessage, contextWindow)) {\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 - turn succeeded but context is getting large\n\t\t// Skip if this was an error (non-overflow errors don't have usage data)\n\t\tif (assistantMessage.stopReason === \"error\") return;\n\n\t\tconst contextTokens = calculateContextTokens(assistantMessage.usage);\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 hookCompaction: CompactionResult | undefined;\n\t\t\tlet fromHook = false;\n\n\t\t\tif (this._hookRunner?.hasHandlers(\"session_before_compact\")) {\n\t\t\t\tconst hookResult = (await this._hookRunner.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 (hookResult?.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 (hookResult?.compaction) {\n\t\t\t\t\thookCompaction = hookResult.compaction;\n\t\t\t\t\tfromHook = 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 (hookCompaction) {\n\t\t\t\t// Hook provided compaction content\n\t\t\t\tsummary = hookCompaction.summary;\n\t\t\t\tfirstKeptEntryId = hookCompaction.firstKeptEntryId;\n\t\t\t\ttokensBefore = hookCompaction.tokensBefore;\n\t\t\t\tdetails = hookCompaction.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\n\t\t\tthis.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook);\n\t\t\tconst newEntries = this.sessionManager.getEntries();\n\t\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\t\tthis.agent.replaceMessages(sessionContext.messages);\n\n\t\t\t// Get the saved compaction entry for the hook\n\t\t\tconst savedCompactionEntry = newEntries.find((e) => e.type === \"compaction\" && e.summary === summary) as\n\t\t\t\t| CompactionEntry\n\t\t\t\t| undefined;\n\n\t\t\tif (this._hookRunner && savedCompactionEntry) {\n\t\t\t\tawait this._hookRunner.emit({\n\t\t\t\t\ttype: \"session_compact\",\n\t\t\t\t\tcompactionEntry: savedCompactionEntry,\n\t\t\t\t\tfromHook,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst result: CompactionResult = {\n\t\t\t\tsummary,\n\t\t\t\tfirstKeptEntryId,\n\t\t\t\ttokensBefore,\n\t\t\t\tdetails,\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}\n\t\t} catch (error) {\n\t\t\tthis._emit({ type: \"auto_compaction_end\", result: undefined, aborted: false, willRetry: false });\n\n\t\t\tif (reason === \"overflow\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Context overflow: ${error instanceof Error ? error.message : \"compaction failed\"}. Your input may be too large for the context window.`,\n\t\t\t\t);\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\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 */\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\t\t// Match: overloaded_error, rate limit, 429, 500, 502, 503, 504, service unavailable, connection error\n\t\treturn /overloaded|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server error|internal error|connection.?error/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) return false;\n\n\t\tthis._retryAttempt++;\n\n\t\t// Create retry promise on first attempt so waitForRetry() can await it\n\t\tif (this._retryAttempt === 1 && !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\tif (this._retryAttempt > settings.maxRetries) {\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 this._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\t/**\n\t * Sleep helper that respects abort signal.\n\t */\n\tprivate _sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (signal?.aborted) {\n\t\t\t\treject(new Error(\"Aborted\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst timeout = setTimeout(resolve, ms);\n\n\t\t\tsignal?.addEventListener(\"abort\", () => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\treject(new Error(\"Aborted\"));\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Cancel in-progress retry.\n\t */\n\tabortRetry(): void {\n\t\tthis._retryAbortController?.abort();\n\t\tthis._retryAttempt = 0;\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 */\n\tasync executeBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string) => void,\n\t\toptions?: { excludeFromContext?: boolean },\n\t): Promise<BashResult> {\n\t\tthis._bashAbortController = new AbortController();\n\n\t\ttry {\n\t\t\tconst result = await executeBashCommand(command, {\n\t\t\t\tonChunk,\n\t\t\t\tsignal: this._bashAbortController.signal,\n\t\t\t});\n\n\t\t\t// Create and save message\n\t\t\tconst bashMessage: BashExecutionMessage = {\n\t\t\t\trole: \"bashExecution\",\n\t\t\t\tcommand,\n\t\t\t\toutput: result.output,\n\t\t\t\texitCode: result.exitCode,\n\t\t\t\tcancelled: result.cancelled,\n\t\t\t\ttruncated: result.truncated,\n\t\t\t\tfullOutputPath: result.fullOutputPath,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\texcludeFromContext: options?.excludeFromContext,\n\t\t\t};\n\n\t\t\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\t\t\tif (this.isStreaming) {\n\t\t\t\t// Queue for later - will be flushed on agent_end\n\t\t\t\tthis._pendingBashMessages.push(bashMessage);\n\t\t\t} else {\n\t\t\t\t// Add to agent state immediately\n\t\t\t\tthis.agent.appendMessage(bashMessage);\n\n\t\t\t\t// Save to session\n\t\t\t\tthis.sessionManager.appendMessage(bashMessage);\n\t\t\t}\n\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 * 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 hook\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._hookRunner?.hasHandlers(\"session_before_switch\")) {\n\t\t\tconst result = (await this._hookRunner.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\n\t\t// Set new session\n\t\tthis.sessionManager.setSessionFile(sessionPath);\n\n\t\t// Reload messages\n\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\n\t\t// Emit session_switch event to hooks\n\t\tif (this._hookRunner) {\n\t\t\tawait this._hookRunner.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\t\tawait this.emitCustomToolSessionEvent(\"switch\", previousSessionFile);\n\n\t\tthis.agent.replaceMessages(sessionContext.messages);\n\n\t\t// Restore model if saved\n\t\tif (sessionContext.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}\n\t\t}\n\n\t\t// Restore thinking level if saved (setThinkingLevel clamps to model capabilities)\n\t\tif (sessionContext.thinkingLevel) {\n\t\t\tthis.setThinkingLevel(sessionContext.thinkingLevel as ThinkingLevel);\n\t\t}\n\n\t\tthis._reconnectToAgent();\n\t\treturn true;\n\t}\n\n\t/**\n\t * Create a branch from a specific entry.\n\t * Emits before_branch/branch session events to hooks.\n\t *\n\t * @param entryId ID of the entry to branch 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 a hook cancelled the branch\n\t */\n\tasync branch(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 branching\");\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_branch event (can be cancelled)\n\t\tif (this._hookRunner?.hasHandlers(\"session_before_branch\")) {\n\t\t\tconst result = (await this._hookRunner.emit({\n\t\t\t\ttype: \"session_before_branch\",\n\t\t\t\tentryId,\n\t\t\t})) as SessionBeforeBranchResult | 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\tif (!selectedEntry.parentId) {\n\t\t\tthis.sessionManager.newSession();\n\t\t} else {\n\t\t\tthis.sessionManager.createBranchedSession(selectedEntry.parentId);\n\t\t}\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// Emit session_branch event to hooks (after branch completes)\n\t\tif (this._hookRunner) {\n\t\t\tawait this._hookRunner.emit({\n\t\t\t\ttype: \"session_branch\",\n\t\t\t\tpreviousSessionFile,\n\t\t\t});\n\t\t}\n\n\t\t// Emit session event to custom tools (with reason \"branch\")\n\t\tawait this.emitCustomToolSessionEvent(\"branch\", previousSessionFile);\n\n\t\tif (!skipConversationRestore) {\n\t\t\tthis.agent.replaceMessages(sessionContext.messages);\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 branch() 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 * @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 } = {},\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\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};\n\n\t\t// Set up abort controller for summarization\n\t\tthis._branchSummaryAbortController = new AbortController();\n\t\tlet hookSummary: { summary: string; details?: unknown } | undefined;\n\t\tlet fromHook = false;\n\n\t\t// Emit session_before_tree event\n\t\tif (this._hookRunner?.hasHandlers(\"session_before_tree\")) {\n\t\t\tconst result = (await this._hookRunner.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\thookSummary = result.summary;\n\t\t\t\tfromHook = true;\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 && !hookSummary) {\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: options.customInstructions,\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 (hookSummary) {\n\t\t\tsummaryText = hookSummary.summary;\n\t\t\tsummaryDetails = hookSummary.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, fromHook);\n\t\t\tsummaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;\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// 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._hookRunner) {\n\t\t\tawait this._hookRunner.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\tfromHook: summaryText ? fromHook : undefined,\n\t\t\t});\n\t\t}\n\n\t\t// Emit to custom tools\n\t\tawait this.emitCustomToolSessionEvent(\"tree\", this.sessionFile);\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 branch selector.\n\t */\n\tgetUserMessagesForBranching(): 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};\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\texportToHtml(outputPath?: string): string {\n\t\tconst themeName = this.settingsManager.getTheme();\n\t\treturn exportSessionToHtml(this.sessionManager, this.state, { outputPath, themeName });\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// Hook System\n\t// =========================================================================\n\n\t/**\n\t * Check if hooks have handlers for a specific event type.\n\t */\n\thasHookHandlers(eventType: string): boolean {\n\t\treturn this._hookRunner?.hasHandlers(eventType) ?? false;\n\t}\n\n\t/**\n\t * Get the hook runner (for setting UI context and error handlers).\n\t */\n\tget hookRunner(): HookRunner | undefined {\n\t\treturn this._hookRunner;\n\t}\n\n\t/**\n\t * Get custom tools (for setting UI context in modes).\n\t */\n\tget customTools(): LoadedCustomTool[] {\n\t\treturn this._customTools;\n\t}\n\n\t/**\n\t * Emit session event to all custom tools.\n\t * Called on session switch, branch, tree navigation, and shutdown.\n\t */\n\tasync emitCustomToolSessionEvent(\n\t\treason: CustomToolSessionEvent[\"reason\"],\n\t\tpreviousSessionFile?: string | undefined,\n\t): Promise<void> {\n\t\tif (!this._customTools) return;\n\n\t\tconst event: CustomToolSessionEvent = { reason, previousSessionFile };\n\t\tconst ctx: CustomToolContext = {\n\t\t\tsessionManager: this.sessionManager,\n\t\t\tmodelRegistry: this._modelRegistry,\n\t\t\tmodel: this.agent.state.model,\n\t\t\tisIdle: () => !this.isStreaming,\n\t\t\thasPendingMessages: () => this.pendingMessageCount > 0,\n\t\t\tabort: () => {\n\t\t\t\tthis.abort();\n\t\t\t},\n\t\t};\n\n\t\tfor (const { tool } of this._customTools) {\n\t\t\tif (tool.onSession) {\n\t\t\t\ttry {\n\t\t\t\t\tawait tool.onSession(event, ctx);\n\t\t\t\t} catch (_err) {\n\t\t\t\t\t// Silently ignore tool errors during session events\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
@@ -317,19 +317,17 @@ export class AgentSession {
317
317
  // =========================================================================
318
318
  /**
319
319
  * Send a prompt to the agent.
320
- * - Validates model and API key before sending
321
- * - Handles hook commands (registered via pi.registerCommand)
320
+ * - Handles hook commands (registered via pi.registerCommand) immediately, even during streaming
322
321
  * - Expands file-based slash commands by default
323
- * @throws Error if no model selected or no API key available
322
+ * - During streaming, queues via steer() or followUp() based on streamingBehavior option
323
+ * - Validates model and API key before sending (when not streaming)
324
+ * @throws Error if streaming and no streamingBehavior specified
325
+ * @throws Error if no model selected or no API key available (when not streaming)
324
326
  */
325
327
  async prompt(text, options) {
326
- if (this.isStreaming) {
327
- throw new Error("Agent is already processing. Use steer() or followUp() to queue messages during streaming.");
328
- }
329
- // Flush any pending bash messages before the new prompt
330
- this._flushPendingBashMessages();
331
328
  const expandCommands = options?.expandSlashCommands ?? true;
332
- // Handle hook commands first (if enabled and text is a slash command)
329
+ // Handle hook commands first (execute immediately, even during streaming)
330
+ // Hook commands manage their own LLM interaction via pi.sendMessage()
333
331
  if (expandCommands && text.startsWith("/")) {
334
332
  const handled = await this._tryExecuteHookCommand(text);
335
333
  if (handled) {
@@ -337,6 +335,23 @@ export class AgentSession {
337
335
  return;
338
336
  }
339
337
  }
338
+ // Expand file-based slash commands if requested
339
+ const expandedText = expandCommands ? expandSlashCommand(text, [...this._fileCommands]) : text;
340
+ // If streaming, queue via steer() or followUp() based on option
341
+ if (this.isStreaming) {
342
+ if (!options?.streamingBehavior) {
343
+ throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
344
+ }
345
+ if (options.streamingBehavior === "followUp") {
346
+ await this._queueFollowUp(expandedText);
347
+ }
348
+ else {
349
+ await this._queueSteer(expandedText);
350
+ }
351
+ return;
352
+ }
353
+ // Flush any pending bash messages before the new prompt
354
+ this._flushPendingBashMessages();
340
355
  // Validate model
341
356
  if (!this.model) {
342
357
  throw new Error("No model selected.\n\n" +
@@ -354,8 +369,6 @@ export class AgentSession {
354
369
  if (lastAssistant) {
355
370
  await this._checkCompaction(lastAssistant, false);
356
371
  }
357
- // Expand file-based slash commands if requested
358
- const expandedText = expandCommands ? expandSlashCommand(text, [...this._fileCommands]) : text;
359
372
  // Build messages array (hook message if any, then user message)
360
373
  const messages = [];
361
374
  // Add user message
@@ -417,8 +430,37 @@ export class AgentSession {
417
430
  /**
418
431
  * Queue a steering message to interrupt the agent mid-run.
419
432
  * Delivered after current tool execution, skips remaining tools.
433
+ * Expands file-based slash commands. Errors on hook commands.
434
+ * @throws Error if text is a hook command
420
435
  */
421
436
  async steer(text) {
437
+ // Check for hook commands (cannot be queued)
438
+ if (text.startsWith("/")) {
439
+ this._throwIfHookCommand(text);
440
+ }
441
+ // Expand file-based slash commands
442
+ const expandedText = expandSlashCommand(text, [...this._fileCommands]);
443
+ await this._queueSteer(expandedText);
444
+ }
445
+ /**
446
+ * Queue a follow-up message to be processed after the agent finishes.
447
+ * Delivered only when agent has no more tool calls or steering messages.
448
+ * Expands file-based slash commands. Errors on hook commands.
449
+ * @throws Error if text is a hook command
450
+ */
451
+ async followUp(text) {
452
+ // Check for hook commands (cannot be queued)
453
+ if (text.startsWith("/")) {
454
+ this._throwIfHookCommand(text);
455
+ }
456
+ // Expand file-based slash commands
457
+ const expandedText = expandSlashCommand(text, [...this._fileCommands]);
458
+ await this._queueFollowUp(expandedText);
459
+ }
460
+ /**
461
+ * Internal: Queue a steering message (already expanded, no hook command check).
462
+ */
463
+ async _queueSteer(text) {
422
464
  this._steeringMessages.push(text);
423
465
  this.agent.steer({
424
466
  role: "user",
@@ -427,10 +469,9 @@ export class AgentSession {
427
469
  });
428
470
  }
429
471
  /**
430
- * Queue a follow-up message to be processed after the agent finishes.
431
- * Delivered only when agent has no more tool calls or steering messages.
472
+ * Internal: Queue a follow-up message (already expanded, no hook command check).
432
473
  */
433
- async followUp(text) {
474
+ async _queueFollowUp(text) {
434
475
  this._followUpMessages.push(text);
435
476
  this.agent.followUp({
436
477
  role: "user",
@@ -438,6 +479,19 @@ export class AgentSession {
438
479
  timestamp: Date.now(),
439
480
  });
440
481
  }
482
+ /**
483
+ * Throw an error if the text is a hook command.
484
+ */
485
+ _throwIfHookCommand(text) {
486
+ if (!this._hookRunner)
487
+ return;
488
+ const spaceIndex = text.indexOf(" ");
489
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
490
+ const command = this._hookRunner.getCommand(commandName);
491
+ if (command) {
492
+ throw new Error(`Hook command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`);
493
+ }
494
+ }
441
495
  /**
442
496
  * Send a hook message to the session. Creates a CustomMessageEntry.
443
497
  *