返回源码地图

packages/coding-agent/src/core/agent-session.ts

v1.3.0 · 71023aec1546 · 03/08:active tools恢复、before_agent_start启动临界区;非全文件逐行审计

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1/**
2 * AgentSession - Core abstraction for agent lifecycle and session management.
3 *
4 * This class is shared between all run modes (interactive, print, rpc).
5 * It encapsulates:
6 * - Agent state access
7 * - Event subscription with automatic session persistence
8 * - Model and thinking level management
9 * - Compaction (manual and auto)
10 * - Bash execution
11 * - Session switching and branching
12 *
13 * Modes use this class and add their own I/O layer on top.
14 */
15
16import { readFileSync } from "node:fs";
17import { basename, dirname } from "node:path";
18import {
19 type AfterToolCallContext,
20 type AfterToolCallResult,
21 type Agent,
22 type AgentContext,
23 type AgentEvent,
24 type AgentMessage,
25 type AgentState,
26 type AgentTool,
27 type AgentToolCallOutcome,
28 type BeforeToolCallContext,
29 type BeforeToolCallResult,
30 type PrepareNextTurnContext,
31 runToolCall,
32 type ThinkingLevel,
33} from "@earendil-works/pi-agent-core";
34import { contentText, getCurrentSystemMessage, retryDelayMs } from "@earendil-works/pi-ai";
35import type {
36 AssistantMessage,
37 AuthResult,
38 ImageContent,
39 Model,
40 ProviderHeaders,
41 SystemMessage,
42 TextContent,
43 ToolResultMessage,
44 Usage,
45} from "@earendil-works/pi-ai/compat";
46import {
47 clampThinkingLevel,
48 cleanupSessionResources,
49 getSupportedThinkingLevels,
50 isContextOverflow,
51 isRecoverableLength,
52 isRetryableAssistantError,
53 modelsAreEqual,
54 type RetryCallbacks,
55 resetApiProviders,
56 streamSimple,
57} from "@earendil-works/pi-ai/compat";
58import { getThemeByName, theme } from "../modes/interactive/theme/theme.ts";
59import { stripFrontmatter } from "../utils/frontmatter.ts";
60import { processImage } from "../utils/image-process.ts";
61import { sleep } from "../utils/sleep.ts";
62import { normalizeToolResultImages } from "../utils/tool-result-images.ts";
63import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.ts";
64import { type BashResult, executeBashWithOperations } from "./bash-executor.ts";
65import { generateBugReportSummary } from "./bug-report.ts";
66import type { CacheWarmer, CacheWarmingStatus } from "./cache-warmer.ts";
67import {
68 type CompactionPreparation,
69 type CompactionResult,
70 calculateContextTokens,
71 collectEntriesForBranchSummary,
72 compact,
73 estimateContextTokens,
74 estimateProjectedContextTokens,
75 estimateTokens,
76 generateBranchSummary,
77 prepareCompaction,
78 shouldCompact,
79} from "./compaction/index.ts";
80import { DEFAULT_THINKING_LEVEL, THINKING_LEVEL_OPTIONS } from "./defaults.ts";
81import { exportSessionToHtml, type ToolHtmlRenderer } from "./export-html/index.ts";
82import { createToolHtmlRenderer } from "./export-html/tool-renderer.ts";
83import {
84 type AgentActivityOutcome,
85 type BoundaryContextPreview,
86 type ContextUsage,
87 type ExecuteToolOptions,
88 type ExtensionCommandContextActions,
89 type ExtensionErrorListener,
90 type ExtensionMode,
91 ExtensionRunner,
92 type ExtensionUIContext,
93 type InputSource,
94 type MessageEndEvent,
95 type MessageStartEvent,
96 type MessageUpdateEvent,
97 type ReplacedSessionContext,
98 type SessionBeforeCompactResult,
99 type SessionBeforeTreeResult,
100 type SessionBoundaryDraft,
101 type SessionCompactFailedEvent,
102 type SessionStartEvent,
103 type ShutdownHandler,
104 type ToolDefinition,
105 type ToolExecutionEndEvent,
106 type ToolExecutionStartEvent,
107 type ToolExecutionUpdateEvent,
108 type ToolExposure,
109 type ToolInfo,
110 type ToolLoadout,
111 type TreePreparation,
112 type TurnStartEvent,
113 wrapRegisteredTools,
114} from "./extensions/index.ts";
115import { type BeforeAgentStartTrigger, emitSessionShutdownEvent } from "./extensions/runner.ts";
116import { createToolNameMatcher, isMcpToolName } from "./mcp-servers.ts";
117import { type BashExecutionMessage, type CustomMessage, convertToLlm } from "./messages.ts";
118import { ModelRegistry } from "./model-registry.ts";
119import type { ModelRuntime } from "./model-runtime.ts";
120import { NestedToolCallRunner } from "./nested-tool-calls.ts";
121import { expandPromptTemplate, type PromptTemplate } from "./prompt-templates.ts";
122import type { ResourceExtensionPaths, ResourceLoader } from "./resource-loader.ts";
123import { exportSessionToJsonl } from "./session-export.ts";
124import {
125 type BranchSummaryEntry,
126 type CompactionEntry,
127 type ContextEditEntry,
128 getLatestCompactionEntry,
129 type SessionEntry,
130 SessionManager,
131 type SessionProjection,
132} from "./session-manager.ts";
133import {
134 applyToolModifiers,
135 type CacheWarmingMode,
136 DEFAULT_TOOL_NAMES,
137 type SettingsManager,
138} from "./settings-manager.ts";
139import type { SlashCommandInfo } from "./slash-commands.ts";
140import { BUILTIN_PATH_PREFIX, createSyntheticSourceInfo, isSyntheticPath, type SourceInfo } from "./source-info.ts";
141import {
142 buildSystemPrompt,
143 buildSystemPromptSections,
144 diffSystemPromptSections,
145 type NormalizedBuildSystemPromptOptions,
146 normalizeBuildSystemPromptOptions,
147} from "./system-prompt.ts";
148import { type BashOperations, createLocalBashOperations } from "./tools/bash.ts";
149import { createAllToolDefinitions } from "./tools/index.ts";
150import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.ts";
151import { addUsageToTotals, combineUsage, createUsageTotals } from "./usage-totals.ts";
152import {
153 findLatestResponse,
154 getBranchSelection,
155 getVirtualModelState,
156 isVirtualModel,
157 VIRTUAL_MODEL_STATE_ENTRY,
158 type VirtualModelStateData,
159} from "./virtual-models.ts";
160
161// ============================================================================
162// Skill Block Parsing
163// ============================================================================
164
165/** Parsed skill block from a user message */
166export interface ParsedSkillBlock {
167 name: string;
168 location: string;
169 content: string;
170 userMessage: string | undefined;
171}
172
173/**
174 * Parse a skill block from message text.
175 * Returns null if the text doesn't contain a skill block.
176 */
177export function parseSkillBlock(text: string): ParsedSkillBlock | null {
178 const match = text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);
179 if (!match) return null;
180 return {
181 name: match[1],
182 location: match[2],
183 content: match[3],
184 userMessage: match[4]?.trim() || undefined,
185 };
186}
187
188/** Tool execution events of calls a tool made through `ctx.executeTool()` carry `parentToolCallId`. */
189type WithParentToolCallId<E> = E extends {
190 type: "tool_execution_start" | "tool_execution_update" | "tool_execution_end";
191}
192 ? E & { parentToolCallId?: string }
193 : E;
194
195/** Session-specific events that extend the core AgentEvent */
196export type AgentSessionEvent =
197 | WithParentToolCallId<Exclude<AgentEvent, { type: "agent_end" }>>
198 | {
199 type: "agent_end";
200 messages: AgentMessage[];
201 willRetry: boolean;
202 }
203 | { type: "agent_settled"; aborted: boolean }
204 | {
205 type: "queue_update";
206 steering: readonly string[];
207 followUp: readonly string[];
208 }
209 | { type: "compaction_start"; reason: "manual" | "threshold" | "overflow" }
210 | { type: "entry_appended"; entry: SessionEntry }
211 | { type: "session_info_changed"; name: string | undefined }
212 | { type: "thinking_level_changed"; level: ThinkingLevel }
213 | {
214 type: "compaction_end";
215 reason: "manual" | "threshold" | "overflow";
216 result: CompactionResult | undefined;
217 aborted: boolean;
218 willRetry: boolean;
219 errorMessage?: string;
220 }
221 | { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }
222 | { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string }
223 | {
224 type: "summarization_retry_scheduled";
225 attempt: number;
226 maxAttempts: number;
227 delayMs: number;
228 errorMessage: string;
229 }
230 | { type: "summarization_retry_attempt_start"; source: "branchSummary" }
231 | {
232 type: "summarization_retry_attempt_start";
233 source: "compaction";
234 reason: "manual" | "threshold" | "overflow";
235 }
236 | { type: "summarization_retry_finished" }
237 | { type: "bash_execution_update"; id?: string; delta: string };
238
239/** Listener function for agent session events */
240export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
241
242// ============================================================================
243// Types
244// ============================================================================
245
246function withoutDeletedHeaders(headers: ProviderHeaders | undefined): Record<string, string> | undefined {
247 return headers
248 ? Object.fromEntries(Object.entries(headers).filter((entry): entry is [string, string] => entry[1] !== null))
249 : undefined;
250}
251
252export interface AgentSessionConfig {
253 agent: Agent;
254 sessionManager: SessionManager;
255 settingsManager: SettingsManager;
256 cwd: string;
257 /** Models to cycle through with Ctrl+P (from --models flag) */
258 scopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;
259 /** Resource loader for extensions, skills, prompts, themes, context files, and system prompt */
260 resourceLoader: ResourceLoader;
261 /** SDK custom tools registered outside extensions */
262 customTools?: ToolDefinition[];
263 /** Canonical model/auth runtime used by coding-agent internals. */
264 modelRuntime: ModelRuntime;
265 /** Keeps the prompt cache entry of the last session request warm. */
266 cacheWarmer?: Pick<CacheWarmer, "cancel" | "status" | "onAgentSettled" | "onModeChanged" | "onWarmed">;
267 /** Initial active built-in tool names. Default: [read, bash, edit, write] */
268 initialActiveToolNames?: string[];
269 /**
270 * Whether the initial tools come from the `defaultTools` setting. When true, a resumed session
271 * replaces them with the loadout its transcript records, with `defaultToolModifiers` applied, and
272 * reload activates tools newly added to the setting. Tools removed from it stay active.
273 */
274 usesDefaultTools?: boolean;
275 /**
276 * `+name`/`-name` entries applied on top of the `defaultTools` setting, from `--tools`. Reload
277 * applies them to the reloaded setting too, so a removed tool stays removed.
278 */
279 defaultToolModifiers?: string[];
280 /**
281 * Optional allowlist of tool names or patterns (`*` matches any characters). When provided, only
282 * matching tools are exposed. A non-empty list without `mcp__` entries also keeps MCP tools
283 * registered for codemode and tool_search; only tool_search can declare them. An empty list
284 * exposes no tools.
285 */
286 allowedToolNames?: string[];
287 /** Optional denylist of tool names or patterns. When provided, matching tools are not exposed. */
288 excludedToolNames?: string[];
289 /**
290 * Override base tools (useful for custom runtimes).
291 *
292 * These are synthesized into minimal ToolDefinitions internally so AgentSession can keep
293 * a definition-first registry even when callers provide plain AgentTool instances.
294 */
295 baseToolsOverride?: Record<string, AgentTool>;
296 /** Mutable ref used by Agent to access the current ExtensionRunner */
297 extensionRunnerRef?: { current?: ExtensionRunner };
298 /** Session start event metadata emitted when extensions bind to this runtime. */
299 sessionStartEvent?: SessionStartEvent;
300}
301
302export interface ExtensionBindings {
303 uiContext?: ExtensionUIContext;
304 mode?: ExtensionMode;
305 commandContextActions?: ExtensionCommandContextActions;
306 abortHandler?: () => void;
307 shutdownHandler?: ShutdownHandler;
308 onError?: ExtensionErrorListener;
309}
310
311export type QueuedInputDisposition = "handled" | "queued";
312export type PromptDisposition = QueuedInputDisposition | "started";
313
314/** Options for AgentSession.prompt() */
315export interface PromptOptions {
316 /** Whether to dispatch extension commands and expand skill commands and prompt templates (default: true) */
317 expandPromptTemplates?: boolean;
318 /** Image attachments */
319 images?: ImageContent[];
320 /** When streaming, how to queue the message: "steer" (interrupt) or "followUp" (wait). Required if streaming. */
321 streamingBehavior?: "steer" | "followUp";
322 /** Source of input for extension input event handlers. Defaults to "interactive". */
323 source?: InputSource;
324 /** Internal hook used by RPC mode to observe how an accepted prompt was dispatched. Not called if the prompt is rejected. */
325 preflightResult?: (disposition: PromptDisposition) => void;
326}
327
328/** Options for model/thinking mutations. */
329export interface ModelMutationOptions {
330 /** Persist the new value to global defaults. Defaults to session-only. */
331 persist?: boolean;
332}
333
334/** Result from cycleModel() */
335export interface ModelCycleResult {
336 model: Model<any>;
337 thinkingLevel: ThinkingLevel;
338 /** Whether cycling through scoped models (--models flag) or all available */
339 isScoped: boolean;
340}
341
342/** Session statistics for /session command */
343export interface SessionStats {
344 sessionFile: string | undefined;
345 sessionId: string;
346 userMessages: number;
347 assistantMessages: number;
348 toolCalls: number;
349 toolResults: number;
350 totalMessages: number;
351 tokens: {
352 input: number;
353 output: number;
354 cacheRead: number;
355 cacheWrite: number;
356 total: number;
357 };
358 cost: number;
359 contextUsage?: ContextUsage;
360}
361
362interface ToolDefinitionEntry {
363 definition: ToolDefinition;
364 sourceInfo: SourceInfo;
365}
366
367function estimateMessagesTokens(messages: AgentMessage[]): number {
368 let tokens = 0;
369 for (const message of messages) {
370 tokens += estimateTokens(message);
371 }
372 return tokens;
373}
374
375// ============================================================================
376// AgentSession Class
377// ============================================================================
378
379export class AgentSession {
380 readonly agent: Agent;
381 readonly sessionManager: SessionManager;
382 readonly settingsManager: SettingsManager;
383
384 private _scopedModels: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;
385
386 // Event subscription state
387 private _unsubscribeAgent?: () => void;
388 private _eventListeners: AgentSessionEventListener[] = [];
389 private _isAgentRunActive = false;
390 private _agentRunAbortRequested = false;
391 private _idleWaitPromise: Promise<void> | undefined;
392 private _resolveIdleWait: (() => void) | undefined;
393
394 /** Tracks pending steering messages for UI display. Removed when delivered. */
395 private _steeringMessages: string[] = [];
396 /** Tracks pending follow-up messages for UI display. Removed when delivered. */
397 private _followUpMessages: string[] = [];
398 /** Messages queued to be included with the next user prompt as context ("asides"). */
399 private _pendingNextTurnMessages: CustomMessage[] = [];
400 /** Context-only custom messages queued during a run, flushed once the current turn's tool results are in. */
401 private _pendingCustomMessages: CustomMessage[] = [];
402
403 // Compaction state
404 private _compactionAbortController: AbortController | undefined = undefined;
405 private _autoCompactionAbortController: AbortController | undefined = undefined;
406 private _overflowRecoveryAttempted = false;
407
408 // Branch summarization state
409 private _branchSummaryAbortController: AbortController | undefined = undefined;
410
411 // Retry state
412 private _retryAbortController: AbortController | undefined = undefined;
413 private _retryAttempt = 0;
414 /**
415 * Failed response that the next request repeats, set by auto-retry and overflow recovery. The
416 * retry is routed with it as `failed`, since the context no longer contains it.
417 */
418 private _failedResponse: AssistantMessage | undefined;
419
420 // Bash execution state
421 private readonly _bashAbortControllers = new Set<AbortController>();
422 private _pendingBashMessages: BashExecutionMessage[] = [];
423
424 // Extension system
425 private _extensionRunner!: ExtensionRunner;
426 private _turnIndex = 0;
427 private readonly _entryIdsByMessage = new WeakMap<object, string>();
428 private readonly _boundaryDispatchedMessages = new WeakSet<object>();
429 private _lastAssistantMessage: AssistantMessage | undefined;
430 private _lastAssistantToolResults: AgentMessage[] = [];
431 private _lastActivityOutcome: AgentActivityOutcome = "completed";
432 private _isBeforeSettle = false;
433 private _abortDuringBeforeSettle = false;
434 private _isEmittingAgentSettled = false;
435 private readonly _deferredSettledActions: Array<() => Promise<void>> = [];
436
437 private _resourceLoader: ResourceLoader;
438 private _customTools: ToolDefinition[];
439 private _baseToolDefinitions: Map<string, ToolDefinition> = new Map();
440 private _cwd: string;
441 private _extensionRunnerRef?: { current?: ExtensionRunner };
442 private _initialActiveToolNames?: string[];
443 /**
444 * Tools of the restored or reloaded loadout that are not registered yet, such as tools of MCP
445 * servers that are still connecting. They are activated when they are registered, and dropped when
446 * `setActiveToolsByName()` deactivates a tool or the next agent run starts.
447 */
448 private _pendingToolNames = new Set<string>();
449 private _usesDefaultTools: boolean;
450 private _defaultToolModifiers: string[];
451 /** Matches the `--tools` entries: tool names or patterns. */
452 private _allowedTools?: (name: string) => boolean;
453 /**
454 * Whether the allowlist filters MCP tools: it is empty (`--no-tools`) or names an MCP tool
455 * (`mcp__*`). Otherwise it keeps MCP tools registered for codemode and tool_search.
456 */
457 private _allowlistFiltersMcp = false;
458 private _excludedTools?: (name: string) => boolean;
459 private _baseToolsOverride?: Record<string, AgentTool>;
460 private _sessionStartEvent: SessionStartEvent;
461 private _extensionUIContext?: ExtensionUIContext;
462 private _extensionMode: ExtensionMode = "print";
463 private _extensionCommandContextActions?: ExtensionCommandContextActions;
464 private _extensionAbortHandler?: () => void;
465 private _extensionShutdownHandler?: ShutdownHandler;
466 private _extensionErrorListener?: ExtensionErrorListener;
467 private _extensionErrorUnsubscriber?: () => void;
468
469 private _modelRuntime: ModelRuntime;
470 private _cacheWarmer?: Pick<CacheWarmer, "cancel" | "status" | "onAgentSettled" | "onModeChanged" | "onWarmed">;
471
472 // Tool registry for extension getTools/setTools
473 private _toolRegistry: Map<string, AgentTool> = new Map();
474 /** Created on the first `ctx.executeTool()` call. */
475 private _nestedToolCalls: NestedToolCallRunner | undefined;
476 /** Declared tools whose declarations requests leave out, from `prepareLoadout` hooks. */
477 private _hiddenDeclarations: ReadonlySet<string> = new Set();
478 private _toolDefinitions: Map<string, ToolDefinitionEntry> = new Map();
479 private _toolPromptSnippets: Map<string, string> = new Map();
480 private _toolPromptGuidelines: Map<string, string[]> = new Map();
481
482 private _baseSystemPromptOptions!: NormalizedBuildSystemPromptOptions;
483 /** Prompt options after before_agent_start mutations for the active run. */
484 private _runSystemPromptOptions?: NormalizedBuildSystemPromptOptions;
485
486 constructor(config: AgentSessionConfig) {
487 this.agent = config.agent;
488 this.sessionManager = config.sessionManager;
489 this.settingsManager = config.settingsManager;
490 this._scopedModels = config.scopedModels ?? [];
491 this._resourceLoader = config.resourceLoader;
492 this._customTools = config.customTools ?? [];
493 this._cwd = config.cwd;
494 this._modelRuntime = config.modelRuntime;
495 this._cacheWarmer = config.cacheWarmer;
496 if (this._cacheWarmer) {
497 this._cacheWarmer.onWarmed = (entry) => this._emit({ type: "entry_appended", entry });
498 }
499 this._extensionRunnerRef = config.extensionRunnerRef;
500 this._initialActiveToolNames = config.initialActiveToolNames;
501 this._usesDefaultTools = config.usesDefaultTools ?? false;
502 this._defaultToolModifiers = config.defaultToolModifiers ?? [];
503 if (config.allowedToolNames) {
504 this._allowedTools = createToolNameMatcher(config.allowedToolNames);
505 this._allowlistFiltersMcp =
506 config.allowedToolNames.length === 0 || config.allowedToolNames.some((entry) => entry.startsWith("mcp__"));
507 }
508 this._excludedTools = config.excludedToolNames ? createToolNameMatcher(config.excludedToolNames) : undefined;
509 this._baseToolsOverride = config.baseToolsOverride;
510 this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
511
512 // Always subscribe to agent events for internal handling
513 // (session persistence, extensions, auto-compaction, retry logic)
514 this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
515 this._installAgentToolHooks();
516 this._installAgentNextTurnRefresh();
517 this._installAgentRequestProjection();
518 this._installAgentBoundaryHooks();
519 this._installHiddenDeclarationsProjection();
520 this._installAgentForcedPromptProjection();
521
522 this._buildRuntime({
523 activeToolNames: this._initialActiveToolNames,
524 includeAllExtensionTools: true,
525 });
526 if (this._usesDefaultTools) this._restoreToolsFromTranscript(this._defaultToolModifiers);
527 }
528
529 get modelRuntime(): ModelRuntime {
530 return this._modelRuntime;
531 }
532
533 private async _getRequiredRequestAuth(
534 model: Model<any>,
535 signal?: AbortSignal,
536 ): Promise<{
537 model: Model<any>;
538 apiKey?: string;
539 headers?: Record<string, string>;
540 env?: Record<string, string>;
541 }> {
542 let result: AuthResult | undefined;
543 try {
544 result = await this._modelRuntime.getAuth(model, { signal });
545 } catch (error) {
546 const cause = error instanceof Error ? error.cause : undefined;
547 if (cause instanceof Error && cause.message === "authHeader requires a resolved API key") {
548 throw new Error(formatNoApiKeyFoundMessage(model.provider));
549 }
550 throw error;
551 }
552 if (result && (result.auth.apiKey || result.auth.headers)) {
553 const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
554 return {
555 model: requestModel,
556 apiKey: result.auth.apiKey,
557 headers: withoutDeletedHeaders(result.auth.headers),
558 env: result.env,
559 };
560 }
561
562 const isOAuth = this._modelRuntime.isUsingOAuth(model.provider);
563 if (isOAuth) {
564 throw new Error(
565 `Authentication failed for "${model.provider}". ` +
566 `Credentials may have expired or network is unavailable. ` +
567 `Run '/login ${model.provider}' to re-authenticate.`,
568 );
569 }
570 throw new Error(formatNoApiKeyFoundMessage(model.provider));
571 }
572
573 private async _getSummarizationRequestAuth(
574 selectedModel: Model<any>,
575 signal?: AbortSignal,
576 ): Promise<{
577 model: Model<any>;
578 apiKey?: string;
579 headers?: Record<string, string>;
580 env?: Record<string, string>;
581 thinkingLevel: ThinkingLevel;
582 }> {
583 // Route a virtual model first: summaries size their input and output from the model they get.
584 const { model, thinkingLevel } = isVirtualModel(selectedModel)
585 ? await this._modelRuntime.resolveModel(selectedModel, convertToLlm(this.messages), {
586 reason: "direct",
587 thinkingLevel: this.thinkingLevel,
588 signal,
589 })
590 : { model: selectedModel, thinkingLevel: this.thinkingLevel };
591 if (this.agent.streamFunction === streamSimple) {
592 return { ...(await this._getRequiredRequestAuth(model, signal)), thinkingLevel };
593 }
594
595 try {
596 const result = await this._modelRuntime.getAuth(model, { signal });
597 if (!result) return { model, thinkingLevel };
598 const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
599 return {
600 model: requestModel,
601 apiKey: result.auth.apiKey,
602 headers: withoutDeletedHeaders(result.auth.headers),
603 env: result.env,
604 thinkingLevel,
605 };
606 } catch (error) {
607 if (signal?.aborted) throw error;
608 return { model, thinkingLevel };
609 }
610 }
611
612 /**
613 * The model whose limits apply to `message`, or undefined when the message came from another
614 * model. Under a virtual selection, that is the physical model that produced it.
615 */
616 private _modelForMessage(message: AssistantMessage): Model<any> | undefined {
617 const model = this.model;
618 if (model && isVirtualModel(model)) return this._modelRuntime.getPhysicalModel(message.provider, message.model);
619 return model?.provider === message.provider && model.id === message.model ? model : undefined;
620 }
621
622 /**
623 * Record the selection on the current branch when the branch implies another one, so a resume
624 * restores it. Tree navigation can leave the latest `model_change` on another branch; responses
625 * cannot record a virtual selection because they name physical models. Responses do record a
626 * physical selection unless the branch holds a virtual one; checking a physical selection against
627 * responses would record it on every prompt while `prepareRequest` redirects to another model.
628 */
629 private _recordSelection(): void {
630 const model = this.model;
631 if (!model) return;
632 const getModel = (provider: string, modelId: string) => this._modelRuntime.getModel(provider, modelId);
633 const recorded = getBranchSelection(this.sessionManager.getBranch(), getModel);
634 if (!recorded || (recorded.provider === model.provider && recorded.modelId === model.id)) return;
635 const recordedModel = getModel(recorded.provider, recorded.modelId);
636 if (!isVirtualModel(model) && !(recordedModel && isVirtualModel(recordedModel))) return;
637 this.sessionManager.appendModelChange(model.provider, model.id);
638 }
639
640 /** The model whose limits apply to the conversation. */
641 private _limitsModel(): Model<any> | undefined {
642 return this.routedModel?.model ?? this.model;
643 }
644
645 /**
646 * Install tool hooks once on the Agent instance.
647 *
648 * The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the
649 * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt
650 * registered tool execution to the extension context. Tool call and tool result interception now
651 * happens here instead of in wrappers.
652 */
653 private _installAgentToolHooks(): void {
654 this.agent.beforeToolCall = (context) => this._beforeToolCall(context);
655 this.agent.afterToolCall = (context) => this._afterToolCall(context);
656 }
657
658 /** `tool_call` handlers. `parentToolCallId` is set for calls another tool made. */
659 private async _beforeToolCall(
660 { toolCall, args }: BeforeToolCallContext,
661 parentToolCallId?: string,
662 ): Promise<BeforeToolCallResult | undefined> {
663 const runner = this._extensionRunner;
664 if (!runner.hasHandlers("tool_call")) {
665 return undefined;
666 }
667
668 try {
669 return await runner.emitToolCall({
670 type: "tool_call",
671 toolName: toolCall.name,
672 toolCallId: toolCall.id,
673 ...(parentToolCallId ? { parentToolCallId } : {}),
674 input: args as Record<string, unknown>,
675 });
676 } catch (err) {
677 if (err instanceof Error) {
678 throw err;
679 }
680 throw new Error(`Extension failed, blocking execution: ${String(err)}`);
681 }
682 }
683
684 /** `tool_result` handlers and image normalization. `parentToolCallId` is set for calls another tool made. */
685 private async _afterToolCall(
686 { toolCall, args, result, isError }: AfterToolCallContext,
687 parentToolCallId?: string,
688 ): Promise<AfterToolCallResult | undefined> {
689 const runner = this._extensionRunner;
690 const hookResult = runner.hasHandlers("tool_result")
691 ? await runner.emitToolResult({
692 type: "tool_result",
693 toolName: toolCall.name,
694 toolCallId: toolCall.id,
695 ...(parentToolCallId ? { parentToolCallId } : {}),
696 input: args as Record<string, unknown>,
697 content: result.content,
698 details: result.details,
699 ...(result.structuredContent === undefined ? {} : { structuredContent: result.structuredContent }),
700 isError,
701 usage: result.usage,
702 })
703 : undefined;
704
705 const content = hookResult?.content ?? result.content ?? [];
706 // Runs after the extension hook so images injected or replaced by extensions are normalized too.
707 const resizeOptions = this._limitsModel()?.inputLimits?.images?.resize;
708 const normalizedContent = await normalizeToolResultImages(content, {
709 autoResizeImages: this.settingsManager.getImageAutoResize(),
710 ...(resizeOptions ? { resizeOptions } : {}),
711 });
712
713 if (!hookResult && normalizedContent === content) {
714 return undefined;
715 }
716
717 // The hook result already dropped structured content that replaced content no longer matches.
718 return {
719 content: normalizedContent,
720 details: hookResult?.details,
721 structuredContent: hookResult ? hookResult.structuredContent : result.structuredContent,
722 isError: hookResult?.isError ?? isError,
723 usage: hookResult?.usage,
724 };
725 }
726
727 /**
728 * Run a call that the tool call `parentToolCallId` made through `ctx.executeTool()`. It goes
729 * through the agent's tool pipeline with the session's hooks, against the callable tools.
730 */
731 private async _executeNestedToolCall(
732 parentToolCallId: string,
733 name: string,
734 args: unknown,
735 options: ExecuteToolOptions,
736 ): Promise<AgentToolCallOutcome> {
737 this._nestedToolCalls ??= new NestedToolCallRunner({
738 getTools: () => this._getCallableTools(),
739 isSequential: () => this.agent.toolExecution === "sequential",
740 runToolCall: (toolCall, parentId, signal, onUpdate) => {
741 const assistantMessage = this._findLastAssistantMessage();
742 if (!assistantMessage) {
743 return Promise.resolve({
744 toolCall,
745 result: { content: [{ type: "text", text: "No assistant message issued this call" }], details: {} },
746 isError: true,
747 });
748 }
749 return runToolCall(toolCall, {
750 tools: this._getCallableTools(),
751 assistantMessage,
752 context: { messages: this.agent.state.messages, tools: this.agent.state.tools },
753 beforeToolCall: (context) => this._beforeToolCall(context, parentId),
754 afterToolCall: (context) => this._afterToolCall(context, parentId),
755 signal,
756 onUpdate,
757 });
758 },
759 emit: async (event) => {
760 await this._extensionRunner.emit(event);
761 this._emit(event);
762 },
763 });
764 return this._nestedToolCalls.execute(parentToolCallId, name, args, options);
765 }
766
767 /** Whether `projection`, the current session projection, exceeds the compaction threshold of `model`. */
768 private _exceedsCompactionThreshold(model: Model<any>, projection: SessionProjection): boolean {
769 if (model.contextWindow <= 0) return false;
770 return shouldCompact(
771 estimateProjectedContextTokens(projection, this.sessionManager.getBranch()).tokens,
772 model.contextWindow,
773 this.settingsManager.getCompactionSettings(this.model),
774 );
775 }
776
777 private async _compactBeforeNextAssistantResponse(context: AgentContext): Promise<AgentContext> {
778 const projection = this.sessionManager.buildSessionProjection();
779 // A virtual selection is checked in prepareRequest, against the model the request is routed to.
780 const model = this.model;
781 if (!model || isVirtualModel(model) || !this._exceedsCompactionThreshold(model, projection)) {
782 return { ...context, messages: projection.messages };
783 }
784 await this._runAutoCompaction("threshold", false);
785 return { ...context, messages: this.sessionManager.buildSessionProjection().messages };
786 }
787
788 private _installAgentRequestProjection(): void {
789 const previousPrepareRequest = this.agent.prepareRequest;
790 this.agent.prepareRequest = async (request, signal) => {
791 const failed = this._failedResponse;
792 this._failedResponse = undefined;
793 const prepare = async () => {
794 const projection = this.sessionManager.buildSessionProjection();
795 const canonicalContext = {
796 ...request.context,
797 messages: projection.messages,
798 // Messages declare the provider-visible loadout; context.tools keeps executable implementations.
799 tools: this.agent.state.tools.slice(),
800 };
801 const previous = await previousPrepareRequest?.(
802 {
803 ...request,
804 context: canonicalContext,
805 model: this.agent.state.model,
806 thinkingLevel: this.agent.state.thinkingLevel,
807 },
808 signal,
809 );
810 return { previous, context: previous?.context ?? canonicalContext, projection };
811 };
812 let { previous, context, projection } = await prepare();
813 const model = previous?.model ?? this.agent.state.model;
814 const thinkingLevel = previous?.thinkingLevel ?? this.agent.state.thinkingLevel;
815 if (!isVirtualModel(model)) return { ...previous, context, model, thinkingLevel };
816
817 // The selection stays in agent state; only this request uses the routed model. A routing
818 // failure rejects, which ends the run with an error response. Only messages the user wrote
819 // start a turn; extension messages can follow them, e.g. from before_agent_start.
820 const lastResponse = context.messages.findLastIndex((message) => message.role === "assistant");
821 const userTurn = context.messages.slice(lastResponse + 1).some((message) => message.role === "user");
822 const state = getVirtualModelState(this.sessionManager.getBranch(), model.provider, model.id);
823 const route = await this._modelRuntime.resolveModel(model, convertToLlm(context.messages), {
824 reason: failed ? "retry" : userTurn ? "user" : "continuation",
825 thinkingLevel,
826 signal,
827 failed,
828 state,
829 });
830 if (route.state !== undefined && route.state !== state) {
831 const data: VirtualModelStateData = { provider: model.provider, modelId: model.id, state: route.state };
832 const entry = this.sessionManager.getEntry(
833 this.sessionManager.appendCustomEntry(VIRTUAL_MODEL_STATE_ENTRY, data),
834 );
835 if (entry) this._emit({ type: "entry_appended", entry });
836 }
837 // The route stands: the router already decided this request. The state entry does not change
838 // the projection.
839 if (this._exceedsCompactionThreshold(route.model, projection)) {
840 await this._runAutoCompaction("threshold", false);
841 ({ previous, context } = await prepare());
842 }
843 return { ...previous, context, model: route.model, thinkingLevel: route.thinkingLevel };
844 };
845 }
846
847 private async _dispatchTurnEndBoundary(
848 message: AssistantMessage,
849 toolResults: ToolResultMessage[],
850 ): Promise<boolean> {
851 this._lastActivityOutcome =
852 message.stopReason === "aborted" ? "aborted" : message.stopReason === "error" ? "error" : "completed";
853 const messageEntryId = this._findPersistedMessageEntryId(message);
854 if (!this._extensionRunner.hasHandlers("turn_end")) return false;
855 if (!messageEntryId) {
856 this._extensionRunner.emitError({
857 extensionPath: "<boundary>",
858 event: "turn_end",
859 error: "turn_end could not resolve the persisted assistant entry ID",
860 });
861 return false;
862 }
863 const toolResultEntryIds = toolResults.flatMap((result) => {
864 const entryId = this._findPersistedMessageEntryId(result);
865 return entryId ? [entryId] : [];
866 });
867 const boundary = await this._extensionRunner.emitBoundary(
868 {
869 type: "turn_end",
870 turnIndex: this._turnIndex,
871 message,
872 toolResults,
873 messageEntryId,
874 toolResultEntryIds,
875 outcome: this._lastActivityOutcome,
876 },
877 (entries) => this._buildBoundaryContext(entries, "turn_end"),
878 );
879 this._commitBoundaryDrafts(boundary.entries);
880 if (boundary.continue && !this._buildBoundaryContext([], "turn_end").canContinue) {
881 this._reportInvalidBoundaryContinuation("turn_end");
882 return false;
883 }
884 return boundary.continue;
885 }
886
887 private _installAgentBoundaryHooks(): void {
888 const previousFinishTurn = this.agent.finishTurn;
889 this.agent.finishTurn = async (turn, signal) => {
890 this._boundaryDispatchedMessages.add(turn.message);
891 const extensionContinue = await this._dispatchTurnEndBoundary(turn.message, turn.toolResults);
892 const previousDecision = await previousFinishTurn?.(turn, signal);
893 if (previousDecision?.action === "end") return previousDecision;
894 if (extensionContinue || previousDecision?.action === "continue") return { action: "continue" };
895 return undefined;
896 };
897 }
898
899 private _installAgentNextTurnRefresh(): void {
900 const previousPrepareNextTurnWithContext =
901 this.agent.prepareNextTurnWithContext ??
902 (this.agent.prepareNextTurn
903 ? async (_turn: PrepareNextTurnContext, signal?: AbortSignal) => await this.agent.prepareNextTurn?.(signal)
904 : undefined);
905 this.agent.prepareNextTurnWithContext = async (turn, signal) => {
906 const context = await this._compactBeforeNextAssistantResponse(turn.context);
907 const previousSnapshot = await previousPrepareNextTurnWithContext?.({ ...turn, context }, signal);
908 const nextContext = previousSnapshot?.context ?? context;
909 const runOptions = this._runSystemPromptOptions ?? this._baseSystemPromptOptions;
910 const options = normalizeBuildSystemPromptOptions({
911 ...runOptions,
912 selectedTools: this.getActiveToolNames(),
913 toolSnippets: { ...this._baseSystemPromptOptions.toolSnippets, ...runOptions.toolSnippets },
914 toolGuidelines: { ...this._baseSystemPromptOptions.toolGuidelines, ...runOptions.toolGuidelines },
915 });
916 const updateMessage = this._preparePromptAndToolLoadout(options, nextContext.messages);
917 // Keep session.systemPrompt and ctx.getSystemPrompt() in step with what the provider sees.
918 this._runSystemPromptOptions = options;
919
920 return {
921 ...previousSnapshot,
922 context: {
923 ...nextContext,
924 tools: this.agent.state.tools.slice(),
925 },
926 messages: updateMessage
927 ? [...(previousSnapshot?.messages ?? []), updateMessage]
928 : previousSnapshot?.messages,
929 model: this.agent.state.model,
930 thinkingLevel: this.agent.state.thinkingLevel,
931 };
932 };
933 }
934
935 // =========================================================================
936 // Event Subscription
937 // =========================================================================
938
939 private _refreshFinalizedContext(): void {
940 const projection = this.sessionManager.buildSessionProjection();
941 for (const entry of projection.entries) {
942 for (const message of entry.messages) this._entryIdsByMessage.set(message, entry.sourceEntry.id);
943 }
944 this.agent.state.messages = projection.messages;
945 }
946
947 private _applyBoundaryDrafts(manager: SessionManager, drafts: SessionBoundaryDraft[]): SessionEntry[] {
948 const appended: SessionEntry[] = [];
949 for (const draft of drafts) {
950 let entryId: string;
951 switch (draft.type) {
952 case "custom":
953 entryId = manager.appendCustomEntry(draft.customType, draft.data);
954 break;
955 case "custom_message":
956 entryId = manager.appendCustomMessageEntry(
957 draft.customType,
958 draft.content,
959 draft.display,
960 draft.details,
961 );
962 break;
963 case "context_edit":
964 entryId = manager.appendContextEdit(draft.targetId, draft.replacement);
965 break;
966 case "compaction": {
967 const tokensBefore = estimateProjectedContextTokens(
968 manager.buildSessionProjection(),
969 manager.getBranch(),
970 ).tokens;
971 entryId = manager.appendCompaction(
972 draft.summary,
973 draft.firstKeptEntryId,
974 tokensBefore,
975 draft.details,
976 true,
977 draft.usage,
978 );
979 break;
980 }
981 }
982 const entry = manager.getEntry(entryId);
983 if (entry) appended.push(entry);
984 }
985 return appended;
986 }
987
988 private _createBoundaryPreviewManager(drafts: SessionBoundaryDraft[]): SessionManager {
989 const header = this.sessionManager.getHeader();
990 if (!header) throw new Error("Session header is missing");
991 const manager = SessionManager.inMemory(this._cwd, undefined, [header, ...this.sessionManager.getBranch()]);
992 this._applyBoundaryDrafts(manager, drafts);
993 return manager;
994 }
995
996 private _getPendingBoundaryMessages(): AgentMessage[] {
997 return [...this.agent.peekQueuedMessages(), ...this._pendingCustomMessages];
998 }
999
1000 private _buildBoundaryContext(
1001 drafts: SessionBoundaryDraft[],
1002 boundary: "turn_end" | "agent_before_settle",
1003 ): BoundaryContextPreview {
1004 const projection = this._createBoundaryPreviewManager(drafts).buildSessionProjection();
1005 const pendingMessages = this._getPendingBoundaryMessages();
1006 const llmMessages = convertToLlm(projection.messages);
1007 const finalRole = llmMessages[llmMessages.length - 1]?.role;
1008 const hasNonSystemContext = llmMessages.some((message) => message.role !== "system");
1009 const contextCanContinue = hasNonSystemContext && finalRole !== "assistant";
1010 const pendingCustomContext = this._pendingCustomMessages.length > 0;
1011 return {
1012 contextEntries: projection.entries,
1013 contextMessages: projection.messages,
1014 llmMessages,
1015 pendingMessages,
1016 canContinue:
1017 contextCanContinue ||
1018 pendingCustomContext ||
1019 (boundary === "turn_end"
1020 ? this.agent.hasQueuedMessages()
1021 : finalRole === "assistant" && this.agent.hasQueuedMessages()),
1022 };
1023 }
1024
1025 private _commitBoundaryDrafts(drafts: SessionBoundaryDraft[]): void {
1026 const appended = this._applyBoundaryDrafts(this.sessionManager, drafts);
1027 this._refreshFinalizedContext();
1028 for (const entry of appended) this._emit({ type: "entry_appended", entry });
1029 }
1030
1031 private _reportInvalidBoundaryContinuation(event: "turn_end" | "agent_before_settle"): void {
1032 this._extensionRunner.emitError({
1033 extensionPath: "<boundary>",
1034 event,
1035 error: `${event} requested continuation without runnable model context`,
1036 });
1037 }
1038
1039 /** Emit an event to all listeners */
1040 private _emit(event: AgentSessionEvent): void {
1041 for (const l of this._eventListeners) {
1042 l(event);
1043 }
1044 }
1045
1046 private _emitQueueUpdate(): void {
1047 this._emit({
1048 type: "queue_update",
1049 steering: [...this._steeringMessages],
1050 followUp: [...this._followUpMessages],
1051 });
1052 }
1053
1054 private async _emitSessionCompactFailed(event: Omit<SessionCompactFailedEvent, "type">): Promise<void> {
1055 if (this._extensionRunner.hasHandlers("session_compact_failed")) {
1056 await this._extensionRunner.emit({ type: "session_compact_failed", ...event });
1057 }
1058 }
1059
1060 private _getIdleWaitPromise(): Promise<void> {
1061 if (!this._idleWaitPromise) {
1062 this._idleWaitPromise = new Promise((resolve) => {
1063 this._resolveIdleWait = resolve;
1064 });
1065 }
1066 return this._idleWaitPromise;
1067 }
1068
1069 private _resolveIdleWaitIfIdle(): void {
1070 if (!this.isIdle || !this._resolveIdleWait) {
1071 return;
1072 }
1073 const resolve = this._resolveIdleWait;
1074 this._idleWaitPromise = undefined;
1075 this._resolveIdleWait = undefined;
1076 resolve();
1077 }
1078
1079 private async _emitAgentSettled(): Promise<void> {
1080 this._cacheWarmer?.onAgentSettled();
1081 this._isAgentRunActive = false;
1082 this._isEmittingAgentSettled = true;
1083 try {
1084 const aborted = this._agentRunAbortRequested;
1085 await this._extensionRunner.emit({ type: "agent_settled", aborted });
1086 this._emit({ type: "agent_settled", aborted });
1087 } finally {
1088 this._isEmittingAgentSettled = false;
1089 }
1090
1091 const deferred = this._deferredSettledActions.splice(0);
1092 if (deferred.length > 0) {
1093 try {
1094 for (const action of deferred) await action();
1095 } finally {
1096 this._resolveIdleWaitIfIdle();
1097 }
1098 return;
1099 }
1100 this._resolveIdleWaitIfIdle();
1101 }
1102
1103 /** Internal handler for agent events - shared by subscribe and reconnect */
1104 private _handleAgentEvent = async (event: AgentEvent): Promise<void> => {
1105 // An abort requested while the run was starting, e.g. during before_agent_start, stops it
1106 // here. agent_start is awaited before the first request.
1107 if (event.type === "agent_start" && this._agentRunAbortRequested) this.agent.abort();
1108 // Record the calls a tool made through ctx.executeTool() and their usage on its result message.
1109 if (this._nestedToolCalls) {
1110 if (event.type === "message_start" && event.message.role === "toolResult") {
1111 const message = event.message;
1112 const summary = this._nestedToolCalls.takeRecord(message.toolCallId);
1113 if (summary?.calls) message.nestedCalls = summary.calls;
1114 if (summary?.usage) {
1115 message.usage = message.usage ? combineUsage(message.usage, summary.usage) : summary.usage;
1116 }
1117 } else if (event.type === "agent_end") {
1118 this._nestedToolCalls.clear();
1119 }
1120 }
1121 // When a user message starts, check if it's from either queue and remove it BEFORE emitting
1122 // This ensures the UI sees the updated queue state
1123 if (event.type === "message_start" && event.message.role === "user") {
1124 this._overflowRecoveryAttempted = false;
1125 const messageText = contentText(event.message.content, "");
1126 if (messageText) {
1127 // Check steering queue first
1128 const steeringIndex = this._steeringMessages.indexOf(messageText);
1129 if (steeringIndex !== -1) {
1130 this._steeringMessages.splice(steeringIndex, 1);
1131 this._emitQueueUpdate();
1132 } else {
1133 // Check follow-up queue
1134 const followUpIndex = this._followUpMessages.indexOf(messageText);
1135 if (followUpIndex !== -1) {
1136 this._followUpMessages.splice(followUpIndex, 1);
1137 this._emitQueueUpdate();
1138 }
1139 }
1140 }
1141 }
1142
1143 // Emit to extensions first, then notify public listeners.
1144 await this._emitExtensionEvent(event);
1145 this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
1146
1147 // Handle session persistence
1148 if (event.type === "message_end") {
1149 let entryId: string | undefined;
1150 // Check if this is a custom message from extensions
1151 if (event.message.role === "custom") {
1152 // Persist as CustomMessageEntry
1153 entryId = this.sessionManager.appendCustomMessageEntry(
1154 event.message.customType,
1155 event.message.content,
1156 event.message.display,
1157 event.message.details,
1158 );
1159 } else if (
1160 event.message.role === "system" ||
1161 event.message.role === "user" ||
1162 event.message.role === "assistant" ||
1163 event.message.role === "toolResult"
1164 ) {
1165 // Regular LLM message - persist as SessionMessageEntry
1166 entryId = this.sessionManager.appendMessage(event.message);
1167 }
1168 if (entryId) this._entryIdsByMessage.set(event.message, entryId);
1169 // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
1170
1171 if (event.message.role === "assistant") {
1172 const assistantMsg = event.message as AssistantMessage;
1173 this._lastAssistantMessage = assistantMsg;
1174 if (assistantMsg.stopReason !== "error" && assistantMsg.stopReason !== "length") {
1175 this._overflowRecoveryAttempted = false;
1176 }
1177
1178 // Reset retry counter immediately on successful assistant response
1179 // This prevents accumulation across multiple LLM calls within a turn
1180 if (assistantMsg.stopReason !== "error" && this._retryAttempt > 0) {
1181 this._emit({
1182 type: "auto_retry_end",
1183 success: true,
1184 attempt: this._retryAttempt,
1185 });
1186 this._retryAttempt = 0;
1187 }
1188 }
1189 }
1190
1191 // A turn ends after its assistant message and every tool result has been appended,
1192 // so this is the first point in the run where a context-only custom message can be
1193 // inserted without landing between a tool call and its result. Flushing after the
1194 // extension and listener dispatch above also picks up messages that turn_end
1195 // handlers queued.
1196 if (event.type === "turn_end") {
1197 this._lastAssistantToolResults = event.toolResults;
1198 this._flushPendingCustomMessages();
1199 }
1200 };
1201
1202 private _willRetryAfterAgentEnd(event: Extract<AgentEvent, { type: "agent_end" }>): boolean {
1203 if (this._agentRunAbortRequested) return false;
1204 const settings = this.settingsManager.getRetrySettings();
1205 if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
1206 return false;
1207 }
1208
1209 for (let i = event.messages.length - 1; i >= 0; i--) {
1210 const message = event.messages[i];
1211 if (message.role === "assistant") {
1212 return this._isRetryableError(message as AssistantMessage);
1213 }
1214 }
1215 return false;
1216 }
1217
1218 private _findPersistedMessageEntryId(message: AgentMessage): string | undefined {
1219 const mapped = this._entryIdsByMessage.get(message);
1220 if (mapped) return mapped;
1221 for (const entry of [...this.sessionManager.getBranch()].reverse()) {
1222 if (entry.type === "message" && entry.message === message) return entry.id;
1223 }
1224
1225 const messageIndex = this.agent.state.messages.indexOf(message);
1226 if (messageIndex < 0) return undefined;
1227 const projection = this.sessionManager.buildSessionProjection();
1228 let projectedIndex = 0;
1229 for (const entry of projection.entries) {
1230 for (let i = 0; i < entry.messages.length; i++) {
1231 if (projectedIndex === messageIndex) {
1232 this._entryIdsByMessage.set(message, entry.sourceEntry.id);
1233 return entry.sourceEntry.id;
1234 }
1235 projectedIndex++;
1236 }
1237 }
1238 return undefined;
1239 }
1240
1241 private _omitRecoveryAttempt(message: AssistantMessage, toolResults: AgentMessage[] = []): void {
1242 const targets = [message, ...toolResults];
1243 const targetIds = targets.map((target) => this._findPersistedMessageEntryId(target));
1244 const unresolvedProjectedTarget = targets.some(
1245 (target, index) => targetIds[index] === undefined && this.agent.state.messages.includes(target),
1246 );
1247 if (unresolvedProjectedTarget) {
1248 throw new Error("Cannot persist recovery omission because a projected message has no source entry");
1249 }
1250 for (const targetId of targetIds) {
1251 if (!targetId) continue;
1252 const editId = this.sessionManager.appendContextEdit(targetId, null);
1253 const entry = this.sessionManager.getEntry(editId);
1254 if (entry) this._emit({ type: "entry_appended", entry });
1255 }
1256 this._refreshFinalizedContext();
1257 }
1258
1259 /** Find the last assistant message in agent state (including aborted ones) */
1260 private _findLastAssistantMessage(): AssistantMessage | undefined {
1261 const messages = this.agent.state.messages;
1262 for (let i = messages.length - 1; i >= 0; i--) {
1263 const msg = messages[i];
1264 if (msg.role === "assistant") {
1265 return msg as AssistantMessage;
1266 }
1267 }
1268 return undefined;
1269 }
1270
1271 private _replaceMessageInPlace(target: AgentMessage, replacement: AgentMessage): void {
1272 // Agent-core stores the finalized message object in its state before emitting message_end.
1273 // SessionManager persistence happens later in _handleAgentEvent() with event.message.
1274 // Mutating this object in place keeps agent state, later turn/agent events, listeners,
1275 // and the eventual SessionManager.appendMessage(event.message) persistence in sync.
1276 if (target === replacement) {
1277 return;
1278 }
1279
1280 const targetRecord = target as unknown as Record<string, unknown>;
1281 for (const key of Object.keys(targetRecord)) {
1282 delete targetRecord[key];
1283 }
1284 Object.assign(targetRecord, replacement);
1285 }
1286
1287 /** Emit extension events based on agent events */
1288 private async _emitExtensionEvent(event: AgentEvent): Promise<void> {
1289 if (event.type === "agent_start") {
1290 this._turnIndex = 0;
1291 await this._extensionRunner.emit({ type: "agent_start" });
1292 } else if (event.type === "agent_end") {
1293 await this._extensionRunner.emit({ type: "agent_end", messages: event.messages });
1294 } else if (event.type === "turn_start") {
1295 const extensionEvent: TurnStartEvent = {
1296 type: "turn_start",
1297 turnIndex: this._turnIndex,
1298 timestamp: Date.now(),
1299 };
1300 await this._extensionRunner.emit(extensionEvent);
1301 } else if (event.type === "turn_end") {
1302 if (event.message.role === "assistant" && !this._boundaryDispatchedMessages.delete(event.message)) {
1303 await this._dispatchTurnEndBoundary(event.message, event.toolResults);
1304 }
1305 this._turnIndex++;
1306 } else if (event.type === "message_start") {
1307 const extensionEvent: MessageStartEvent = {
1308 type: "message_start",
1309 message: event.message,
1310 };
1311 await this._extensionRunner.emit(extensionEvent);
1312 } else if (event.type === "message_update") {
1313 const extensionEvent: MessageUpdateEvent = {
1314 type: "message_update",
1315 message: event.message,
1316 assistantMessageEvent: event.assistantMessageEvent,
1317 };
1318 await this._extensionRunner.emit(extensionEvent);
1319 } else if (event.type === "message_end") {
1320 const extensionEvent: MessageEndEvent = {
1321 type: "message_end",
1322 message: event.message,
1323 };
1324 const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
1325 if (replacement) {
1326 // Untyped extension handlers can return messages with null/missing content;
1327 // normalize so it never enters agent state or session history.
1328 const normalized =
1329 (replacement.role === "user" ||
1330 replacement.role === "assistant" ||
1331 replacement.role === "toolResult" ||
1332 replacement.role === "custom") &&
1333 replacement.content == null
1334 ? ({ ...replacement, content: [] } as AgentMessage)
1335 : replacement;
1336 this._replaceMessageInPlace(event.message, normalized);
1337 }
1338 } else if (event.type === "tool_execution_start") {
1339 const extensionEvent: ToolExecutionStartEvent = {
1340 type: "tool_execution_start",
1341 toolCallId: event.toolCallId,
1342 toolName: event.toolName,
1343 args: event.args,
1344 };
1345 await this._extensionRunner.emit(extensionEvent);
1346 } else if (event.type === "tool_execution_update") {
1347 const extensionEvent: ToolExecutionUpdateEvent = {
1348 type: "tool_execution_update",
1349 toolCallId: event.toolCallId,
1350 toolName: event.toolName,
1351 args: event.args,
1352 partialResult: event.partialResult,
1353 };
1354 await this._extensionRunner.emit(extensionEvent);
1355 } else if (event.type === "tool_execution_end") {
1356 const extensionEvent: ToolExecutionEndEvent = {
1357 type: "tool_execution_end",
1358 toolCallId: event.toolCallId,
1359 toolName: event.toolName,
1360 result: event.result,
1361 isError: event.isError,
1362 ...(event.durationMs === undefined ? {} : { durationMs: event.durationMs }),
1363 };
1364 await this._extensionRunner.emit(extensionEvent);
1365 }
1366 }
1367
1368 /**
1369 * Subscribe to agent events.
1370 * Session persistence is handled internally (saves messages on message_end).
1371 * Multiple listeners can be added. Returns unsubscribe function for this listener.
1372 */
1373 subscribe(listener: AgentSessionEventListener): () => void {
1374 this._eventListeners.push(listener);
1375
1376 // Return unsubscribe function for this specific listener
1377 return () => {
1378 const index = this._eventListeners.indexOf(listener);
1379 if (index !== -1) {
1380 this._eventListeners.splice(index, 1);
1381 }
1382 };
1383 }
1384
1385 /** Disconnect from agent events during disposal. */
1386 private _disconnectFromAgent(): void {
1387 if (this._unsubscribeAgent) {
1388 this._unsubscribeAgent();
1389 this._unsubscribeAgent = undefined;
1390 }
1391 }
1392
1393 /**
1394 * Remove all listeners and disconnect from agent.
1395 * Call this when completely done with the session.
1396 */
1397 dispose(): void {
1398 try {
1399 this.abortRetry();
1400 this.abortCompaction();
1401 this.abortBranchSummary();
1402 this.abortBash();
1403 this.agent.abort();
1404 } catch {
1405 // Dispose must succeed even if an abort hook throws.
1406 }
1407
1408 this._extensionRunner.invalidate(
1409 "This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().",
1410 );
1411 this._disconnectFromAgent();
1412 this._eventListeners = [];
1413 if (this._cacheWarmer) {
1414 this._cacheWarmer.onWarmed = undefined;
1415 this._cacheWarmer.cancel();
1416 }
1417 cleanupSessionResources(this.sessionId);
1418 }
1419
1420 // =========================================================================
1421 // Read-only State Access
1422 // =========================================================================
1423
1424 /** Refresh the public finalized transcript from the canonical session projection. */
1425 refreshContext(): void {
1426 this._refreshFinalizedContext();
1427 }
1428
1429 /** Full agent state */
1430 get state(): AgentState {
1431 return this.agent.state;
1432 }
1433
1434 /** Current cache-warming state and the policy inputs that produced it. */
1435 get cacheWarmingStatus(): CacheWarmingStatus | undefined {
1436 return this._cacheWarmer?.status;
1437 }
1438
1439 /** Persist the cache-warming mode and immediately reconcile active warming. */
1440 setCacheWarmingMode(mode: CacheWarmingMode): void {
1441 this.settingsManager.setCacheWarmingMode(mode);
1442 this._cacheWarmer?.onModeChanged();
1443 }
1444
1445 /** Current model (may be undefined if not yet selected) */
1446 get model(): Model<any> | undefined {
1447 return this.agent.state.model;
1448 }
1449
1450 /** Current thinking level */
1451 get thinkingLevel(): ThinkingLevel {
1452 return this.agent.state.thinkingLevel;
1453 }
1454
1455 /** Under a virtual selection, the physical model and thinking level of the latest successful response. */
1456 get routedModel(): { model: Model<any>; thinkingLevel?: ThinkingLevel } | undefined {
1457 if (!this.model || !isVirtualModel(this.model)) return undefined;
1458 const latest = findLatestResponse(this.agent.state.messages);
1459 const model = latest && this._modelRuntime.getPhysicalModel(latest.provider, latest.model);
1460 return model && { model, thinkingLevel: latest?.thinkingLevel };
1461 }
1462
1463 /** Whether the session is currently processing an agent run or post-run continuation. */
1464 get isStreaming(): boolean {
1465 return this._isAgentRunActive;
1466 }
1467
1468 /** Whether the session has no active agent run, compaction, branch summary, retry, or queued continuation. */
1469 get isIdle(): boolean {
1470 return !this._isAgentRunActive && !this.isCompacting;
1471 }
1472
1473 /** Current effective system prompt, including changes not yet sent to the model. */
1474 get systemPrompt(): string {
1475 return buildSystemPrompt(this._runSystemPromptOptions ?? this._baseSystemPromptOptions);
1476 }
1477
1478 /** Current retry attempt (0 if not retrying) */
1479 get retryAttempt(): number {
1480 return this._retryAttempt;
1481 }
1482
1483 /**
1484 * Get the names of currently active tools, which are the tools declared to the model.
1485 * Tools with `codemode` or `deferred` exposure are callable from other tools without being active.
1486 */
1487 getActiveToolNames(): string[] {
1488 return this.agent.state.tools.map((t) => t.name);
1489 }
1490
1491 /** Get the names of the tools that tools can call through `ctx.executeTool()`. */
1492 getCallableToolNames(): string[] {
1493 return this._getCallableTools().map((t) => t.name);
1494 }
1495
1496 /**
1497 * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.
1498 */
1499 getAllTools(): ToolInfo[] {
1500 return Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({
1501 name: definition.name,
1502 description: definition.description,
1503 parameters: definition.parameters,
1504 promptGuidelines: definition.promptGuidelines,
1505 exposure: this._getToolExposure(definition.name),
1506 ...(definition.namespace ? { namespace: definition.namespace } : {}),
1507 ...(definition.annotations ? { annotations: { ...definition.annotations } } : {}),
1508 ...(definition.reachesTools ? { reachesTools: definition.reachesTools } : {}),
1509 sourceInfo,
1510 }));
1511 }
1512
1513 getToolDefinition(name: string): ToolDefinition | undefined {
1514 return this._toolDefinitions.get(name)?.definition;
1515 }
1516
1517 /**
1518 * Set active tools by name.
1519 * Only tools in the registry can be enabled. Unknown and hidden tool names are ignored.
1520 * Also rebuilds the system prompt to reflect the new tool set.
1521 * Changes take effect on the next agent turn.
1522 */
1523 setActiveToolsByName(toolNames: string[]): void {
1524 const previous = this.getActiveToolNames();
1525 this._setActiveTools(toolNames);
1526 // A loadout that deactivates a tool replaces the restored one, whose pending tools are dropped.
1527 // One that only adds tools, like activating tool_search, keeps them.
1528 const active = new Set(this.getActiveToolNames());
1529 if (previous.some((name) => !active.has(name))) this._pendingToolNames.clear();
1530 }
1531
1532 private _setActiveTools(toolNames: string[]): void {
1533 const tools = this._applyToolLoadout(toolNames);
1534 for (const tool of tools) this._pendingToolNames.delete(tool.name);
1535 this._rebuildSystemPrompt(tools.map((tool) => tool.name));
1536 }
1537
1538 /**
1539 * Whether `--tools` and `--exclude-tools` keep the tool registered. MCP tools stay registered
1540 * unless the allowlist filters them (see `_allowlistFiltersMcp`).
1541 */
1542 private _isAllowedTool(name: string): boolean {
1543 if (this._excludedTools?.(name)) return false;
1544 if (!this._allowedTools || this._allowedTools(name)) return true;
1545 return !this._allowlistFiltersMcp && isMcpToolName(name);
1546 }
1547
1548 /**
1549 * Whether the tool may be active, which declares it to the model. MCP tools the allowlist keeps
1550 * without matching them are only for codemode and tool_search: they may be declared only when
1551 * tool_search can load them (non-`direct` exposure and tool_search registered). This also applies
1552 * to tools restored from the transcript or set by extensions.
1553 */
1554 private _isActivatable(name: string): boolean {
1555 if (!this._allowedTools || this._allowedTools(name) || !isMcpToolName(name)) return true;
1556 return this._getToolExposure(name) !== "direct" && this._toolRegistry.has("tool_search");
1557 }
1558
1559 private _getToolExposure(name: string): ToolExposure {
1560 return this._toolDefinitions.get(name)?.definition.exposure ?? "direct";
1561 }
1562
1563 /**
1564 * Tools callable through `ctx.executeTool()`: the active `direct` tools and every registered
1565 * `codemode` or `deferred` tool.
1566 */
1567 private _getCallableTools(active: ReadonlySet<string> = new Set(this.getActiveToolNames())): AgentTool[] {
1568 return [...this._toolRegistry.values()].filter((tool) => {
1569 const exposure = this._getToolExposure(tool.name);
1570 return exposure === "codemode" || exposure === "deferred" || (exposure === "direct" && active.has(tool.name));
1571 });
1572 }
1573
1574 /**
1575 * Set the agent's tools for the given active tool names and return them. The active tools are
1576 * the registered, non-hidden ones; they are declared to the model. Active tools with a
1577 * `prepareLoadout` hook can change the declared descriptions and hide declarations from
1578 * requests (see {@link _installHiddenDeclarationsProjection}).
1579 */
1580 private _applyToolLoadout(toolNames: string[]): AgentTool[] {
1581 const tools = [...new Set(toolNames)].flatMap((name) => {
1582 const tool = this._toolRegistry.get(name);
1583 return tool && this._getToolExposure(name) !== "hidden" && this._isActivatable(name) ? [tool] : [];
1584 });
1585 const hooks = tools.flatMap((tool) => {
1586 const entry = this._toolDefinitions.get(tool.name);
1587 return entry?.definition.prepareLoadout ? [entry] : [];
1588 });
1589 const hidden = new Set<string>();
1590 let declared = tools;
1591 if (hooks.length > 0) {
1592 const loadout: ToolLoadout = {
1593 declared: tools,
1594 callable: this._getCallableTools(new Set(tools.map((tool) => tool.name))),
1595 registered: [...this._toolRegistry.values()],
1596 getExposure: (name) => this._getToolExposure(name),
1597 getNamespace: (name) => this._toolDefinitions.get(name)?.definition.namespace,
1598 getPromptGuidelines: (name) => this._toolPromptGuidelines.get(name) ?? [],
1599 };
1600 const descriptions = new Map<string, string>();
1601 for (const { definition, sourceInfo } of hooks) {
1602 try {
1603 const changes = definition.prepareLoadout?.(loadout);
1604 for (const [name, description] of Object.entries(changes?.descriptions ?? {})) {
1605 descriptions.set(name, description);
1606 }
1607 for (const name of changes?.hiddenDeclarations ?? []) hidden.add(name);
1608 } catch (error) {
1609 this._extensionRunner.emitError({
1610 extensionPath: sourceInfo.path,
1611 event: "prepare_loadout",
1612 error: error instanceof Error ? error.message : String(error),
1613 stack: error instanceof Error ? error.stack : undefined,
1614 });
1615 }
1616 }
1617 declared = tools.map((tool) => {
1618 const description = descriptions.get(tool.name);
1619 return description === undefined ? tool : { ...tool, description };
1620 });
1621 }
1622 this._hiddenDeclarations = hidden;
1623 this.agent.state.tools = declared;
1624 return declared;
1625 }
1626
1627 /** Whether compaction or branch summarization is currently running */
1628 get isCompacting(): boolean {
1629 return (
1630 this._autoCompactionAbortController !== undefined ||
1631 this._compactionAbortController !== undefined ||
1632 this._branchSummaryAbortController !== undefined
1633 );
1634 }
1635
1636 /** All messages including custom types like BashExecutionMessage */
1637 get messages(): AgentMessage[] {
1638 return this.agent.state.messages;
1639 }
1640
1641 /** Current steering mode */
1642 get steeringMode(): "all" | "one-at-a-time" {
1643 return this.agent.steeringMode;
1644 }
1645
1646 /** Current follow-up mode */
1647 get followUpMode(): "all" | "one-at-a-time" {
1648 return this.agent.followUpMode;
1649 }
1650
1651 /** Current session file path, or undefined if sessions are disabled */
1652 get sessionFile(): string | undefined {
1653 return this.sessionManager.getSessionFile();
1654 }
1655
1656 /** Current session ID */
1657 get sessionId(): string {
1658 return this.sessionManager.getSessionId();
1659 }
1660
1661 /** Current session display name, if set */
1662 get sessionName(): string | undefined {
1663 return this.sessionManager.getSessionName();
1664 }
1665
1666 /** Scoped models for cycling (from --models flag) */
1667 get scopedModels(): ReadonlyArray<{ model: Model<any>; thinkingLevel?: ThinkingLevel }> {
1668 return this._scopedModels;
1669 }
1670
1671 /** Update scoped models for cycling */
1672 setScopedModels(scopedModels: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>): void {
1673 this._scopedModels = scopedModels;
1674 }
1675
1676 /** File-based prompt templates */
1677 get promptTemplates(): ReadonlyArray<PromptTemplate> {
1678 return this._resourceLoader.getPrompts().prompts;
1679 }
1680
1681 private _normalizePromptSnippet(text: string | undefined): string | undefined {
1682 if (!text) return undefined;
1683 const oneLine = text
1684 .replace(/[\r\n]+/g, " ")
1685 .replace(/\s+/g, " ")
1686 .trim();
1687 return oneLine.length > 0 ? oneLine : undefined;
1688 }
1689
1690 private _normalizePromptGuidelines(guidelines: string[] | undefined): string[] {
1691 if (!guidelines || guidelines.length === 0) {
1692 return [];
1693 }
1694
1695 const unique = new Set<string>();
1696 for (const guideline of guidelines) {
1697 const normalized = guideline.trim();
1698 if (normalized.length > 0) {
1699 unique.add(normalized);
1700 }
1701 }
1702 return Array.from(unique);
1703 }
1704
1705 private _rebuildSystemPrompt(toolNames: string[]): void {
1706 const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
1707 const toolSnippets: Record<string, string> = {};
1708 for (const name of this._toolRegistry.keys()) {
1709 const snippet = this._toolPromptSnippets.get(name);
1710 // Tools without a snippet are not listed.
1711 if (snippet) toolSnippets[name] = snippet;
1712 }
1713
1714 const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
1715 const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
1716 const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : "";
1717 const loadedSkills = this._resourceLoader.getSkills().skills;
1718 const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
1719
1720 this._baseSystemPromptOptions = normalizeBuildSystemPromptOptions({
1721 cwd: this._cwd,
1722 skills: loadedSkills,
1723 contextFiles: loadedContextFiles,
1724 customPrompt: loaderSystemPrompt,
1725 appendSystemPrompt,
1726 selectedTools: validToolNames,
1727 hiddenTools: [...this._hiddenDeclarations],
1728 toolSnippets,
1729 toolGuidelines: Object.fromEntries(this._toolPromptGuidelines),
1730 });
1731 }
1732
1733 /**
1734 * Apply a prompt and tool loadout for the next request. Sets the executable tools and
1735 * returns a system message patching the prompt sections the model currently has (replayed
1736 * from `messages`), or undefined when the prompt is unchanged. Tool changes are declared by
1737 * the agent loop before the request.
1738 *
1739 * A forced prompt does not affect the transcript: the structured sections are still diffed
1740 * and persisted, and the forced text is projected onto the request by
1741 * {@link _installAgentForcedPromptProjection}.
1742 */
1743 private _preparePromptAndToolLoadout(
1744 options: NormalizedBuildSystemPromptOptions,
1745 messages: AgentMessage[] = this.agent.state.messages,
1746 ): SystemMessage | undefined {
1747 options.selectedTools = this._applyToolLoadout(options.selectedTools).map((tool) => tool.name);
1748 // The tool list and rules must match the declarations the request carries.
1749 options.hiddenTools = [...this._hiddenDeclarations];
1750 const sections = diffSystemPromptSections(
1751 getCurrentSystemMessage(messages)?.sections ?? {},
1752 buildSystemPromptSections(options),
1753 );
1754 return sections ? { role: "system", content: "", sections, timestamp: Date.now() } : undefined;
1755 }
1756
1757 /**
1758 * Send a forced prompt as the provider's leading system prompt without recording it.
1759 *
1760 * A `before_agent_start` handler that returns `systemPrompt` needs that exact text at the
1761 * head of the request; a mid-conversation system message would leave the original prompt
1762 * in place. The forced text is a rendering of the current prompt, so the transcript keeps
1763 * its structured sections and the request is projected instead: the system messages
1764 * collapse into one head holding the forced text and the current tools. Runs after the
1765 * `context` extension handlers.
1766 */
1767 /**
1768 * Remove the declarations that `prepareLoadout` hooks hide from every request. The whole
1769 * transcript is filtered with the current set, so the projected declarations stay consistent
1770 * across requests and only change when the loadout does.
1771 */
1772 private _installHiddenDeclarationsProjection(): void {
1773 const previousTransformContext = this.agent.transformContext;
1774 this.agent.transformContext = async (messages, signal) => {
1775 const transformed = previousTransformContext ? await previousTransformContext(messages, signal) : messages;
1776 const hidden = this._hiddenDeclarations;
1777 if (hidden.size === 0) return transformed;
1778 return transformed.map((message) => {
1779 if (message.role !== "system" || (!message.toolsAdded && !message.toolsRemoved)) return message;
1780 const { toolsAdded, toolsRemoved, ...rest } = message;
1781 const added = toolsAdded?.filter((tool) => !hidden.has(tool.name)) ?? [];
1782 const removed = toolsRemoved?.filter((tool) => !hidden.has(tool.name)) ?? [];
1783 return {
1784 ...rest,
1785 ...(added.length > 0 ? { toolsAdded: added } : {}),
1786 ...(removed.length > 0 ? { toolsRemoved: removed } : {}),
1787 };
1788 });
1789 };
1790 }
1791
1792 private _installAgentForcedPromptProjection(): void {
1793 const previousTransformContext = this.agent.transformContext;
1794 this.agent.transformContext = async (messages, signal) => {
1795 const transformed = previousTransformContext ? await previousTransformContext(messages, signal) : messages;
1796 const forced = this._runSystemPromptOptions?.forceSystemPrompt;
1797 if (forced === undefined) return transformed;
1798 const current = getCurrentSystemMessage(transformed);
1799 const head: SystemMessage = {
1800 role: "system",
1801 content: forced,
1802 ...(current?.toolsAdded ? { toolsAdded: current.toolsAdded } : {}),
1803 timestamp: current?.timestamp ?? Date.now(),
1804 };
1805 return [head, ...transformed.filter((message) => message.role !== "system")];
1806 };
1807 }
1808
1809 /**
1810 * Restore the active tool loadout declared by the session transcript, if it declares one.
1811 * Tools reachable only from other tools are never declared, but they do not depend on the active
1812 * set, so the transcript's declarations are the whole loadout.
1813 * @param modifiers `+name`/`-name` entries applied to the restored loadout.
1814 */
1815 private _restoreToolsFromTranscript(modifiers: readonly string[] = []): void {
1816 this._pendingToolNames.clear();
1817 const current = getCurrentSystemMessage(this.sessionManager.buildSessionContext().messages);
1818 if (!current) return;
1819 const names = applyToolModifiers(
1820 (current.toolsAdded ?? []).map((tool) => tool.name),
1821 modifiers,
1822 );
1823 this._pendingToolNames = new Set(names.filter((name) => this._isAllowedTool(name)));
1824 this._setActiveTools(names);
1825 }
1826
1827 // =========================================================================
1828 // Prompting
1829 // =========================================================================
1830
1831 /**
1832 * Start a run from a user or custom message. The session counts as busy from here on, so
1833 * messages sent while before_agent_start handlers run are queued into this run instead of
1834 * starting another, and an abort requested meanwhile aborts the run as soon as it exists.
1835 * @param onStarted Called once the run's messages are prepared, before the first request.
1836 */
1837 private async _startRun(trigger: BeforeAgentStartTrigger, onStarted?: () => void): Promise<void> {
1838 this._isAgentRunActive = true;
1839 this._agentRunAbortRequested = false;
1840 let messages: AgentMessage[];
1841 try {
1842 messages = await this._prepareRun(trigger);
1843 } catch (error) {
1844 this._isAgentRunActive = false;
1845 this._flushPendingBashMessages();
1846 this._flushPendingCustomMessages();
1847 this._resolveIdleWaitIfIdle();
1848 throw error;
1849 }
1850 // Messages held while the run was starting go before its starting messages, as they would
1851 // have while idle. No run exists yet, so they cannot split a tool call from its result.
1852 this._flushPendingBashMessages();
1853 this._flushPendingCustomMessages();
1854 onStarted?.();
1855
1856 // Compaction before the prompt may have scheduled a retry; the new prompt replaces it.
1857 this._failedResponse = undefined;
1858 this._recordSelection();
1859 // The run records the loadout in the transcript; restored tools that did not register by now
1860 // are dropped, so a tool that never registers does not stay pending.
1861 this._pendingToolNames.clear();
1862 try {
1863 await this.agent.prompt(messages);
1864 while (!this._agentRunAbortRequested) {
1865 if (await this._handlePostAgentRun()) {
1866 if (this._agentRunAbortRequested) break;
1867 await this.agent.continue();
1868 continue;
1869 }
1870 if (this._agentRunAbortRequested || !(await this._runBeforeSettleBoundary())) break;
1871 if (this._agentRunAbortRequested) break;
1872 await this.agent.continue();
1873 }
1874 } finally {
1875 if (this._agentRunAbortRequested) this._finishCancelledRetry();
1876 this._failedResponse = undefined;
1877 this._runSystemPromptOptions = undefined;
1878 this._flushPendingBashMessages();
1879 this._flushPendingCustomMessages();
1880 await this._emitAgentSettled();
1881 }
1882 }
1883
1884 /**
1885 * Prepare a run and return its starting messages: compact first when needed, emit
1886 * before_agent_start, apply the run's prompt options and tool loadout, and build the starting
1887 * message followed by pending nextTurn messages (consumed here) and handler messages, with a
1888 * system patch first when the prompt changed.
1889 */
1890 private async _prepareRun(trigger: BeforeAgentStartTrigger): Promise<AgentMessage[]> {
1891 // Check if we need to compact before sending (catches aborted responses).
1892 // The starting message is sent below, so do not call agent.continue() here.
1893 const lastAssistant = this._findLastAssistantMessage();
1894 if (lastAssistant) {
1895 await this._checkCompaction(lastAssistant, false);
1896 }
1897
1898 const selectedToolsBefore = this._baseSystemPromptOptions.selectedTools;
1899 const result = await this._extensionRunner.emitBeforeAgentStart(trigger, this._baseSystemPromptOptions);
1900 // Handlers may edit event.systemPromptOptions.selectedTools or call setActiveTools(),
1901 // which updates the live loadout instead. An explicit edit wins; otherwise the live
1902 // loadout is authoritative, so a setActiveTools() call is not undone here.
1903 const handlerEditedTools =
1904 result.systemPromptOptions.selectedTools.length !== selectedToolsBefore.length ||
1905 result.systemPromptOptions.selectedTools.some((name, index) => name !== selectedToolsBefore[index]);
1906 if (!handlerEditedTools) result.systemPromptOptions.selectedTools = this.getActiveToolNames();
1907
1908 const messages: AgentMessage[] = [];
1909 if (trigger.messageType === "custom") {
1910 messages.push(trigger.message);
1911 } else {
1912 // Normalize images after before_agent_start so extension-driven model selection
1913 // determines the resize profile used for the request and history.
1914 const normalized = await this._normalizePromptImages(trigger.images);
1915 const text =
1916 normalized.hints.length > 0 ? `${trigger.prompt}\n\n${normalized.hints.join("\n")}` : trigger.prompt;
1917 messages.push({
1918 role: "user",
1919 content: [{ type: "text", text }, ...normalized.images],
1920 timestamp: Date.now(),
1921 });
1922 }
1923 // Inject any pending "nextTurn" messages as context alongside the starting message
1924 messages.push(...this._pendingNextTurnMessages);
1925 this._pendingNextTurnMessages = [];
1926 for (const msg of result.messages) {
1927 messages.push({
1928 role: "custom",
1929 customType: msg.customType,
1930 // Untyped extensions can pass null/missing content; normalize at ingestion.
1931 content: msg.content ?? [],
1932 display: msg.display,
1933 details: msg.details,
1934 timestamp: Date.now(),
1935 });
1936 }
1937 const updateMessage = this._preparePromptAndToolLoadout(result.systemPromptOptions);
1938 this._runSystemPromptOptions = result.systemPromptOptions;
1939 if (updateMessage) messages.unshift(updateMessage);
1940 return messages;
1941 }
1942
1943 private async _handlePostAgentRun(): Promise<boolean> {
1944 const message = this._lastAssistantMessage;
1945 const toolResults = this._lastAssistantToolResults;
1946 this._lastAssistantMessage = undefined;
1947 this._lastAssistantToolResults = [];
1948 if (this._agentRunAbortRequested) {
1949 this._finishCancelledRetry();
1950 return false;
1951 }
1952 if (!message) return this.agent.hasQueuedMessages();
1953
1954 if (this._isRetryableError(message) && (await this._prepareRetry(message))) {
1955 if (this._agentRunAbortRequested) this._finishCancelledRetry();
1956 this._failedResponse = message;
1957 return !this._agentRunAbortRequested;
1958 }
1959 if (this._agentRunAbortRequested) {
1960 this._finishCancelledRetry();
1961 return false;
1962 }
1963
1964 if (message.stopReason === "error" && this._retryAttempt > 0) {
1965 this._emit({
1966 type: "auto_retry_end",
1967 success: false,
1968 attempt: this._retryAttempt,
1969 finalError: message.errorMessage,
1970 });
1971 this._retryAttempt = 0;
1972 }
1973
1974 if (await this._checkCompaction(message, true, toolResults)) {
1975 return !this._agentRunAbortRequested;
1976 }
1977
1978 // The low-level loop drains both queues before agent_end. Messages queued by
1979 // agent_end handlers require a fresh run before pre-settlement handlers fire.
1980 return !this._agentRunAbortRequested && this.agent.hasQueuedMessages();
1981 }
1982
1983 private async _runBeforeSettleBoundary(): Promise<boolean> {
1984 if (!this._extensionRunner.hasHandlers("agent_before_settle")) return this.agent.hasQueuedMessages();
1985 this._isBeforeSettle = true;
1986 this._abortDuringBeforeSettle = false;
1987 try {
1988 const result = await this._extensionRunner.emitBoundary(
1989 { type: "agent_before_settle", outcome: this._lastActivityOutcome },
1990 (entries) => this._buildBoundaryContext(entries, "agent_before_settle"),
1991 );
1992 this._commitBoundaryDrafts(result.entries);
1993 this._flushPendingCustomMessages();
1994 const finalContext = this._buildBoundaryContext([], "agent_before_settle");
1995 if (this._abortDuringBeforeSettle) return false;
1996 const shouldContinue = result.continue || this.agent.hasQueuedMessages();
1997 if (shouldContinue && !finalContext.canContinue) {
1998 if (result.continue) this._reportInvalidBoundaryContinuation("agent_before_settle");
1999 return false;
2000 }
2001 return shouldContinue;
2002 } finally {
2003 this._isBeforeSettle = false;
2004 }
2005 }
2006
2007 private async _runInputHandlers(
2008 text: string,
2009 images: ImageContent[] | undefined,
2010 source: InputSource,
2011 streamingBehavior?: "steer" | "followUp",
2012 ): Promise<{ text: string; images: ImageContent[] | undefined } | undefined> {
2013 if (!this._extensionRunner.hasHandlers("input")) {
2014 return { text, images };
2015 }
2016
2017 const inputResult = await this._extensionRunner.emitInput(text, images, source, streamingBehavior);
2018 if (inputResult.action === "handled") {
2019 return undefined;
2020 }
2021 if (inputResult.action === "transform") {
2022 return { text: inputResult.text, images: inputResult.images ?? images };
2023 }
2024 return { text, images };
2025 }
2026
2027 private async _normalizePromptImages(
2028 images: ImageContent[] | undefined,
2029 ): Promise<{ images: ImageContent[]; hints: string[] }> {
2030 if (!images) return { images: [], hints: [] };
2031
2032 const normalizedImages: ImageContent[] = [];
2033 const hints: string[] = [];
2034 for (const image of images) {
2035 const processed = await processImage(Buffer.from(image.data, "base64"), image.mimeType, {
2036 autoResizeImages: this.settingsManager.getImageAutoResize(),
2037 resizeOptions: this._limitsModel()?.inputLimits?.images?.resize,
2038 });
2039 if (!processed.ok) {
2040 hints.push(processed.message);
2041 continue;
2042 }
2043 normalizedImages.push({ type: "image", data: processed.data, mimeType: processed.mimeType });
2044 hints.push(...processed.hints);
2045 }
2046 return { images: normalizedImages, hints };
2047 }
2048
2049 /**
2050 * Send a prompt to the agent.
2051 * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
2052 * - Expands file-based prompt templates by default
2053 * - During streaming, queues via steer() or followUp() based on streamingBehavior option
2054 * - Validates model and API key before sending (when not streaming)
2055 * @throws Error if streaming and no streamingBehavior specified
2056 * @throws Error if no model selected or no API key available (when not streaming)
2057 */
2058 async prompt(text: string, options?: PromptOptions): Promise<void> {
2059 if (this._isEmittingAgentSettled) {
2060 this._deferredSettledActions.push(async () => await this.prompt(text, options));
2061 return;
2062 }
2063 const expandPromptTemplates = options?.expandPromptTemplates ?? true;
2064 const preflightResult = options?.preflightResult;
2065 // Handle extension commands first (execute immediately, even during streaming)
2066 // Extension commands manage their own LLM interaction via pi.sendMessage()
2067 if (expandPromptTemplates && text.startsWith("/")) {
2068 const handled = await this._tryExecuteExtensionCommand(text);
2069 if (handled) {
2070 // Extension command executed, no prompt to send
2071 preflightResult?.("handled");
2072 return;
2073 }
2074 }
2075
2076 if (this._compactionAbortController !== undefined) {
2077 throw new Error(
2078 "Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.",
2079 );
2080 }
2081
2082 // Emit input event for extension interception (before skill/template expansion)
2083 const processedInput = await this._runInputHandlers(
2084 text,
2085 options?.images,
2086 options?.source ?? "interactive",
2087 this.isStreaming ? options?.streamingBehavior : undefined,
2088 );
2089 if (!processedInput) {
2090 preflightResult?.("handled");
2091 return;
2092 }
2093 const { text: currentText, images: currentImages } = processedInput;
2094
2095 // Expand skill commands (/skill:name args) and prompt templates (/template args)
2096 let expandedText = currentText;
2097 if (expandPromptTemplates) {
2098 expandedText = this._expandSkillCommand(expandedText);
2099 expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
2100 }
2101
2102 // If streaming, queue via steer() or followUp() based on option
2103 if (this.isStreaming) {
2104 if (!options?.streamingBehavior) {
2105 throw new Error(
2106 "Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.",
2107 );
2108 }
2109 if (options.streamingBehavior === "followUp") {
2110 await this._queueFollowUp(expandedText, currentImages);
2111 } else {
2112 await this._queueSteer(expandedText, currentImages);
2113 }
2114 preflightResult?.("queued");
2115 return;
2116 }
2117
2118 // Validate model
2119 if (!this.model) {
2120 throw new Error(formatNoModelSelectedMessage());
2121 }
2122
2123 const hasConfiguredAuth =
2124 this._modelRuntime.hasConfiguredAuth(this.model.provider) ||
2125 (await this._modelRuntime.checkAuth(this.model.provider)) !== undefined;
2126 if (!hasConfiguredAuth) {
2127 const isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);
2128 if (isOAuth) {
2129 throw new Error(
2130 `Authentication failed for "${this.model.provider}". ` +
2131 `Credentials may have expired or network is unavailable. ` +
2132 `Run '/login ${this.model.provider}' to re-authenticate.`,
2133 );
2134 }
2135 throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
2136 }
2137
2138 await this._startRun({ messageType: "user", prompt: expandedText, images: currentImages }, () =>
2139 preflightResult?.("started"),
2140 );
2141 }
2142
2143 /**
2144 * Try to execute an extension command. Returns true if command was found and executed.
2145 */
2146 private async _tryExecuteExtensionCommand(text: string): Promise<boolean> {
2147 // Parse command name and args
2148 const spaceIndex = text.indexOf(" ");
2149 const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
2150 const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
2151
2152 const command = this._extensionRunner.getCommand(commandName);
2153 if (!command) return false;
2154
2155 // Get command context from extension runner (includes session control methods)
2156 const ctx = this._extensionRunner.createCommandContext();
2157
2158 try {
2159 await command.handler(args, ctx);
2160 return true;
2161 } catch (err) {
2162 // Emit error via extension runner
2163 this._extensionRunner.emitError({
2164 extensionPath: `command:${commandName}`,
2165 event: "command",
2166 error: err instanceof Error ? err.message : String(err),
2167 });
2168 return true;
2169 }
2170 }
2171
2172 /**
2173 * Expand skill commands (/skill:name args) to their full content.
2174 * Returns the expanded text, or the original text if not a skill command or skill not found.
2175 * Emits errors via extension runner if file read fails.
2176 */
2177 private _expandSkillCommand(text: string): string {
2178 if (!text.startsWith("/skill:")) return text;
2179
2180 const spaceIndex = text.indexOf(" ");
2181 const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
2182 const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim();
2183
2184 const skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);
2185 if (!skill) return text; // Unknown skill, pass through
2186
2187 try {
2188 const content = readFileSync(skill.filePath, "utf-8");
2189 const body = stripFrontmatter(content).trim();
2190 const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
2191 return args ? `${skillBlock}\n\n${args}` : skillBlock;
2192 } catch (err) {
2193 // Emit error like extension commands do
2194 this._extensionRunner.emitError({
2195 extensionPath: skill.filePath,
2196 event: "skill_expansion",
2197 error: err instanceof Error ? err.message : String(err),
2198 });
2199 return text; // Return original on error
2200 }
2201 }
2202
2203 private async _queueUserInput(
2204 text: string,
2205 images: ImageContent[] | undefined,
2206 behavior: "steer" | "followUp",
2207 source: InputSource,
2208 ): Promise<QueuedInputDisposition> {
2209 if (text.startsWith("/")) {
2210 this._throwIfExtensionCommand(text);
2211 }
2212
2213 const processedInput = await this._runInputHandlers(
2214 text,
2215 images,
2216 source,
2217 this.isStreaming ? behavior : undefined,
2218 );
2219 if (!processedInput) return "handled";
2220
2221 let expandedText = this._expandSkillCommand(processedInput.text);
2222 expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
2223
2224 if (behavior === "steer") {
2225 await this._queueSteer(expandedText, processedInput.images);
2226 } else {
2227 await this._queueFollowUp(expandedText, processedInput.images);
2228 }
2229 return "queued";
2230 }
2231
2232 /**
2233 * Queue a steering message while the agent is running.
2234 * Delivered after the current assistant turn finishes executing its tool calls,
2235 * before the next LLM call.
2236 * Expands skill commands and prompt templates. Errors on extension commands.
2237 * @param images Optional image attachments to include with the message
2238 * @param options Input source; defaults to interactive
2239 * @throws Error if text is an extension command
2240 */
2241 async steer(
2242 text: string,
2243 images?: ImageContent[],
2244 options?: { source?: InputSource },
2245 ): Promise<QueuedInputDisposition> {
2246 return this._queueUserInput(text, images, "steer", options?.source ?? "interactive");
2247 }
2248
2249 /**
2250 * Queue a follow-up message to be processed after the agent finishes.
2251 * Delivered only when agent has no more tool calls or steering messages.
2252 * Expands skill commands and prompt templates. Errors on extension commands.
2253 * @param images Optional image attachments to include with the message
2254 * @param options Input source; defaults to interactive
2255 * @throws Error if text is an extension command
2256 */
2257 async followUp(
2258 text: string,
2259 images?: ImageContent[],
2260 options?: { source?: InputSource },
2261 ): Promise<QueuedInputDisposition> {
2262 return this._queueUserInput(text, images, "followUp", options?.source ?? "interactive");
2263 }
2264
2265 /**
2266 * Internal: Queue a steering message (already expanded, no extension command check).
2267 */
2268 private async _queueSteer(text: string, images?: ImageContent[]): Promise<void> {
2269 this._steeringMessages.push(text);
2270 this._emitQueueUpdate();
2271 const content: (TextContent | ImageContent)[] = [{ type: "text", text }];
2272 if (images) {
2273 content.push(...images);
2274 }
2275 this.agent.steer({
2276 role: "user",
2277 content,
2278 timestamp: Date.now(),
2279 });
2280 }
2281
2282 /**
2283 * Internal: Queue a follow-up message (already expanded, no extension command check).
2284 */
2285 private async _queueFollowUp(text: string, images?: ImageContent[]): Promise<void> {
2286 this._followUpMessages.push(text);
2287 this._emitQueueUpdate();
2288 const content: (TextContent | ImageContent)[] = [{ type: "text", text }];
2289 if (images) {
2290 content.push(...images);
2291 }
2292 this.agent.followUp({ role: "user", content, timestamp: Date.now() });
2293 }
2294
2295 /**
2296 * Throw an error if the text is an extension command.
2297 */
2298 private _throwIfExtensionCommand(text: string): void {
2299 const spaceIndex = text.indexOf(" ");
2300 const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
2301 const command = this._extensionRunner.getCommand(commandName);
2302
2303 if (command) {
2304 throw new Error(
2305 `Extension command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`,
2306 );
2307 }
2308 }
2309
2310 /**
2311 * Send a custom message to the session. Creates a CustomMessageEntry.
2312 *
2313 * Handles four cases:
2314 * - Streaming: queues message, processed when loop pulls from queue
2315 * - Streaming + triggerTurn false: appended to state/session once the current turn ends
2316 * - Not streaming + triggerTurn: appends to state/session, starts new turn
2317 * - Not streaming + no trigger: appends to state/session, no turn
2318 *
2319 * @param message Custom message with customType, content, display, details
2320 * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
2321 * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
2322 */
2323 async sendCustomMessage<T = unknown>(
2324 message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">,
2325 options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn" },
2326 ): Promise<void> {
2327 const appMessage = {
2328 role: "custom" as const,
2329 customType: message.customType,
2330 // Untyped extensions can pass null/missing content; normalize at ingestion.
2331 content: message.content ?? [],
2332 display: message.display,
2333 details: message.details,
2334 timestamp: Date.now(),
2335 } satisfies CustomMessage<T>;
2336 if (options?.deliverAs === "nextTurn") {
2337 this._pendingNextTurnMessages.push(appMessage);
2338 } else if (this.isStreaming && options?.triggerTurn !== false) {
2339 if (options?.deliverAs === "followUp") {
2340 this.agent.followUp(appMessage);
2341 } else {
2342 this.agent.steer(appMessage);
2343 }
2344 } else if (options?.triggerTurn) {
2345 if (this._isEmittingAgentSettled) {
2346 this._deferredSettledActions.push(async () => await this.sendCustomMessage(message, options));
2347 return;
2348 }
2349 await this._startRun({ messageType: "custom", message: appMessage });
2350 } else if (this.isStreaming) {
2351 // Appending now would put the message between an assistant tool call and its
2352 // result, which providers that validate message order reject on replay. Defer
2353 // to the end of the turn. Nothing is emitted yet: message events must not
2354 // describe messages the session tree does not contain.
2355 this._pendingCustomMessages.push(appMessage);
2356 } else {
2357 this._appendCustomMessage(appMessage);
2358 }
2359 }
2360
2361 private _appendCustomMessage(appMessage: CustomMessage): void {
2362 this.sessionManager.appendCustomMessageEntry(
2363 appMessage.customType,
2364 appMessage.content,
2365 appMessage.display,
2366 appMessage.details,
2367 );
2368 this._refreshFinalizedContext();
2369 this._emit({ type: "message_start", message: appMessage });
2370 this._emit({ type: "message_end", message: appMessage });
2371 }
2372
2373 /**
2374 * Append custom messages queued while the agent was running.
2375 * Called once the current turn's tool results are in agent state and session history.
2376 */
2377 private _flushPendingCustomMessages(): void {
2378 if (this._pendingCustomMessages.length === 0) return;
2379
2380 const pending = this._pendingCustomMessages;
2381 this._pendingCustomMessages = [];
2382 for (const appMessage of pending) {
2383 this._appendCustomMessage(appMessage);
2384 }
2385 }
2386
2387 /**
2388 * Send a user message to the agent. Always triggers a turn.
2389 * When the agent is streaming, use deliverAs to specify how to queue the message.
2390 *
2391 * @param content User message content (string or content array)
2392 * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
2393 * @param options.expandPromptTemplates Whether to dispatch extension commands and expand skill commands and prompt templates. Default: false.
2394 */
2395 async sendUserMessage(
2396 content: string | (TextContent | ImageContent)[],
2397 options?: { deliverAs?: "steer" | "followUp"; expandPromptTemplates?: boolean },
2398 ): Promise<void> {
2399 // Normalize content to text string + optional images
2400 let text: string;
2401 let images: ImageContent[] | undefined;
2402
2403 if (typeof content === "string") {
2404 text = content;
2405 } else {
2406 const textParts: string[] = [];
2407 images = [];
2408 for (const part of content) {
2409 if (part.type === "text") {
2410 textParts.push(part.text);
2411 } else {
2412 images.push(part);
2413 }
2414 }
2415 text = textParts.join("\n");
2416 if (images.length === 0) images = undefined;
2417 }
2418
2419 await this.prompt(text, {
2420 expandPromptTemplates: options?.expandPromptTemplates ?? false,
2421 streamingBehavior: options?.deliverAs,
2422 images,
2423 source: "extension",
2424 });
2425 }
2426
2427 /**
2428 * Clear all queued messages and return them.
2429 * Useful for restoring to editor when user aborts.
2430 * @returns Object with steering and followUp arrays
2431 */
2432 clearQueue(): { steering: string[]; followUp: string[] } {
2433 const steering = [...this._steeringMessages];
2434 const followUp = [...this._followUpMessages];
2435 this._steeringMessages = [];
2436 this._followUpMessages = [];
2437 this.agent.clearAllQueues();
2438 this._emitQueueUpdate();
2439 return { steering, followUp };
2440 }
2441
2442 /** Number of pending messages (includes both steering and follow-up) */
2443 get pendingMessageCount(): number {
2444 return this._steeringMessages.length + this._followUpMessages.length;
2445 }
2446
2447 /** Get pending steering messages (read-only) */
2448 getSteeringMessages(): readonly string[] {
2449 return this._steeringMessages;
2450 }
2451
2452 /** Get pending follow-up messages (read-only) */
2453 getFollowUpMessages(): readonly string[] {
2454 return this._followUpMessages;
2455 }
2456
2457 get resourceLoader(): ResourceLoader {
2458 return this._resourceLoader;
2459 }
2460
2461 /**
2462 * Abort current operation and wait for agent to become idle.
2463 */
2464 async abort(): Promise<void> {
2465 if (this._isAgentRunActive) {
2466 this._agentRunAbortRequested = true;
2467 }
2468 this.abortRetry();
2469 this.abortCompaction();
2470 this.abortBranchSummary();
2471 if (this._isBeforeSettle) this._abortDuringBeforeSettle = true;
2472 this.agent.abort();
2473 await this.waitForIdle();
2474 }
2475
2476 async waitForIdle(): Promise<void> {
2477 if (this.isIdle) {
2478 return;
2479 }
2480 await this._getIdleWaitPromise();
2481 }
2482
2483 // =========================================================================
2484 // Model Management
2485 // =========================================================================
2486
2487 private async _emitModelSelect(
2488 nextModel: Model<any>,
2489 previousModel: Model<any> | undefined,
2490 source: "set" | "cycle" | "restore",
2491 ): Promise<void> {
2492 if (modelsAreEqual(previousModel, nextModel)) return;
2493 await this._extensionRunner.emit({
2494 type: "model_select",
2495 model: nextModel,
2496 previousModel,
2497 source,
2498 });
2499 }
2500
2501 /**
2502 * Set model directly.
2503 * Validates that auth is configured and saves to the session transcript.
2504 * Persists to global defaults only when options.persist is true.
2505 * @throws Error if no auth is configured for the model
2506 */
2507 async setModel(model: Model<any>, options: ModelMutationOptions = {}): Promise<void> {
2508 if (!(await this._modelRuntime.checkAuth(model.provider))) {
2509 throw new Error(`No API key for ${model.provider}/${model.id}`);
2510 }
2511
2512 const previousModel = this.model;
2513 const thinkingLevel = this._getThinkingLevelForModelSwitch(model);
2514 this.agent.state.model = model;
2515 this.sessionManager.appendModelChange(model.provider, model.id);
2516 if (options.persist) {
2517 this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
2518 this._addPersistedDefaultToNonEmptyScope(model);
2519 }
2520
2521 // Apply thinking level for the new model.
2522 // Per-model thinking level overrides take priority over the global default.
2523 // Model persistence does not implicitly rewrite the global thinking default.
2524 this.setThinkingLevel(thinkingLevel);
2525
2526 await this._emitModelSelect(model, previousModel, "set");
2527 }
2528
2529 private _addPersistedDefaultToNonEmptyScope(model: Model<any>): void {
2530 if (this._scopedModels.length === 0) return;
2531 if (this._scopedModels.some((scoped) => modelsAreEqual(scoped.model, model))) return;
2532
2533 this._scopedModels = [...this._scopedModels, { model }];
2534
2535 const enabledModels = this.settingsManager.getEnabledModels();
2536 if (!enabledModels?.length) return;
2537
2538 const modelReference = `${model.provider}/${model.id}`;
2539 if (enabledModels.some((pattern) => pattern.toLowerCase() === modelReference.toLowerCase())) return;
2540 this.settingsManager.setEnabledModels([...enabledModels, modelReference]);
2541 }
2542
2543 /**
2544 * Cycle to next/previous model.
2545 * Uses scoped models (from --models flag) if available, otherwise all available models.
2546 * @param direction - "forward" (default) or "backward"
2547 * @returns The new model info, or undefined if only one model available
2548 */
2549 async cycleModel(
2550 direction: "forward" | "backward" = "forward",
2551 options: ModelMutationOptions = {},
2552 ): Promise<ModelCycleResult | undefined> {
2553 if (this._scopedModels.length > 0) {
2554 return this._cycleScopedModel(direction, options);
2555 }
2556 return this._cycleAvailableModel(direction, options);
2557 }
2558
2559 private async _cycleScopedModel(
2560 direction: "forward" | "backward",
2561 options: ModelMutationOptions,
2562 ): Promise<ModelCycleResult | undefined> {
2563 const availableIds = new Set(
2564 this._modelRuntime.getAvailableSnapshot().map((model) => `${model.provider}\0${model.id}`),
2565 );
2566 const scopedModels = this._scopedModels.filter((scoped) =>
2567 availableIds.has(`${scoped.model.provider}\0${scoped.model.id}`),
2568 );
2569 if (scopedModels.length <= 1) return undefined;
2570
2571 const currentModel = this.model;
2572 let currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
2573
2574 if (currentIndex === -1) currentIndex = 0;
2575 const len = scopedModels.length;
2576 const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
2577 const next = scopedModels[nextIndex];
2578 const thinkingLevel = this._getThinkingLevelForModelSwitch(next.model, next.thinkingLevel);
2579
2580 // Apply model
2581 this.agent.state.model = next.model;
2582 this.sessionManager.appendModelChange(next.model.provider, next.model.id);
2583 if (options.persist) {
2584 this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
2585 this._addPersistedDefaultToNonEmptyScope(next.model);
2586 }
2587
2588 // Apply thinking level for the new model.
2589 // - Explicit scoped model thinking level overrides defaults
2590 // - Per-model thinking level overrides take priority over the global default
2591 // setThinkingLevel clamps to model capabilities.
2592 // Model persistence does not implicitly rewrite the global thinking default.
2593 this.setThinkingLevel(thinkingLevel);
2594
2595 await this._emitModelSelect(next.model, currentModel, "cycle");
2596
2597 return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
2598 }
2599
2600 private async _cycleAvailableModel(
2601 direction: "forward" | "backward",
2602 options: ModelMutationOptions,
2603 ): Promise<ModelCycleResult | undefined> {
2604 const availableModels = this._modelRuntime.getAvailableSnapshot();
2605 if (availableModels.length <= 1) return undefined;
2606
2607 const currentModel = this.model;
2608 let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
2609
2610 if (currentIndex === -1) currentIndex = 0;
2611 const len = availableModels.length;
2612 const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
2613 const nextModel = availableModels[nextIndex];
2614
2615 const thinkingLevel = this._getThinkingLevelForModelSwitch(nextModel);
2616 this.agent.state.model = nextModel;
2617 this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
2618 if (options.persist) {
2619 this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
2620 this._addPersistedDefaultToNonEmptyScope(nextModel);
2621 }
2622
2623 // Apply thinking level for the new model.
2624 // Model persistence does not implicitly rewrite the global thinking default.
2625 this.setThinkingLevel(thinkingLevel);
2626
2627 await this._emitModelSelect(nextModel, currentModel, "cycle");
2628
2629 return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
2630 }
2631
2632 // =========================================================================
2633 // Thinking Level Management
2634 // =========================================================================
2635
2636 /**
2637 * Set thinking level.
2638 * Clamps to model capabilities based on available thinking levels.
2639 * Saves the clamped level to the session transcript only if the level actually changes.
2640 * Persists the requested level to global defaults only when options.persist is true.
2641 */
2642 setThinkingLevel(level: ThinkingLevel, options: ModelMutationOptions = {}): void {
2643 const availableLevels = this.getAvailableThinkingLevels();
2644 const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
2645
2646 // Only persist if actually changing
2647 const previousLevel = this.agent.state.thinkingLevel;
2648 const isChanging = effectiveLevel !== previousLevel;
2649
2650 this.agent.state.thinkingLevel = effectiveLevel;
2651
2652 if (options.persist) {
2653 this.settingsManager.setDefaultThinkingLevel(level);
2654 }
2655
2656 if (isChanging) {
2657 this.sessionManager.appendThinkingLevelChange(effectiveLevel);
2658 this._emit({ type: "thinking_level_changed", level: effectiveLevel });
2659 void this._extensionRunner.emit({
2660 type: "thinking_level_select",
2661 level: effectiveLevel,
2662 previousLevel,
2663 });
2664 }
2665 }
2666
2667 /**
2668 * Cycle to next thinking level.
2669 * @returns New level, or undefined if model doesn't support thinking
2670 */
2671 cycleThinkingLevel(options: ModelMutationOptions = {}): ThinkingLevel | undefined {
2672 if (!this.supportsThinking()) return undefined;
2673
2674 const levels = this.getAvailableThinkingLevels();
2675 const currentIndex = levels.indexOf(this.thinkingLevel);
2676 const nextIndex = (currentIndex + 1) % levels.length;
2677 const nextLevel = levels[nextIndex];
2678
2679 this.setThinkingLevel(nextLevel, options);
2680 return nextLevel;
2681 }
2682
2683 /**
2684 * Get available thinking levels for current model.
2685 * The provider will clamp to what the specific model supports internally.
2686 */
2687 getAvailableThinkingLevels(): ThinkingLevel[] {
2688 if (!this.model) return [...THINKING_LEVEL_OPTIONS];
2689 return getSupportedThinkingLevels(this.model) as ThinkingLevel[];
2690 }
2691
2692 /**
2693 * Check if current model supports thinking/reasoning.
2694 */
2695 supportsThinking(): boolean {
2696 return !!this.model?.reasoning;
2697 }
2698
2699 private _getThinkingLevelForModelSwitch(targetModel?: Model<any>, explicitLevel?: ThinkingLevel): ThinkingLevel {
2700 if (explicitLevel !== undefined) {
2701 return explicitLevel;
2702 }
2703 // Per-model default takes priority when switching to a model that has one
2704 if (targetModel) {
2705 const perModel = this.settingsManager.getModelThinkingLevel(targetModel.provider, targetModel.id);
2706 if (perModel !== undefined) {
2707 return perModel;
2708 }
2709 }
2710 return this.settingsManager.getDefaultThinkingLevel() ?? this.thinkingLevel ?? DEFAULT_THINKING_LEVEL;
2711 }
2712
2713 private _clampThinkingLevel(level: ThinkingLevel, _availableLevels: ThinkingLevel[]): ThinkingLevel {
2714 return this.model ? (clampThinkingLevel(this.model, level) as ThinkingLevel) : "off";
2715 }
2716
2717 // =========================================================================
2718 // Queue Mode Management
2719 // =========================================================================
2720
2721 private syncQueueModesFromSettings(): void {
2722 this.agent.steeringMode = this.settingsManager.getSteeringMode();
2723 this.agent.followUpMode = this.settingsManager.getFollowUpMode();
2724 }
2725
2726 /**
2727 * Set steering message mode.
2728 * Saves to settings.
2729 */
2730 setSteeringMode(mode: "all" | "one-at-a-time"): void {
2731 this.agent.steeringMode = mode;
2732 this.settingsManager.setSteeringMode(mode);
2733 }
2734
2735 /**
2736 * Set follow-up message mode.
2737 * Saves to settings.
2738 */
2739 setFollowUpMode(mode: "all" | "one-at-a-time"): void {
2740 this.agent.followUpMode = mode;
2741 this.settingsManager.setFollowUpMode(mode);
2742 }
2743
2744 // =========================================================================
2745 // Compaction
2746 // =========================================================================
2747
2748 /** Generate Pi's built-in compaction summary for manual and automatic compaction. */
2749 private async _runDefaultCompaction(
2750 preparation: CompactionPreparation,
2751 model: Model<any>,
2752 customInstructions: string | undefined,
2753 signal: AbortSignal,
2754 reason: "manual" | "threshold" | "overflow",
2755 ): Promise<CompactionResult> {
2756 // Resolve the request only when Pi summarizes itself: routing may call models or fail.
2757 const request = await this._getSummarizationRequestAuth(model, signal);
2758 return compact(
2759 preparation,
2760 request.model,
2761 request.apiKey,
2762 request.headers,
2763 customInstructions,
2764 signal,
2765 request.thinkingLevel,
2766 this.agent.streamFunction,
2767 request.env,
2768 this.settingsManager.getRetrySettings(),
2769 this._summarizationRetryCallbacks({ source: "compaction", reason }),
2770 undefined, // sessionId
2771 );
2772 }
2773
2774 private _clearManualCompactionState(): void {
2775 this._compactionAbortController = undefined;
2776 this._resolveIdleWaitIfIdle();
2777 }
2778
2779 /**
2780 * Manually compact the session context.
2781 *
2782 * This is the manual entry point used by `/compact`, RPC, and extensions. It is
2783 * separate from automatic threshold/overflow compaction, which enters through
2784 * `_checkCompaction()` and `_runAutoCompaction()`. After preparation and the
2785 * `session_before_compact` hook, both paths call the lower-level `compact()`
2786 * function imported from `./compaction/index.ts`, unless the hook cancels or
2787 * supplies a custom result.
2788 *
2789 * Aborts the current agent operation first. Manual compaction never retries or
2790 * continues the interrupted agent turn.
2791 *
2792 * @param customInstructions Optional instructions for the compaction summary
2793 */
2794 async compact(customInstructions?: string): Promise<CompactionResult> {
2795 await this.abort();
2796 this._compactionAbortController = new AbortController();
2797 this._emit({ type: "compaction_start", reason: "manual" });
2798 let fromExtension = false;
2799 let cancelledByExtension = false;
2800
2801 try {
2802 const model = this.model;
2803 if (!model) {
2804 throw new Error(formatNoModelSelectedMessage());
2805 }
2806
2807 const settings = this.settingsManager.getCompactionSettings(model);
2808 const pathEntries = this.sessionManager.getBranch();
2809
2810 const preparation = prepareCompaction(pathEntries, settings);
2811 if (!preparation) {
2812 // Check why we can't compact
2813 const lastEntry = pathEntries[pathEntries.length - 1];
2814 if (lastEntry?.type === "compaction") {
2815 throw new Error("Already compacted");
2816 }
2817 throw new Error("Nothing to compact (session too small)");
2818 }
2819
2820 let extensionCompaction: CompactionResult | undefined;
2821
2822 if (this._extensionRunner.hasHandlers("session_before_compact")) {
2823 const result = (await this._extensionRunner.emit({
2824 type: "session_before_compact",
2825 preparation,
2826 branchEntries: pathEntries,
2827 customInstructions,
2828 reason: "manual",
2829 willRetry: false,
2830 signal: this._compactionAbortController.signal,
2831 })) as SessionBeforeCompactResult | undefined;
2832
2833 if (result?.cancel) {
2834 cancelledByExtension = true;
2835 throw new Error("Compaction cancelled");
2836 }
2837
2838 if (result?.compaction) {
2839 extensionCompaction = result.compaction;
2840 fromExtension = true;
2841 }
2842 }
2843
2844 let summary: string;
2845 let firstKeptEntryId: string;
2846 let tokensBefore: number;
2847 let usage: Usage | undefined;
2848 let details: unknown;
2849
2850 if (extensionCompaction) {
2851 // Extension provided compaction content
2852 summary = extensionCompaction.summary;
2853 firstKeptEntryId = extensionCompaction.firstKeptEntryId;
2854 tokensBefore = extensionCompaction.tokensBefore;
2855 usage = extensionCompaction.usage;
2856 details = extensionCompaction.details;
2857 } else {
2858 // Shared default summary generator, also used by automatic compaction.
2859 const result = await this._runDefaultCompaction(
2860 preparation,
2861 model,
2862 customInstructions,
2863 this._compactionAbortController.signal,
2864 "manual",
2865 );
2866 summary = result.summary;
2867 firstKeptEntryId = result.firstKeptEntryId;
2868 tokensBefore = result.tokensBefore;
2869 usage = result.usage;
2870 details = result.details;
2871 }
2872
2873 if (this._compactionAbortController.signal.aborted) {
2874 throw new Error("Compaction cancelled");
2875 }
2876
2877 this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
2878 const newEntries = this.sessionManager.getEntries();
2879 this._refreshFinalizedContext();
2880 const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
2881
2882 // Get the saved compaction entry for the extension event
2883 const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary) as
2884 | CompactionEntry
2885 | undefined;
2886
2887 if (this._extensionRunner && savedCompactionEntry) {
2888 await this._extensionRunner.emit({
2889 type: "session_compact",
2890 compactionEntry: savedCompactionEntry,
2891 fromExtension,
2892 reason: "manual",
2893 willRetry: false,
2894 });
2895 }
2896
2897 const compactionResult: CompactionResult = {
2898 summary,
2899 firstKeptEntryId,
2900 tokensBefore,
2901 estimatedTokensAfter,
2902 usage,
2903 details,
2904 };
2905 // compaction_end listeners may submit queued prompts, so expose idle state before notifying them.
2906 this._clearManualCompactionState();
2907 this._emit({
2908 type: "compaction_end",
2909 reason: "manual",
2910 result: compactionResult,
2911 aborted: false,
2912 willRetry: false,
2913 });
2914 return compactionResult;
2915 } catch (error) {
2916 const message = error instanceof Error ? error.message : String(error);
2917 const aborted = this._compactionAbortController.signal.aborted || cancelledByExtension;
2918 const errorMessage = aborted ? undefined : `Compaction failed: ${message}`;
2919 this._clearManualCompactionState();
2920 this._emit({
2921 type: "compaction_end",
2922 reason: "manual",
2923 result: undefined,
2924 aborted,
2925 willRetry: false,
2926 errorMessage,
2927 });
2928 await this._emitSessionCompactFailed({
2929 reason: "manual",
2930 errorMessage,
2931 aborted,
2932 willRetry: false,
2933 fromExtension,
2934 });
2935 throw error;
2936 } finally {
2937 this._clearManualCompactionState();
2938 }
2939 }
2940
2941 /**
2942 * Cancel in-progress compaction (manual or auto).
2943 */
2944 abortCompaction(): void {
2945 this._compactionAbortController?.abort();
2946 this._autoCompactionAbortController?.abort();
2947 }
2948
2949 /**
2950 * Cancel in-progress branch summarization.
2951 */
2952 abortBranchSummary(): void {
2953 this._branchSummaryAbortController?.abort();
2954 }
2955
2956 /**
2957 * Dispatch automatic compaction after `agent_end` or before prompt submission.
2958 * Manual compaction does not call this method; it enters through `compact()`.
2959 *
2960 * Automatic cases:
2961 * 1. Overflow with retry: a context-overflow error or recoverable length stop;
2962 * remove the failed assistant message, compact, and retry the turn once.
2963 * 2. Overflow without retry: a successful response exceeded the configured
2964 * context window; compact but preserve the completed response.
2965 * 3. Threshold without retry: valid or estimated context usage crossed the
2966 * configured threshold; compact without retrying the completed response.
2967 *
2968 * Each case calls `_runAutoCompaction()`. After preparation and the
2969 * `session_before_compact` hook, that method calls the lower-level `compact()`
2970 * function imported from `./compaction/index.ts`, unless the hook cancels or
2971 * supplies a custom result.
2972 *
2973 * @param assistantMessage The assistant message to check
2974 * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
2975 * @returns Whether the post-run loop should call `agent.continue()` for overflow recovery or queued messages
2976 */
2977 private async _checkCompaction(
2978 assistantMessage: AssistantMessage,
2979 skipAbortedCheck = true,
2980 toolResults: AgentMessage[] = [],
2981 ): Promise<boolean> {
2982 const settings = this.settingsManager.getCompactionSettings(this.model);
2983 if (!settings.enabled) return false;
2984
2985 // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
2986 if (skipAbortedCheck && assistantMessage.stopReason === "aborted") return false;
2987
2988 // Skip overflow check if the message came from a different model.
2989 // This handles the case where user switched from a smaller-context model (e.g. opus)
2990 // to a larger-context model (e.g. codex) - the overflow error from the old model
2991 // shouldn't trigger compaction for the new model. Under a virtual selection, the
2992 // physical model that produced the message supplies the limits.
2993 const messageModel = this._modelForMessage(assistantMessage);
2994 const sameModel = messageModel !== undefined;
2995 const contextWindow = (messageModel ?? this.model)?.contextWindow ?? 0;
2996
2997 // Skip compaction checks if this assistant message is older than the latest
2998 // compaction boundary. This prevents a stale pre-compaction usage/error
2999 // from retriggering compaction on the first prompt after compaction.
3000 const compactionEntry = getLatestCompactionEntry(this.sessionManager.getBranch());
3001 const assistantIsFromBeforeCompaction =
3002 compactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();
3003 if (assistantIsFromBeforeCompaction) {
3004 return false;
3005 }
3006
3007 // Automatic cases 1 and 2: context overflow.
3008 // A length stop is recoverable when output ended below the model's original desired limit,
3009 // independent of the configured context size or any context-clamped provider request limit.
3010 const currentProjection = this.sessionManager.buildSessionProjection();
3011 const assistantEntryId = this._findPersistedMessageEntryId(assistantMessage);
3012 const assistantIsProjected =
3013 assistantEntryId === undefined ||
3014 currentProjection.entries.some(
3015 (entry) =>
3016 entry.sourceEntry.id === assistantEntryId &&
3017 entry.messages.some((message) => message.role === "assistant"),
3018 );
3019 const branch = this.sessionManager.getBranch();
3020 const assistantIndex = assistantEntryId ? branch.findIndex((entry) => entry.id === assistantEntryId) : -1;
3021 const entriesAfterAssistant = assistantIndex >= 0 ? branch.slice(assistantIndex + 1) : [];
3022 const hasPostAssistantContextEdit = entriesAfterAssistant.some((entry) => entry.type === "context_edit");
3023 const latestAssistantEdit = entriesAfterAssistant
3024 .filter(
3025 (entry): entry is ContextEditEntry => entry.type === "context_edit" && entry.targetId === assistantEntryId,
3026 )
3027 .at(-1);
3028 const assistantRetainedForExplicitRecovery =
3029 assistantEntryId === undefined ||
3030 (!entriesAfterAssistant.some((entry) => entry.type === "compaction") &&
3031 latestAssistantEdit?.replacement !== null);
3032 const assistantUsageMatchesProjection = assistantIsProjected && !hasPostAssistantContextEdit;
3033 const explicitOverflow = assistantMessage.stopReason === "error" && isContextOverflow(assistantMessage);
3034 const contextOverflow =
3035 sameModel &&
3036 ((explicitOverflow && assistantRetainedForExplicitRecovery) ||
3037 (assistantUsageMatchesProjection && isContextOverflow(assistantMessage, contextWindow)));
3038 const recoverableLength =
3039 sameModel && assistantIsProjected && isRecoverableLength(assistantMessage, messageModel.maxTokens);
3040 if (contextOverflow || recoverableLength) {
3041 const willRetry = assistantMessage.stopReason !== "stop";
3042
3043 // Case 2: the response completed successfully. Compact, but do not retry because
3044 // agent.continue() cannot continue from a completed assistant response.
3045 if (!willRetry) {
3046 return await this._runAutoCompaction("overflow", false);
3047 }
3048
3049 if (this._overflowRecoveryAttempted) {
3050 const errorMessage = contextOverflow
3051 ? "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model."
3052 : "Truncated response recovery failed after one compact-and-retry attempt.";
3053 this._emit({
3054 type: "compaction_end",
3055 reason: "overflow",
3056 result: undefined,
3057 aborted: false,
3058 willRetry: false,
3059 errorMessage,
3060 });
3061 await this._emitSessionCompactFailed({
3062 reason: "overflow",
3063 errorMessage,
3064 aborted: false,
3065 willRetry: false,
3066 fromExtension: false,
3067 });
3068 return false;
3069 }
3070
3071 // Persistently omit the selected final attempt before post-run recovery compaction.
3072 this._overflowRecoveryAttempted = true;
3073 this._omitRecoveryAttempt(assistantMessage, toolResults);
3074 const retry = await this._runAutoCompaction("overflow", willRetry);
3075 if (retry) this._failedResponse = assistantMessage;
3076 return retry;
3077 }
3078
3079 // Case 3: threshold compaction without retry.
3080 // For error messages or all-zero usage messages, estimate from the last valid response.
3081 // This ensures sessions that hit persistent API errors (e.g. 529) or malformed zero-usage
3082 // responses can still compact and do not reset context accounting.
3083 let contextTokens: number;
3084 const projection = currentProjection;
3085 const hasContextEdits = projection.entries.some((entry) => entry.sourceEntry.type === "context_edit");
3086 const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
3087 if (hasContextEdits) {
3088 contextTokens = estimateProjectedContextTokens(projection, branch).tokens;
3089 } else if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
3090 const messages = this.agent.state.messages;
3091 const estimate = estimateContextTokens(messages);
3092 // Without provider usage, estimate.tokens is the pure message-size estimate.
3093 // Only usage-backed estimates need the stale pre-compaction check.
3094 if (estimate.lastUsageIndex !== null) {
3095 // Verify the usage source is post-compaction. Kept pre-compaction messages
3096 // have stale usage reflecting the old (larger) context and would falsely
3097 // trigger compaction right after one just finished.
3098 const usageMsg = messages[estimate.lastUsageIndex];
3099 if (
3100 compactionEntry &&
3101 usageMsg.role === "assistant" &&
3102 (usageMsg as AssistantMessage).timestamp <= new Date(compactionEntry.timestamp).getTime()
3103 ) {
3104 return false;
3105 }
3106 }
3107 contextTokens = estimate.tokens;
3108 } else {
3109 contextTokens = directContextTokens;
3110 }
3111 if (shouldCompact(contextTokens, contextWindow, settings)) {
3112 return await this._runAutoCompaction("threshold", false);
3113 }
3114 return false;
3115 }
3116
3117 /**
3118 * Execute threshold or overflow compaction. Manual compaction uses
3119 * `AgentSession.compact()` instead. Both paths call the lower-level `compact()`
3120 * function imported from `./compaction/index.ts` after preparation and extension
3121 * interception.
3122 *
3123 * @param reason Automatic trigger selected by `_checkCompaction()`
3124 * @param willRetry Whether to continue the interrupted turn after overflow compaction
3125 * @returns Whether the post-run loop should call `agent.continue()`
3126 */
3127 private async _runAutoCompaction(reason: "overflow" | "threshold", willRetry: boolean): Promise<boolean> {
3128 const model = this.model;
3129 const settings = this.settingsManager.getCompactionSettings(model);
3130 let abortController: AbortController | undefined;
3131 let started = false;
3132 let fromExtension = false;
3133 let cancelledByExtension = false;
3134
3135 try {
3136 if (!model) {
3137 return false;
3138 }
3139
3140 const pathEntries = this.sessionManager.getBranch();
3141 const preparation = prepareCompaction(pathEntries, settings);
3142 if (!preparation) {
3143 return false;
3144 }
3145
3146 abortController = new AbortController();
3147 this._autoCompactionAbortController = abortController;
3148 started = true;
3149 this._emit({ type: "compaction_start", reason });
3150 abortController.signal.throwIfAborted();
3151
3152 let extensionCompaction: CompactionResult | undefined;
3153
3154 if (this._extensionRunner.hasHandlers("session_before_compact")) {
3155 const extensionResult = (await this._extensionRunner.emit({
3156 type: "session_before_compact",
3157 preparation,
3158 branchEntries: pathEntries,
3159 customInstructions: undefined,
3160 reason,
3161 willRetry,
3162 signal: abortController.signal,
3163 })) as SessionBeforeCompactResult | undefined;
3164
3165 if (extensionResult?.cancel) {
3166 cancelledByExtension = true;
3167 throw new Error("Compaction cancelled");
3168 }
3169
3170 if (extensionResult?.compaction) {
3171 extensionCompaction = extensionResult.compaction;
3172 fromExtension = true;
3173 }
3174 }
3175 abortController.signal.throwIfAborted();
3176
3177 let summary: string;
3178 let firstKeptEntryId: string;
3179 let tokensBefore: number;
3180 let usage: Usage | undefined;
3181 let details: unknown;
3182
3183 if (extensionCompaction) {
3184 // Extension provided compaction content
3185 summary = extensionCompaction.summary;
3186 firstKeptEntryId = extensionCompaction.firstKeptEntryId;
3187 tokensBefore = extensionCompaction.tokensBefore;
3188 usage = extensionCompaction.usage;
3189 details = extensionCompaction.details;
3190 } else {
3191 // Shared default summary generator, also used by manual compaction.
3192 const compactResult = await this._runDefaultCompaction(
3193 preparation,
3194 model,
3195 undefined,
3196 abortController.signal,
3197 reason,
3198 );
3199 summary = compactResult.summary;
3200 firstKeptEntryId = compactResult.firstKeptEntryId;
3201 tokensBefore = compactResult.tokensBefore;
3202 usage = compactResult.usage;
3203 details = compactResult.details;
3204 }
3205 abortController.signal.throwIfAborted();
3206
3207 this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
3208 const newEntries = this.sessionManager.getEntries();
3209 this._refreshFinalizedContext();
3210 const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
3211
3212 // Get the saved compaction entry for the extension event
3213 const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary) as
3214 | CompactionEntry
3215 | undefined;
3216
3217 if (this._extensionRunner && savedCompactionEntry) {
3218 await this._extensionRunner.emit({
3219 type: "session_compact",
3220 compactionEntry: savedCompactionEntry,
3221 fromExtension,
3222 reason,
3223 willRetry,
3224 });
3225 }
3226
3227 const result: CompactionResult = {
3228 summary,
3229 firstKeptEntryId,
3230 tokensBefore,
3231 estimatedTokensAfter,
3232 usage,
3233 details,
3234 };
3235 this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
3236
3237 if (willRetry) return true;
3238
3239 // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
3240 // Continue once so queued messages are delivered.
3241 return this.agent.hasQueuedMessages();
3242 } catch (error) {
3243 const message = error instanceof Error ? error.message : "compaction failed";
3244 const aborted = abortController?.signal.aborted === true || cancelledByExtension;
3245 if (started) {
3246 const errorMessage = aborted
3247 ? undefined
3248 : reason === "overflow"
3249 ? `Context overflow recovery failed: ${message}`
3250 : `Auto-compaction failed: ${message}`;
3251 this._emit({
3252 type: "compaction_end",
3253 reason,
3254 result: undefined,
3255 aborted,
3256 willRetry: false,
3257 errorMessage,
3258 });
3259 await this._emitSessionCompactFailed({
3260 reason,
3261 errorMessage,
3262 aborted,
3263 willRetry: false,
3264 fromExtension,
3265 });
3266 }
3267 return false;
3268 } finally {
3269 if (this._autoCompactionAbortController === abortController) {
3270 this._autoCompactionAbortController = undefined;
3271 }
3272 this._resolveIdleWaitIfIdle();
3273 }
3274 }
3275
3276 /**
3277 * Toggle auto-compaction setting.
3278 */
3279 setAutoCompactionEnabled(enabled: boolean): void {
3280 this.settingsManager.setCompactionEnabled(enabled);
3281 }
3282
3283 /** Whether auto-compaction is enabled */
3284 get autoCompactionEnabled(): boolean {
3285 return this.settingsManager.getCompactionEnabled();
3286 }
3287
3288 async bindExtensions(bindings: ExtensionBindings): Promise<void> {
3289 if (bindings.uiContext !== undefined) {
3290 this._extensionUIContext = bindings.uiContext;
3291 }
3292 if (bindings.mode !== undefined) {
3293 this._extensionMode = bindings.mode;
3294 }
3295 if (bindings.commandContextActions !== undefined) {
3296 this._extensionCommandContextActions = bindings.commandContextActions;
3297 }
3298 if (bindings.abortHandler !== undefined) {
3299 this._extensionAbortHandler = bindings.abortHandler;
3300 }
3301 if (bindings.shutdownHandler !== undefined) {
3302 this._extensionShutdownHandler = bindings.shutdownHandler;
3303 }
3304 if (bindings.onError !== undefined) {
3305 this._extensionErrorListener = bindings.onError;
3306 }
3307
3308 this._applyExtensionBindings(this._extensionRunner);
3309 await this._extensionRunner.emit(this._sessionStartEvent);
3310 this._extensionRunner.reportUnhandledMcpServers();
3311 await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
3312 }
3313
3314 private async extendResourcesFromExtensions(reason: "startup" | "reload"): Promise<void> {
3315 if (!this._extensionRunner.hasHandlers("resources_discover")) {
3316 return;
3317 }
3318
3319 const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(
3320 this._cwd,
3321 reason,
3322 );
3323
3324 if (skillPaths.length === 0 && promptPaths.length === 0 && themePaths.length === 0) {
3325 return;
3326 }
3327
3328 const extensionPaths: ResourceExtensionPaths = {
3329 skillPaths: this.buildExtensionResourcePaths(skillPaths),
3330 promptPaths: this.buildExtensionResourcePaths(promptPaths),
3331 themePaths: this.buildExtensionResourcePaths(themePaths),
3332 };
3333
3334 this._resourceLoader.extendResources(extensionPaths);
3335 this._rebuildSystemPrompt(this.getActiveToolNames());
3336 }
3337
3338 private buildExtensionResourcePaths(entries: Array<{ path: string; extensionPath: string }>): Array<{
3339 path: string;
3340 metadata: { source: string; scope: "temporary"; origin: "top-level"; baseDir?: string };
3341 }> {
3342 return entries.map((entry) => {
3343 const source = this.getExtensionSourceLabel(entry.extensionPath);
3344 const baseDir = isSyntheticPath(entry.extensionPath) ? undefined : dirname(entry.extensionPath);
3345 return {
3346 path: entry.path,
3347 metadata: {
3348 source,
3349 scope: "temporary",
3350 origin: "top-level",
3351 baseDir,
3352 },
3353 };
3354 });
3355 }
3356
3357 private getExtensionSourceLabel(extensionPath: string): string {
3358 if (isSyntheticPath(extensionPath)) {
3359 return `extension:${extensionPath.replace(/[<>]/g, "")}`;
3360 }
3361 const base = basename(extensionPath);
3362 const name = base.replace(/\.(ts|js)$/, "");
3363 return `extension:${name}`;
3364 }
3365
3366 private _applyExtensionBindings(runner: ExtensionRunner): void {
3367 runner.setUIContext(this._extensionUIContext, this._extensionMode);
3368 runner.bindCommandContext(this._extensionCommandContextActions);
3369
3370 this._extensionErrorUnsubscriber?.();
3371 this._extensionErrorUnsubscriber = this._extensionErrorListener
3372 ? runner.onError(this._extensionErrorListener)
3373 : undefined;
3374 }
3375
3376 private _refreshCurrentModelFromRegistry(): void {
3377 const currentModel = this.model;
3378 if (!currentModel) {
3379 return;
3380 }
3381
3382 const refreshedModel = this._modelRuntime.getModel(currentModel.provider, currentModel.id);
3383 if (!refreshedModel || refreshedModel === currentModel) {
3384 return;
3385 }
3386
3387 this.agent.state.model = refreshedModel;
3388 }
3389
3390 private _bindExtensionCore(runner: ExtensionRunner): void {
3391 const getCommands = (): SlashCommandInfo[] => {
3392 const extensionCommands: SlashCommandInfo[] = runner.getRegisteredCommands().map((command) => ({
3393 name: command.invocationName,
3394 description: command.description,
3395 source: "extension",
3396 sourceInfo: command.sourceInfo,
3397 }));
3398
3399 const templates: SlashCommandInfo[] = this.promptTemplates.map((template) => ({
3400 name: template.name,
3401 description: template.description,
3402 source: "prompt",
3403 sourceInfo: template.sourceInfo,
3404 }));
3405
3406 const skills: SlashCommandInfo[] = this._resourceLoader.getSkills().skills.map((skill) => ({
3407 name: `skill:${skill.name}`,
3408 description: skill.description,
3409 source: "skill",
3410 sourceInfo: skill.sourceInfo,
3411 }));
3412
3413 return [...extensionCommands, ...templates, ...skills];
3414 };
3415
3416 runner.bindCore(
3417 {
3418 sendMessage: (message, options) => {
3419 this.sendCustomMessage(message, options).catch((err) => {
3420 runner.emitError({
3421 extensionPath: "<runtime>",
3422 event: "send_message",
3423 error: err instanceof Error ? err.message : String(err),
3424 });
3425 });
3426 },
3427 sendUserMessage: (content, options) => {
3428 this.sendUserMessage(content, options).catch((err) => {
3429 runner.emitError({
3430 extensionPath: "<runtime>",
3431 event: "send_user_message",
3432 error: err instanceof Error ? err.message : String(err),
3433 });
3434 });
3435 },
3436 appendEntry: (customType, data) => {
3437 const entryId = this.sessionManager.appendCustomEntry(customType, data);
3438 const entry = this.sessionManager.getEntry(entryId);
3439 if (entry) {
3440 this._emit({ type: "entry_appended", entry });
3441 }
3442 },
3443 setSessionName: (name) => {
3444 this.setSessionName(name);
3445 },
3446 getSessionName: () => {
3447 return this.sessionManager.getSessionName();
3448 },
3449 setLabel: (entryId, label) => {
3450 this.sessionManager.appendLabelChange(entryId, label);
3451 },
3452 getActiveTools: () => this.getActiveToolNames(),
3453 getAllTools: () => this.getAllTools(),
3454 getSettings: () => this.settingsManager.getSettings(),
3455 setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
3456 refreshTools: () => this._refreshToolRegistry(),
3457 getCommands,
3458 setModel: async (model) => {
3459 if (!this._modelRuntime.hasConfiguredAuth(model.provider)) return false;
3460 await this.setModel(model);
3461 return true;
3462 },
3463 getThinkingLevel: () => this.thinkingLevel,
3464 setThinkingLevel: (level) => this.setThinkingLevel(level),
3465 },
3466 {
3467 getModel: () => this.model,
3468 getScopedModels: () => this._scopedModels,
3469 isIdle: () => this.isIdle,
3470 isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
3471 getSignal: () => this.agent.signal,
3472 abort: () => {
3473 if (this._extensionAbortHandler) {
3474 this._extensionAbortHandler();
3475 return;
3476 }
3477 void this.abort();
3478 },
3479 hasPendingMessages: () => this.pendingMessageCount > 0,
3480 shutdown: () => {
3481 this._extensionShutdownHandler?.();
3482 },
3483 getContextUsage: () => this.getContextUsage(),
3484 compact: (options) => {
3485 void (async () => {
3486 try {
3487 const result = await this.compact(options?.customInstructions);
3488 options?.onComplete?.(result);
3489 } catch (error) {
3490 const err = error instanceof Error ? error : new Error(String(error));
3491 options?.onError?.(err);
3492 }
3493 })();
3494 },
3495 getSystemPrompt: () => this.systemPrompt,
3496 getSystemPromptOptions: () => this._baseSystemPromptOptions,
3497 executeTool: (callerId, name, args, options) => this._executeNestedToolCall(callerId, name, args, options),
3498 getCallableTools: () => this._getCallableTools(),
3499 },
3500 {
3501 registerProvider: (name, config) => {
3502 this._modelRuntime.registerProvider(name, config);
3503 this._refreshCurrentModelFromRegistry();
3504 },
3505 registerNativeProvider: (provider) => {
3506 this._modelRuntime.registerNativeProvider(provider);
3507 this._refreshCurrentModelFromRegistry();
3508 },
3509 unregisterProvider: (name) => {
3510 this._modelRuntime.unregisterProvider(name);
3511 this._refreshCurrentModelFromRegistry();
3512 },
3513 registerVirtualModel: (definition) => {
3514 this._modelRuntime.registerVirtualModel(definition);
3515 this._refreshCurrentModelFromRegistry();
3516 },
3517 unregisterVirtualModel: (provider, id) => {
3518 this._modelRuntime.unregisterVirtualModel(provider, id);
3519 this._refreshCurrentModelFromRegistry();
3520 },
3521 },
3522 );
3523 }
3524
3525 private _refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void {
3526 // Tools that were already activated on registration. A tool whose exposure changes to
3527 // `direct` or `model-only` (for example from `hidden`) is activated like a new tool.
3528 const previousActivatedOnRegistration = new Set(
3529 [...this._toolRegistry.keys()].filter((name) => this._isActivatedOnRegistration(name)),
3530 );
3531 const previousActiveToolNames = this.getActiveToolNames();
3532 const allowedTools = this._allowedTools;
3533
3534 const registeredTools = this._extensionRunner.getAllRegisteredTools();
3535 const allCustomTools = [
3536 ...registeredTools,
3537 ...this._customTools.map((definition) => ({
3538 definition,
3539 sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
3540 })),
3541 ].filter((tool) => this._isAllowedTool(tool.definition.name));
3542 const definitionRegistry = new Map<string, ToolDefinitionEntry>(
3543 Array.from(this._baseToolDefinitions.entries())
3544 .filter(([name]) => this._isAllowedTool(name))
3545 .map(([name, definition]) => [
3546 name,
3547 {
3548 definition,
3549 sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${name}`, { source: "builtin" }),
3550 },
3551 ]),
3552 );
3553 for (const tool of allCustomTools) {
3554 definitionRegistry.set(tool.definition.name, {
3555 definition: tool.definition,
3556 sourceInfo: tool.sourceInfo,
3557 });
3558 }
3559 this._toolDefinitions = definitionRegistry;
3560 this._toolPromptSnippets = new Map(
3561 Array.from(definitionRegistry.values())
3562 .map(({ definition }) => {
3563 const snippet = this._normalizePromptSnippet(definition.promptSnippet);
3564 return snippet ? ([definition.name, snippet] as const) : undefined;
3565 })
3566 .filter((entry): entry is readonly [string, string] => entry !== undefined),
3567 );
3568 this._toolPromptGuidelines = new Map(
3569 Array.from(definitionRegistry.values())
3570 .map(({ definition }) => {
3571 const guidelines = this._normalizePromptGuidelines(definition.promptGuidelines);
3572 return guidelines.length > 0 ? ([definition.name, guidelines] as const) : undefined;
3573 })
3574 .filter((entry): entry is readonly [string, string[]] => entry !== undefined),
3575 );
3576 const runner = this._extensionRunner;
3577 const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
3578 const wrappedBuiltInTools = wrapRegisteredTools(
3579 Array.from(this._baseToolDefinitions.values())
3580 .filter((definition) => this._isAllowedTool(definition.name))
3581 .map((definition) => ({
3582 definition,
3583 sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${definition.name}`, {
3584 source: "builtin",
3585 }),
3586 })),
3587 runner,
3588 );
3589
3590 const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
3591 for (const tool of wrappedExtensionTools as AgentTool[]) {
3592 toolRegistry.set(tool.name, tool);
3593 }
3594 this._toolRegistry = toolRegistry;
3595
3596 const nextActiveToolNames = (
3597 options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]
3598 ).filter((name) => this._isAllowedTool(name));
3599
3600 if (allowedTools) {
3601 for (const toolName of this._toolRegistry.keys()) {
3602 // Naming or matching a tool activates it even when it is not active by default. MCP tools
3603 // kept registered without being named stay inactive.
3604 if (allowedTools(toolName) && this._isDeclarable(toolName)) {
3605 nextActiveToolNames.push(toolName);
3606 }
3607 }
3608 } else if (options?.includeAllExtensionTools) {
3609 for (const tool of wrappedExtensionTools) {
3610 if (this._isActivatedOnRegistration(tool.name)) nextActiveToolNames.push(tool.name);
3611 }
3612 } else if (!options?.activeToolNames) {
3613 for (const toolName of this._toolRegistry.keys()) {
3614 if (!previousActivatedOnRegistration.has(toolName) && this._isActivatedOnRegistration(toolName)) {
3615 nextActiveToolNames.push(toolName);
3616 }
3617 }
3618 }
3619 // Pending tools that are registered now become active.
3620 nextActiveToolNames.push(...this._pendingToolNames);
3621
3622 this._setActiveTools([...new Set(nextActiveToolNames)]);
3623 }
3624
3625 /** Whether activating the tool declares it to the model. */
3626 private _isDeclarable(name: string): boolean {
3627 const exposure = this._getToolExposure(name);
3628 return exposure === "direct" || exposure === "model-only";
3629 }
3630
3631 /** Whether registering the tool activates it, which declares it to the model. */
3632 private _isActivatedOnRegistration(name: string): boolean {
3633 return this._isDeclarable(name) && this._toolDefinitions.get(name)?.definition.defaultActive !== false;
3634 }
3635
3636 private _buildRuntime(options: {
3637 activeToolNames?: string[];
3638 flagValues?: Map<string, boolean | string>;
3639 includeAllExtensionTools?: boolean;
3640 }): void {
3641 const autoResizeImages = this.settingsManager.getImageAutoResize();
3642 const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
3643 const shellPath = this.settingsManager.getShellPath();
3644 const baseToolDefinitions = this._baseToolsOverride
3645 ? Object.fromEntries(
3646 Object.entries(this._baseToolsOverride).map(([name, tool]) => [
3647 name,
3648 createToolDefinitionFromAgentTool(tool),
3649 ]),
3650 )
3651 : createAllToolDefinitions(this._cwd, {
3652 read: { autoResizeImages },
3653 bash: { commandPrefix: shellCommandPrefix, shellPath },
3654 });
3655
3656 this._baseToolDefinitions = new Map(
3657 Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool as ToolDefinition]),
3658 );
3659
3660 const extensionsResult = this._resourceLoader.getExtensions();
3661 if (options.flagValues) {
3662 for (const [name, value] of options.flagValues) {
3663 extensionsResult.runtime.flagValues.set(name, value);
3664 }
3665 }
3666
3667 this._extensionRunner = new ExtensionRunner(
3668 extensionsResult.extensions,
3669 extensionsResult.runtime,
3670 this._cwd,
3671 this.sessionManager,
3672 new ModelRegistry(this._modelRuntime),
3673 );
3674 if (this._extensionRunnerRef) {
3675 this._extensionRunnerRef.current = this._extensionRunner;
3676 }
3677 this._bindExtensionCore(this._extensionRunner);
3678 this._applyExtensionBindings(this._extensionRunner);
3679
3680 const defaultActiveToolNames = this._baseToolsOverride
3681 ? Object.keys(this._baseToolsOverride)
3682 : ["read", "bash", "edit", "write"];
3683 const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
3684 this._refreshToolRegistry({
3685 activeToolNames: baseActiveToolNames,
3686 includeAllExtensionTools: options.includeAllExtensionTools,
3687 });
3688 }
3689
3690 async reload(options?: { beforeSessionStart?: () => void | Promise<void> }): Promise<void> {
3691 const oldRunner = this._extensionRunner;
3692 const previousFlagValues = oldRunner.getFlagValues();
3693 await emitSessionShutdownEvent(oldRunner, { type: "session_shutdown", reason: "reload" });
3694 oldRunner.invalidate();
3695 const getDefaultTools = () =>
3696 this._usesDefaultTools
3697 ? applyToolModifiers(
3698 this.settingsManager.getDefaultTools() ?? DEFAULT_TOOL_NAMES,
3699 this._defaultToolModifiers,
3700 )
3701 : [];
3702 const previousDefaultTools = new Set(getDefaultTools());
3703 await this.settingsManager.reload();
3704 this.syncQueueModesFromSettings();
3705 resetApiProviders();
3706 await this._resourceLoader.reload();
3707 // Activate tools newly added to defaultTools. Removed ones stay active, and tools disabled
3708 // during the session stay disabled unless the setting newly adds them.
3709 const addedDefaultTools = getDefaultTools().filter((name) => !previousDefaultTools.has(name));
3710 // Tools the new extensions register later, such as MCP tools, are pending until then.
3711 for (const name of this.getActiveToolNames()) this._pendingToolNames.add(name);
3712 this._buildRuntime({
3713 activeToolNames: [...this.getActiveToolNames(), ...addedDefaultTools],
3714 flagValues: previousFlagValues,
3715 includeAllExtensionTools: true,
3716 });
3717
3718 const hasBindings =
3719 this._extensionUIContext ||
3720 this._extensionCommandContextActions ||
3721 this._extensionShutdownHandler ||
3722 this._extensionErrorListener;
3723 if (hasBindings) {
3724 await options?.beforeSessionStart?.();
3725 await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
3726 this._extensionRunner.reportUnhandledMcpServers();
3727 await this.extendResourcesFromExtensions("reload");
3728 }
3729 }
3730
3731 // =========================================================================
3732 // Auto-Retry
3733 // =========================================================================
3734
3735 /**
3736 * Check if an error is retryable (overloaded, rate limit, server errors).
3737 * Context overflow errors are NOT retryable (handled by compaction instead).
3738 */
3739 private _isRetryableError(message: AssistantMessage): boolean {
3740 // Context overflow is handled by compaction, not retry.
3741 if (isContextOverflow(message, (this._modelForMessage(message) ?? this.model)?.contextWindow ?? 0)) return false;
3742 return isRetryableAssistantError(message);
3743 }
3744
3745 /**
3746 * Retry policy + callbacks shared by compaction and branch-summary summarization calls.
3747 * Uses the same `settings.retry` budget/backoff as agent-turn retries so a single transient
3748 * stream drop no longer fails the whole operation. `source` carries the context
3749 * the TUI needs to render the retry and recreate the underlying indicator.
3750 */
3751 private _summarizationRetryCallbacks(
3752 source: { source: "branchSummary" } | { source: "compaction"; reason: "manual" | "threshold" | "overflow" },
3753 ): RetryCallbacks {
3754 return {
3755 onRetryScheduled: (attempt, maxAttempts, delayMs, errorMessage) => {
3756 this._emit({
3757 type: "summarization_retry_scheduled",
3758 attempt,
3759 maxAttempts,
3760 delayMs,
3761 errorMessage,
3762 });
3763 },
3764 onRetryAttemptStart: () => {
3765 this._emit({
3766 type: "summarization_retry_attempt_start",
3767 ...source,
3768 });
3769 },
3770 onRetryFinished: () => {
3771 this._emit({ type: "summarization_retry_finished" });
3772 },
3773 };
3774 }
3775
3776 private _finishCancelledRetry(): void {
3777 if (this._retryAttempt === 0) return;
3778 const attempt = this._retryAttempt;
3779 this._retryAttempt = 0;
3780 this._emit({
3781 type: "auto_retry_end",
3782 success: false,
3783 attempt,
3784 finalError: "Retry cancelled",
3785 });
3786 }
3787
3788 /**
3789 * Prepare a retryable error for continuation with exponential backoff.
3790 * @returns true if the caller should continue the agent, false otherwise
3791 */
3792 private async _prepareRetry(message: AssistantMessage): Promise<boolean> {
3793 const settings = this.settingsManager.getRetrySettings();
3794 if (!settings.enabled) {
3795 return false;
3796 }
3797
3798 this._retryAttempt++;
3799
3800 if (this._retryAttempt > settings.maxRetries) {
3801 // Preserve the completed attempt count so post-run handling can emit the final failure.
3802 this._retryAttempt--;
3803 return false;
3804 }
3805
3806 const delayMs = retryDelayMs(settings, this._retryAttempt);
3807
3808 this._emit({
3809 type: "auto_retry_start",
3810 attempt: this._retryAttempt,
3811 maxAttempts: settings.maxRetries,
3812 delayMs,
3813 errorMessage: message.errorMessage || "Unknown error",
3814 });
3815
3816 // Keep the failed attempt in raw history while durably omitting it from model projection.
3817 this._omitRecoveryAttempt(message);
3818
3819 // Wait with exponential backoff (abortable)
3820 this._retryAbortController = new AbortController();
3821 try {
3822 await sleep(delayMs, this._retryAbortController.signal);
3823 } catch {
3824 // Aborted during sleep - emit end event so UI can clean up
3825 this._finishCancelledRetry();
3826 return false;
3827 } finally {
3828 this._retryAbortController = undefined;
3829 }
3830
3831 return true;
3832 }
3833
3834 /**
3835 * Cancel in-progress retry.
3836 */
3837 abortRetry(): void {
3838 this._retryAbortController?.abort();
3839 }
3840
3841 /** Whether auto-retry is currently in progress */
3842 get isRetrying(): boolean {
3843 return this._retryAbortController !== undefined;
3844 }
3845
3846 /** Whether auto-retry is enabled */
3847 get autoRetryEnabled(): boolean {
3848 return this.settingsManager.getRetryEnabled();
3849 }
3850
3851 /**
3852 * Toggle auto-retry setting.
3853 */
3854 setAutoRetryEnabled(enabled: boolean): void {
3855 this.settingsManager.setRetryEnabled(enabled);
3856 }
3857
3858 // =========================================================================
3859 // Bash Execution
3860 // =========================================================================
3861
3862 /**
3863 * Execute a bash command.
3864 * Adds result to agent context and session.
3865 * @param command The bash command to execute
3866 * @param onChunk Optional streaming callback for output
3867 * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
3868 * @param options.id Optional identifier included in bash execution update events
3869 * @param options.operations Custom BashOperations for remote execution
3870 */
3871 async executeBash(
3872 command: string,
3873 onChunk?: (chunk: string) => void,
3874 options?: { excludeFromContext?: boolean; id?: string; operations?: BashOperations },
3875 ): Promise<BashResult> {
3876 const abortController = new AbortController();
3877 this._bashAbortControllers.add(abortController);
3878
3879 // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
3880 const prefix = this.settingsManager.getShellCommandPrefix();
3881 const shellPath = this.settingsManager.getShellPath();
3882 const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
3883
3884 try {
3885 const result = await executeBashWithOperations(
3886 resolvedCommand,
3887 this.sessionManager.getCwd(),
3888 options?.operations ?? createLocalBashOperations({ shellPath }),
3889 {
3890 onChunk: (delta) => {
3891 onChunk?.(delta);
3892 this._emit({ type: "bash_execution_update", id: options?.id, delta });
3893 },
3894 signal: abortController.signal,
3895 },
3896 );
3897
3898 this.recordBashResult(command, result, options);
3899 return result;
3900 } finally {
3901 this._bashAbortControllers.delete(abortController);
3902 }
3903 }
3904
3905 /**
3906 * Record a bash execution result in session history.
3907 * Used by executeBash and by extensions that handle bash execution themselves.
3908 */
3909 recordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {
3910 const bashMessage: BashExecutionMessage = {
3911 role: "bashExecution",
3912 command,
3913 output: result.output,
3914 exitCode: result.exitCode,
3915 cancelled: result.cancelled,
3916 truncated: result.truncated,
3917 fullOutputPath: result.fullOutputPath,
3918 timestamp: Date.now(),
3919 excludeFromContext: options?.excludeFromContext,
3920 };
3921
3922 // If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
3923 if (this.isStreaming) {
3924 // Queue for later - will be flushed on agent_end
3925 this._pendingBashMessages.push(bashMessage);
3926 } else {
3927 this.sessionManager.appendMessage(bashMessage);
3928 this._refreshFinalizedContext();
3929 }
3930 }
3931
3932 /**
3933 * Cancel running bash command.
3934 */
3935 abortBash(): void {
3936 for (const abortController of [...this._bashAbortControllers]) {
3937 abortController.abort();
3938 }
3939 }
3940
3941 /** Whether a bash command is currently running */
3942 get isBashRunning(): boolean {
3943 return this._bashAbortControllers.size > 0;
3944 }
3945
3946 /** Whether there are pending bash messages waiting to be flushed */
3947 get hasPendingBashMessages(): boolean {
3948 return this._pendingBashMessages.length > 0;
3949 }
3950
3951 /**
3952 * Flush pending bash messages to agent state and session.
3953 * Called after agent turn completes to maintain proper message ordering.
3954 */
3955 private _flushPendingBashMessages(): void {
3956 if (this._pendingBashMessages.length === 0) return;
3957
3958 for (const bashMessage of this._pendingBashMessages) {
3959 this.sessionManager.appendMessage(bashMessage);
3960 }
3961 this._pendingBashMessages = [];
3962 this._refreshFinalizedContext();
3963 }
3964
3965 // =========================================================================
3966 // Session Management
3967 // =========================================================================
3968
3969 /**
3970 * Set a display name for the current session.
3971 */
3972 setSessionName(name: string): void {
3973 this.sessionManager.appendSessionInfo(name);
3974 const event = { type: "session_info_changed", name: this.sessionManager.getSessionName() } as const;
3975 this._emit(event);
3976 void this._extensionRunner.emit(event);
3977 }
3978
3979 // =========================================================================
3980 // Tree Navigation
3981 // =========================================================================
3982
3983 /**
3984 * Navigate to a different node in the session tree.
3985 * Unlike fork() which creates a new session file, this stays in the same file.
3986 *
3987 * @param targetId The entry ID to navigate to
3988 * @param options.summarize Whether user wants to summarize abandoned branch
3989 * @param options.customInstructions Custom instructions for summarizer
3990 * @param options.replaceInstructions If true, customInstructions replaces the default prompt
3991 * @param options.label Label to attach to the branch summary entry
3992 * @returns Result with editorText (if user message) and cancelled status
3993 */
3994 async navigateTree(
3995 targetId: string,
3996 options: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string } = {},
3997 ): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {
3998 if (this.isStreaming) {
3999 throw new Error("Wait for the current response to finish before navigating the session tree.");
4000 }
4001 if (this.isCompacting) {
4002 throw new Error(
4003 "Wait for the current compaction or tree navigation to finish before navigating the session tree.",
4004 );
4005 }
4006
4007 const oldLeafId = this.sessionManager.getLeafId();
4008
4009 // No-op if already at target
4010 if (targetId === oldLeafId) {
4011 return { cancelled: false };
4012 }
4013
4014 // Model required for summarization
4015 if (options.summarize && !this.model) {
4016 throw new Error("No model available for summarization");
4017 }
4018
4019 const targetEntry = this.sessionManager.getEntry(targetId);
4020 if (!targetEntry) {
4021 throw new Error(`Entry ${targetId} not found`);
4022 }
4023
4024 // Collect entries to summarize (from old leaf to common ancestor)
4025 const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(
4026 this.sessionManager,
4027 oldLeafId,
4028 targetId,
4029 );
4030
4031 // Prepare event data - mutable so extensions can override
4032 let customInstructions = options.customInstructions;
4033 let replaceInstructions = options.replaceInstructions;
4034 let label = options.label;
4035
4036 const preparation: TreePreparation = {
4037 targetId,
4038 oldLeafId,
4039 commonAncestorId,
4040 entriesToSummarize,
4041 userWantsSummary: options.summarize ?? false,
4042 customInstructions,
4043 replaceInstructions,
4044 label,
4045 };
4046
4047 // Set up abort controller for summarization
4048 this._branchSummaryAbortController = new AbortController();
4049
4050 try {
4051 let extensionSummary: { summary: string; details?: unknown; usage?: Usage } | undefined;
4052 let fromExtension = false;
4053
4054 // Emit session_before_tree event
4055 if (this._extensionRunner.hasHandlers("session_before_tree")) {
4056 const result = (await this._extensionRunner.emit({
4057 type: "session_before_tree",
4058 preparation,
4059 signal: this._branchSummaryAbortController.signal,
4060 })) as SessionBeforeTreeResult | undefined;
4061
4062 if (result?.cancel) {
4063 return { cancelled: true };
4064 }
4065
4066 if (result?.summary && options.summarize) {
4067 extensionSummary = result.summary;
4068 fromExtension = true;
4069 }
4070
4071 // Allow extensions to override instructions and label
4072 if (result?.customInstructions !== undefined) {
4073 customInstructions = result.customInstructions;
4074 }
4075 if (result?.replaceInstructions !== undefined) {
4076 replaceInstructions = result.replaceInstructions;
4077 }
4078 if (result?.label !== undefined) {
4079 label = result.label;
4080 }
4081 }
4082
4083 // Run default summarizer if needed
4084 let summaryText: string | undefined;
4085 let summaryDetails: unknown;
4086 let summaryUsage: Usage | undefined;
4087 if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
4088 const signal = this._branchSummaryAbortController.signal;
4089 const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
4090 const result = await generateBranchSummary(entriesToSummarize, {
4091 ...(await this._getSummarizationRequestAuth(this.model!, signal)),
4092 signal,
4093 customInstructions,
4094 replaceInstructions,
4095 reserveTokens: branchSummarySettings.reserveTokens,
4096 streamFn: this.agent.streamFunction,
4097 retry: this.settingsManager.getRetrySettings(),
4098 callbacks: this._summarizationRetryCallbacks({ source: "branchSummary" }),
4099 });
4100 if (result.aborted) {
4101 return { cancelled: true, aborted: true };
4102 }
4103 if (result.error) {
4104 throw new Error(result.error);
4105 }
4106 summaryText = result.summary;
4107 summaryUsage = result.usage;
4108 summaryDetails = {
4109 readFiles: result.readFiles || [],
4110 modifiedFiles: result.modifiedFiles || [],
4111 };
4112 } else if (extensionSummary) {
4113 summaryText = extensionSummary.summary;
4114 summaryDetails = extensionSummary.details;
4115 summaryUsage = extensionSummary.usage;
4116 }
4117
4118 // Determine the new leaf position based on target type
4119 let newLeafId: string | null;
4120 let editorText: string | undefined;
4121
4122 if (targetEntry.type === "message" && targetEntry.message.role === "user") {
4123 // User message: leaf = parent (null if root), text goes to editor
4124 newLeafId = targetEntry.parentId;
4125 editorText = contentText(targetEntry.message.content, "");
4126 } else if (targetEntry.type === "custom_message") {
4127 // Custom message: leaf = parent (null if root), text goes to editor
4128 newLeafId = targetEntry.parentId;
4129 editorText = contentText(targetEntry.content, "");
4130 } else {
4131 // Non-user message: leaf = selected node
4132 newLeafId = targetId;
4133 }
4134
4135 // Switch leaf (with or without summary)
4136 // Summary is attached at the navigation target position (newLeafId), not the old branch
4137 let summaryEntry: BranchSummaryEntry | undefined;
4138 if (summaryText) {
4139 // Create summary at target position (can be null for root)
4140 const summaryId = this.sessionManager.branchWithSummary(
4141 newLeafId,
4142 summaryText,
4143 summaryDetails,
4144 fromExtension,
4145 summaryUsage,
4146 );
4147 summaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;
4148
4149 // Attach label to the summary entry
4150 if (label) {
4151 this.sessionManager.appendLabelChange(summaryId, label);
4152 }
4153 } else if (newLeafId === null) {
4154 // No summary, navigating to root - reset leaf
4155 this.sessionManager.resetLeaf();
4156 } else {
4157 // No summary, navigating to non-root
4158 this.sessionManager.branch(newLeafId);
4159 }
4160
4161 // Attach label to target entry when not summarizing (no summary entry to label)
4162 if (label && !summaryText) {
4163 this.sessionManager.appendLabelChange(targetId, label);
4164 }
4165
4166 // Update finalized context from the canonical session projection.
4167 this._refreshFinalizedContext();
4168 this._restoreToolsFromTranscript();
4169
4170 // Emit session_tree event
4171 await this._extensionRunner.emit({
4172 type: "session_tree",
4173 newLeafId: this.sessionManager.getLeafId(),
4174 oldLeafId,
4175 summaryEntry,
4176 fromExtension: summaryText ? fromExtension : undefined,
4177 });
4178
4179 // Emit to custom tools
4180
4181 return { editorText, cancelled: false, summaryEntry };
4182 } finally {
4183 this._branchSummaryAbortController = undefined;
4184 this._resolveIdleWaitIfIdle();
4185 }
4186 }
4187
4188 /**
4189 * Get all user messages from session for fork selector.
4190 */
4191 getUserMessagesForForking(): Array<{ entryId: string; text: string }> {
4192 const entries = this.sessionManager.getEntries();
4193 const result: Array<{ entryId: string; text: string }> = [];
4194
4195 for (const entry of entries) {
4196 if (entry.type !== "message") continue;
4197 if (entry.message.role !== "user") continue;
4198
4199 const text = contentText(entry.message.content, "");
4200 if (text) {
4201 result.push({ entryId: entry.id, text });
4202 }
4203 }
4204
4205 return result;
4206 }
4207
4208 /**
4209 * Get session statistics. Aggregates over ALL session entries (including
4210 * history that was compacted away), so token/cost totals reflect what was
4211 * actually billed across the session.
4212 */
4213 getSessionStats(): SessionStats {
4214 let userMessages = 0;
4215 let assistantMessages = 0;
4216 let toolResults = 0;
4217 let totalMessages = 0;
4218 let toolCalls = 0;
4219 const usageTotals = createUsageTotals();
4220
4221 for (const entry of this.sessionManager.getEntries()) {
4222 if (entry.type === "usage") {
4223 addUsageToTotals(usageTotals, entry.usage);
4224 } else if ((entry.type === "branch_summary" || entry.type === "compaction") && entry.usage) {
4225 addUsageToTotals(usageTotals, entry.usage);
4226 }
4227 if (entry.type !== "message") continue;
4228 totalMessages++;
4229 const message = entry.message;
4230 if (message.role === "user") {
4231 userMessages++;
4232 } else if (message.role === "toolResult") {
4233 toolResults++;
4234 if (message.usage) {
4235 addUsageToTotals(usageTotals, message.usage);
4236 }
4237 } else if (message.role === "assistant") {
4238 assistantMessages++;
4239 const assistantMsg = message as AssistantMessage;
4240 if (Array.isArray(assistantMsg.content)) {
4241 toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
4242 }
4243 addUsageToTotals(usageTotals, assistantMsg.usage);
4244 }
4245 }
4246
4247 return {
4248 sessionFile: this.sessionFile,
4249 sessionId: this.sessionId,
4250 userMessages,
4251 assistantMessages,
4252 toolCalls,
4253 toolResults,
4254 totalMessages,
4255 tokens: {
4256 input: usageTotals.input,
4257 output: usageTotals.output,
4258 cacheRead: usageTotals.cacheRead,
4259 cacheWrite: usageTotals.cacheWrite,
4260 total: usageTotals.input + usageTotals.output + usageTotals.cacheRead + usageTotals.cacheWrite,
4261 },
4262 cost: usageTotals.cost,
4263 contextUsage: this.getContextUsage(),
4264 };
4265 }
4266
4267 getContextUsage(): ContextUsage | undefined {
4268 const model = this._limitsModel();
4269 if (!model) return undefined;
4270
4271 const contextWindow = model.contextWindow ?? 0;
4272 if (contextWindow <= 0) return undefined;
4273
4274 // After compaction, the last assistant usage reflects pre-compaction context size.
4275 // We can only trust usage from an assistant that responded after the latest compaction.
4276 // If no such assistant exists, context token count is unknown until the next LLM response.
4277 const projection = this.sessionManager.buildSessionProjection();
4278 const branch = this.sessionManager.getBranch();
4279 const latestCompaction = getLatestCompactionEntry(branch);
4280
4281 if (latestCompaction) {
4282 const projectedAssistants = new Set(
4283 projection.entries.flatMap((entry) =>
4284 entry.messages.some(
4285 (message) =>
4286 message.role === "assistant" &&
4287 message.stopReason !== "aborted" &&
4288 message.stopReason !== "error" &&
4289 calculateContextTokens(message.usage) > 0,
4290 )
4291 ? [entry.sourceEntry.id]
4292 : [],
4293 ),
4294 );
4295 const compactionIndex = branch.findIndex((entry) => entry.id === latestCompaction.id);
4296 const hasPostCompactionUsage = branch
4297 .slice(compactionIndex + 1)
4298 .some((entry) => projectedAssistants.has(entry.id));
4299 if (!hasPostCompactionUsage) return { tokens: null, contextWindow, percent: null };
4300 }
4301
4302 const estimate = estimateProjectedContextTokens(projection, branch);
4303 const percent = (estimate.tokens / contextWindow) * 100;
4304
4305 return {
4306 tokens: estimate.tokens,
4307 contextWindow,
4308 percent,
4309 };
4310 }
4311
4312 /**
4313 * Export session to HTML.
4314 * @param outputPath Optional output path (defaults to session directory)
4315 * @param options Optional export presentation settings
4316 * @returns Path to exported file
4317 */
4318 async exportToHtml(outputPath?: string, options: { themeName?: string } = {}): Promise<string> {
4319 const themeName = [options.themeName, this.settingsManager.getTheme()].find(
4320 (candidate) => candidate !== undefined && getThemeByName(candidate) !== undefined,
4321 );
4322
4323 // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
4324 const toolRenderer: ToolHtmlRenderer = createToolHtmlRenderer({
4325 getToolRenderers: (name) =>
4326 this._extensionRunner.resolveToolRenderers(name, () => this.getToolDefinition(name)),
4327 theme,
4328 cwd: this.sessionManager.getCwd(),
4329 });
4330
4331 return await exportSessionToHtml(this.sessionManager, this.state, {
4332 outputPath,
4333 themeName,
4334 toolRenderer,
4335 });
4336 }
4337
4338 /**
4339 * Export the current session branch to a JSONL file.
4340 * Writes the session header followed by all entries on the current branch path.
4341 * @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
4342 * @returns The resolved output file path.
4343 */
4344 exportToJsonl(outputPath?: string): string {
4345 return exportSessionToJsonl(this.sessionManager, outputPath);
4346 }
4347
4348 /**
4349 * Ask the current model to describe what went wrong in this session for a bug report.
4350 * Used when the user declines to share the transcript itself.
4351 */
4352 async summarizeForBugReport(options: { hint?: string; signal: AbortSignal }): Promise<string> {
4353 const model = this.model;
4354 if (!model) {
4355 throw new Error("No model selected");
4356 }
4357 return generateBugReportSummary({
4358 ...(await this._getSummarizationRequestAuth(model, options.signal)),
4359 messages: this.messages,
4360 hint: options.hint,
4361 signal: options.signal,
4362 streamFn: this.agent.streamFunction,
4363 retry: this.settingsManager.getRetrySettings(),
4364 sessionId: this.sessionId,
4365 });
4366 }
4367
4368 // =========================================================================
4369 // Utilities
4370 // =========================================================================
4371
4372 /**
4373 * Get text content of last assistant message.
4374 * Useful for /copy command.
4375 * @returns Text content, or undefined if no assistant message exists
4376 */
4377 getLastAssistantText(): string | undefined {
4378 const lastAssistant = this.messages
4379 .slice()
4380 .reverse()
4381 .find((m) => {
4382 if (m.role !== "assistant") return false;
4383 const msg = m as AssistantMessage;
4384 // Skip aborted messages with no content
4385 if (msg.stopReason === "aborted" && msg.content.length === 0) return false;
4386 return true;
4387 });
4388
4389 if (!lastAssistant) return undefined;
4390
4391 let text = "";
4392 for (const content of (lastAssistant as AssistantMessage).content) {
4393 if (content.type === "text") {
4394 text += content.text;
4395 }
4396 }
4397
4398 return text.trim() || undefined;
4399 }
4400
4401 // =========================================================================
4402 // Extension System
4403 // =========================================================================
4404
4405 createReplacedSessionContext(): ReplacedSessionContext {
4406 const context = Object.defineProperties(
4407 {},
4408 Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()),
4409 ) as ReplacedSessionContext;
4410 context.sendMessage = (message, options) => this.sendCustomMessage(message, options);
4411 context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
4412 return context;
4413 }
4414
4415 /**
4416 * Check if extensions have handlers for a specific event type.
4417 */
4418 hasExtensionHandlers(eventType: string): boolean {
4419 return this._extensionRunner.hasHandlers(eventType);
4420 }
4421
4422 /**
4423 * Get the extension runner (for setting UI context and error handlers).
4424 */
4425 get extensionRunner(): ExtensionRunner {
4426 return this._extensionRunner;
4427 }
4428}