@linxiraos/pi-agent-core 1.0.0

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.
Files changed (71) hide show
  1. package/CHANGELOG.md +1263 -0
  2. package/README.md +473 -0
  3. package/dist/types/agent-loop.d.ts +137 -0
  4. package/dist/types/agent.d.ts +465 -0
  5. package/dist/types/append-only-context.d.ts +131 -0
  6. package/dist/types/compaction/branch-summarization.d.ts +101 -0
  7. package/dist/types/compaction/compaction-v2-streaming.d.ts +85 -0
  8. package/dist/types/compaction/compaction.d.ts +307 -0
  9. package/dist/types/compaction/entries.d.ts +111 -0
  10. package/dist/types/compaction/errors.d.ts +38 -0
  11. package/dist/types/compaction/index.d.ts +13 -0
  12. package/dist/types/compaction/message-cache.d.ts +23 -0
  13. package/dist/types/compaction/messages.d.ts +79 -0
  14. package/dist/types/compaction/openai.d.ts +117 -0
  15. package/dist/types/compaction/pruning.d.ts +105 -0
  16. package/dist/types/compaction/shake.d.ts +97 -0
  17. package/dist/types/compaction/tool-protection.d.ts +19 -0
  18. package/dist/types/compaction/utils.d.ts +61 -0
  19. package/dist/types/compaction.d.ts +1 -0
  20. package/dist/types/index.d.ts +13 -0
  21. package/dist/types/pause.d.ts +46 -0
  22. package/dist/types/proxy.d.ts +91 -0
  23. package/dist/types/replay-policy.d.ts +5 -0
  24. package/dist/types/run-collector.d.ts +196 -0
  25. package/dist/types/telemetry.d.ts +608 -0
  26. package/dist/types/thinking.d.ts +18 -0
  27. package/dist/types/tokenizer.d.ts +2 -0
  28. package/dist/types/types.d.ts +781 -0
  29. package/dist/types/utils/yield.d.ts +71 -0
  30. package/package.json +79 -0
  31. package/src/agent-loop.ts +2926 -0
  32. package/src/agent.ts +1748 -0
  33. package/src/append-only-context.ts +348 -0
  34. package/src/compaction/branch-summarization.ts +369 -0
  35. package/src/compaction/compaction-v2-streaming.ts +846 -0
  36. package/src/compaction/compaction.ts +1733 -0
  37. package/src/compaction/entries.ts +141 -0
  38. package/src/compaction/errors.ts +47 -0
  39. package/src/compaction/index.ts +14 -0
  40. package/src/compaction/message-cache.ts +92 -0
  41. package/src/compaction/messages.ts +241 -0
  42. package/src/compaction/openai.ts +992 -0
  43. package/src/compaction/prompts/auto-handoff-threshold-focus.md +1 -0
  44. package/src/compaction/prompts/branch-summary-context.md +5 -0
  45. package/src/compaction/prompts/branch-summary-preamble.md +2 -0
  46. package/src/compaction/prompts/branch-summary.md +30 -0
  47. package/src/compaction/prompts/compaction-short-summary.md +9 -0
  48. package/src/compaction/prompts/compaction-summary-context.md +5 -0
  49. package/src/compaction/prompts/compaction-summary.md +38 -0
  50. package/src/compaction/prompts/compaction-turn-prefix.md +17 -0
  51. package/src/compaction/prompts/compaction-update-summary.md +45 -0
  52. package/src/compaction/prompts/context-window-truncated-output.md +1 -0
  53. package/src/compaction/prompts/file-operations.md +5 -0
  54. package/src/compaction/prompts/handoff-document.md +49 -0
  55. package/src/compaction/prompts/snapcompact-archive-context.md +3 -0
  56. package/src/compaction/prompts/summarization-system.md +3 -0
  57. package/src/compaction/pruning.ts +427 -0
  58. package/src/compaction/shake.ts +446 -0
  59. package/src/compaction/tool-protection.ts +65 -0
  60. package/src/compaction/utils.ts +343 -0
  61. package/src/compaction.ts +1 -0
  62. package/src/index.ts +26 -0
  63. package/src/pause.ts +107 -0
  64. package/src/proxy.ts +391 -0
  65. package/src/replay-policy.ts +13 -0
  66. package/src/run-collector.ts +631 -0
  67. package/src/telemetry.ts +2078 -0
  68. package/src/thinking.ts +20 -0
  69. package/src/tokenizer.ts +27 -0
  70. package/src/types.ts +875 -0
  71. package/src/utils/yield.ts +183 -0
package/src/agent.ts ADDED
@@ -0,0 +1,1748 @@
1
+ /** Agent class that uses the agent-loop directly.
2
+ * No transport abstraction - calls streamSimple via the loop.
3
+ */
4
+ import { isPromise } from "node:util/types";
5
+ import {
6
+ type ApiKey,
7
+ type AssistantMessage,
8
+ type AssistantMessageEvent,
9
+ type Context,
10
+ type CursorExecHandlers,
11
+ type CursorToolResultHandler,
12
+ type Effort,
13
+ type ImageContent,
14
+ type Message,
15
+ type Model,
16
+ type ProviderSessionState,
17
+ type ServiceTier,
18
+ type SimpleStreamOptions,
19
+ streamSimple,
20
+ type TextContent,
21
+ type ThinkingBudgets,
22
+ type ToolChoice,
23
+ type ToolResultMessage,
24
+ } from "@linxiraos/pi-ai";
25
+ import type { Dialect } from "@linxiraos/pi-ai/dialect";
26
+ import type { HarmonyAuditEvent } from "@linxiraos/pi-ai/utils/harmony-leak";
27
+ import { getBundledModel } from "@linxiraos/pi-catalog/models";
28
+ import { logger } from "@linxiraos/pi-utils";
29
+ import {
30
+ abortReasonText,
31
+ agentLoop,
32
+ agentLoopContinue,
33
+ createSyntheticToolResultMessage,
34
+ normalizeMessagesForProvider,
35
+ normalizeTools,
36
+ resolveOwnedDialectFromEnv,
37
+ } from "./agent-loop";
38
+ import type { AppendOnlyContextManager } from "./append-only-context";
39
+ import { isProviderRefusalMessage } from "./replay-policy";
40
+ import type {
41
+ AgentBeforeModelCall,
42
+ AgentContext,
43
+ AgentEvent,
44
+ AgentLoopConfig,
45
+ AgentMessage,
46
+ AgentState,
47
+ AgentTool,
48
+ AgentToolContext,
49
+ AgentTurnEndContext,
50
+ AsideMessage,
51
+ StreamFn,
52
+ ToolCallContext,
53
+ ToolChoiceDirective,
54
+ } from "./types";
55
+ import { isSoftToolRequirement } from "./types";
56
+ import { EventLoopKeepalive } from "./utils/yield";
57
+
58
+ /**
59
+ * Default convertToLlm: Keep only LLM-compatible replay messages.
60
+ */
61
+ function defaultConvertToLlm(messages: AgentMessage[]): Message[] {
62
+ return messages.filter((m): m is Message => {
63
+ if (m.role === "assistant") return !isProviderRefusalMessage(m);
64
+ return m.role === "user" || m.role === "toolResult";
65
+ });
66
+ }
67
+
68
+ function refreshToolChoiceForActiveTools(
69
+ toolChoice: ToolChoice | undefined,
70
+ tools: AgentContext["tools"] = [],
71
+ ): ToolChoice | undefined {
72
+ if (!toolChoice || typeof toolChoice === "string") {
73
+ return toolChoice;
74
+ }
75
+ if (toolChoice.type === "computer") {
76
+ return tools.some(tool => tool.native?.type === "computer") ? toolChoice : undefined;
77
+ }
78
+
79
+ const toolName =
80
+ toolChoice.type === "tool"
81
+ ? toolChoice.name
82
+ : "function" in toolChoice
83
+ ? toolChoice.function.name
84
+ : toolChoice.name;
85
+
86
+ return tools.some(tool => tool.name === toolName) ? toolChoice : undefined;
87
+ }
88
+
89
+ export class AgentBusyError extends Error {
90
+ constructor(
91
+ message: string = "Agent is already processing. Use steer() or followUp() to queue messages, or wait for completion.",
92
+ ) {
93
+ super(message);
94
+ this.name = "AgentBusyError";
95
+ }
96
+ }
97
+ export interface AgentOptions {
98
+ initialState?: Partial<AgentState>;
99
+
100
+ /**
101
+ * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
102
+ * Default filters to user/assistant/toolResult and converts attachments.
103
+ */
104
+ convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
105
+
106
+ /**
107
+ * Optional transform applied to context before convertToLlm.
108
+ * Use for context pruning, injecting external context, etc.
109
+ */
110
+ transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
111
+
112
+ /**
113
+ * Optional transform applied after provider context assembly and before
114
+ * telemetry capture/provider send.
115
+ */
116
+ transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
117
+
118
+ /**
119
+ * Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
120
+ */
121
+ steeringMode?: "all" | "one-at-a-time";
122
+
123
+ /**
124
+ * Follow-up mode: "all" = send all follow-up messages at once, "one-at-a-time" = one per turn
125
+ */
126
+ followUpMode?: "all" | "one-at-a-time";
127
+
128
+ /**
129
+ * When to interrupt tool execution for steering messages.
130
+ * - "immediate": check after each tool call (default)
131
+ * - "wait": defer steering until the current turn completes
132
+ */
133
+ interruptMode?: "immediate" | "wait";
134
+
135
+ /**
136
+ * API format for Kimi Code provider: "openai" or "anthropic" (default: "anthropic")
137
+ */
138
+ kimiApiFormat?: "openai" | "anthropic";
139
+
140
+ /** Hint that websocket transport should be preferred when supported by the provider implementation. */
141
+ preferWebsockets?: boolean;
142
+
143
+ /**
144
+ * Custom stream function (for proxy backends, etc.). Default uses streamSimple.
145
+ */
146
+ streamFn?: StreamFn;
147
+ /** Absolute wall-clock deadline in Unix epoch milliseconds. */
148
+ deadline?: number;
149
+
150
+ /**
151
+ * Optional session identifier forwarded to LLM providers.
152
+ * Used by providers that support session-based caching (e.g., OpenAI Codex).
153
+ */
154
+ sessionId?: string;
155
+ /**
156
+ * Optional prompt cache key forwarded to LLM providers.
157
+ * When omitted, providers may fall back to sessionId.
158
+ */
159
+ promptCacheKey?: string;
160
+ /**
161
+ * Shared provider state map for session-scoped transport/session caches.
162
+ */
163
+ providerSessionState?: Map<string, ProviderSessionState>;
164
+
165
+ /**
166
+ * Resolves an API key or resolver dynamically for each LLM call.
167
+ * Useful for expiring tokens and model-scoped credential routing.
168
+ */
169
+ getApiKey?: (model: Model) => Promise<ApiKey | undefined> | ApiKey | undefined;
170
+
171
+ /**
172
+ * Inspect or replace provider payloads before they are sent.
173
+ */
174
+ onPayload?: SimpleStreamOptions["onPayload"];
175
+ /**
176
+ * Inspect provider response metadata after headers arrive and before streaming body consumption.
177
+ */
178
+ onResponse?: SimpleStreamOptions["onResponse"];
179
+ /**
180
+ * Inspect raw Server-Sent Events from HTTP streaming providers.
181
+ */
182
+ onSseEvent?: SimpleStreamOptions["onSseEvent"];
183
+ /**
184
+ * Inspect assistant streaming events before they are emitted to subscribers.
185
+ * Use this when abort decisions must happen before buffered events continue flowing.
186
+ */
187
+ onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
188
+
189
+ /**
190
+ * Called when GPT-5 Harmony protocol leakage is detected and mitigated.
191
+ */
192
+ onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
193
+ /**
194
+ * Custom token budgets for thinking levels (token-based providers only).
195
+ */
196
+ thinkingBudgets?: ThinkingBudgets;
197
+
198
+ /**
199
+ * Sampling temperature for LLM calls. `undefined` uses provider default.
200
+ */
201
+ temperature?: number;
202
+
203
+ /** Additional sampling controls for providers that support them. */
204
+ topP?: number;
205
+ topK?: number;
206
+ minP?: number;
207
+ presencePenalty?: number;
208
+ repetitionPenalty?: number;
209
+ serviceTier?: ServiceTier;
210
+ /**
211
+ * Per-call effective service-tier resolver. When set, it authoritatively
212
+ * supplies the request's tier (replacing the static `serviceTier` and its
213
+ * telemetry) per model — used to scope a provider/model into a priority
214
+ * serving path without mutating the shared session `serviceTier`.
215
+ */
216
+ serviceTierResolver?: (model: Model) => ServiceTier | undefined;
217
+ /**
218
+ * If true, request that the underlying provider omit reasoning/thinking summaries
219
+ * from the response. The model still reasons internally; only the human-readable
220
+ * summary stream is suppressed. Useful when the UI hides thinking blocks anyway.
221
+ */
222
+ hideThinkingSummary?: boolean;
223
+
224
+ /**
225
+ * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
226
+ * If the server's requested delay exceeds this value, the request fails immediately,
227
+ * allowing higher-level retry logic to handle it with user visibility.
228
+ * Default: 60000 (60 seconds). Set to 0 to disable the cap.
229
+ */
230
+ maxRetryDelayMs?: number;
231
+
232
+ /**
233
+ * Provides tool execution context, resolved per tool call.
234
+ * Use for late-bound UI or session state access.
235
+ */
236
+ getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
237
+
238
+ /**
239
+ * Optional transform applied to tool call arguments before execution.
240
+ * Use for deobfuscating secrets or rewriting arguments.
241
+ */
242
+ transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
243
+
244
+ /**
245
+ * Resolve a tool call whose name matched no advertised tool. Lets hosts
246
+ * route calls to tools exposed through side transports (e.g. `xd://`
247
+ * device mounts) instead of failing with "Tool not found".
248
+ */
249
+ resolveFallbackTool?: (name: string) => AgentTool<any> | undefined;
250
+
251
+ /** Enable intent tracing schema injection/stripping in the harness. */
252
+ intentTracing?: boolean;
253
+ /**
254
+ * Strip tool descriptions from provider-bound tool specs (top-level + nested
255
+ * schema annotations). Use when the full catalog is rendered into the system
256
+ * prompt so descriptions are not duplicated on the wire. Native tool calling only.
257
+ */
258
+ pruneToolDescriptions?: boolean;
259
+ /** Owned tool-calling dialect. Undefined keeps provider-native tool calling. */
260
+ dialect?: Dialect;
261
+ /**
262
+ * When owned tool calling is active and the model fabricates a tool result
263
+ * mid-turn: `true` (default) aborts the provider request immediately; `false`
264
+ * drains the request and discards the fabricated continuation. Forwarded to
265
+ * the loop's {@link AgentLoopConfig.abortOnFabricatedToolResult}.
266
+ */
267
+ abortOnFabricatedToolResult?: boolean;
268
+ /** Dynamic tool-choice directive (hard {@link ToolChoice} or {@link SoftToolRequirement}), resolved once per turn. */
269
+ getToolChoice?: () => ToolChoiceDirective | undefined;
270
+ /** Reject a deferred hard choice when its named tool is no longer active. */
271
+ onToolChoiceUnavailable?: () => void;
272
+
273
+ /**
274
+ * Cursor exec handlers for local tool execution.
275
+ */
276
+ cursorExecHandlers?: CursorExecHandlers;
277
+ /** Additional tools Cursor executes through its MCP request-context bridge, resolved before each provider call. */
278
+ getCursorTools?: () => AgentTool[];
279
+
280
+ /**
281
+ * Optional rewrite of Cursor exec-channel tool results. May return a Promise.
282
+ *
283
+ * The Agent reserves the original result in its Cursor result buffer first,
284
+ * then awaits this hook and patches the reserved entry in place. That keeps
285
+ * the call paired even if `message_end` arrives while the Promise is still
286
+ * pending, and `#emitCursorSplitAssistantMessage` waits for any transformer
287
+ * still in flight before persisting, so a late rewrite is not lost. A
288
+ * rejecting transformer is swallowed and the reserved payload stands in.
289
+ * Hosts that only pass `cursorExecHandlers` (the coding-agent path) never
290
+ * hit this hook.
291
+ */
292
+ cursorOnToolResult?: CursorToolResultHandler;
293
+
294
+ /** Current working directory used by local tool execution. */
295
+ cwd?: string;
296
+ /**
297
+ * Resolver for the live working directory, re-read on every turn. When set, it
298
+ * overrides the static {@link cwd} at config-build time so a session move
299
+ * (`/move`, which updates the host's cwd without reconstructing the Agent) is
300
+ * reflected in provider options — e.g. GitLab Duo Agent namespace/project
301
+ * discovery keys off this cwd's git remote. Falls back to `cwd` when it returns
302
+ * `undefined`.
303
+ */
304
+ cwdResolver?: () => string | undefined;
305
+ /**
306
+ * Called after a tool call has been validated and is about to execute.
307
+ * See {@link AgentLoopConfig.beforeToolCall} for full semantics.
308
+ */
309
+ beforeToolCall?: AgentLoopConfig["beforeToolCall"];
310
+
311
+ /**
312
+ * Called after a tool finishes executing, before `tool_execution_end` and the tool-result
313
+ * message are emitted. See {@link AgentLoopConfig.afterToolCall} for full semantics.
314
+ */
315
+ afterToolCall?: AgentLoopConfig["afterToolCall"];
316
+
317
+ /**
318
+ * Called once an assistant message is finalized, before it reaches the
319
+ * context, the UI, or tool dispatch. May mutate the message in place (text +
320
+ * tool-call arguments). See {@link AgentLoopConfig.transformAssistantMessage}.
321
+ */
322
+ transformAssistantMessage?: AgentLoopConfig["transformAssistantMessage"];
323
+
324
+ /**
325
+ * Opt-in OpenTelemetry instrumentation. Passing `{}` enables the loop's
326
+ * GenAI-semantic-convention spans using the global tracer provider. See
327
+ * {@link AgentLoopConfig.telemetry} for the full surface.
328
+ */
329
+ telemetry?: AgentLoopConfig["telemetry"];
330
+ /**
331
+ * Immutable context mode — stabilizes system prompt + tool spec bytes
332
+ * across turns so DeepSeek/Anthropic prefix caches hit at maximum rate.
333
+ */
334
+ appendOnlyContext?: AppendOnlyContextManager;
335
+ }
336
+
337
+ export interface AgentPromptOptions {
338
+ toolChoice?: ToolChoice;
339
+ }
340
+
341
+ /** Buffered Cursor exec-channel tool result waiting to be emitted after the assistant message. */
342
+ interface CursorToolResultEntry {
343
+ toolResult: ToolResultMessage;
344
+ /**
345
+ * Set while an async `cursorOnToolResult` transformer is still running for
346
+ * this entry, and cleared once it settles. The drain awaits it so a
347
+ * transformer that rewrites the payload is not silently discarded when
348
+ * `message_end` lands in the same chunk as the tool result.
349
+ */
350
+ pending?: Promise<void>;
351
+ }
352
+
353
+ export class Agent {
354
+ #state: AgentState = {
355
+ systemPrompt: [],
356
+ model: getBundledModel("google", "gemini-2.5-flash-lite-preview-06-17"),
357
+ thinkingLevel: undefined,
358
+ disableReasoning: false,
359
+ tools: [],
360
+ messages: [],
361
+ isStreaming: false,
362
+ streamMessage: null,
363
+ pendingToolCalls: new Set<string>(),
364
+ error: undefined,
365
+ };
366
+
367
+ #listeners = new Set<(e: AgentEvent) => void>();
368
+ #abortController?: AbortController;
369
+ #convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
370
+ #transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
371
+ #transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
372
+ #steeringQueue: AgentMessage[] = [];
373
+ #followUpQueue: AgentMessage[] = [];
374
+ #steeringWaiters = new Set<() => void>();
375
+
376
+ #steeringMode: "all" | "one-at-a-time";
377
+ #followUpMode: "all" | "one-at-a-time";
378
+ #interruptMode: "immediate" | "wait";
379
+ #sessionId?: string;
380
+ #deadline?: number;
381
+ #promptCacheKey?: string;
382
+ #metadata?: Record<string, unknown>;
383
+ #metadataResolver?: (provider: string) => Record<string, unknown> | undefined;
384
+ #providerSessionState?: Map<string, ProviderSessionState>;
385
+ #thinkingBudgets?: ThinkingBudgets;
386
+ #temperature?: number;
387
+ #topP?: number;
388
+ #topK?: number;
389
+ #minP?: number;
390
+ #presencePenalty?: number;
391
+ #repetitionPenalty?: number;
392
+ #serviceTier?: ServiceTier;
393
+ #serviceTierResolver?: (model: Model) => ServiceTier | undefined;
394
+ #hideThinkingSummary?: boolean;
395
+ #maxRetryDelayMs?: number;
396
+ #getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
397
+ #cursorExecHandlers?: CursorExecHandlers;
398
+ #getCursorTools?: () => AgentTool[];
399
+ #cursorOnToolResult?: CursorToolResultHandler;
400
+ #cwd?: string;
401
+ #cwdResolver?: () => string | undefined;
402
+
403
+ #runningPrompt?: Promise<void>;
404
+ #resolveRunningPrompt?: () => void;
405
+ #kimiApiFormat?: "openai" | "anthropic";
406
+ #preferWebsockets?: boolean;
407
+ #transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
408
+ #resolveFallbackTool?: (name: string) => AgentTool<any> | undefined;
409
+ #intentTracing: boolean;
410
+ #pruneToolDescriptions: boolean;
411
+ #dialect?: Dialect;
412
+ #abortOnFabricatedToolResult?: boolean;
413
+ #getToolChoice?: () => ToolChoiceDirective | undefined;
414
+ #onToolChoiceUnavailable?: () => void;
415
+ #softToolRequirementState: NonNullable<AgentLoopConfig["softToolRequirementState"]> = { escalations: 0 };
416
+ #deferredToolChoice?: ToolChoice;
417
+ #onPayload?: SimpleStreamOptions["onPayload"];
418
+ #onResponse?: SimpleStreamOptions["onResponse"];
419
+ #onSseEvent?: SimpleStreamOptions["onSseEvent"];
420
+ #onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
421
+ #onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
422
+ #onBeforeYield?: () => Promise<void> | void;
423
+ #onTurnEnd?: (messages: AgentMessage[], signal?: AbortSignal, context?: AgentTurnEndContext) => Promise<void> | void;
424
+ #beforeModelCall?: AgentBeforeModelCall;
425
+ #additionalBeforeModelCalls = new Set<AgentBeforeModelCall>();
426
+ #asideMessageProvider?: () => AsideMessage[] | Promise<AsideMessage[]>;
427
+ #telemetry?: AgentLoopConfig["telemetry"];
428
+ #appendOnlyContext?: AppendOnlyContextManager;
429
+ #beforeQueuedMessageDequeueHooks = new Set<(signal?: AbortSignal) => Promise<void> | void>();
430
+ #beforeModelCallHooks = new Set<(signal?: AbortSignal) => Promise<void> | void>();
431
+
432
+ /** Buffered Cursor tool results with text length at time of call (for correct ordering) */
433
+ #cursorToolResultBuffer: CursorToolResultEntry[] = [];
434
+
435
+ streamFn: StreamFn;
436
+ getApiKey?: (model: Model) => Promise<ApiKey | undefined> | ApiKey | undefined;
437
+ /**
438
+ * Hook invoked after tool arguments are validated and before execution.
439
+ * Reassign at any time to swap the implementation (e.g. on extension reload).
440
+ */
441
+ beforeToolCall?: AgentLoopConfig["beforeToolCall"];
442
+ /**
443
+ * Hook invoked after tool execution and before `tool_execution_end` / tool-result
444
+ * message emission. Reassign at any time to swap the implementation.
445
+ */
446
+ afterToolCall?: AgentLoopConfig["afterToolCall"];
447
+ /**
448
+ * Hook invoked once an assistant message is finalized, before context append,
449
+ * UI emission, and tool dispatch. Reassign at any time to swap the implementation.
450
+ */
451
+ transformAssistantMessage?: AgentLoopConfig["transformAssistantMessage"];
452
+ /**
453
+ * Hook that peeks whether interrupting IRC asides are queued for the next boundary.
454
+ */
455
+ hasIrcInterrupts?: AgentLoopConfig["hasIrcInterrupts"];
456
+
457
+ constructor(opts: AgentOptions = {}) {
458
+ this.#state = { ...this.#state, ...opts.initialState };
459
+ if (opts.initialState?.messages) this.#state.messages = opts.initialState.messages.slice();
460
+ if (opts.initialState?.pendingToolCalls)
461
+ this.#state.pendingToolCalls = new Set(opts.initialState.pendingToolCalls);
462
+ this.#convertToLlm = opts.convertToLlm || defaultConvertToLlm;
463
+ this.#transformContext = opts.transformContext;
464
+ this.#steeringMode = opts.steeringMode || "one-at-a-time";
465
+ this.#followUpMode = opts.followUpMode || "one-at-a-time";
466
+ this.#interruptMode = opts.interruptMode || "immediate";
467
+ this.streamFn = opts.streamFn || streamSimple;
468
+ this.#sessionId = opts.sessionId;
469
+ this.#deadline = opts.deadline;
470
+ this.#promptCacheKey = opts.promptCacheKey;
471
+ this.#providerSessionState = opts.providerSessionState;
472
+ this.#thinkingBudgets = opts.thinkingBudgets;
473
+ this.#temperature = opts.temperature;
474
+ this.#topP = opts.topP;
475
+ this.#topK = opts.topK;
476
+ this.#minP = opts.minP;
477
+ this.#presencePenalty = opts.presencePenalty;
478
+ this.#repetitionPenalty = opts.repetitionPenalty;
479
+ this.#serviceTier = opts.serviceTier;
480
+ this.#serviceTierResolver = opts.serviceTierResolver;
481
+ this.#hideThinkingSummary = opts.hideThinkingSummary;
482
+ this.#maxRetryDelayMs = opts.maxRetryDelayMs;
483
+ this.getApiKey = opts.getApiKey;
484
+ this.#onPayload = opts.onPayload;
485
+ this.#onResponse = opts.onResponse;
486
+ this.#onSseEvent = opts.onSseEvent;
487
+ this.#getToolContext = opts.getToolContext;
488
+ this.#cursorExecHandlers = opts.cursorExecHandlers;
489
+ this.#getCursorTools = opts.getCursorTools;
490
+ this.#cursorOnToolResult = opts.cursorOnToolResult;
491
+ this.#cwd = opts.cwd;
492
+ this.#cwdResolver = opts.cwdResolver;
493
+ this.#kimiApiFormat = opts.kimiApiFormat;
494
+ this.#preferWebsockets = opts.preferWebsockets;
495
+ this.#transformToolCallArguments = opts.transformToolCallArguments;
496
+ this.#resolveFallbackTool = opts.resolveFallbackTool;
497
+ this.#intentTracing = opts.intentTracing === true;
498
+ this.#pruneToolDescriptions = opts.pruneToolDescriptions === true;
499
+ this.#dialect = opts.dialect;
500
+ this.#abortOnFabricatedToolResult = opts.abortOnFabricatedToolResult;
501
+ this.#getToolChoice = opts.getToolChoice;
502
+ this.#onToolChoiceUnavailable = opts.onToolChoiceUnavailable;
503
+ this.#onAssistantMessageEvent = opts.onAssistantMessageEvent;
504
+ this.#onHarmonyLeak = opts.onHarmonyLeak;
505
+ this.beforeToolCall = opts.beforeToolCall;
506
+ this.afterToolCall = opts.afterToolCall;
507
+ this.transformAssistantMessage = opts.transformAssistantMessage;
508
+ this.#telemetry = opts.telemetry;
509
+ this.#appendOnlyContext = opts.appendOnlyContext;
510
+ this.#transformProviderContext = opts.transformProviderContext;
511
+ }
512
+
513
+ /**
514
+ * Get the current session ID used for provider caching.
515
+ */
516
+ get sessionId(): string | undefined {
517
+ return this.#sessionId;
518
+ }
519
+
520
+ /**
521
+ * Set the session ID for provider caching.
522
+ * Call this when switching sessions (new session, branch, resume).
523
+ */
524
+ set sessionId(value: string | undefined) {
525
+ this.#sessionId = value;
526
+ }
527
+
528
+ /**
529
+ * Get the prompt cache key forwarded to providers.
530
+ */
531
+ get promptCacheKey(): string | undefined {
532
+ return this.#promptCacheKey;
533
+ }
534
+
535
+ /**
536
+ * Set the prompt cache key forwarded to providers.
537
+ */
538
+ set promptCacheKey(value: string | undefined) {
539
+ this.#promptCacheKey = value;
540
+ }
541
+
542
+ /**
543
+ * Static metadata forwarded to every API request when no resolver is installed
544
+ * (e.g. `metadata.user_id` for Anthropic session attribution). Setting this
545
+ * clears any installed resolver.
546
+ *
547
+ * For live/provider-aware metadata (e.g. Anthropic OAuth `account_uuid` that
548
+ * must reflect the credential selected per-request), use
549
+ * {@link setMetadataResolver} and read via {@link metadataForProvider}.
550
+ */
551
+ get metadata(): Record<string, unknown> | undefined {
552
+ return this.#metadata;
553
+ }
554
+
555
+ set metadata(value: Record<string, unknown> | undefined) {
556
+ this.#metadata = value;
557
+ this.#metadataResolver = undefined;
558
+ }
559
+
560
+ /**
561
+ * Resolve request metadata for the given provider at call time. When a
562
+ * resolver is installed via {@link setMetadataResolver}, it is invoked with
563
+ * the provider string so the result can be scoped (e.g. `account_uuid` is
564
+ * only included for `"anthropic"` requests). Falls back to the static
565
+ * {@link metadata} value when no resolver is set.
566
+ */
567
+ metadataForProvider(provider: string): Record<string, unknown> | undefined {
568
+ if (this.#metadataResolver) return this.#metadataResolver(provider);
569
+ return this.#metadata;
570
+ }
571
+
572
+ /**
573
+ * Install a function that resolves request metadata at call time. The
574
+ * resolver receives the target provider string and can gate provider-specific
575
+ * fields (e.g. `account_uuid` only for `"anthropic"`). Invoked per LLM
576
+ * request by `agent-loop` after `getApiKey` selects the session-sticky
577
+ * credential. Pass `undefined` to clear and revert to the static
578
+ * {@link metadata} value.
579
+ */
580
+ setMetadataResolver(resolver: ((provider: string) => Record<string, unknown> | undefined) | undefined): void {
581
+ this.#metadataResolver = resolver;
582
+ }
583
+
584
+ /**
585
+ * Read the active OpenTelemetry configuration. Returns `undefined` when
586
+ * instrumentation is disabled. Callers spawning child runs (e.g. subagent
587
+ * dispatch) forward this to the child's loop so its spans appear under the
588
+ * parent's active context with the subagent's own identity stamped.
589
+ */
590
+ get telemetry(): AgentLoopConfig["telemetry"] | undefined {
591
+ return this.#telemetry;
592
+ }
593
+
594
+ /**
595
+ * Replace the active OpenTelemetry configuration. Pass `undefined` to
596
+ * disable instrumentation. Applies to the *next* `agentLoop` invocation —
597
+ * in-flight loops keep the configuration they started with.
598
+ */
599
+ setTelemetry(telemetry: AgentLoopConfig["telemetry"] | undefined): void {
600
+ this.#telemetry = telemetry;
601
+ }
602
+
603
+ /**
604
+ * Get provider-scoped mutable session state store.
605
+ */
606
+ get providerSessionState(): Map<string, ProviderSessionState> | undefined {
607
+ return this.#providerSessionState;
608
+ }
609
+
610
+ /**
611
+ * Set provider-scoped mutable session state store.
612
+ */
613
+ set providerSessionState(value: Map<string, ProviderSessionState> | undefined) {
614
+ this.#providerSessionState = value;
615
+ }
616
+
617
+ /**
618
+ * Get the current thinking budgets.
619
+ */
620
+ get thinkingBudgets(): ThinkingBudgets | undefined {
621
+ return this.#thinkingBudgets;
622
+ }
623
+
624
+ /**
625
+ * Set custom thinking budgets for token-based providers.
626
+ */
627
+ set thinkingBudgets(value: ThinkingBudgets | undefined) {
628
+ this.#thinkingBudgets = value;
629
+ }
630
+
631
+ /**
632
+ * Get the current sampling temperature.
633
+ */
634
+ get temperature(): number | undefined {
635
+ return this.#temperature;
636
+ }
637
+
638
+ /**
639
+ * Set sampling temperature for LLM calls. `undefined` uses provider default.
640
+ */
641
+ set temperature(value: number | undefined) {
642
+ this.#temperature = value;
643
+ }
644
+
645
+ get topP(): number | undefined {
646
+ return this.#topP;
647
+ }
648
+
649
+ set topP(value: number | undefined) {
650
+ this.#topP = value;
651
+ }
652
+
653
+ get topK(): number | undefined {
654
+ return this.#topK;
655
+ }
656
+
657
+ set topK(value: number | undefined) {
658
+ this.#topK = value;
659
+ }
660
+
661
+ get minP(): number | undefined {
662
+ return this.#minP;
663
+ }
664
+
665
+ set minP(value: number | undefined) {
666
+ this.#minP = value;
667
+ }
668
+
669
+ get presencePenalty(): number | undefined {
670
+ return this.#presencePenalty;
671
+ }
672
+
673
+ set presencePenalty(value: number | undefined) {
674
+ this.#presencePenalty = value;
675
+ }
676
+
677
+ get repetitionPenalty(): number | undefined {
678
+ return this.#repetitionPenalty;
679
+ }
680
+
681
+ set repetitionPenalty(value: number | undefined) {
682
+ this.#repetitionPenalty = value;
683
+ }
684
+
685
+ get serviceTier(): ServiceTier | undefined {
686
+ return this.#serviceTier;
687
+ }
688
+
689
+ set serviceTier(value: ServiceTier | undefined) {
690
+ this.#serviceTier = value;
691
+ }
692
+
693
+ get serviceTierResolver(): ((model: Model) => ServiceTier | undefined) | undefined {
694
+ return this.#serviceTierResolver;
695
+ }
696
+
697
+ set serviceTierResolver(value: ((model: Model) => ServiceTier | undefined) | undefined) {
698
+ this.#serviceTierResolver = value;
699
+ }
700
+
701
+ get hideThinkingSummary(): boolean | undefined {
702
+ return this.#hideThinkingSummary;
703
+ }
704
+
705
+ set hideThinkingSummary(value: boolean | undefined) {
706
+ this.#hideThinkingSummary = value;
707
+ }
708
+
709
+ /**
710
+ * Get the current max retry delay in milliseconds.
711
+ */
712
+ get maxRetryDelayMs(): number | undefined {
713
+ return this.#maxRetryDelayMs;
714
+ }
715
+
716
+ /**
717
+ * Set the maximum delay to wait for server-requested retries.
718
+ * Set to 0 to disable the cap.
719
+ */
720
+ set maxRetryDelayMs(value: number | undefined) {
721
+ this.#maxRetryDelayMs = value;
722
+ }
723
+
724
+ get state(): AgentState {
725
+ return this.#state;
726
+ }
727
+
728
+ get appendOnlyContext(): AppendOnlyContextManager | undefined {
729
+ return this.#appendOnlyContext;
730
+ }
731
+
732
+ setAppendOnlyContext(manager?: AppendOnlyContextManager): void {
733
+ this.#appendOnlyContext = manager;
734
+ }
735
+
736
+ #toolsForModel(model: Model): AgentTool[] {
737
+ if (model.api !== "cursor-agent" || !this.#getCursorTools) return this.#state.tools;
738
+ const cursorTools = this.#getCursorTools();
739
+ if (cursorTools.length === 0) return this.#state.tools;
740
+
741
+ const names = new Set(this.#state.tools.map(tool => tool.name));
742
+ let merged: AgentTool[] | undefined;
743
+ for (const tool of cursorTools) {
744
+ if (names.has(tool.name)) continue;
745
+ merged ??= this.#state.tools.slice();
746
+ merged.push(tool);
747
+ names.add(tool.name);
748
+ }
749
+ return merged ?? this.#state.tools;
750
+ }
751
+
752
+ /**
753
+ * Assemble the provider Context for a side-channel (no-loop) request, mirroring
754
+ * the main loop's prefix (system + normalized tools) so it shares the prompt
755
+ * cache. Never touches the append-only log or the tool-choice queue. Owned/
756
+ * in-band dialect sessions stay tools-less (matching their no-native-tools wire
757
+ * shape and avoiding tool-markup leakage). `llmMessages` is already converted
758
+ * (and, in production, obfuscated) by the caller.
759
+ *
760
+ * `systemPrompt` defaults to the live agent prompt so the side request hits the
761
+ * same cached prefix as the main loop. Callers that must pin a different prompt
762
+ * (e.g. handoff generation, which uses the base prompt rather than a per-turn
763
+ * `before_agent_start` hook override) pass it explicitly.
764
+ */
765
+ async buildSideRequestContext(
766
+ llmMessages: Message[],
767
+ systemPrompt: string[] = this.#state.systemPrompt,
768
+ ): Promise<Context> {
769
+ const model = this.#state.model;
770
+ if (!model) throw new Error("No active model on agent");
771
+ const ownedDialect = this.#dialect ?? resolveOwnedDialectFromEnv(Bun.env.PI_DIALECT);
772
+ const messages = normalizeMessagesForProvider(llmMessages, model);
773
+ const tools = ownedDialect
774
+ ? []
775
+ : (normalizeTools(this.#toolsForModel(model), {
776
+ injectIntent: this.#intentTracing,
777
+ pruneDescriptions: this.#pruneToolDescriptions,
778
+ }) ?? []);
779
+ let context: Context = { systemPrompt, messages, tools };
780
+ if (this.#transformProviderContext) context = await this.#transformProviderContext(context, model);
781
+ return context;
782
+ }
783
+
784
+ subscribe(fn: (e: AgentEvent) => void): () => void {
785
+ this.#listeners.add(fn);
786
+ return () => this.#listeners.delete(fn);
787
+ }
788
+
789
+ /** Register an independently removable hook that runs before queued messages are consumed. */
790
+ addBeforeQueuedMessageDequeueHook(hook: (signal?: AbortSignal) => Promise<void> | void): () => void {
791
+ const registration = (signal?: AbortSignal) => hook(signal);
792
+ this.#beforeQueuedMessageDequeueHooks.add(registration);
793
+ return () => this.#beforeQueuedMessageDequeueHooks.delete(registration);
794
+ }
795
+
796
+ /** Register an independently removable hook that runs immediately before each model call. */
797
+ addBeforeModelCallHook(hook: (signal?: AbortSignal) => Promise<void> | void): () => void {
798
+ const registration = (signal?: AbortSignal) => hook(signal);
799
+ this.#beforeModelCallHooks.add(registration);
800
+ return () => this.#beforeModelCallHooks.delete(registration);
801
+ }
802
+
803
+ async #runBeforeModelCallHooks(signal?: AbortSignal): Promise<void> {
804
+ for (const hook of this.#beforeModelCallHooks) await hook(signal);
805
+ }
806
+
807
+ async #runBeforeQueuedMessageDequeueHooks(signal?: AbortSignal): Promise<void> {
808
+ for (const hook of this.#beforeQueuedMessageDequeueHooks) await hook(signal);
809
+ }
810
+
811
+ async #dequeueSteeringMessagesAfterHooks(signal?: AbortSignal): Promise<AgentMessage[]> {
812
+ if (signal?.aborted || this.#steeringQueue.length === 0) return [];
813
+ await this.#runBeforeQueuedMessageDequeueHooks(signal);
814
+ return signal?.aborted ? [] : this.#dequeueSteeringMessages();
815
+ }
816
+
817
+ async #dequeueFollowUpMessagesAfterHooks(signal?: AbortSignal): Promise<AgentMessage[]> {
818
+ if (signal?.aborted || this.#followUpQueue.length === 0) return [];
819
+ await this.#runBeforeQueuedMessageDequeueHooks(signal);
820
+ return signal?.aborted ? [] : this.#dequeueFollowUpMessages();
821
+ }
822
+
823
+ setProviderResponseInterceptor(fn: SimpleStreamOptions["onResponse"] | undefined): void {
824
+ this.#onResponse = fn;
825
+ }
826
+
827
+ setRawSseEventInterceptor(fn: SimpleStreamOptions["onSseEvent"] | undefined): void {
828
+ this.#onSseEvent = fn;
829
+ }
830
+
831
+ setAssistantMessageEventInterceptor(
832
+ fn: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined,
833
+ ): void {
834
+ this.#onAssistantMessageEvent = fn;
835
+ }
836
+
837
+ setOnBeforeYield(fn: (() => Promise<void> | void) | undefined): void {
838
+ this.#onBeforeYield = fn;
839
+ }
840
+ setOnTurnEnd(
841
+ fn:
842
+ | ((messages: AgentMessage[], signal?: AbortSignal, context?: AgentTurnEndContext) => Promise<void> | void)
843
+ | undefined,
844
+ ): void {
845
+ this.#onTurnEnd = fn;
846
+ }
847
+
848
+ /**
849
+ * Install or replace the host pre-model-call gate; pass `undefined` to
850
+ * remove it. Gates are sampled when a run starts: installing the first
851
+ * gate while a run is in flight takes effect on the next run.
852
+ */
853
+ setBeforeModelCall(fn: AgentBeforeModelCall | undefined): void {
854
+ this.#beforeModelCall = fn;
855
+ }
856
+
857
+ /**
858
+ * Add a pre-model callback without replacing callbacks owned by the host.
859
+ * Returns a disposer that removes only this callback. Like
860
+ * {@link setBeforeModelCall}, the first gate installed while a run is in
861
+ * flight takes effect on the next run.
862
+ */
863
+ addBeforeModelCall(fn: AgentBeforeModelCall): () => void {
864
+ this.#additionalBeforeModelCalls.add(fn);
865
+ return () => {
866
+ this.#additionalBeforeModelCalls.delete(fn);
867
+ };
868
+ }
869
+
870
+ /**
871
+ * Provide a source of non-interrupting "aside" messages (e.g. background-job
872
+ * completions, late LSP diagnostics) drained at each step boundary. Never
873
+ * aborts in-flight tools. See `AgentLoopConfig.getAsideMessages`.
874
+ */
875
+ setAsideMessageProvider(fn: (() => AsideMessage[] | Promise<AsideMessage[]>) | undefined): void {
876
+ this.#asideMessageProvider = fn;
877
+ }
878
+
879
+ emitExternalEvent(event: AgentEvent) {
880
+ switch (event.type) {
881
+ case "message_start":
882
+ case "message_update":
883
+ this.#state.streamMessage = event.message;
884
+ break;
885
+ case "message_end":
886
+ this.#state.streamMessage = null;
887
+ this.appendMessage(event.message);
888
+ break;
889
+ case "tool_execution_start":
890
+ this.#state.pendingToolCalls.add(event.toolCallId);
891
+ break;
892
+ case "tool_execution_end":
893
+ this.#state.pendingToolCalls.delete(event.toolCallId);
894
+ break;
895
+ }
896
+
897
+ this.#emit(event);
898
+ }
899
+
900
+ // State mutators
901
+ setSystemPrompt(v: string[] | string) {
902
+ this.#state.systemPrompt = typeof v === "string" ? [v] : v;
903
+ }
904
+
905
+ setModel(m: Model) {
906
+ this.#state.model = m;
907
+ }
908
+
909
+ setThinkingLevel(l: Effort | undefined) {
910
+ this.#state.thinkingLevel = l;
911
+ }
912
+
913
+ setDisableReasoning(disabled: boolean) {
914
+ this.#state.disableReasoning = disabled;
915
+ }
916
+
917
+ setSteeringMode(mode: "all" | "one-at-a-time") {
918
+ this.#steeringMode = mode;
919
+ }
920
+
921
+ getSteeringMode(): "all" | "one-at-a-time" {
922
+ return this.#steeringMode;
923
+ }
924
+
925
+ setFollowUpMode(mode: "all" | "one-at-a-time") {
926
+ this.#followUpMode = mode;
927
+ }
928
+
929
+ getFollowUpMode(): "all" | "one-at-a-time" {
930
+ return this.#followUpMode;
931
+ }
932
+
933
+ setInterruptMode(mode: "immediate" | "wait") {
934
+ this.#interruptMode = mode;
935
+ }
936
+
937
+ getInterruptMode(): "immediate" | "wait" {
938
+ return this.#interruptMode;
939
+ }
940
+
941
+ setTools(t: AgentTool<any>[]) {
942
+ this.#state.tools = t;
943
+ }
944
+
945
+ replaceMessages(ms: AgentMessage[]) {
946
+ // New array assignment is intentional: caller-owned `ms` may be mutated
947
+ // after handoff; snapshot it so external mutations cannot leak in.
948
+ this.#state.messages = ms.slice();
949
+ }
950
+
951
+ replaceQueues(steering: AgentMessage[], followUp: AgentMessage[]) {
952
+ this.#steeringQueue = steering.slice();
953
+ this.#followUpQueue = followUp.slice();
954
+ this.#notifySteeringWaiters();
955
+ }
956
+
957
+ appendMessage(m: AgentMessage) {
958
+ this.#state.messages.push(m);
959
+ }
960
+
961
+ popMessage(): AgentMessage | undefined {
962
+ const removed = this.#state.messages.pop();
963
+ if (removed && this.#state.streamMessage === removed) {
964
+ this.#state.streamMessage = null;
965
+ }
966
+ return removed;
967
+ }
968
+
969
+ /**
970
+ * Queue a steering message to interrupt the agent mid-run.
971
+ * Delivered after current tool execution, skips remaining tools.
972
+ */
973
+ steer(m: AgentMessage) {
974
+ this.#steeringQueue.push(m);
975
+ this.#notifySteeringWaiters();
976
+ }
977
+
978
+ /**
979
+ * Queue a follow-up message to be processed after the agent finishes.
980
+ * Delivered only when agent has no more tool calls or steering messages.
981
+ */
982
+ followUp(m: AgentMessage) {
983
+ this.#followUpQueue.push(m);
984
+ }
985
+
986
+ clearSteeringQueue() {
987
+ this.#steeringQueue = [];
988
+ this.#notifySteeringWaiters();
989
+ }
990
+
991
+ clearFollowUpQueue() {
992
+ this.#followUpQueue = [];
993
+ }
994
+
995
+ /**
996
+ * Drop tool-directive state retained across a gate-stopped run: the
997
+ * deferred hard choice and the soft-requirement lifecycle.
998
+ */
999
+ clearDeferredToolDirectives() {
1000
+ this.#deferredToolChoice = undefined;
1001
+ this.#softToolRequirementState = { escalations: 0 };
1002
+ }
1003
+
1004
+ clearAllQueues() {
1005
+ this.#steeringQueue = [];
1006
+ this.#followUpQueue = [];
1007
+ this.#notifySteeringWaiters();
1008
+ this.clearDeferredToolDirectives();
1009
+ }
1010
+
1011
+ hasQueuedMessages(): boolean {
1012
+ return this.#steeringQueue.length > 0 || this.#followUpQueue.length > 0;
1013
+ }
1014
+
1015
+ /** Non-consuming view of the pending steering queue (insertion order, newest
1016
+ * last). The session layer derives its queued-message display/count from
1017
+ * this live view instead of a mirror, so the agent-core queue stays the
1018
+ * single source of truth. */
1019
+ peekSteeringQueue(): readonly AgentMessage[] {
1020
+ return this.#steeringQueue;
1021
+ }
1022
+
1023
+ /** Non-consuming view of the pending follow-up queue. See
1024
+ * {@link peekSteeringQueue}. */
1025
+ peekFollowUpQueue(): readonly AgentMessage[] {
1026
+ return this.#followUpQueue;
1027
+ }
1028
+
1029
+ get isAborting(): boolean {
1030
+ return this.#abortController?.signal.aborted === true && this.#state.isStreaming;
1031
+ }
1032
+
1033
+ #dequeueSteeringMessages(): AgentMessage[] {
1034
+ if (this.#steeringMode === "one-at-a-time") {
1035
+ if (this.#steeringQueue.length > 0) {
1036
+ const first = this.#steeringQueue[0];
1037
+ this.#steeringQueue = this.#steeringQueue.slice(1);
1038
+ return [first];
1039
+ }
1040
+ return [];
1041
+ }
1042
+ const steering = this.#steeringQueue.slice();
1043
+ this.#steeringQueue = [];
1044
+ return steering;
1045
+ }
1046
+
1047
+ #dequeueFollowUpMessages(): AgentMessage[] {
1048
+ if (this.#followUpMode === "one-at-a-time") {
1049
+ if (this.#followUpQueue.length > 0) {
1050
+ const first = this.#followUpQueue[0];
1051
+ this.#followUpQueue = this.#followUpQueue.slice(1);
1052
+ return [first];
1053
+ }
1054
+ return [];
1055
+ }
1056
+ const followUp = this.#followUpQueue.slice();
1057
+ this.#followUpQueue = [];
1058
+ return followUp;
1059
+ }
1060
+
1061
+ /**
1062
+ * Remove and return the last steering message from the queue (LIFO).
1063
+ * Used by dequeue keybinding.
1064
+ */
1065
+ popLastSteer(): AgentMessage | undefined {
1066
+ return this.#steeringQueue.pop();
1067
+ }
1068
+
1069
+ /**
1070
+ * Remove and return the last follow-up message from the queue (LIFO).
1071
+ * Used by dequeue keybinding.
1072
+ */
1073
+ popLastFollowUp(): AgentMessage | undefined {
1074
+ return this.#followUpQueue.pop();
1075
+ }
1076
+
1077
+ clearMessages() {
1078
+ this.#state.messages.length = 0;
1079
+ }
1080
+
1081
+ abort(reason?: unknown) {
1082
+ this.#abortController?.abort(reason);
1083
+ }
1084
+
1085
+ waitForIdle(): Promise<void> {
1086
+ return this.#runningPrompt ?? Promise.resolve();
1087
+ }
1088
+
1089
+ /**
1090
+ * Wait for a steering message without consuming the steering queue.
1091
+ *
1092
+ * The signal releases the waiter when the prompt ends, so an in-flight
1093
+ * tool watcher never survives the tool batch that owns it.
1094
+ */
1095
+ #waitForSteeringMessages(signal?: AbortSignal): Promise<void> {
1096
+ if (this.#steeringQueue.length > 0 || signal?.aborted) return Promise.resolve();
1097
+ const { promise, resolve } = Promise.withResolvers<void>();
1098
+ const onAbort = (): void => resolve();
1099
+ this.#steeringWaiters.add(resolve);
1100
+ signal?.addEventListener("abort", onAbort, { once: true });
1101
+ return promise.finally(() => {
1102
+ this.#steeringWaiters.delete(resolve);
1103
+ signal?.removeEventListener("abort", onAbort);
1104
+ });
1105
+ }
1106
+
1107
+ #notifySteeringWaiters(): void {
1108
+ const waiters = [...this.#steeringWaiters];
1109
+ for (const resolve of waiters) resolve();
1110
+ }
1111
+
1112
+ reset() {
1113
+ this.#state.messages.length = 0;
1114
+ this.#state.isStreaming = false;
1115
+ this.#state.streamMessage = null;
1116
+ this.#state.pendingToolCalls.clear();
1117
+ this.#state.error = undefined;
1118
+ this.#steeringQueue = [];
1119
+ this.#followUpQueue = [];
1120
+ this.#notifySteeringWaiters();
1121
+ this.clearDeferredToolDirectives();
1122
+ }
1123
+
1124
+ /** Send a prompt with an AgentMessage */
1125
+ async prompt(message: AgentMessage | AgentMessage[], options?: AgentPromptOptions): Promise<void>;
1126
+ async prompt(input: string, options?: AgentPromptOptions): Promise<void>;
1127
+ async prompt(input: string, images?: ImageContent[], options?: AgentPromptOptions): Promise<void>;
1128
+ async prompt(
1129
+ input: string | AgentMessage | AgentMessage[],
1130
+ imagesOrOptions?: ImageContent[] | AgentPromptOptions,
1131
+ options?: AgentPromptOptions,
1132
+ ) {
1133
+ if (this.#state.isStreaming) {
1134
+ throw new AgentBusyError();
1135
+ }
1136
+
1137
+ const model = this.#state.model;
1138
+ if (!model) throw new Error("No model configured");
1139
+
1140
+ let msgs: AgentMessage[];
1141
+ let promptOptions: AgentPromptOptions | undefined;
1142
+ let images: ImageContent[] | undefined;
1143
+
1144
+ if (Array.isArray(input)) {
1145
+ msgs = input;
1146
+ promptOptions = imagesOrOptions as AgentPromptOptions | undefined;
1147
+ } else if (typeof input === "string") {
1148
+ if (Array.isArray(imagesOrOptions)) {
1149
+ images = imagesOrOptions;
1150
+ promptOptions = options;
1151
+ } else {
1152
+ promptOptions = imagesOrOptions;
1153
+ }
1154
+ const content: Array<TextContent | ImageContent> = [{ type: "text", text: input }];
1155
+ if (images && images.length > 0) {
1156
+ content.push(...images);
1157
+ }
1158
+ msgs = [
1159
+ {
1160
+ role: "user",
1161
+ content,
1162
+ timestamp: Date.now(),
1163
+ },
1164
+ ];
1165
+ } else {
1166
+ msgs = [input];
1167
+ promptOptions = imagesOrOptions as AgentPromptOptions | undefined;
1168
+ }
1169
+
1170
+ await this.#runLoop(msgs, promptOptions);
1171
+ }
1172
+
1173
+ /**
1174
+ * Continue from current context (used for retries and resuming queued messages).
1175
+ */
1176
+ #continuationDequeueSignal(signal?: AbortSignal): AbortSignal | undefined {
1177
+ const signals: AbortSignal[] = [];
1178
+ if (this.#abortController) signals.push(this.#abortController.signal);
1179
+ if (signal) signals.push(signal);
1180
+ if (this.#deadline !== undefined) {
1181
+ const delay = this.#deadline - Date.now();
1182
+ if (delay <= 0) {
1183
+ const controller = new AbortController();
1184
+ controller.abort(new DOMException("Deadline exceeded", "TimeoutError"));
1185
+ signals.push(controller.signal);
1186
+ } else {
1187
+ signals.push(AbortSignal.timeout(delay));
1188
+ }
1189
+ }
1190
+ if (signals.length === 0) return undefined;
1191
+ return signals.length === 1 ? signals[0] : AbortSignal.any(signals);
1192
+ }
1193
+
1194
+ async continue(signal?: AbortSignal) {
1195
+ if (this.#state.isStreaming) {
1196
+ throw new AgentBusyError();
1197
+ }
1198
+
1199
+ const { promise, resolve } = Promise.withResolvers<void>();
1200
+ this.#runningPrompt = promise;
1201
+ this.#resolveRunningPrompt = resolve;
1202
+ const continuationAbortController = new AbortController();
1203
+ this.#abortController = continuationAbortController;
1204
+ this.#state.isStreaming = true;
1205
+ this.#state.streamMessage = null;
1206
+ this.#state.error = undefined;
1207
+
1208
+ try {
1209
+ const dequeueSignal = this.#continuationDequeueSignal(signal);
1210
+ const messages = this.#state.messages;
1211
+ if (messages.length === 0) {
1212
+ // An empty transcript has nothing to resume, but a queued steer/follow-up
1213
+ // must still be delivered as the opening turn — mirroring the assistant-tail
1214
+ // branch below. Throwing here leaves the message undeliverable, and idle-drain
1215
+ // callers (AgentSession#scheduleQueuedMessageDrain) re-arm continue() on every
1216
+ // microtask because hasQueuedMessages() never clears, spinning an unbounded
1217
+ // allocation loop until OOM (issue #6344).
1218
+ const queuedSteering = await this.#dequeueSteeringMessagesAfterHooks(dequeueSignal);
1219
+ if (queuedSteering.length > 0) {
1220
+ await this.#runLoop(queuedSteering, { skipInitialSteeringPoll: true }, signal, true);
1221
+ return;
1222
+ }
1223
+ const queuedFollowUp = await this.#dequeueFollowUpMessagesAfterHooks(dequeueSignal);
1224
+ if (queuedFollowUp.length > 0) {
1225
+ await this.#runLoop(queuedFollowUp, undefined, signal, true);
1226
+ return;
1227
+ }
1228
+ throw new Error("No messages to continue from");
1229
+ }
1230
+ if (messages[messages.length - 1].role === "assistant") {
1231
+ const queuedSteering = await this.#dequeueSteeringMessagesAfterHooks(dequeueSignal);
1232
+ if (queuedSteering.length > 0) {
1233
+ await this.#runLoop(queuedSteering, { skipInitialSteeringPoll: true }, signal, true);
1234
+ return;
1235
+ }
1236
+
1237
+ const queuedFollowUp = await this.#dequeueFollowUpMessagesAfterHooks(dequeueSignal);
1238
+ if (queuedFollowUp.length > 0) {
1239
+ await this.#runLoop(queuedFollowUp, undefined, signal, true);
1240
+ return;
1241
+ }
1242
+
1243
+ throw new Error("Cannot continue from message role: assistant");
1244
+ }
1245
+
1246
+ await this.#runLoop(undefined, undefined, signal, true);
1247
+ } finally {
1248
+ resolve();
1249
+ if (this.#abortController === continuationAbortController) {
1250
+ this.#state.isStreaming = false;
1251
+ this.#state.streamMessage = null;
1252
+ this.#state.pendingToolCalls.clear();
1253
+ this.#abortController = undefined;
1254
+ if (this.#runningPrompt === promise) {
1255
+ this.#runningPrompt = undefined;
1256
+ this.#resolveRunningPrompt = undefined;
1257
+ }
1258
+ }
1259
+ }
1260
+ }
1261
+
1262
+ /**
1263
+ * Run the agent loop.
1264
+ * If messages are provided, starts a new conversation turn with those messages.
1265
+ * Otherwise, continues from existing context.
1266
+ */
1267
+ async #runLoop(
1268
+ messages?: AgentMessage[],
1269
+ options?: AgentPromptOptions & { skipInitialSteeringPoll?: boolean },
1270
+ continuationSignal?: AbortSignal,
1271
+ runStateClaimed = false,
1272
+ ) {
1273
+ const model = this.#state.model;
1274
+ if (!model) throw new Error("No model configured");
1275
+
1276
+ let skipInitialSteeringPoll = options?.skipInitialSteeringPoll === true;
1277
+ using _ = new EventLoopKeepalive();
1278
+ if (!runStateClaimed) {
1279
+ const { promise, resolve } = Promise.withResolvers<void>();
1280
+ this.#runningPrompt = promise;
1281
+ this.#resolveRunningPrompt = resolve;
1282
+ this.#abortController = new AbortController();
1283
+ }
1284
+ const resolveRun = this.#resolveRunningPrompt;
1285
+ const loopAbortController = this.#abortController;
1286
+ if (!loopAbortController) throw new Error("Agent run state was not initialized");
1287
+ const loopSignal = continuationSignal
1288
+ ? AbortSignal.any([loopAbortController.signal, continuationSignal])
1289
+ : loopAbortController.signal;
1290
+ this.#state.isStreaming = true;
1291
+ this.#state.streamMessage = null;
1292
+ this.#state.error = undefined;
1293
+
1294
+ // Clear Cursor tool result buffer at start of each run
1295
+ this.#cursorToolResultBuffer = [];
1296
+
1297
+ const reasoning = this.#state.thinkingLevel;
1298
+
1299
+ const context: AgentContext = {
1300
+ systemPrompt: this.#state.systemPrompt,
1301
+ messages: this.#state.messages.slice(),
1302
+ tools: this.#state.tools,
1303
+ };
1304
+
1305
+ // Installed unconditionally. Both `cursorExecHandlers` and
1306
+ // `cursorOnToolResult` are optional, but the Cursor provider resolves
1307
+ // native todo calls server-side and synthesizes exec blocks regardless,
1308
+ // marking both `kCursorExecResolved` — `agent-loop.ts` then emits no
1309
+ // placeholder result for them. The provider always offers a paired result
1310
+ // for those blocks (its todo fallback, and every `resolveExecHandler`
1311
+ // exit including the no-handler one), but only through this sink: without
1312
+ // it the result is dropped on the floor, the assistant block is left
1313
+ // unpaired, and `buildSessionContext` strips the whole interaction on
1314
+ // replay. A non-Cursor provider never calls this, so the closure costs
1315
+ // nothing.
1316
+ const cursorOnToolResult = async (message: ToolResultMessage) => {
1317
+ // Cursor executes tools server-side during streaming. We buffer each
1318
+ // toolResult and emit them right after the assistant message closes
1319
+ // (see `#emitCursorSplitAssistantMessage`), so replay receives
1320
+ // (assistant with interleaved toolCall blocks) → results.
1321
+ //
1322
+ // The entry is reserved SYNCHRONOUSLY, before awaiting the optional
1323
+ // transformer. The provider's data loop dispatches messages with
1324
+ // `void handleServerMessage(...)`, so a `message_end` decoded from the
1325
+ // same chunk can drain the buffer while a transformer is still pending
1326
+ // — pushing afterwards would drop the result and strip its toolCall
1327
+ // block as dangling on replay.
1328
+ //
1329
+ // The transformer's in-flight promise is recorded on the entry so the
1330
+ // drain can await it (`#emitCursorSplitAssistantMessage`). Without
1331
+ // that, a transformer resolving after the swap would patch a detached
1332
+ // object while the persisted result kept the original payload — the
1333
+ // rewrite silently lost.
1334
+ const entry: CursorToolResultEntry = { toolResult: message };
1335
+ this.#cursorToolResultBuffer.push(entry);
1336
+ const transform = this.#cursorOnToolResult;
1337
+ if (transform) {
1338
+ const pending = (async () => {
1339
+ try {
1340
+ const updated = await transform(message);
1341
+ if (updated) entry.toolResult = updated;
1342
+ } catch {}
1343
+ })();
1344
+ entry.pending = pending;
1345
+ await pending;
1346
+ entry.pending = undefined;
1347
+ }
1348
+ return entry.toolResult;
1349
+ };
1350
+
1351
+ let claimedToolChoice: ToolChoice | undefined;
1352
+ const getToolChoice = (): ToolChoiceDirective | undefined => {
1353
+ claimedToolChoice = undefined;
1354
+ const deferred = this.#deferredToolChoice;
1355
+ if (deferred !== undefined) {
1356
+ this.#deferredToolChoice = undefined;
1357
+ const active = refreshToolChoiceForActiveTools(deferred, this.#state.tools);
1358
+ if (active !== undefined) {
1359
+ claimedToolChoice = deferred;
1360
+ return active;
1361
+ }
1362
+ this.#onToolChoiceUnavailable?.();
1363
+ }
1364
+
1365
+ const queued = this.#getToolChoice?.();
1366
+ if (queued !== undefined) {
1367
+ if (isSoftToolRequirement(queued)) {
1368
+ return (this.#state.tools ?? []).some(tool => tool.name === queued.toolName) ? queued : undefined;
1369
+ }
1370
+ const active = refreshToolChoiceForActiveTools(queued, this.#state.tools);
1371
+ if (active !== undefined) claimedToolChoice = queued;
1372
+ return active;
1373
+ }
1374
+ return refreshToolChoiceForActiveTools(options?.toolChoice, this.#state.tools);
1375
+ };
1376
+
1377
+ const config: AgentLoopConfig = {
1378
+ model,
1379
+ reasoning,
1380
+ disableReasoning: this.#state.disableReasoning,
1381
+ temperature: this.#temperature,
1382
+ topP: this.#topP,
1383
+ topK: this.#topK,
1384
+ minP: this.#minP,
1385
+ presencePenalty: this.#presencePenalty,
1386
+ repetitionPenalty: this.#repetitionPenalty,
1387
+ serviceTier: this.#serviceTier,
1388
+ hideThinkingSummary: this.#hideThinkingSummary,
1389
+ interruptMode: this.#interruptMode,
1390
+ sessionId: this.#sessionId,
1391
+ deadline: this.#deadline,
1392
+ promptCacheKey: this.#promptCacheKey,
1393
+ metadata: this.#metadataResolver ? undefined : this.#metadata,
1394
+ metadataResolver: this.#metadataResolver,
1395
+ providerSessionState: this.#providerSessionState,
1396
+ thinkingBudgets: this.#thinkingBudgets,
1397
+ maxRetryDelayMs: this.#maxRetryDelayMs,
1398
+ kimiApiFormat: this.#kimiApiFormat,
1399
+ preferWebsockets: this.#preferWebsockets,
1400
+ convertToLlm: this.#convertToLlm,
1401
+ transformProviderContext: this.#transformProviderContext,
1402
+ transformContext: this.#transformContext,
1403
+ onPayload: this.#onPayload,
1404
+ onResponse: this.#onResponse,
1405
+ onSseEvent: this.#onSseEvent,
1406
+ getApiKey: this.getApiKey,
1407
+ getToolContext: this.#getToolContext,
1408
+ syncContextBeforeModelCall: async (context, signal) => {
1409
+ await this.#runBeforeModelCallHooks(signal);
1410
+ if (this.#listeners.size > 0) {
1411
+ await Bun.sleep(0);
1412
+ }
1413
+ context.systemPrompt = this.#state.systemPrompt;
1414
+ context.tools = this.#toolsForModel(this.#state.model ?? model);
1415
+ },
1416
+ beforeModelCall:
1417
+ this.#beforeModelCall || this.#additionalBeforeModelCalls.size > 0
1418
+ ? async (context, signal) => {
1419
+ const result = (await this.#beforeModelCall?.(context, signal)) || undefined;
1420
+ if (result?.stop) return result;
1421
+ for (const callback of this.#additionalBeforeModelCalls) {
1422
+ const callbackResult = (await callback(context, signal)) || undefined;
1423
+ if (callbackResult?.stop) return callbackResult;
1424
+ }
1425
+ return undefined;
1426
+ }
1427
+ : undefined,
1428
+ cursorExecHandlers: this.#cursorExecHandlers,
1429
+ cursorOnToolResult,
1430
+ cwd: this.#cwd,
1431
+ getCwd: this.#cwdResolver,
1432
+ transformToolCallArguments: this.#transformToolCallArguments,
1433
+ resolveFallbackTool: this.#resolveFallbackTool,
1434
+ intentTracing: this.#intentTracing,
1435
+ pruneToolDescriptions: this.#pruneToolDescriptions,
1436
+ dialect: this.#dialect,
1437
+ abortOnFabricatedToolResult: this.#abortOnFabricatedToolResult,
1438
+ appendOnlyContext: this.#appendOnlyContext,
1439
+ beforeToolCall: this.beforeToolCall ? (ctx, signal) => this.beforeToolCall?.(ctx, signal) : undefined,
1440
+ afterToolCall: this.afterToolCall ? (ctx, signal) => this.afterToolCall?.(ctx, signal) : undefined,
1441
+ transformAssistantMessage: this.transformAssistantMessage
1442
+ ? (message, signal) => this.transformAssistantMessage?.(message, signal)
1443
+ : undefined,
1444
+ onAssistantMessageEvent: this.#onAssistantMessageEvent,
1445
+ onHarmonyLeak: this.#onHarmonyLeak,
1446
+ onTurnEnd: (messages, signal, context) => this.#onTurnEnd?.(messages, signal, context),
1447
+ getToolChoice,
1448
+ softToolRequirementState: this.#softToolRequirementState,
1449
+ onToolChoiceRejected: () => {
1450
+ if (claimedToolChoice !== undefined) this.#deferredToolChoice = claimedToolChoice;
1451
+ },
1452
+ getModel: () => this.#state.model ?? model,
1453
+ getReasoning: () => this.#state.thinkingLevel,
1454
+ getDisableReasoning: () => this.#state.disableReasoning,
1455
+ getServiceTier: this.#serviceTierResolver,
1456
+ getSteeringMessages: async signal => {
1457
+ if (skipInitialSteeringPoll) {
1458
+ skipInitialSteeringPoll = false;
1459
+ return [];
1460
+ }
1461
+ return this.#dequeueSteeringMessagesAfterHooks(signal);
1462
+ },
1463
+ hasSteeringMessages: () => {
1464
+ if (this.#steeringQueue.length === 0) {
1465
+ return { queued: false };
1466
+ }
1467
+ const messageCount = this.#steeringMode === "one-at-a-time" ? 1 : this.#steeringQueue.length;
1468
+ let hasAgentSteering = false;
1469
+ for (let i = 0; i < messageCount; i++) {
1470
+ const message = this.#steeringQueue[i];
1471
+ const role = "role" in message ? message.role : undefined;
1472
+ const attribution = "attribution" in message ? message.attribution : undefined;
1473
+ if (attribution === "user") {
1474
+ return { queued: true, source: "user" };
1475
+ }
1476
+ if (role !== "user") continue;
1477
+ if (attribution !== "agent") {
1478
+ return { queued: true, source: "user" };
1479
+ }
1480
+ hasAgentSteering = true;
1481
+ }
1482
+ return { queued: true, source: hasAgentSteering ? "agent" : "system" };
1483
+ },
1484
+ waitForSteeringMessages: signal => this.#waitForSteeringMessages(signal),
1485
+ hasIrcInterrupts: this.hasIrcInterrupts,
1486
+ getFollowUpMessages: signal => this.#dequeueFollowUpMessagesAfterHooks(signal),
1487
+ getAsideMessages: async () => (await this.#asideMessageProvider?.()) ?? [],
1488
+ onBeforeYield: () => this.#onBeforeYield?.(),
1489
+ telemetry: this.#telemetry,
1490
+ };
1491
+
1492
+ let partial: AgentMessage | null = null;
1493
+ const completedToolCallIds = new Set<string>();
1494
+ let turnOpen = false;
1495
+
1496
+ try {
1497
+ const stream = messages
1498
+ ? agentLoop(messages, context, config, loopSignal, this.streamFn)
1499
+ : agentLoopContinue(context, config, loopSignal, this.streamFn);
1500
+
1501
+ for await (const event of stream) {
1502
+ if (event.type === "turn_start") turnOpen = true;
1503
+ if (event.type === "turn_end") turnOpen = false;
1504
+ // Update internal state based on events
1505
+ switch (event.type) {
1506
+ case "message_start":
1507
+ partial = event.message;
1508
+ this.#state.streamMessage = event.message;
1509
+ break;
1510
+
1511
+ case "message_update":
1512
+ partial = event.message;
1513
+ this.#state.streamMessage = event.message;
1514
+ if (event.assistantMessageEvent.type === "toolcall_end") {
1515
+ completedToolCallIds.add(event.assistantMessageEvent.toolCall.id);
1516
+ }
1517
+ break;
1518
+
1519
+ case "message_end":
1520
+ partial = null;
1521
+ // Check if this is an assistant message with buffered Cursor tool results.
1522
+ // If so, split the message to emit tool results at the correct position.
1523
+ if (event.message.role === "assistant" && this.#cursorToolResultBuffer.length > 0) {
1524
+ await this.#emitCursorSplitAssistantMessage(event.message as AssistantMessage);
1525
+ continue; // Skip default emit - split method handles everything
1526
+ }
1527
+ this.#state.streamMessage = null;
1528
+ this.appendMessage(event.message);
1529
+ break;
1530
+
1531
+ case "tool_execution_start":
1532
+ this.#state.pendingToolCalls.add(event.toolCallId);
1533
+ break;
1534
+
1535
+ case "tool_execution_end":
1536
+ this.#state.pendingToolCalls.delete(event.toolCallId);
1537
+ break;
1538
+
1539
+ case "turn_end":
1540
+ if (event.message.role === "assistant" && (event.message as any).errorMessage) {
1541
+ this.#state.error = (event.message as any).errorMessage;
1542
+ }
1543
+ break;
1544
+
1545
+ case "agent_end":
1546
+ this.#state.isStreaming = false;
1547
+ this.#state.streamMessage = null;
1548
+ break;
1549
+ }
1550
+
1551
+ // Emit to listeners
1552
+ this.#emit(event);
1553
+ }
1554
+
1555
+ // Handle any remaining partial message
1556
+ if (partial && partial.role === "assistant" && Array.isArray(partial.content) && partial.content.length > 0) {
1557
+ const onlyEmpty = !partial.content.some(
1558
+ c =>
1559
+ (c.type === "thinking" && c.thinking.trim().length > 0) ||
1560
+ (c.type === "text" && c.text.trim().length > 0) ||
1561
+ (c.type === "toolCall" && c.name.trim().length > 0),
1562
+ );
1563
+ if (!onlyEmpty) {
1564
+ this.appendMessage(partial);
1565
+ } else {
1566
+ if (loopSignal.aborted) {
1567
+ throw new Error("Request was aborted");
1568
+ }
1569
+ }
1570
+ }
1571
+ } catch (err) {
1572
+ const stoppedForAbort = loopSignal.aborted;
1573
+ const errorMessage = stoppedForAbort
1574
+ ? abortReasonText(loopSignal)
1575
+ : err instanceof Error
1576
+ ? err.message
1577
+ : String(err);
1578
+ const shouldEmitVisibleError = !stoppedForAbort;
1579
+ const assistantPartial = partial?.role === "assistant" ? partial : undefined;
1580
+ const hadAssistantStart = assistantPartial !== undefined;
1581
+ // Same contract as the normal drain in `#emitCursorSplitAssistantMessage`:
1582
+ // a transformer still in flight must be awaited before the payload is
1583
+ // snapshotted, or its rewrite patches an entry this catch path already
1584
+ // detached and the original is persisted instead. A provider error is
1585
+ // exactly when a transform is most likely to be mid-flight.
1586
+ const pendingTransforms = this.#cursorToolResultBuffer
1587
+ .filter(entry => entry.pending !== undefined)
1588
+ .map(entry => entry.pending);
1589
+ if (pendingTransforms.length > 0) await Promise.all(pendingTransforms);
1590
+ const bufferedCursorResults = this.#cursorToolResultBuffer.map(({ toolResult }) => toolResult);
1591
+ const retainedToolCallIds = new Set(completedToolCallIds);
1592
+ for (const { toolCallId } of bufferedCursorResults) retainedToolCallIds.add(toolCallId);
1593
+ const errorMsg: AssistantMessage =
1594
+ shouldEmitVisibleError && assistantPartial
1595
+ ? {
1596
+ ...assistantPartial,
1597
+ content: assistantPartial.content.filter(
1598
+ block => block.type !== "toolCall" || retainedToolCallIds.has(block.id),
1599
+ ),
1600
+ stopReason: "error",
1601
+ errorMessage,
1602
+ }
1603
+ : {
1604
+ role: "assistant",
1605
+ content: [{ type: "text", text: "" }],
1606
+ api: model.api,
1607
+ provider: model.provider,
1608
+ model: model.id,
1609
+ usage: {
1610
+ input: 0,
1611
+ output: 0,
1612
+ cacheRead: 0,
1613
+ cacheWrite: 0,
1614
+ totalTokens: 0,
1615
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
1616
+ },
1617
+ stopReason: stoppedForAbort ? "aborted" : "error",
1618
+ errorMessage,
1619
+ timestamp: Date.now(),
1620
+ };
1621
+
1622
+ if (shouldEmitVisibleError) {
1623
+ if (!turnOpen) {
1624
+ this.#emit({ type: "turn_start" });
1625
+ turnOpen = true;
1626
+ }
1627
+ if (!hadAssistantStart) {
1628
+ this.#state.streamMessage = errorMsg;
1629
+ this.#emit({ type: "message_start", message: errorMsg });
1630
+ }
1631
+ this.#state.streamMessage = null;
1632
+ this.appendMessage(errorMsg);
1633
+ this.#state.error = errorMessage;
1634
+ this.#emit({ type: "message_end", message: errorMsg });
1635
+ const toolResults: ToolResultMessage[] = [];
1636
+ this.#cursorToolResultBuffer = [];
1637
+ const bufferedCursorToolCallIds = new Set(bufferedCursorResults.map(({ toolCallId }) => toolCallId));
1638
+ for (const toolResult of bufferedCursorResults) {
1639
+ this.appendMessage(toolResult);
1640
+ this.#emit({ type: "message_start", message: toolResult });
1641
+ this.#emit({ type: "message_end", message: toolResult });
1642
+ toolResults.push(toolResult);
1643
+ }
1644
+ for (const block of errorMsg.content) {
1645
+ if (block.type !== "toolCall") continue;
1646
+ if (bufferedCursorToolCallIds.has(block.id)) continue;
1647
+ const toolResult = createSyntheticToolResultMessage(block, "error", errorMessage);
1648
+ this.#emit({
1649
+ type: "tool_execution_start",
1650
+ toolCallId: block.id,
1651
+ toolName: block.name,
1652
+ args: block.arguments,
1653
+ intent: block.intent,
1654
+ });
1655
+ this.#emit({
1656
+ type: "tool_execution_end",
1657
+ toolCallId: block.id,
1658
+ toolName: block.name,
1659
+ result: { content: toolResult.content, details: toolResult.details },
1660
+ isError: true,
1661
+ });
1662
+ this.appendMessage(toolResult);
1663
+ this.#emit({ type: "message_start", message: toolResult });
1664
+ this.#emit({ type: "message_end", message: toolResult });
1665
+ toolResults.push(toolResult);
1666
+ }
1667
+ this.#emit({ type: "turn_end", message: errorMsg, toolResults });
1668
+ turnOpen = false;
1669
+ this.#emit({ type: "agent_end", messages: [errorMsg, ...toolResults] });
1670
+ } else {
1671
+ this.appendMessage(errorMsg);
1672
+ this.#state.error = errorMessage;
1673
+ this.#emit({ type: "agent_end", messages: [errorMsg] });
1674
+ }
1675
+ } finally {
1676
+ resolveRun?.();
1677
+ if (this.#abortController === loopAbortController) {
1678
+ this.#state.isStreaming = false;
1679
+ this.#state.streamMessage = null;
1680
+ this.#state.pendingToolCalls.clear();
1681
+ this.#abortController = undefined;
1682
+ this.#runningPrompt = undefined;
1683
+ this.#resolveRunningPrompt = undefined;
1684
+ }
1685
+ }
1686
+ }
1687
+
1688
+ #emit(e: AgentEvent) {
1689
+ for (const listener of this.#listeners) {
1690
+ try {
1691
+ const result = listener(e) as unknown;
1692
+ if (isPromise(result)) {
1693
+ result.catch(err => {
1694
+ logger.warn("Agent listener rejected", {
1695
+ error: err instanceof Error ? err.message : String(err),
1696
+ });
1697
+ });
1698
+ }
1699
+ } catch (err) {
1700
+ logger.warn("Agent listener threw", {
1701
+ error: err instanceof Error ? err.message : String(err),
1702
+ });
1703
+ }
1704
+ }
1705
+ }
1706
+
1707
+ /**
1708
+ * Emit a Cursor assistant message with buffered exec-channel toolResults.
1709
+ *
1710
+ * Since the Cursor provider now synthesizes `toolCall` content blocks at the
1711
+ * point each exec tool starts (issue #4348), the assistant message content
1712
+ * already interleaves text/thinking with toolCall blocks in execution order.
1713
+ * We emit the message as-is and let the buffered toolResults follow — the
1714
+ * transcript rebuild in `renderSessionContext` pairs them by `toolCallId`.
1715
+ *
1716
+ * Historical note: this used to split the assistant message at
1717
+ * `textLengthAtCall` to interpose toolResults between preamble and
1718
+ * continuation. That workaround existed because native cursor tools had no
1719
+ * toolCall blocks; it also copied `preambleText` into every text block on
1720
+ * multi-text turns, producing duplicated text on replay.
1721
+ */
1722
+ async #emitCursorSplitAssistantMessage(assistantMessage: AssistantMessage): Promise<void> {
1723
+ // Snapshot and detach immediately so a still-pending `cursorOnToolResult`
1724
+ // cannot push into a drained buffer. Entries already reserved stay paired
1725
+ // with their toolCall.
1726
+ const buffer = this.#cursorToolResultBuffer;
1727
+ this.#cursorToolResultBuffer = [];
1728
+
1729
+ // Await any transformer still running for a reserved entry before reading
1730
+ // its payload. The provider dispatches with `void handleServerMessage(…)`,
1731
+ // so a `message_end` from the same chunk can reach this point while a
1732
+ // transformer is mid-flight; without the await its rewrite would land on
1733
+ // the detached entry after the original was already appended and emitted.
1734
+ // Each `pending` swallows its own rejection, so this cannot throw.
1735
+ const pending = buffer.filter(entry => entry.pending !== undefined).map(entry => entry.pending);
1736
+ if (pending.length > 0) await Promise.all(pending);
1737
+
1738
+ this.#state.streamMessage = null;
1739
+ this.appendMessage(assistantMessage);
1740
+ this.#emit({ type: "message_end", message: assistantMessage });
1741
+
1742
+ for (const { toolResult } of buffer) {
1743
+ this.#emit({ type: "message_start", message: toolResult });
1744
+ this.appendMessage(toolResult);
1745
+ this.#emit({ type: "message_end", message: toolResult });
1746
+ }
1747
+ }
1748
+ }