@muha-sdk/pi-adapter 0.0.0-stage → 0.1.14

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