@sayknow-cli/agent-core 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +588 -0
  2. package/README.md +473 -0
  3. package/dist/types/agent-loop.d.ts +56 -0
  4. package/dist/types/agent.d.ts +381 -0
  5. package/dist/types/append-only-context.d.ts +124 -0
  6. package/dist/types/compaction/branch-summarization.d.ts +103 -0
  7. package/dist/types/compaction/compaction.d.ts +253 -0
  8. package/dist/types/compaction/entries.d.ts +109 -0
  9. package/dist/types/compaction/errors.d.ts +26 -0
  10. package/dist/types/compaction/index.d.ts +11 -0
  11. package/dist/types/compaction/messages.d.ts +61 -0
  12. package/dist/types/compaction/openai.d.ts +62 -0
  13. package/dist/types/compaction/pruning.d.ts +37 -0
  14. package/dist/types/compaction/utils.d.ts +32 -0
  15. package/dist/types/compaction.d.ts +1 -0
  16. package/dist/types/harmony-leak.d.ts +99 -0
  17. package/dist/types/index.d.ts +10 -0
  18. package/dist/types/proxy.d.ts +84 -0
  19. package/dist/types/run-collector.d.ts +196 -0
  20. package/dist/types/telemetry.d.ts +596 -0
  21. package/dist/types/thinking.d.ts +18 -0
  22. package/dist/types/types.d.ts +430 -0
  23. package/package.json +75 -0
  24. package/src/agent-loop.ts +1302 -0
  25. package/src/agent.ts +1531 -0
  26. package/src/append-only-context.ts +460 -0
  27. package/src/compaction/branch-summarization.ts +358 -0
  28. package/src/compaction/compaction.ts +1342 -0
  29. package/src/compaction/entries.ts +139 -0
  30. package/src/compaction/errors.ts +31 -0
  31. package/src/compaction/index.ts +12 -0
  32. package/src/compaction/messages.ts +212 -0
  33. package/src/compaction/openai.ts +570 -0
  34. package/src/compaction/prompts/auto-handoff-threshold-focus.md +1 -0
  35. package/src/compaction/prompts/branch-summary-context.md +5 -0
  36. package/src/compaction/prompts/branch-summary-preamble.md +2 -0
  37. package/src/compaction/prompts/branch-summary.md +30 -0
  38. package/src/compaction/prompts/compaction-short-summary.md +9 -0
  39. package/src/compaction/prompts/compaction-summary-context.md +5 -0
  40. package/src/compaction/prompts/compaction-summary.md +38 -0
  41. package/src/compaction/prompts/compaction-turn-prefix.md +17 -0
  42. package/src/compaction/prompts/compaction-update-summary.md +45 -0
  43. package/src/compaction/prompts/file-operations.md +10 -0
  44. package/src/compaction/prompts/handoff-document.md +49 -0
  45. package/src/compaction/prompts/summarization-system.md +3 -0
  46. package/src/compaction/pruning.ts +431 -0
  47. package/src/compaction/utils.ts +185 -0
  48. package/src/compaction.ts +1 -0
  49. package/src/harmony-leak.ts +428 -0
  50. package/src/index.ts +19 -0
  51. package/src/proxy.ts +326 -0
  52. package/src/run-collector.ts +631 -0
  53. package/src/telemetry.ts +2049 -0
  54. package/src/thinking.ts +20 -0
  55. package/src/types.ts +490 -0
package/src/agent.ts ADDED
@@ -0,0 +1,1531 @@
1
+ /** Agent class that uses the agent-loop directly.
2
+ * No transport abstraction - calls streamSimple via the loop.
3
+ */
4
+ import {
5
+ type AssistantMessage,
6
+ type AssistantMessageEvent,
7
+ type CursorExecHandlers,
8
+ type CursorToolResultHandler,
9
+ type Effort,
10
+ getBundledModel,
11
+ type ImageContent,
12
+ type Message,
13
+ type Model,
14
+ type ProviderSessionState,
15
+ type ServiceTier,
16
+ type SimpleStreamOptions,
17
+ streamSimple,
18
+ type TextContent,
19
+ type ThinkingBudgets,
20
+ type ToolChoice,
21
+ type ToolResultMessage,
22
+ } from "@sayknow-cli/ai";
23
+ import { agentLoop, agentLoopContinue } from "./agent-loop";
24
+ import type { AppendOnlyContextManager } from "./append-only-context";
25
+ import type { HarmonyAuditEvent } from "./harmony-leak";
26
+ import type {
27
+ AgentContext,
28
+ AgentEvent,
29
+ AgentLoopConfig,
30
+ AgentMessage,
31
+ AgentState,
32
+ AgentTool,
33
+ AgentToolContext,
34
+ StreamFn,
35
+ ToolCallContext,
36
+ } from "./types";
37
+
38
+ /**
39
+ * Default convertToLlm: Keep only LLM-compatible messages, convert attachments.
40
+ */
41
+ function defaultConvertToLlm(messages: AgentMessage[]): Message[] {
42
+ return messages.filter((m): m is Message => m.role === "user" || m.role === "assistant" || m.role === "toolResult");
43
+ }
44
+
45
+ function refreshToolChoiceForActiveTools(
46
+ toolChoice: ToolChoice | undefined,
47
+ tools: AgentContext["tools"] = [],
48
+ ): ToolChoice | undefined {
49
+ if (!toolChoice || typeof toolChoice === "string") {
50
+ return toolChoice;
51
+ }
52
+
53
+ const toolName =
54
+ toolChoice.type === "tool"
55
+ ? toolChoice.name
56
+ : "function" in toolChoice
57
+ ? toolChoice.function.name
58
+ : toolChoice.name;
59
+
60
+ return tools.some(tool => tool.name === toolName) ? toolChoice : undefined;
61
+ }
62
+
63
+ export class AgentBusyError extends Error {
64
+ constructor(
65
+ message: string = "Agent is already processing. Use steer() or followUp() to queue messages, or wait for completion.",
66
+ ) {
67
+ super(message);
68
+ this.name = "AgentBusyError";
69
+ }
70
+ }
71
+ export interface AgentOptions {
72
+ initialState?: Partial<AgentState>;
73
+
74
+ /**
75
+ * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
76
+ * Default filters to user/assistant/toolResult and converts attachments.
77
+ */
78
+ convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
79
+
80
+ /**
81
+ * Optional transform applied to context before convertToLlm.
82
+ * Use for context pruning, injecting external context, etc.
83
+ */
84
+ transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
85
+
86
+ /**
87
+ * Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
88
+ */
89
+ steeringMode?: "all" | "one-at-a-time";
90
+
91
+ /**
92
+ * Follow-up mode: "all" = send all follow-up messages at once, "one-at-a-time" = one per turn
93
+ */
94
+ followUpMode?: "all" | "one-at-a-time";
95
+
96
+ /**
97
+ * When to interrupt tool execution for steering messages.
98
+ * - "immediate": check after each tool call (default)
99
+ * - "wait": defer steering until the current turn completes
100
+ */
101
+ interruptMode?: "immediate" | "wait";
102
+ /** Cooperative pause checkpoint passed through to AgentLoopConfig.shouldPause. */
103
+ shouldPause?: AgentLoopConfig["shouldPause"];
104
+
105
+ /**
106
+ * API format for Kimi Code provider: "openai" or "anthropic" (default: "anthropic")
107
+ */
108
+ kimiApiFormat?: "openai" | "anthropic";
109
+
110
+ /** Hint that websocket transport should be preferred when supported by the provider implementation. */
111
+ preferWebsockets?: boolean;
112
+
113
+ /**
114
+ * Custom stream function (for proxy backends, etc.). Default uses streamSimple.
115
+ */
116
+ streamFn?: StreamFn;
117
+
118
+ /**
119
+ * Optional session identifier forwarded to LLM providers.
120
+ * Used by providers that support session-based caching (e.g., OpenAI code provider).
121
+ */
122
+ sessionId?: string;
123
+ /** Provider-facing cache/session affinity identifier. */
124
+ providerSessionId?: string;
125
+ /**
126
+ * Shared provider state map for session-scoped transport/session caches.
127
+ */
128
+ providerSessionState?: Map<string, ProviderSessionState>;
129
+
130
+ /**
131
+ * Resolves an API key dynamically for each LLM call.
132
+ * Useful for expiring tokens (e.g., GitHub Copilot OAuth).
133
+ */
134
+ getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
135
+ getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
136
+
137
+ /**
138
+ * Inspect or replace provider payloads before they are sent.
139
+ */
140
+ onPayload?: SimpleStreamOptions["onPayload"];
141
+ /**
142
+ * Inspect provider response metadata after headers arrive and before streaming body consumption.
143
+ */
144
+ onResponse?: SimpleStreamOptions["onResponse"];
145
+ /**
146
+ * Inspect raw Server-Sent Events from HTTP streaming providers.
147
+ */
148
+ onSseEvent?: SimpleStreamOptions["onSseEvent"];
149
+ /**
150
+ * Inspect assistant streaming events before they are emitted to subscribers.
151
+ * Use this when abort decisions must happen before buffered events continue flowing.
152
+ */
153
+ onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
154
+ /** Called for non-content tool-choice incapability stream events. */
155
+ onToolChoiceIncapability?: AgentLoopConfig["onToolChoiceIncapability"];
156
+
157
+ /**
158
+ * Called when GPT-5 Harmony protocol leakage is detected and mitigated.
159
+ */
160
+ onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
161
+ /**
162
+ * Custom token budgets for thinking levels (token-based providers only).
163
+ */
164
+ thinkingBudgets?: ThinkingBudgets;
165
+
166
+ /**
167
+ * Sampling temperature for LLM calls. `undefined` uses provider default.
168
+ */
169
+ temperature?: number;
170
+
171
+ /** Additional sampling controls for providers that support them. */
172
+ topP?: number;
173
+ topK?: number;
174
+ minP?: number;
175
+ presencePenalty?: number;
176
+ repetitionPenalty?: number;
177
+ serviceTier?: ServiceTier;
178
+ /**
179
+ * If true, request that the underlying provider omit reasoning/thinking summaries
180
+ * from the response. The model still reasons internally; only the human-readable
181
+ * summary stream is suppressed. Useful when the UI hides thinking blocks anyway.
182
+ */
183
+ hideThinkingSummary?: boolean;
184
+
185
+ /**
186
+ * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
187
+ * If the server's requested delay exceeds this value, the request fails immediately,
188
+ * allowing higher-level retry logic to handle it with user visibility.
189
+ * Default: 60000 (60 seconds). Set to 0 to disable the cap.
190
+ */
191
+ maxRetryDelayMs?: number;
192
+ /** Provider request retry budget. Counts retries, not the initial attempt. */
193
+ requestMaxRetries?: number;
194
+ /** Provider stream replay retry budget. Counts retries, not the initial attempt. */
195
+ streamMaxRetries?: number;
196
+
197
+ /**
198
+ * Provides tool execution context, resolved per tool call.
199
+ * Use for late-bound UI or session state access.
200
+ */
201
+ getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
202
+
203
+ /**
204
+ * Optional transform applied to tool call arguments before execution.
205
+ * Use for deobfuscating secrets or rewriting arguments.
206
+ */
207
+ transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
208
+
209
+ /** Enable intent tracing schema injection/stripping in the harness. */
210
+ intentTracing?: boolean;
211
+ /** Dynamic tool choice override, resolved per LLM call. */
212
+ getToolChoice?: () => ToolChoice | undefined;
213
+
214
+ /**
215
+ * Cursor exec handlers for local tool execution.
216
+ */
217
+ cursorExecHandlers?: CursorExecHandlers;
218
+
219
+ /**
220
+ * Cursor tool result callback for exec tool responses.
221
+ */
222
+ cursorOnToolResult?: CursorToolResultHandler;
223
+
224
+ /**
225
+ * Called after a tool call has been validated and is about to execute.
226
+ * See {@link AgentLoopConfig.beforeToolCall} for full semantics.
227
+ */
228
+ beforeToolCall?: AgentLoopConfig["beforeToolCall"];
229
+
230
+ /**
231
+ * Called after a tool finishes executing, before `tool_execution_end` and the tool-result
232
+ * message are emitted. See {@link AgentLoopConfig.afterToolCall} for full semantics.
233
+ */
234
+ afterToolCall?: AgentLoopConfig["afterToolCall"];
235
+
236
+ /**
237
+ * Opt-in OpenTelemetry instrumentation. Passing `{}` enables the loop's
238
+ * GenAI-semantic-convention spans using the global tracer provider. See
239
+ * {@link AgentLoopConfig.telemetry} for the full surface.
240
+ */
241
+ telemetry?: AgentLoopConfig["telemetry"];
242
+ /**
243
+ * Immutable context mode — stabilizes system prompt + tool spec bytes
244
+ * across turns so DeepSeek/Anthropic prefix caches hit at maximum rate.
245
+ */
246
+ appendOnlyContext?: AppendOnlyContextManager;
247
+ }
248
+
249
+ export interface AgentPromptOptions {
250
+ toolChoice?: ToolChoice;
251
+ }
252
+
253
+ /** Buffered Cursor tool result with text position at time of call */
254
+ interface CursorToolResultEntry {
255
+ toolResult: ToolResultMessage;
256
+ textLengthAtCall: number;
257
+ }
258
+
259
+ export class Agent {
260
+ #state: AgentState = {
261
+ systemPrompt: [],
262
+ model: getBundledModel("google", "gemini-2.5-flash-lite-preview-06-17"),
263
+ thinkingLevel: undefined,
264
+ tools: [],
265
+ messages: [],
266
+ isStreaming: false,
267
+ streamMessage: null,
268
+ pendingToolCalls: new Set<string>(),
269
+ error: undefined,
270
+ };
271
+
272
+ #listeners = new Set<(e: AgentEvent) => void>();
273
+ #abortController?: AbortController;
274
+ #convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
275
+ #transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
276
+ #steeringQueue: AgentMessage[] = [];
277
+ #followUpQueue: AgentMessage[] = [];
278
+ #steeringMode: "all" | "one-at-a-time";
279
+ #followUpMode: "all" | "one-at-a-time";
280
+ #interruptMode: "immediate" | "wait";
281
+ #sessionId?: string;
282
+ #providerSessionId?: string;
283
+ #metadata?: Record<string, unknown>;
284
+ #metadataResolver?: (provider: string) => Record<string, unknown> | undefined;
285
+ #providerSessionState?: Map<string, ProviderSessionState>;
286
+ #thinkingBudgets?: ThinkingBudgets;
287
+ #temperature?: number;
288
+ #topP?: number;
289
+ #topK?: number;
290
+ #minP?: number;
291
+ #presencePenalty?: number;
292
+ #repetitionPenalty?: number;
293
+ #serviceTier?: ServiceTier;
294
+ #hideThinkingSummary?: boolean;
295
+ #maxRetryDelayMs?: number;
296
+ #requestMaxRetries?: number;
297
+ #streamMaxRetries?: number;
298
+ #getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
299
+ #cursorExecHandlers?: CursorExecHandlers;
300
+ #cursorOnToolResult?: CursorToolResultHandler;
301
+ #runningPrompt?: Promise<void>;
302
+ #resolveRunningPrompt?: () => void;
303
+ #runSequence = 0;
304
+ #activeRunId?: number;
305
+ #kimiApiFormat?: "openai" | "anthropic";
306
+ #preferWebsockets?: boolean;
307
+ #transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
308
+ #intentTracing: boolean;
309
+ #getToolChoice?: () => ToolChoice | undefined;
310
+ #onPayload?: SimpleStreamOptions["onPayload"];
311
+ #onResponse?: SimpleStreamOptions["onResponse"];
312
+ #onSseEvent?: SimpleStreamOptions["onSseEvent"];
313
+ #onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
314
+ #onToolChoiceIncapability?: AgentLoopConfig["onToolChoiceIncapability"];
315
+ #onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
316
+ #onBeforeYield?: () => Promise<void> | void;
317
+ #shouldPause?: AgentLoopConfig["shouldPause"];
318
+ #telemetry?: AgentLoopConfig["telemetry"];
319
+ #appendOnlyContext?: AppendOnlyContextManager;
320
+
321
+ get intentTracing(): boolean {
322
+ return this.#intentTracing;
323
+ }
324
+
325
+ /** Buffered Cursor tool results with text length at time of call (for correct ordering) */
326
+ #cursorToolResultBuffer: CursorToolResultEntry[] = [];
327
+
328
+ streamFn: StreamFn;
329
+ getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
330
+ getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
331
+ /**
332
+ * Hook invoked after tool arguments are validated and before execution.
333
+ * Reassign at any time to swap the implementation (e.g. on extension reload).
334
+ */
335
+ beforeToolCall?: AgentLoopConfig["beforeToolCall"];
336
+ /**
337
+ * Hook invoked after tool execution and before `tool_execution_end` / tool-result
338
+ * message emission. Reassign at any time to swap the implementation.
339
+ */
340
+ afterToolCall?: AgentLoopConfig["afterToolCall"];
341
+
342
+ constructor(opts: AgentOptions = {}) {
343
+ this.#state = { ...this.#state, ...opts.initialState };
344
+ this.#convertToLlm = opts.convertToLlm || defaultConvertToLlm;
345
+ this.#transformContext = opts.transformContext;
346
+ this.#steeringMode = opts.steeringMode || "one-at-a-time";
347
+ this.#followUpMode = opts.followUpMode || "one-at-a-time";
348
+ this.#interruptMode = opts.interruptMode || "immediate";
349
+ this.streamFn = opts.streamFn || streamSimple;
350
+ this.#sessionId = opts.sessionId;
351
+ this.#providerSessionId = opts.providerSessionId;
352
+ this.#providerSessionState = opts.providerSessionState;
353
+ this.#thinkingBudgets = opts.thinkingBudgets;
354
+ this.#temperature = opts.temperature;
355
+ this.#topP = opts.topP;
356
+ this.#topK = opts.topK;
357
+ this.#minP = opts.minP;
358
+ this.#presencePenalty = opts.presencePenalty;
359
+ this.#repetitionPenalty = opts.repetitionPenalty;
360
+ this.#serviceTier = opts.serviceTier;
361
+ this.#hideThinkingSummary = opts.hideThinkingSummary;
362
+ this.#maxRetryDelayMs = opts.maxRetryDelayMs;
363
+ this.#requestMaxRetries = opts.requestMaxRetries;
364
+ this.#streamMaxRetries = opts.streamMaxRetries;
365
+ this.getApiKey = opts.getApiKey;
366
+ this.getAuthCredentialType = opts.getAuthCredentialType;
367
+ this.#onPayload = opts.onPayload;
368
+ this.#onResponse = opts.onResponse;
369
+ this.#onSseEvent = opts.onSseEvent;
370
+ this.#getToolContext = opts.getToolContext;
371
+ this.#cursorExecHandlers = opts.cursorExecHandlers;
372
+ this.#cursorOnToolResult = opts.cursorOnToolResult;
373
+ this.#kimiApiFormat = opts.kimiApiFormat;
374
+ this.#preferWebsockets = opts.preferWebsockets;
375
+ this.#transformToolCallArguments = opts.transformToolCallArguments;
376
+ this.#intentTracing = opts.intentTracing === true;
377
+ this.#getToolChoice = opts.getToolChoice;
378
+ this.#onAssistantMessageEvent = opts.onAssistantMessageEvent;
379
+ this.#onToolChoiceIncapability = opts.onToolChoiceIncapability;
380
+ this.#onHarmonyLeak = opts.onHarmonyLeak;
381
+ this.#shouldPause = opts.shouldPause;
382
+ this.beforeToolCall = opts.beforeToolCall;
383
+ this.afterToolCall = opts.afterToolCall;
384
+ this.#telemetry = opts.telemetry;
385
+ this.#appendOnlyContext = opts.appendOnlyContext;
386
+ }
387
+
388
+ /**
389
+ * Get the current session ID used for provider caching.
390
+ */
391
+ get sessionId(): string | undefined {
392
+ return this.#sessionId;
393
+ }
394
+
395
+ /**
396
+ * Set the session ID for provider caching.
397
+ * Call this when switching sessions (new session, branch, resume).
398
+ */
399
+ set sessionId(value: string | undefined) {
400
+ this.#sessionId = value;
401
+ }
402
+
403
+ get providerSessionId(): string | undefined {
404
+ return this.#providerSessionId;
405
+ }
406
+
407
+ set providerSessionId(value: string | undefined) {
408
+ this.#providerSessionId = value;
409
+ }
410
+
411
+ /**
412
+ * Whether websocket transport is preferred when the provider implementation
413
+ * supports it. Read by maintenance one-shot calls (compaction, handoff,
414
+ * branch summary) so they forward the same transport preference as live turns.
415
+ */
416
+ get preferWebsockets(): boolean | undefined {
417
+ return this.#preferWebsockets;
418
+ }
419
+
420
+ /**
421
+ * Static metadata forwarded to every API request when no resolver is installed
422
+ * (e.g. `metadata.user_id` for Anthropic session attribution). Setting this
423
+ * clears any installed resolver.
424
+ *
425
+ * For live/provider-aware metadata (e.g. Anthropic OAuth `account_uuid` that
426
+ * must reflect the credential selected per-request), use
427
+ * {@link setMetadataResolver} and read via {@link metadataForProvider}.
428
+ */
429
+ get metadata(): Record<string, unknown> | undefined {
430
+ return this.#metadata;
431
+ }
432
+
433
+ set metadata(value: Record<string, unknown> | undefined) {
434
+ this.#metadata = value;
435
+ this.#metadataResolver = undefined;
436
+ }
437
+
438
+ /**
439
+ * Resolve request metadata for the given provider at call time. When a
440
+ * resolver is installed via {@link setMetadataResolver}, it is invoked with
441
+ * the provider string so the result can be scoped (e.g. `account_uuid` is
442
+ * only included for `"anthropic"` requests). Falls back to the static
443
+ * {@link metadata} value when no resolver is set.
444
+ */
445
+ metadataForProvider(provider: string): Record<string, unknown> | undefined {
446
+ if (this.#metadataResolver) return this.#metadataResolver(provider);
447
+ return this.#metadata;
448
+ }
449
+
450
+ /**
451
+ * Install a function that resolves request metadata at call time. The
452
+ * resolver receives the target provider string and can gate provider-specific
453
+ * fields (e.g. `account_uuid` only for `"anthropic"`). Invoked per LLM
454
+ * request by `agent-loop` after `getApiKey` selects the session-sticky
455
+ * credential. Pass `undefined` to clear and revert to the static
456
+ * {@link metadata} value.
457
+ */
458
+ setMetadataResolver(resolver: ((provider: string) => Record<string, unknown> | undefined) | undefined): void {
459
+ this.#metadataResolver = resolver;
460
+ }
461
+
462
+ /**
463
+ * Read the active OpenTelemetry configuration. Returns `undefined` when
464
+ * instrumentation is disabled. Callers spawning child runs (e.g. subagent
465
+ * dispatch) forward this to the child's loop so its spans appear under the
466
+ * parent's active context with the subagent's own identity stamped.
467
+ */
468
+ get telemetry(): AgentLoopConfig["telemetry"] | undefined {
469
+ return this.#telemetry;
470
+ }
471
+
472
+ /**
473
+ * Replace the active OpenTelemetry configuration. Pass `undefined` to
474
+ * disable instrumentation. Applies to the *next* `agentLoop` invocation —
475
+ * in-flight loops keep the configuration they started with.
476
+ */
477
+ setTelemetry(telemetry: AgentLoopConfig["telemetry"] | undefined): void {
478
+ this.#telemetry = telemetry;
479
+ }
480
+
481
+ /**
482
+ * Get provider-scoped mutable session state store.
483
+ */
484
+ get providerSessionState(): Map<string, ProviderSessionState> | undefined {
485
+ return this.#providerSessionState;
486
+ }
487
+
488
+ /**
489
+ * Set provider-scoped mutable session state store.
490
+ */
491
+ set providerSessionState(value: Map<string, ProviderSessionState> | undefined) {
492
+ this.#providerSessionState = value;
493
+ }
494
+
495
+ /**
496
+ * Get the current thinking budgets.
497
+ */
498
+ get thinkingBudgets(): ThinkingBudgets | undefined {
499
+ return this.#thinkingBudgets;
500
+ }
501
+
502
+ /**
503
+ * Set custom thinking budgets for token-based providers.
504
+ */
505
+ set thinkingBudgets(value: ThinkingBudgets | undefined) {
506
+ this.#thinkingBudgets = value;
507
+ }
508
+
509
+ /**
510
+ * Get the current sampling temperature.
511
+ */
512
+ get temperature(): number | undefined {
513
+ return this.#temperature;
514
+ }
515
+
516
+ /**
517
+ * Set sampling temperature for LLM calls. `undefined` uses provider default.
518
+ */
519
+ set temperature(value: number | undefined) {
520
+ this.#temperature = value;
521
+ }
522
+
523
+ get topP(): number | undefined {
524
+ return this.#topP;
525
+ }
526
+
527
+ set topP(value: number | undefined) {
528
+ this.#topP = value;
529
+ }
530
+
531
+ get topK(): number | undefined {
532
+ return this.#topK;
533
+ }
534
+
535
+ set topK(value: number | undefined) {
536
+ this.#topK = value;
537
+ }
538
+
539
+ get minP(): number | undefined {
540
+ return this.#minP;
541
+ }
542
+
543
+ set minP(value: number | undefined) {
544
+ this.#minP = value;
545
+ }
546
+
547
+ get presencePenalty(): number | undefined {
548
+ return this.#presencePenalty;
549
+ }
550
+
551
+ set presencePenalty(value: number | undefined) {
552
+ this.#presencePenalty = value;
553
+ }
554
+
555
+ get repetitionPenalty(): number | undefined {
556
+ return this.#repetitionPenalty;
557
+ }
558
+
559
+ set repetitionPenalty(value: number | undefined) {
560
+ this.#repetitionPenalty = value;
561
+ }
562
+
563
+ get serviceTier(): ServiceTier | undefined {
564
+ return this.#serviceTier;
565
+ }
566
+
567
+ set serviceTier(value: ServiceTier | undefined) {
568
+ this.#serviceTier = value;
569
+ }
570
+
571
+ get hideThinkingSummary(): boolean | undefined {
572
+ return this.#hideThinkingSummary;
573
+ }
574
+
575
+ set hideThinkingSummary(value: boolean | undefined) {
576
+ this.#hideThinkingSummary = value;
577
+ }
578
+
579
+ /**
580
+ * Get the current max retry delay in milliseconds.
581
+ */
582
+ get maxRetryDelayMs(): number | undefined {
583
+ return this.#maxRetryDelayMs;
584
+ }
585
+
586
+ /**
587
+ * Set the maximum delay to wait for server-requested retries.
588
+ * Set to 0 to disable the cap.
589
+ */
590
+ set maxRetryDelayMs(value: number | undefined) {
591
+ this.#maxRetryDelayMs = value;
592
+ }
593
+
594
+ get requestMaxRetries(): number | undefined {
595
+ return this.#requestMaxRetries;
596
+ }
597
+
598
+ set requestMaxRetries(value: number | undefined) {
599
+ this.#requestMaxRetries = value;
600
+ }
601
+
602
+ get streamMaxRetries(): number | undefined {
603
+ return this.#streamMaxRetries;
604
+ }
605
+
606
+ set streamMaxRetries(value: number | undefined) {
607
+ this.#streamMaxRetries = value;
608
+ }
609
+
610
+ get state(): AgentState {
611
+ return this.#state;
612
+ }
613
+
614
+ get appendOnlyContext(): AppendOnlyContextManager | undefined {
615
+ return this.#appendOnlyContext;
616
+ }
617
+
618
+ setAppendOnlyContext(manager?: AppendOnlyContextManager): void {
619
+ this.#appendOnlyContext = manager;
620
+ }
621
+
622
+ subscribe(fn: (e: AgentEvent) => void): () => void {
623
+ this.#listeners.add(fn);
624
+ return () => this.#listeners.delete(fn);
625
+ }
626
+
627
+ setProviderResponseInterceptor(fn: SimpleStreamOptions["onResponse"] | undefined): void {
628
+ this.#onResponse = fn;
629
+ }
630
+
631
+ setRawSseEventInterceptor(fn: SimpleStreamOptions["onSseEvent"] | undefined): void {
632
+ this.#onSseEvent = fn;
633
+ }
634
+
635
+ setAssistantMessageEventInterceptor(
636
+ fn: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined,
637
+ ): void {
638
+ this.#onAssistantMessageEvent = fn;
639
+ }
640
+
641
+ setOnBeforeYield(fn: (() => Promise<void> | void) | undefined): void {
642
+ this.#onBeforeYield = fn;
643
+ }
644
+
645
+ setShouldPause(fn: AgentLoopConfig["shouldPause"] | undefined): void {
646
+ this.#shouldPause = fn;
647
+ }
648
+
649
+ emitExternalEvent(event: AgentEvent) {
650
+ switch (event.type) {
651
+ case "message_start":
652
+ case "message_update":
653
+ this.#state.streamMessage = event.message;
654
+ break;
655
+ case "message_end":
656
+ this.#state.streamMessage = null;
657
+ this.appendMessage(event.message);
658
+ break;
659
+ case "tool_execution_start": {
660
+ const pending = new Set(this.#state.pendingToolCalls);
661
+ pending.add(event.toolCallId);
662
+ this.#state.pendingToolCalls = pending;
663
+ break;
664
+ }
665
+ case "tool_execution_end": {
666
+ const pending = new Set(this.#state.pendingToolCalls);
667
+ pending.delete(event.toolCallId);
668
+ this.#state.pendingToolCalls = pending;
669
+ break;
670
+ }
671
+ }
672
+
673
+ this.#emit(event);
674
+ }
675
+
676
+ createExternalEventEmitterForCurrentRun(): ((event: AgentEvent) => void) | undefined {
677
+ const runId = this.#activeRunId;
678
+ if (runId === undefined) return undefined;
679
+ return (event: AgentEvent) => {
680
+ if (this.#activeRunId !== runId) return;
681
+ this.emitExternalEvent(event);
682
+ };
683
+ }
684
+
685
+ #assertActiveRun(runId: number): void {
686
+ if (this.#activeRunId !== runId) {
687
+ throw new Error("Ignoring Cursor exec callback from an inactive agent run.");
688
+ }
689
+ }
690
+
691
+ #cursorExecHandlersForRun(runId: number): CursorExecHandlers | undefined {
692
+ const source = this.#cursorExecHandlers;
693
+ if (!source) return undefined;
694
+
695
+ const guarded: CursorExecHandlers = {};
696
+ // Bind each handler to `source`: they are methods of a CursorExecHandlers
697
+ // instance that reference private fields via `this`. Extracting them bare
698
+ // (`const read = source.read`) and calling `read(args)` would invoke them with
699
+ // `this === undefined`, throwing "undefined is not an object (this.#optionsForCall)".
700
+ const read = source.read?.bind(source);
701
+ if (read) {
702
+ guarded.read = async args => {
703
+ this.#assertActiveRun(runId);
704
+ const result = await read(args);
705
+ this.#assertActiveRun(runId);
706
+ return result;
707
+ };
708
+ }
709
+ const ls = source.ls?.bind(source);
710
+ if (ls) {
711
+ guarded.ls = async args => {
712
+ this.#assertActiveRun(runId);
713
+ const result = await ls(args);
714
+ this.#assertActiveRun(runId);
715
+ return result;
716
+ };
717
+ }
718
+ const grep = source.grep?.bind(source);
719
+ if (grep) {
720
+ guarded.grep = async args => {
721
+ this.#assertActiveRun(runId);
722
+ const result = await grep(args);
723
+ this.#assertActiveRun(runId);
724
+ return result;
725
+ };
726
+ }
727
+ const write = source.write?.bind(source);
728
+ if (write) {
729
+ guarded.write = async args => {
730
+ this.#assertActiveRun(runId);
731
+ const result = await write(args);
732
+ this.#assertActiveRun(runId);
733
+ return result;
734
+ };
735
+ }
736
+ const deleteHandler = source.delete?.bind(source);
737
+ if (deleteHandler) {
738
+ guarded.delete = async args => {
739
+ this.#assertActiveRun(runId);
740
+ const result = await deleteHandler(args);
741
+ this.#assertActiveRun(runId);
742
+ return result;
743
+ };
744
+ }
745
+ const shell = source.shell?.bind(source);
746
+ if (shell) {
747
+ guarded.shell = async args => {
748
+ this.#assertActiveRun(runId);
749
+ const result = await shell(args);
750
+ this.#assertActiveRun(runId);
751
+ return result;
752
+ };
753
+ }
754
+ const shellStream = source.shellStream?.bind(source);
755
+ if (shellStream) {
756
+ guarded.shellStream = async (args, callbacks) => {
757
+ this.#assertActiveRun(runId);
758
+ const result = await shellStream(args, callbacks);
759
+ this.#assertActiveRun(runId);
760
+ return result;
761
+ };
762
+ }
763
+ const diagnostics = source.diagnostics?.bind(source);
764
+ if (diagnostics) {
765
+ guarded.diagnostics = async args => {
766
+ this.#assertActiveRun(runId);
767
+ const result = await diagnostics(args);
768
+ this.#assertActiveRun(runId);
769
+ return result;
770
+ };
771
+ }
772
+ const mcp = source.mcp?.bind(source);
773
+ if (mcp) {
774
+ guarded.mcp = async call => {
775
+ this.#assertActiveRun(runId);
776
+ const result = await mcp(call);
777
+ this.#assertActiveRun(runId);
778
+ return result;
779
+ };
780
+ }
781
+ const onToolResult = source.onToolResult;
782
+ if (onToolResult) {
783
+ guarded.onToolResult = async message => {
784
+ this.#assertActiveRun(runId);
785
+ const result = await onToolResult(message);
786
+ this.#assertActiveRun(runId);
787
+ return result;
788
+ };
789
+ }
790
+ return guarded;
791
+ }
792
+
793
+ // State mutators
794
+ setSystemPrompt(v: string[]) {
795
+ this.#state.systemPrompt = v;
796
+ }
797
+
798
+ setModel(m: Model) {
799
+ this.#state.model = m;
800
+ }
801
+
802
+ setThinkingLevel(l: Effort | undefined) {
803
+ this.#state.thinkingLevel = l;
804
+ }
805
+
806
+ setSteeringMode(mode: "all" | "one-at-a-time") {
807
+ this.#steeringMode = mode;
808
+ }
809
+
810
+ getSteeringMode(): "all" | "one-at-a-time" {
811
+ return this.#steeringMode;
812
+ }
813
+
814
+ setFollowUpMode(mode: "all" | "one-at-a-time") {
815
+ this.#followUpMode = mode;
816
+ }
817
+
818
+ getFollowUpMode(): "all" | "one-at-a-time" {
819
+ return this.#followUpMode;
820
+ }
821
+
822
+ setInterruptMode(mode: "immediate" | "wait") {
823
+ this.#interruptMode = mode;
824
+ }
825
+
826
+ getInterruptMode(): "immediate" | "wait" {
827
+ return this.#interruptMode;
828
+ }
829
+
830
+ setTools(t: AgentTool<any>[]) {
831
+ this.#state.tools = t;
832
+ }
833
+
834
+ replaceMessages(ms: AgentMessage[]) {
835
+ this.#state.messages = ms.slice();
836
+ }
837
+
838
+ appendMessage(m: AgentMessage) {
839
+ // In-place push (not [...messages, m]): appending M messages over a session of
840
+ // N is O(N+M), not O(M*N). Consumers read state.messages fresh; run() snapshots
841
+ // via slice() at the API boundary, so no caller relies on per-append array identity.
842
+ this.#state.messages.push(m);
843
+ }
844
+
845
+ popMessage(): AgentMessage | undefined {
846
+ const messages = this.#state.messages.slice(0, -1);
847
+ const removed = this.#state.messages.at(-1);
848
+ this.#state.messages = messages;
849
+
850
+ if (removed && this.#state.streamMessage === removed) {
851
+ this.#state.streamMessage = null;
852
+ }
853
+
854
+ return removed;
855
+ }
856
+
857
+ /**
858
+ * Queue a steering message to interrupt the agent mid-run.
859
+ * Delivered after current tool execution, skips remaining tools.
860
+ */
861
+ steer(m: AgentMessage) {
862
+ this.#steeringQueue.push(m);
863
+ }
864
+
865
+ /**
866
+ * Queue a follow-up message to be processed after the agent finishes.
867
+ * Delivered only when agent has no more tool calls or steering messages.
868
+ */
869
+ followUp(m: AgentMessage) {
870
+ this.#followUpQueue.push(m);
871
+ }
872
+
873
+ clearSteeringQueue() {
874
+ this.#steeringQueue = [];
875
+ }
876
+
877
+ clearFollowUpQueue() {
878
+ this.#followUpQueue = [];
879
+ }
880
+
881
+ clearAllQueues() {
882
+ this.#steeringQueue = [];
883
+ this.#followUpQueue = [];
884
+ }
885
+
886
+ hasQueuedMessages(): boolean {
887
+ return this.#steeringQueue.length > 0 || this.#followUpQueue.length > 0;
888
+ }
889
+
890
+ hasQueuedSteering(): boolean {
891
+ return this.#steeringQueue.length > 0;
892
+ }
893
+
894
+ /**
895
+ * Snapshot the steering queue without mutating it. Used to preserve queued
896
+ * steering across maintenance ops (compaction/handoff) that call reset().
897
+ */
898
+ snapshotSteering(): AgentMessage[] {
899
+ return this.#steeringQueue.slice();
900
+ }
901
+
902
+ /**
903
+ * Restore previously snapshotted steering messages ahead of any newly
904
+ * queued ones. No-op for an empty snapshot.
905
+ */
906
+ restoreSteering(messages: AgentMessage[]): void {
907
+ if (messages.length === 0) return;
908
+ this.#steeringQueue = [...messages, ...this.#steeringQueue];
909
+ }
910
+
911
+ /** Snapshot the follow-up queue without mutating it. */
912
+ snapshotFollowUp(): AgentMessage[] {
913
+ return this.#followUpQueue.slice();
914
+ }
915
+
916
+ /** Restore previously snapshotted follow-up messages ahead of any newly queued ones. */
917
+ restoreFollowUp(messages: AgentMessage[]): void {
918
+ if (messages.length === 0) return;
919
+ this.#followUpQueue = [...messages, ...this.#followUpQueue];
920
+ }
921
+
922
+ #dequeueSteeringMessages(): AgentMessage[] {
923
+ if (this.#steeringMode === "one-at-a-time") {
924
+ if (this.#steeringQueue.length > 0) {
925
+ const first = this.#steeringQueue[0];
926
+ this.#steeringQueue = this.#steeringQueue.slice(1);
927
+ return [first];
928
+ }
929
+ return [];
930
+ }
931
+ const steering = this.#steeringQueue.slice();
932
+ this.#steeringQueue = [];
933
+ return steering;
934
+ }
935
+
936
+ #dequeueFollowUpMessages(): AgentMessage[] {
937
+ if (this.#followUpMode === "one-at-a-time") {
938
+ if (this.#followUpQueue.length > 0) {
939
+ const first = this.#followUpQueue[0];
940
+ this.#followUpQueue = this.#followUpQueue.slice(1);
941
+ return [first];
942
+ }
943
+ return [];
944
+ }
945
+ const followUp = this.#followUpQueue.slice();
946
+ this.#followUpQueue = [];
947
+ return followUp;
948
+ }
949
+
950
+ /**
951
+ * Remove and return the last steering message from the queue (LIFO).
952
+ * Used by dequeue keybinding.
953
+ */
954
+ popLastSteer(): AgentMessage | undefined {
955
+ return this.#steeringQueue.pop();
956
+ }
957
+
958
+ /**
959
+ * Remove and return the last follow-up message from the queue (LIFO).
960
+ * Used by dequeue keybinding.
961
+ */
962
+ popLastFollowUp(): AgentMessage | undefined {
963
+ return this.#followUpQueue.pop();
964
+ }
965
+
966
+ /** Remove queued steering+follow-up messages matching `predicate`, preserving order of the rest. */
967
+ removeQueuedMessages(predicate: (message: AgentMessage) => boolean): {
968
+ steering: number;
969
+ followUp: number;
970
+ total: number;
971
+ } {
972
+ const beforeSteering = this.#steeringQueue.length;
973
+ const beforeFollowUp = this.#followUpQueue.length;
974
+ this.#steeringQueue = this.#steeringQueue.filter(m => !predicate(m));
975
+ this.#followUpQueue = this.#followUpQueue.filter(m => !predicate(m));
976
+ const steering = beforeSteering - this.#steeringQueue.length;
977
+ const followUp = beforeFollowUp - this.#followUpQueue.length;
978
+ return { steering, followUp, total: steering + followUp };
979
+ }
980
+
981
+ clearMessages() {
982
+ this.#state.messages = [];
983
+ }
984
+
985
+ abort() {
986
+ this.#abortController?.abort();
987
+ }
988
+
989
+ /**
990
+ * Force the current run out of the busy/streaming state when cooperative abort
991
+ * did not drain. The abandoned provider/tool stream may still settle later, so
992
+ * #runLoop guards every state mutation with a run id.
993
+ */
994
+ forceAbort(reason = "Force aborted"): boolean {
995
+ const hadActiveRun = this.#runningPrompt !== undefined || this.#state.isStreaming;
996
+ if (!hadActiveRun) return false;
997
+
998
+ this.#abortController?.abort(reason);
999
+ this.#activeRunId = undefined;
1000
+ this.#state.isStreaming = false;
1001
+ this.#state.streamMessage = null;
1002
+ this.#state.pendingToolCalls = new Set<string>();
1003
+ this.#abortController = undefined;
1004
+ this.#cursorToolResultBuffer = [];
1005
+
1006
+ const resolve = this.#resolveRunningPrompt;
1007
+ this.#runningPrompt = undefined;
1008
+ this.#resolveRunningPrompt = undefined;
1009
+ resolve?.();
1010
+
1011
+ this.#emit({ type: "agent_end", messages: [] });
1012
+ return true;
1013
+ }
1014
+
1015
+ waitForIdle(): Promise<void> {
1016
+ return this.#runningPrompt ?? Promise.resolve();
1017
+ }
1018
+
1019
+ reset() {
1020
+ this.#state.messages = [];
1021
+ this.#state.isStreaming = false;
1022
+ this.#state.streamMessage = null;
1023
+ this.#state.pendingToolCalls = new Set<string>();
1024
+ this.#state.error = undefined;
1025
+ this.#steeringQueue = [];
1026
+ this.#followUpQueue = [];
1027
+ }
1028
+
1029
+ /** Send a prompt with an AgentMessage */
1030
+ async prompt(message: AgentMessage | AgentMessage[], options?: AgentPromptOptions): Promise<void>;
1031
+ async prompt(input: string, options?: AgentPromptOptions): Promise<void>;
1032
+ async prompt(input: string, images?: ImageContent[], options?: AgentPromptOptions): Promise<void>;
1033
+ async prompt(
1034
+ input: string | AgentMessage | AgentMessage[],
1035
+ imagesOrOptions?: ImageContent[] | AgentPromptOptions,
1036
+ options?: AgentPromptOptions,
1037
+ ) {
1038
+ if (this.#state.isStreaming) {
1039
+ throw new AgentBusyError();
1040
+ }
1041
+
1042
+ const model = this.#state.model;
1043
+ if (!model) throw new Error("No model configured");
1044
+
1045
+ let msgs: AgentMessage[];
1046
+ let promptOptions: AgentPromptOptions | undefined;
1047
+ let images: ImageContent[] | undefined;
1048
+
1049
+ if (Array.isArray(input)) {
1050
+ msgs = input;
1051
+ promptOptions = imagesOrOptions as AgentPromptOptions | undefined;
1052
+ } else if (typeof input === "string") {
1053
+ if (Array.isArray(imagesOrOptions)) {
1054
+ images = imagesOrOptions;
1055
+ promptOptions = options;
1056
+ } else {
1057
+ promptOptions = imagesOrOptions;
1058
+ }
1059
+ const content: Array<TextContent | ImageContent> = [{ type: "text", text: input }];
1060
+ if (images && images.length > 0) {
1061
+ content.push(...images);
1062
+ }
1063
+ msgs = [
1064
+ {
1065
+ role: "user",
1066
+ content,
1067
+ timestamp: Date.now(),
1068
+ },
1069
+ ];
1070
+ } else {
1071
+ msgs = [input];
1072
+ promptOptions = imagesOrOptions as AgentPromptOptions | undefined;
1073
+ }
1074
+
1075
+ await this.#runLoop(msgs, promptOptions);
1076
+ }
1077
+
1078
+ /**
1079
+ * Continue from current context (used for retries and resuming queued messages).
1080
+ */
1081
+ async continue() {
1082
+ if (this.#state.isStreaming) {
1083
+ throw new AgentBusyError();
1084
+ }
1085
+
1086
+ const messages = this.#state.messages;
1087
+ if (messages.length === 0) {
1088
+ throw new Error("No messages to continue from");
1089
+ }
1090
+ if (messages[messages.length - 1].role === "assistant") {
1091
+ const queuedSteering = this.#dequeueSteeringMessages();
1092
+ if (queuedSteering.length > 0) {
1093
+ await this.#runLoop(queuedSteering, { skipInitialSteeringPoll: true });
1094
+ return;
1095
+ }
1096
+
1097
+ const queuedFollowUp = this.#dequeueFollowUpMessages();
1098
+ if (queuedFollowUp.length > 0) {
1099
+ await this.#runLoop(queuedFollowUp);
1100
+ return;
1101
+ }
1102
+
1103
+ throw new Error("Cannot continue from message role: assistant");
1104
+ }
1105
+
1106
+ await this.#runLoop(undefined);
1107
+ }
1108
+
1109
+ /**
1110
+ * Run the agent loop.
1111
+ * If messages are provided, starts a new conversation turn with those messages.
1112
+ * Otherwise, continues from existing context.
1113
+ */
1114
+ async #runLoop(messages?: AgentMessage[], options?: AgentPromptOptions & { skipInitialSteeringPoll?: boolean }) {
1115
+ const model = this.#state.model;
1116
+ if (!model) throw new Error("No model configured");
1117
+
1118
+ let skipInitialSteeringPoll = options?.skipInitialSteeringPoll === true;
1119
+
1120
+ const { promise, resolve } = Promise.withResolvers<void>();
1121
+ this.#runningPrompt = promise;
1122
+ this.#resolveRunningPrompt = resolve;
1123
+
1124
+ const runId = ++this.#runSequence;
1125
+ this.#activeRunId = runId;
1126
+ const abortController = new AbortController();
1127
+ this.#abortController = abortController;
1128
+ this.#state.isStreaming = true;
1129
+ this.#state.streamMessage = null;
1130
+ this.#state.error = undefined;
1131
+
1132
+ // Clear Cursor tool result buffer at start of each run
1133
+ this.#cursorToolResultBuffer = [];
1134
+
1135
+ const reasoning = this.#state.thinkingLevel;
1136
+
1137
+ const context: AgentContext = {
1138
+ systemPrompt: this.#state.systemPrompt,
1139
+ messages: this.#state.messages.slice(),
1140
+ tools: this.#state.tools,
1141
+ };
1142
+
1143
+ const cursorOnToolResult =
1144
+ this.#cursorExecHandlers || this.#cursorOnToolResult
1145
+ ? async (message: ToolResultMessage) => {
1146
+ let finalMessage = message;
1147
+ if (this.#activeRunId !== runId) {
1148
+ return finalMessage;
1149
+ }
1150
+ if (this.#cursorOnToolResult) {
1151
+ try {
1152
+ const updated = await this.#cursorOnToolResult(message);
1153
+ if (this.#activeRunId !== runId) {
1154
+ return finalMessage;
1155
+ }
1156
+ if (updated) {
1157
+ finalMessage = updated;
1158
+ }
1159
+ } catch {}
1160
+ }
1161
+ // Buffer tool result with current text length for correct ordering later.
1162
+ // Cursor executes tools server-side during streaming, so the assistant message
1163
+ // already incorporates results. We buffer here and emit in correct order
1164
+ // when the assistant message ends.
1165
+ const textLength = this.#getAssistantTextLength(this.#state.streamMessage);
1166
+ this.#cursorToolResultBuffer.push({ toolResult: finalMessage, textLengthAtCall: textLength });
1167
+ return finalMessage;
1168
+ }
1169
+ : undefined;
1170
+
1171
+ const getToolChoice = () =>
1172
+ this.#getToolChoice?.() ?? refreshToolChoiceForActiveTools(options?.toolChoice, this.#state.tools);
1173
+ const cursorExecHandlers = this.#cursorExecHandlersForRun(runId);
1174
+
1175
+ const config: AgentLoopConfig = {
1176
+ model,
1177
+ reasoning,
1178
+ temperature: this.#temperature,
1179
+ topP: this.#topP,
1180
+ topK: this.#topK,
1181
+ minP: this.#minP,
1182
+ presencePenalty: this.#presencePenalty,
1183
+ repetitionPenalty: this.#repetitionPenalty,
1184
+ serviceTier: this.#serviceTier,
1185
+ hideThinkingSummary: this.#hideThinkingSummary,
1186
+ interruptMode: this.#interruptMode,
1187
+ sessionId: this.#sessionId,
1188
+ providerSessionId: this.#providerSessionId,
1189
+ metadata: this.#metadataResolver ? undefined : this.#metadata,
1190
+ metadataResolver: this.#metadataResolver,
1191
+ providerSessionState: this.#providerSessionState,
1192
+ thinkingBudgets: this.#thinkingBudgets,
1193
+ maxRetryDelayMs: this.#maxRetryDelayMs,
1194
+ requestMaxRetries: this.#requestMaxRetries,
1195
+ streamMaxRetries: this.#streamMaxRetries,
1196
+ kimiApiFormat: this.#kimiApiFormat,
1197
+ preferWebsockets: this.#preferWebsockets,
1198
+ convertToLlm: this.#convertToLlm,
1199
+ transformContext: this.#transformContext,
1200
+ onPayload: this.#onPayload,
1201
+ onResponse: this.#onResponse,
1202
+ onSseEvent: this.#onSseEvent,
1203
+ signal: abortController.signal,
1204
+ getApiKey: this.getApiKey,
1205
+ getAuthCredentialType: this.getAuthCredentialType,
1206
+ getToolContext: this.#getToolContext,
1207
+ syncContextBeforeModelCall: async context => {
1208
+ if (this.#listeners.size > 0) {
1209
+ await Bun.sleep(0);
1210
+ }
1211
+ context.systemPrompt = this.#state.systemPrompt;
1212
+ context.tools = this.#state.tools;
1213
+ },
1214
+ cursorExecHandlers,
1215
+ cursorOnToolResult,
1216
+ transformToolCallArguments: this.#transformToolCallArguments,
1217
+ intentTracing: this.#intentTracing,
1218
+ appendOnlyContext: this.#appendOnlyContext,
1219
+ beforeToolCall: this.beforeToolCall
1220
+ ? async (ctx, signal) => {
1221
+ if (this.#activeRunId !== runId) return undefined;
1222
+ const result = await this.beforeToolCall?.(ctx, signal);
1223
+ if (this.#activeRunId !== runId) return undefined;
1224
+ return result;
1225
+ }
1226
+ : undefined,
1227
+ afterToolCall: this.afterToolCall
1228
+ ? async (ctx, signal) => {
1229
+ if (this.#activeRunId !== runId) return undefined;
1230
+ const result = await this.afterToolCall?.(ctx, signal);
1231
+ if (this.#activeRunId !== runId) return undefined;
1232
+ return result;
1233
+ }
1234
+ : undefined,
1235
+ onAssistantMessageEvent: this.#onAssistantMessageEvent
1236
+ ? (message, event) => {
1237
+ if (this.#activeRunId !== runId) return;
1238
+ this.#onAssistantMessageEvent?.(message, event);
1239
+ }
1240
+ : undefined,
1241
+ onToolChoiceIncapability: this.#onToolChoiceIncapability
1242
+ ? event => {
1243
+ if (this.#activeRunId !== runId) return;
1244
+ this.#onToolChoiceIncapability?.(event);
1245
+ }
1246
+ : undefined,
1247
+ onHarmonyLeak: this.#onHarmonyLeak,
1248
+ getToolChoice,
1249
+ getReasoning: () => this.#state.thinkingLevel,
1250
+ getSteeringMessages: async () => {
1251
+ if (this.#activeRunId !== runId) {
1252
+ return [];
1253
+ }
1254
+ if (skipInitialSteeringPoll) {
1255
+ skipInitialSteeringPoll = false;
1256
+ return [];
1257
+ }
1258
+ const queued = this.#dequeueSteeringMessages();
1259
+ if (this.#activeRunId !== runId) {
1260
+ this.#steeringQueue = [...queued, ...this.#steeringQueue];
1261
+ return [];
1262
+ }
1263
+ return queued;
1264
+ },
1265
+ getFollowUpMessages: async () => {
1266
+ if (this.#activeRunId !== runId) {
1267
+ return [];
1268
+ }
1269
+ const queued = this.#dequeueFollowUpMessages();
1270
+ if (this.#activeRunId !== runId) {
1271
+ this.#followUpQueue = [...queued, ...this.#followUpQueue];
1272
+ return [];
1273
+ }
1274
+ return queued;
1275
+ },
1276
+ onBeforeYield: async () => {
1277
+ if (this.#activeRunId !== runId) return;
1278
+ await this.#onBeforeYield?.();
1279
+ },
1280
+ shouldPause: () => {
1281
+ if (this.#activeRunId !== runId) return false;
1282
+ return this.#shouldPause?.() === true;
1283
+ },
1284
+ telemetry: this.#telemetry,
1285
+ };
1286
+
1287
+ let partial: AgentMessage | null = null;
1288
+
1289
+ try {
1290
+ const stream = messages
1291
+ ? agentLoop(messages, context, config, abortController.signal, this.streamFn)
1292
+ : agentLoopContinue(context, config, abortController.signal, this.streamFn);
1293
+
1294
+ for await (const event of stream) {
1295
+ if (this.#activeRunId !== runId) {
1296
+ break;
1297
+ }
1298
+
1299
+ // Update internal state based on events
1300
+ switch (event.type) {
1301
+ case "message_start":
1302
+ partial = event.message;
1303
+ this.#state.streamMessage = event.message;
1304
+ break;
1305
+
1306
+ case "message_update":
1307
+ partial = event.message;
1308
+ this.#state.streamMessage = event.message;
1309
+ break;
1310
+
1311
+ case "message_end":
1312
+ partial = null;
1313
+ // Check if this is an assistant message with buffered Cursor tool results.
1314
+ // If so, split the message to emit tool results at the correct position.
1315
+ if (event.message.role === "assistant" && this.#cursorToolResultBuffer.length > 0) {
1316
+ this.#emitCursorSplitAssistantMessage(event.message as AssistantMessage);
1317
+ continue; // Skip default emit - split method handles everything
1318
+ }
1319
+ this.#state.streamMessage = null;
1320
+ this.appendMessage(event.message);
1321
+ break;
1322
+
1323
+ case "tool_execution_start": {
1324
+ const s = new Set(this.#state.pendingToolCalls);
1325
+ s.add(event.toolCallId);
1326
+ this.#state.pendingToolCalls = s;
1327
+ break;
1328
+ }
1329
+
1330
+ case "tool_execution_end": {
1331
+ const s = new Set(this.#state.pendingToolCalls);
1332
+ s.delete(event.toolCallId);
1333
+ this.#state.pendingToolCalls = s;
1334
+ break;
1335
+ }
1336
+
1337
+ case "turn_end":
1338
+ if (event.message.role === "assistant" && (event.message as any).errorMessage) {
1339
+ this.#state.error = (event.message as any).errorMessage;
1340
+ }
1341
+ break;
1342
+
1343
+ case "agent_end":
1344
+ this.#state.isStreaming = false;
1345
+ this.#state.streamMessage = null;
1346
+ break;
1347
+ }
1348
+
1349
+ // Emit to listeners
1350
+ this.#emit(event);
1351
+ }
1352
+
1353
+ if (this.#activeRunId !== runId) {
1354
+ return;
1355
+ }
1356
+
1357
+ // Handle any remaining partial message
1358
+ if (partial && partial.role === "assistant" && Array.isArray(partial.content) && partial.content.length > 0) {
1359
+ const onlyEmpty = !partial.content.some(
1360
+ c =>
1361
+ (c.type === "thinking" && c.thinking.trim().length > 0) ||
1362
+ (c.type === "text" && c.text.trim().length > 0) ||
1363
+ (c.type === "toolCall" && c.name.trim().length > 0),
1364
+ );
1365
+ if (!onlyEmpty) {
1366
+ this.appendMessage(partial);
1367
+ } else {
1368
+ if (abortController.signal.aborted) {
1369
+ throw new Error("Request was aborted");
1370
+ }
1371
+ }
1372
+ }
1373
+ } catch (err: any) {
1374
+ if (this.#activeRunId !== runId) {
1375
+ return;
1376
+ }
1377
+
1378
+ const errorMsg: AgentMessage = {
1379
+ role: "assistant",
1380
+ content: [{ type: "text", text: "" }],
1381
+ api: model.api,
1382
+ provider: model.provider,
1383
+ model: model.id,
1384
+ usage: {
1385
+ input: 0,
1386
+ output: 0,
1387
+ cacheRead: 0,
1388
+ cacheWrite: 0,
1389
+ totalTokens: 0,
1390
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
1391
+ },
1392
+ stopReason: abortController.signal.aborted ? "aborted" : "error",
1393
+ errorMessage: err?.message || String(err),
1394
+ timestamp: Date.now(),
1395
+ } as AgentMessage;
1396
+
1397
+ this.appendMessage(errorMsg);
1398
+ this.#state.error = err?.message || String(err);
1399
+ this.#emit({ type: "agent_end", messages: [errorMsg] });
1400
+ } finally {
1401
+ if (this.#activeRunId === runId) {
1402
+ this.#state.isStreaming = false;
1403
+ this.#state.streamMessage = null;
1404
+ this.#state.pendingToolCalls = new Set<string>();
1405
+ this.#abortController = undefined;
1406
+ this.#activeRunId = undefined;
1407
+ this.#resolveRunningPrompt?.();
1408
+ this.#runningPrompt = undefined;
1409
+ this.#resolveRunningPrompt = undefined;
1410
+ }
1411
+ }
1412
+ }
1413
+
1414
+ #emit(e: AgentEvent) {
1415
+ for (const listener of this.#listeners) {
1416
+ listener(e);
1417
+ }
1418
+ }
1419
+
1420
+ /** Calculate total text length from an assistant message's content blocks */
1421
+ #getAssistantTextLength(message: AgentMessage | null): number {
1422
+ if (message?.role !== "assistant" || !Array.isArray(message.content)) {
1423
+ return 0;
1424
+ }
1425
+ let length = 0;
1426
+ for (const block of message.content) {
1427
+ if (block.type === "text") {
1428
+ length += (block as TextContent).text.length;
1429
+ }
1430
+ }
1431
+ return length;
1432
+ }
1433
+
1434
+ /**
1435
+ * Emit a Cursor assistant message split around tool results.
1436
+ * This fixes the ordering issue where tool results appear after the full explanation.
1437
+ *
1438
+ * Output order: Assistant(preamble) -> ToolResults -> Assistant(continuation)
1439
+ */
1440
+ #emitCursorSplitAssistantMessage(assistantMessage: AssistantMessage): void {
1441
+ const buffer = this.#cursorToolResultBuffer;
1442
+ this.#cursorToolResultBuffer = [];
1443
+
1444
+ if (buffer.length === 0) {
1445
+ // No tool results, emit normally
1446
+ this.#state.streamMessage = null;
1447
+ this.appendMessage(assistantMessage);
1448
+ this.#emit({ type: "message_end", message: assistantMessage });
1449
+ return;
1450
+ }
1451
+
1452
+ // Find the split point: minimum text length at first tool call
1453
+ const splitPoint = Math.min(...buffer.map(r => r.textLengthAtCall));
1454
+
1455
+ // Extract text content from assistant message
1456
+ const content = assistantMessage.content;
1457
+ let fullText = "";
1458
+ for (const block of content) {
1459
+ if (block.type === "text") {
1460
+ fullText += block.text;
1461
+ }
1462
+ }
1463
+
1464
+ // If no text or split point is 0 or at/past end, don't split
1465
+ if (fullText.length === 0 || splitPoint <= 0 || splitPoint >= fullText.length) {
1466
+ // Emit assistant message first, then tool results (original behavior but with buffered results)
1467
+ this.#state.streamMessage = null;
1468
+ this.appendMessage(assistantMessage);
1469
+ this.#emit({ type: "message_end", message: assistantMessage });
1470
+
1471
+ // Emit buffered tool results
1472
+ for (const { toolResult } of buffer) {
1473
+ this.#emit({ type: "message_start", message: toolResult });
1474
+ this.appendMessage(toolResult);
1475
+ this.#emit({ type: "message_end", message: toolResult });
1476
+ }
1477
+ return;
1478
+ }
1479
+
1480
+ // Split the text
1481
+ const preambleText = fullText.slice(0, splitPoint);
1482
+ const continuationText = fullText.slice(splitPoint);
1483
+
1484
+ // Create preamble message (text before tools)
1485
+ const preambleContent = content.map(block => {
1486
+ if (block.type === "text") {
1487
+ return { ...block, text: preambleText };
1488
+ }
1489
+ return block;
1490
+ });
1491
+ const preambleMessage: AssistantMessage = {
1492
+ ...assistantMessage,
1493
+ content: preambleContent,
1494
+ };
1495
+
1496
+ // Emit preamble
1497
+ this.#state.streamMessage = null;
1498
+ this.appendMessage(preambleMessage);
1499
+ this.#emit({ type: "message_end", message: preambleMessage });
1500
+
1501
+ // Emit buffered tool results
1502
+ for (const { toolResult } of buffer) {
1503
+ this.#emit({ type: "message_start", message: toolResult });
1504
+ this.appendMessage(toolResult);
1505
+ this.#emit({ type: "message_end", message: toolResult });
1506
+ }
1507
+
1508
+ // Emit continuation message (text after tools) if non-empty
1509
+ const trimmedContinuation = continuationText.trim();
1510
+ if (trimmedContinuation.length > 0) {
1511
+ // Create continuation message with only text content (no thinking/toolCalls)
1512
+ const continuationContent: TextContent[] = [{ type: "text", text: continuationText }];
1513
+ const continuationMessage: AssistantMessage = {
1514
+ ...assistantMessage,
1515
+ content: continuationContent,
1516
+ // Zero out usage for continuation since it's part of same response
1517
+ usage: {
1518
+ input: 0,
1519
+ output: 0,
1520
+ cacheRead: 0,
1521
+ cacheWrite: 0,
1522
+ totalTokens: 0,
1523
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
1524
+ },
1525
+ };
1526
+ this.#emit({ type: "message_start", message: continuationMessage });
1527
+ this.appendMessage(continuationMessage);
1528
+ this.#emit({ type: "message_end", message: continuationMessage });
1529
+ }
1530
+ }
1531
+ }