@hyperspaceng/neural-agent-core 0.64.1 → 0.65.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -124,7 +124,7 @@ The last message in context must be `user` or `toolResult` (not `assistant`).
124
124
  | Event | Description |
125
125
  |-------|-------------|
126
126
  | `agent_start` | Agent begins processing |
127
- | `agent_end` | Agent completes with all new messages |
127
+ | `agent_end` | Final event for the run. Awaited subscribers for this event still count toward settlement |
128
128
  | `turn_start` | New turn begins (one LLM call + tool executions) |
129
129
  | `turn_end` | Turn completes with assistant message and tool results |
130
130
  | `message_start` | Any message begins (user, assistant, toolResult) |
@@ -133,6 +133,8 @@ The last message in context must be `user` or `toolResult` (not `assistant`).
133
133
  | `tool_execution_start` | Tool begins |
134
134
  | `tool_execution_update` | Tool streams progress |
135
135
  | `tool_execution_end` | Tool completes |
136
+ +
137
+ +`Agent.subscribe()` listeners are awaited in registration order. `agent_end` means no more loop events will be emitted, but `await agent.waitForIdle()` and `await agent.prompt(...)` only settle after awaited `agent_end` listeners finish.
136
138
 
137
139
  ## Agent Options
138
140
 
@@ -204,14 +206,20 @@ interface AgentState {
204
206
  thinkingLevel: ThinkingLevel;
205
207
  tools: AgentTool<any>[];
206
208
  messages: AgentMessage[];
207
- isStreaming: boolean;
208
- streamMessage: AgentMessage | null; // Current partial during streaming
209
- pendingToolCalls: Set<string>;
210
- error?: string;
209
+ readonly isStreaming: boolean;
210
+ readonly streamingMessage?: AgentMessage;
211
+ readonly pendingToolCalls: ReadonlySet<string>;
212
+ readonly errorMessage?: string;
211
213
  }
212
214
  ```
213
215
 
214
- Access via `agent.state`. During streaming, `streamMessage` contains the partial assistant message.
216
+ Access state via `agent.state`.
217
+
218
+ Assigning `agent.state.tools = [...]` or `agent.state.messages = [...]` copies the top-level array before storing it. Mutating the returned array mutates the current agent state.
219
+
220
+ During streaming, `agent.state.streamingMessage` contains the current partial assistant message.
221
+
222
+ `agent.state.isStreaming` remains `true` until the run fully settles, including awaited `agent_end` subscribers.
215
223
 
216
224
  ## Methods
217
225
 
@@ -236,17 +244,16 @@ await agent.continue();
236
244
  ### State Management
237
245
 
238
246
  ```typescript
239
- agent.setSystemPrompt("New prompt");
240
- agent.setModel(getModel("openai", "gpt-4o"));
241
- agent.setThinkingLevel("medium");
242
- agent.setTools([myTool]);
243
- agent.setToolExecution("sequential");
244
- agent.setBeforeToolCall(async ({ toolCall }) => undefined);
245
- agent.setAfterToolCall(async ({ toolCall, result }) => undefined);
246
- agent.replaceMessages(newMessages);
247
- agent.appendMessage(message);
248
- agent.clearMessages();
249
- agent.reset(); // Clear everything
247
+ agent.state.systemPrompt = "New prompt";
248
+ agent.state.model = getModel("openai", "gpt-4o");
249
+ agent.state.thinkingLevel = "medium";
250
+ agent.state.tools = [myTool];
251
+ agent.toolExecution = "sequential";
252
+ agent.beforeToolCall = async ({ toolCall }) => undefined;
253
+ agent.afterToolCall = async ({ toolCall, result }) => undefined;
254
+ agent.state.messages = newMessages; // top-level array is copied
255
+ agent.state.messages.push(message);
256
+ agent.reset();
250
257
  ```
251
258
 
252
259
  ### Session and Thinking Budgets
@@ -272,8 +279,11 @@ await agent.waitForIdle(); // Wait for completion
272
279
  ### Events
273
280
 
274
281
  ```typescript
275
- const unsubscribe = agent.subscribe((event) => {
276
- console.log(event.type);
282
+ const unsubscribe = agent.subscribe(async (event, signal) => {
283
+ if (event.type === "agent_end") {
284
+ // Final barrier work for the run
285
+ await flushSessionState(signal);
286
+ }
277
287
  });
278
288
  unsubscribe();
279
289
  ```
@@ -283,8 +293,8 @@ unsubscribe();
283
293
  Steering messages let you interrupt the agent while tools are running. Follow-up messages let you queue work after the agent would otherwise stop.
284
294
 
285
295
  ```typescript
286
- agent.setSteeringMode("one-at-a-time");
287
- agent.setFollowUpMode("one-at-a-time");
296
+ agent.steeringMode = "one-at-a-time";
297
+ agent.followUpMode = "one-at-a-time";
288
298
 
289
299
  // While agent is running tools
290
300
  agent.steer({
@@ -300,8 +310,8 @@ agent.followUp({
300
310
  timestamp: Date.now(),
301
311
  });
302
312
 
303
- const steeringMode = agent.getSteeringMode();
304
- const followUpMode = agent.getFollowUpMode();
313
+ const steeringMode = agent.steeringMode;
314
+ const followUpMode = agent.followUpMode;
305
315
 
306
316
  agent.clearSteeringQueue();
307
317
  agent.clearFollowUpQueue();
@@ -370,7 +380,7 @@ const readFileTool: AgentTool = {
370
380
  },
371
381
  };
372
382
 
373
- agent.setTools([readFileTool]);
383
+ agent.state.tools = [readFileTool];
374
384
  ```
375
385
 
376
386
  ### Error Handling
package/dist/agent.d.ts CHANGED
@@ -1,174 +1,115 @@
1
- /**
2
- * Agent class that uses the agent-loop directly.
3
- * No transport abstraction - calls streamSimple via the loop.
4
- */
5
- import { type ImageContent, type Message, type Model, type SimpleStreamOptions, type ThinkingBudgets, type Transport } from "@hyperspaceng/neural-ai";
6
- import type { AfterToolCallContext, AfterToolCallResult, AgentEvent, AgentMessage, AgentState, AgentTool, BeforeToolCallContext, BeforeToolCallResult, StreamFn, ThinkingLevel, ToolExecutionMode } from "./types.js";
1
+ import { type ImageContent, type Message, type SimpleStreamOptions, type ThinkingBudgets, type Transport } from "@hyperspaceng/neural-ai";
2
+ import type { AfterToolCallContext, AfterToolCallResult, AgentEvent, AgentMessage, AgentState, BeforeToolCallContext, BeforeToolCallResult, StreamFn, ToolExecutionMode } from "./types.js";
3
+ type QueueMode = "all" | "one-at-a-time";
4
+ /** Options for constructing an {@link Agent}. */
7
5
  export interface AgentOptions {
8
- initialState?: Partial<AgentState>;
9
- /**
10
- * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
11
- * Default filters to user/assistant/toolResult and converts attachments.
12
- */
6
+ initialState?: Partial<Omit<AgentState, "pendingToolCalls" | "isStreaming" | "streamingMessage" | "errorMessage">>;
13
7
  convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
14
- /**
15
- * Optional transform applied to context before convertToLlm.
16
- * Use for context pruning, injecting external context, etc.
17
- */
18
8
  transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
19
- /**
20
- * Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
21
- */
22
- steeringMode?: "all" | "one-at-a-time";
23
- /**
24
- * Follow-up mode: "all" = send all follow-up messages at once, "one-at-a-time" = one per turn
25
- */
26
- followUpMode?: "all" | "one-at-a-time";
27
- /**
28
- * Custom stream function (for proxy backends, etc.). Default uses streamSimple.
29
- */
30
9
  streamFn?: StreamFn;
31
- /**
32
- * Optional session identifier forwarded to LLM providers.
33
- * Used by providers that support session-based caching (e.g., OpenAI Codex).
34
- */
35
- sessionId?: string;
36
- /**
37
- * Resolves an API key dynamically for each LLM call.
38
- * Useful for expiring tokens (e.g., GitHub Copilot OAuth).
39
- */
40
10
  getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
41
- /**
42
- * Inspect or replace provider payloads before they are sent.
43
- */
44
11
  onPayload?: SimpleStreamOptions["onPayload"];
45
- /**
46
- * Custom token budgets for thinking levels (token-based providers only).
47
- */
12
+ beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
13
+ afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
14
+ steeringMode?: QueueMode;
15
+ followUpMode?: QueueMode;
16
+ sessionId?: string;
48
17
  thinkingBudgets?: ThinkingBudgets;
49
- /**
50
- * Preferred transport for providers that support multiple transports.
51
- */
52
18
  transport?: Transport;
53
- /**
54
- * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
55
- * If the server's requested delay exceeds this value, the request fails immediately,
56
- * allowing higher-level retry logic to handle it with user visibility.
57
- * Default: 60000 (60 seconds). Set to 0 to disable the cap.
58
- */
59
19
  maxRetryDelayMs?: number;
60
- /** Tool execution mode. Default: "parallel" */
61
20
  toolExecution?: ToolExecutionMode;
62
- /** Called before a tool is executed, after arguments have been validated. */
63
- beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
64
- /** Called after a tool finishes executing, before final tool events are emitted. */
65
- afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
66
21
  }
22
+ /**
23
+ * Stateful wrapper around the low-level agent loop.
24
+ *
25
+ * `Agent` owns the current transcript, emits lifecycle events, executes tools,
26
+ * and exposes queueing APIs for steering and follow-up messages.
27
+ */
67
28
  export declare class Agent {
68
29
  private _state;
69
- private listeners;
70
- private abortController?;
71
- private convertToLlm;
72
- private transformContext?;
73
- private steeringQueue;
74
- private followUpQueue;
75
- private steeringMode;
76
- private followUpMode;
30
+ private readonly listeners;
31
+ private readonly steeringQueue;
32
+ private readonly followUpQueue;
33
+ convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
34
+ transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
77
35
  streamFn: StreamFn;
78
- private _sessionId?;
79
36
  getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
80
- private _onPayload?;
81
- private runningPrompt?;
82
- private resolveRunningPrompt?;
83
- private _thinkingBudgets?;
84
- private _transport;
85
- private _maxRetryDelayMs?;
86
- private _toolExecution;
87
- private _beforeToolCall?;
88
- private _afterToolCall?;
89
- constructor(opts?: AgentOptions);
90
- /**
91
- * Get the current session ID used for provider caching.
92
- */
93
- get sessionId(): string | undefined;
94
- /**
95
- * Set the session ID for provider caching.
96
- * Call this when switching sessions (new session, branch, resume).
97
- */
98
- set sessionId(value: string | undefined);
99
- /**
100
- * Get the current thinking budgets.
101
- */
102
- get thinkingBudgets(): ThinkingBudgets | undefined;
103
- /**
104
- * Set custom thinking budgets for token-based providers.
105
- */
106
- set thinkingBudgets(value: ThinkingBudgets | undefined);
107
- /**
108
- * Get the current preferred transport.
109
- */
110
- get transport(): Transport;
111
- /**
112
- * Set the preferred transport.
113
- */
114
- setTransport(value: Transport): void;
37
+ onPayload?: SimpleStreamOptions["onPayload"];
38
+ beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
39
+ afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
40
+ private activeRun?;
41
+ /** Session identifier forwarded to providers for cache-aware backends. */
42
+ sessionId?: string;
43
+ /** Optional per-level thinking token budgets forwarded to the stream function. */
44
+ thinkingBudgets?: ThinkingBudgets;
45
+ /** Preferred transport forwarded to the stream function. */
46
+ transport: Transport;
47
+ /** Optional cap for provider-requested retry delays. */
48
+ maxRetryDelayMs?: number;
49
+ /** Tool execution strategy for assistant messages that contain multiple tool calls. */
50
+ toolExecution: ToolExecutionMode;
51
+ constructor(options?: AgentOptions);
115
52
  /**
116
- * Get the current max retry delay in milliseconds.
53
+ * Subscribe to agent lifecycle events.
54
+ *
55
+ * Listener promises are awaited in subscription order and are included in
56
+ * the current run's settlement. Listeners also receive the active abort
57
+ * signal for the current run.
58
+ *
59
+ * `agent_end` is the final emitted event for a run, but the agent does not
60
+ * become idle until all awaited listeners for that event have settled.
117
61
  */
118
- get maxRetryDelayMs(): number | undefined;
62
+ subscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void;
119
63
  /**
120
- * Set the maximum delay to wait for server-requested retries.
121
- * Set to 0 to disable the cap.
64
+ * Current agent state.
65
+ *
66
+ * Assigning `state.tools` or `state.messages` copies the provided top-level array.
122
67
  */
123
- set maxRetryDelayMs(value: number | undefined);
124
- get toolExecution(): ToolExecutionMode;
125
- setToolExecution(value: ToolExecutionMode): void;
126
- setBeforeToolCall(value: ((context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>) | undefined): void;
127
- setAfterToolCall(value: ((context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>) | undefined): void;
128
68
  get state(): AgentState;
129
- subscribe(fn: (e: AgentEvent) => void): () => void;
130
- setSystemPrompt(v: string): void;
131
- setModel(m: Model<any>): void;
132
- setThinkingLevel(l: ThinkingLevel): void;
133
- setSteeringMode(mode: "all" | "one-at-a-time"): void;
134
- getSteeringMode(): "all" | "one-at-a-time";
135
- setFollowUpMode(mode: "all" | "one-at-a-time"): void;
136
- getFollowUpMode(): "all" | "one-at-a-time";
137
- setTools(t: AgentTool<any>[]): void;
138
- replaceMessages(ms: AgentMessage[]): void;
139
- appendMessage(m: AgentMessage): void;
140
- /**
141
- * Queue a steering message while the agent is running.
142
- * Delivered after the current assistant turn finishes executing its tool calls,
143
- * before the next LLM call.
144
- */
145
- steer(m: AgentMessage): void;
146
- /**
147
- * Queue a follow-up message to be processed after the agent finishes.
148
- * Delivered only when agent has no more tool calls or steering messages.
149
- */
150
- followUp(m: AgentMessage): void;
69
+ /** Controls how queued steering messages are drained. */
70
+ set steeringMode(mode: QueueMode);
71
+ get steeringMode(): QueueMode;
72
+ /** Controls how queued follow-up messages are drained. */
73
+ set followUpMode(mode: QueueMode);
74
+ get followUpMode(): QueueMode;
75
+ /** Queue a message to be injected after the current assistant turn finishes. */
76
+ steer(message: AgentMessage): void;
77
+ /** Queue a message to run only after the agent would otherwise stop. */
78
+ followUp(message: AgentMessage): void;
79
+ /** Remove all queued steering messages. */
151
80
  clearSteeringQueue(): void;
81
+ /** Remove all queued follow-up messages. */
152
82
  clearFollowUpQueue(): void;
83
+ /** Remove all queued steering and follow-up messages. */
153
84
  clearAllQueues(): void;
85
+ /** Returns true when either queue still contains pending messages. */
154
86
  hasQueuedMessages(): boolean;
155
- private dequeueSteeringMessages;
156
- private dequeueFollowUpMessages;
157
- clearMessages(): void;
158
- /** The current abort signal, or undefined when the agent is not streaming. */
87
+ /** Active abort signal for the current run, if any. */
159
88
  get signal(): AbortSignal | undefined;
89
+ /** Abort the current run, if one is active. */
160
90
  abort(): void;
91
+ /**
92
+ * Resolve when the current run and all awaited event listeners have finished.
93
+ *
94
+ * This resolves after `agent_end` listeners settle.
95
+ */
161
96
  waitForIdle(): Promise<void>;
97
+ /** Clear transcript state, runtime state, and queued messages. */
162
98
  reset(): void;
163
- /** Send a prompt with an AgentMessage */
99
+ /** Start a new prompt from text, a single message, or a batch of messages. */
164
100
  prompt(message: AgentMessage | AgentMessage[]): Promise<void>;
165
101
  prompt(input: string, images?: ImageContent[]): Promise<void>;
166
- /**
167
- * Continue from current context (used for retries and resuming queued messages).
168
- */
102
+ /** Continue from the current transcript. The last message must be a user or tool-result message. */
169
103
  continue(): Promise<void>;
170
- private _processLoopEvent;
171
- private _runLoop;
172
- private emit;
104
+ private normalizePromptInput;
105
+ private runPromptMessages;
106
+ private runContinuation;
107
+ private createContextSnapshot;
108
+ private createLoopConfig;
109
+ private runWithLifecycle;
110
+ private handleRunFailure;
111
+ private finishRun;
112
+ private processEvents;
173
113
  }
114
+ export {};
174
115
  //# sourceMappingURL=agent.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAEN,KAAK,YAAY,EACjB,KAAK,OAAO,EACZ,KAAK,KAAK,EACV,KAAK,mBAAmB,EAGxB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,MAAM,qBAAqB,CAAC;AAE7B,OAAO,KAAK,EACX,oBAAoB,EACpB,mBAAmB,EAEnB,UAAU,EAEV,YAAY,EACZ,UAAU,EACV,SAAS,EACT,qBAAqB,EACrB,oBAAoB,EACpB,QAAQ,EACR,aAAa,EACb,iBAAiB,EACjB,MAAM,YAAY,CAAC;AASpB,MAAM,WAAW,YAAY;IAC5B,YAAY,CAAC,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;IAEnC;;;OAGG;IACH,YAAY,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IAE5E;;;OAGG;IACH,gBAAgB,CAAC,EAAE,CA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,uBAAuB;IAe/B,aAAa,SAEZ;IAED,8EAA8E;IAC9E,IAAI,MAAM,IAAI,WAAW,GAAG,SAAS,CAEpC;IAED,KAAK,SAEJ;IAED,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAE3B;IAED,KAAK,SAQJ;IAED,yCAAyC;IACnC,MAAM,CAAC,OAAO,EAAE,YAAY,GAAG,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAkCpE;;OAEG;IACG,QAAQ,kBA0Bb;IAED,OAAO,CAAC,iBAAiB;YAiDX,QAAQ;IAoGtB,OAAO,CAAC,IAAI;CAKZ","sourcesContent":["/**\n * Agent class that uses the agent-loop directly.\n * No transport abstraction - calls streamSimple via the loop.\n */\n\nimport {\n\tgetModel,\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@hyperspaceng/neural-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.js\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tStreamFn,\n\tThinkingLevel,\n\tToolExecutionMode,\n} from \"./types.js\";\n\n/**\n * Default convertToLlm: Keep only LLM-compatible messages, convert attachments.\n */\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter((m) => m.role === \"user\" || m.role === \"assistant\" || m.role === \"toolResult\");\n}\n\nexport interface AgentOptions {\n\tinitialState?: Partial<AgentState>;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t * Default filters to user/assistant/toolResult and converts attachments.\n\t */\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to context before convertToLlm.\n\t * Use for context pruning, injecting external context, etc.\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Steering mode: \"all\" = send all steering messages at once, \"one-at-a-time\" = one per turn\n\t */\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\n\t/**\n\t * Follow-up mode: \"all\" = send all follow-up messages at once, \"one-at-a-time\" = one per turn\n\t */\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\n\t/**\n\t * Custom stream function (for proxy backends, etc.). Default uses streamSimple.\n\t */\n\tstreamFn?: StreamFn;\n\n\t/**\n\t * Optional session identifier forwarded to LLM providers.\n\t * Used by providers that support session-based caching (e.g., OpenAI Codex).\n\t */\n\tsessionId?: string;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t * Useful for expiring tokens (e.g., GitHub Copilot OAuth).\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Inspect or replace provider payloads before they are sent.\n\t */\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\n\t/**\n\t * Custom token budgets for thinking levels (token-based providers only).\n\t */\n\tthinkingBudgets?: ThinkingBudgets;\n\n\t/**\n\t * Preferred transport for providers that support multiple transports.\n\t */\n\ttransport?: Transport;\n\n\t/**\n\t * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.\n\t * If the server's requested delay exceeds this value, the request fails immediately,\n\t * allowing higher-level retry logic to handle it with user visibility.\n\t * Default: 60000 (60 seconds). Set to 0 to disable the cap.\n\t */\n\tmaxRetryDelayMs?: number;\n\n\t/** Tool execution mode. Default: \"parallel\" */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/** Called before a tool is executed, after arguments have been validated. */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/** Called after a tool finishes executing, before final tool events are emitted. */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\nexport class Agent {\n\tprivate _state: AgentState = {\n\t\tsystemPrompt: \"\",\n\t\tmodel: getModel(\"google\", \"gemini-2.5-flash-lite-preview-06-17\"),\n\t\tthinkingLevel: \"off\",\n\t\ttools: [],\n\t\tmessages: [],\n\t\tisStreaming: false,\n\t\tstreamMessage: null,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terror: undefined,\n\t};\n\n\tprivate listeners = new Set<(e: AgentEvent) => void>();\n\tprivate abortController?: AbortController;\n\tprivate convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tprivate transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tprivate steeringQueue: AgentMessage[] = [];\n\tprivate followUpQueue: AgentMessage[] = [];\n\tprivate steeringMode: \"all\" | \"one-at-a-time\";\n\tprivate followUpMode: \"all\" | \"one-at-a-time\";\n\tpublic streamFn: StreamFn;\n\tprivate _sessionId?: string;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tprivate _onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tprivate runningPrompt?: Promise<void>;\n\tprivate resolveRunningPrompt?: () => void;\n\tprivate _thinkingBudgets?: ThinkingBudgets;\n\tprivate _transport: Transport;\n\tprivate _maxRetryDelayMs?: number;\n\tprivate _toolExecution: ToolExecutionMode;\n\tprivate _beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tprivate _afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\n\tconstructor(opts: AgentOptions = {}) {\n\t\tthis._state = { ...this._state, ...opts.initialState };\n\t\tthis.convertToLlm = opts.convertToLlm || defaultConvertToLlm;\n\t\tthis.transformContext = opts.transformContext;\n\t\tthis.steeringMode = opts.steeringMode || \"one-at-a-time\";\n\t\tthis.followUpMode = opts.followUpMode || \"one-at-a-time\";\n\t\tthis.streamFn = opts.streamFn || streamSimple;\n\t\tthis._sessionId = opts.sessionId;\n\t\tthis.getApiKey = opts.getApiKey;\n\t\tthis._onPayload = opts.onPayload;\n\t\tthis._thinkingBudgets = opts.thinkingBudgets;\n\t\tthis._transport = opts.transport ?? \"sse\";\n\t\tthis._maxRetryDelayMs = opts.maxRetryDelayMs;\n\t\tthis._toolExecution = opts.toolExecution ?? \"parallel\";\n\t\tthis._beforeToolCall = opts.beforeToolCall;\n\t\tthis._afterToolCall = opts.afterToolCall;\n\t}\n\n\t/**\n\t * Get the current session ID used for provider caching.\n\t */\n\tget sessionId(): string | undefined {\n\t\treturn this._sessionId;\n\t}\n\n\t/**\n\t * Set the session ID for provider caching.\n\t * Call this when switching sessions (new session, branch, resume).\n\t */\n\tset sessionId(value: string | undefined) {\n\t\tthis._sessionId = value;\n\t}\n\n\t/**\n\t * Get the current thinking budgets.\n\t */\n\tget thinkingBudgets(): ThinkingBudgets | undefined {\n\t\treturn this._thinkingBudgets;\n\t}\n\n\t/**\n\t * Set custom thinking budgets for token-based providers.\n\t */\n\tset thinkingBudgets(value: ThinkingBudgets | undefined) {\n\t\tthis._thinkingBudgets = value;\n\t}\n\n\t/**\n\t * Get the current preferred transport.\n\t */\n\tget transport(): Transport {\n\t\treturn this._transport;\n\t}\n\n\t/**\n\t * Set the preferred transport.\n\t */\n\tsetTransport(value: Transport) {\n\t\tthis._transport = value;\n\t}\n\n\t/**\n\t * Get the current max retry delay in milliseconds.\n\t */\n\tget maxRetryDelayMs(): number | undefined {\n\t\treturn this._maxRetryDelayMs;\n\t}\n\n\t/**\n\t * Set the maximum delay to wait for server-requested retries.\n\t * Set to 0 to disable the cap.\n\t */\n\tset maxRetryDelayMs(value: number | undefined) {\n\t\tthis._maxRetryDelayMs = value;\n\t}\n\n\tget toolExecution(): ToolExecutionMode {\n\t\treturn this._toolExecution;\n\t}\n\n\tsetToolExecution(value: ToolExecutionMode) {\n\t\tthis._toolExecution = value;\n\t}\n\n\tsetBeforeToolCall(\n\t\tvalue:\n\t\t\t| ((context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>)\n\t\t\t| undefined,\n\t) {\n\t\tthis._beforeToolCall = value;\n\t}\n\n\tsetAfterToolCall(\n\t\tvalue:\n\t\t\t| ((context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>)\n\t\t\t| undefined,\n\t) {\n\t\tthis._afterToolCall = value;\n\t}\n\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\tsubscribe(fn: (e: AgentEvent) => void): () => void {\n\t\tthis.listeners.add(fn);\n\t\treturn () => this.listeners.delete(fn);\n\t}\n\n\t// State mutators\n\tsetSystemPrompt(v: string) {\n\t\tthis._state.systemPrompt = v;\n\t}\n\n\tsetModel(m: Model<any>) {\n\t\tthis._state.model = m;\n\t}\n\n\tsetThinkingLevel(l: ThinkingLevel) {\n\t\tthis._state.thinkingLevel = l;\n\t}\n\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\") {\n\t\tthis.steeringMode = mode;\n\t}\n\n\tgetSteeringMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.steeringMode;\n\t}\n\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\") {\n\t\tthis.followUpMode = mode;\n\t}\n\n\tgetFollowUpMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.followUpMode;\n\t}\n\n\tsetTools(t: AgentTool<any>[]) {\n\t\tthis._state.tools = t;\n\t}\n\n\treplaceMessages(ms: AgentMessage[]) {\n\t\tthis._state.messages = ms.slice();\n\t}\n\n\tappendMessage(m: AgentMessage) {\n\t\tthis._state.messages = [...this._state.messages, m];\n\t}\n\n\t/**\n\t * Queue a steering message while the agent is running.\n\t * Delivered after the current assistant turn finishes executing its tool calls,\n\t * before the next LLM call.\n\t */\n\tsteer(m: AgentMessage) {\n\t\tthis.steeringQueue.push(m);\n\t}\n\n\t/**\n\t * Queue a follow-up message to be processed after the agent finishes.\n\t * Delivered only when agent has no more tool calls or steering messages.\n\t */\n\tfollowUp(m: AgentMessage) {\n\t\tthis.followUpQueue.push(m);\n\t}\n\n\tclearSteeringQueue() {\n\t\tthis.steeringQueue = [];\n\t}\n\n\tclearFollowUpQueue() {\n\t\tthis.followUpQueue = [];\n\t}\n\n\tclearAllQueues() {\n\t\tthis.steeringQueue = [];\n\t\tthis.followUpQueue = [];\n\t}\n\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.length > 0 || this.followUpQueue.length > 0;\n\t}\n\n\tprivate dequeueSteeringMessages(): AgentMessage[] {\n\t\tif (this.steeringMode === \"one-at-a-time\") {\n\t\t\tif (this.steeringQueue.length > 0) {\n\t\t\t\tconst first = this.steeringQueue[0];\n\t\t\t\tthis.steeringQueue = this.steeringQueue.slice(1);\n\t\t\t\treturn [first];\n\t\t\t}\n\t\t\treturn [];\n\t\t}\n\n\t\tconst steering = this.steeringQueue.slice();\n\t\tthis.steeringQueue = [];\n\t\treturn steering;\n\t}\n\n\tprivate dequeueFollowUpMessages(): AgentMessage[] {\n\t\tif (this.followUpMode === \"one-at-a-time\") {\n\t\t\tif (this.followUpQueue.length > 0) {\n\t\t\t\tconst first = this.followUpQueue[0];\n\t\t\t\tthis.followUpQueue = this.followUpQueue.slice(1);\n\t\t\t\treturn [first];\n\t\t\t}\n\t\t\treturn [];\n\t\t}\n\n\t\tconst followUp = this.followUpQueue.slice();\n\t\tthis.followUpQueue = [];\n\t\treturn followUp;\n\t}\n\n\tclearMessages() {\n\t\tthis._state.messages = [];\n\t}\n\n\t/** The current abort signal, or undefined when the agent is not streaming. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.abortController?.signal;\n\t}\n\n\tabort() {\n\t\tthis.abortController?.abort();\n\t}\n\n\twaitForIdle(): Promise<void> {\n\t\treturn this.runningPrompt ?? Promise.resolve();\n\t}\n\n\treset() {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamMessage = null;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.error = undefined;\n\t\tthis.steeringQueue = [];\n\t\tthis.followUpQueue = [];\n\t}\n\n\t/** Send a prompt with an AgentMessage */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]) {\n\t\tif (this._state.isStreaming) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\n\t\tconst model = this._state.model;\n\t\tif (!model) throw new Error(\"No model configured\");\n\n\t\tlet msgs: AgentMessage[];\n\n\t\tif (Array.isArray(input)) {\n\t\t\tmsgs = input;\n\t\t} else if (typeof input === \"string\") {\n\t\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\t\tif (images && images.length > 0) {\n\t\t\t\tcontent.push(...images);\n\t\t\t}\n\t\t\tmsgs = [\n\t\t\t\t{\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t},\n\t\t\t];\n\t\t} else {\n\t\t\tmsgs = [input];\n\t\t}\n\n\t\tawait this._runLoop(msgs);\n\t}\n\n\t/**\n\t * Continue from current context (used for retries and resuming queued messages).\n\t */\n\tasync continue() {\n\t\tif (this._state.isStreaming) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst messages = this._state.messages;\n\t\tif (messages.length === 0) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\t\tif (messages[messages.length - 1].role === \"assistant\") {\n\t\t\tconst queuedSteering = this.dequeueSteeringMessages();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this._runLoop(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUp = this.dequeueFollowUpMessages();\n\t\t\tif (queuedFollowUp.length > 0) {\n\t\t\t\tawait this._runLoop(queuedFollowUp);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this._runLoop(undefined);\n\t}\n\n\tprivate _processLoopEvent(event: AgentEvent): void {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamMessage = null;\n\t\t\t\tthis.appendMessage(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && (event.message as any).errorMessage) {\n\t\t\t\t\tthis._state.error = (event.message as any).errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.isStreaming = false;\n\t\t\t\tthis._state.streamMessage = null;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tthis.emit(event);\n\t}\n\n\t/**\n\t * Run the agent loop.\n\t * If messages are provided, starts a new conversation turn with those messages.\n\t * Otherwise, continues from existing context.\n\t */\n\tprivate async _runLoop(messages?: AgentMessage[], options?: { skipInitialSteeringPoll?: boolean }) {\n\t\tconst model = this._state.model;\n\t\tif (!model) throw new Error(\"No model configured\");\n\n\t\tthis.runningPrompt = new Promise<void>((resolve) => {\n\t\t\tthis.resolveRunningPrompt = resolve;\n\t\t});\n\n\t\tthis.abortController = new AbortController();\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamMessage = null;\n\t\tthis._state.error = undefined;\n\n\t\tconst reasoning = this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel;\n\n\t\tconst context: AgentContext = {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools,\n\t\t};\n\n\t\tlet skipInitialSteeringPoll = options?.skipInitialSteeringPoll === true;\n\n\t\tconst config: AgentLoopConfig = {\n\t\t\tmodel,\n\t\t\treasoning,\n\t\t\tsessionId: this._sessionId,\n\t\t\tonPayload: this._onPayload,\n\t\t\ttransport: this._transport,\n\t\t\tthinkingBudgets: this._thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this._maxRetryDelayMs,\n\t\t\ttoolExecution: this._toolExecution,\n\t\t\tbeforeToolCall: this._beforeToolCall,\n\t\t\tafterToolCall: this._afterToolCall,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.dequeueSteeringMessages();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.dequeueFollowUpMessages(),\n\t\t};\n\n\t\ttry {\n\t\t\tif (messages) {\n\t\t\t\tawait runAgentLoop(\n\t\t\t\t\tmessages,\n\t\t\t\t\tcontext,\n\t\t\t\t\tconfig,\n\t\t\t\t\tasync (event) => this._processLoopEvent(event),\n\t\t\t\t\tthis.abortController.signal,\n\t\t\t\t\tthis.streamFn,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tawait runAgentLoopContinue(\n\t\t\t\t\tcontext,\n\t\t\t\t\tconfig,\n\t\t\t\t\tasync (event) => this._processLoopEvent(event),\n\t\t\t\t\tthis.abortController.signal,\n\t\t\t\t\tthis.streamFn,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (err: any) {\n\t\t\tconst errorMsg: AgentMessage = {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\t\tapi: model.api,\n\t\t\t\tprovider: model.provider,\n\t\t\t\tmodel: model.id,\n\t\t\t\tusage: {\n\t\t\t\t\tinput: 0,\n\t\t\t\t\toutput: 0,\n\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotalTokens: 0,\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t},\n\t\t\t\tstopReason: this.abortController?.signal.aborted ? \"aborted\" : \"error\",\n\t\t\t\terrorMessage: err?.message || String(err),\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as AgentMessage;\n\n\t\t\tthis.appendMessage(errorMsg);\n\t\t\tthis._state.error = err?.message || String(err);\n\t\t\tthis.emit({ type: \"agent_end\", messages: [errorMsg] });\n\t\t} finally {\n\t\t\tthis._state.isStreaming = false;\n\t\t\tthis._state.streamMessage = null;\n\t\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\t\tthis.abortController = undefined;\n\t\t\tthis.resolveRunningPrompt?.();\n\t\t\tthis.runningPrompt = undefined;\n\t\t\tthis.resolveRunningPrompt = undefined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AI,WAAW,GAAG,SAAS,CAEpC;IAED,+CAA+C;IAC/C,KAAK,IAAI,IAAI,CAEZ;IAED;;;;OAIG;IACH,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAE3B;IAED,kEAAkE;IAClE,KAAK,IAAI,IAAI,CAQZ;IAED,8EAA8E;IACxE,MAAM,CAAC,OAAO,EAAE,YAAY,GAAG,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAWpE,oGAAoG;IAC9F,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CA2B9B;IAED,OAAO,CAAC,oBAAoB;YAmBd,iBAAiB;YAgBjB,eAAe;IAY7B,OAAO,CAAC,qBAAqB;IAQ7B,OAAO,CAAC,gBAAgB;YA2BV,gBAAgB;YAyBhB,gBAAgB;IAiB9B,OAAO,CAAC,SAAS;YAeH,aAAa;CAgD3B","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@hyperspaceng/neural-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.js\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.js\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype QueueMode = \"all\" | \"one-at-a-time\";\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\n\tconstructor(public mode: QueueMode) {}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"sse\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tthis._state.messages.push(failureMessage);\n\t\tthis._state.errorMessage = failureMessage.errorMessage;\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}