@draht/agent-core 2026.3.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.
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Agent loop that works with AgentMessage throughout.
3
+ * Transforms to Message[] only at the LLM call boundary.
4
+ */
5
+ import { EventStream, streamSimple, validateToolArguments, } from "@draht/ai";
6
+ /**
7
+ * Start an agent loop with a new prompt message.
8
+ * The prompt is added to the context and events are emitted for it.
9
+ */
10
+ export function agentLoop(prompts, context, config, signal, streamFn) {
11
+ const stream = createAgentStream();
12
+ (async () => {
13
+ const newMessages = [...prompts];
14
+ const currentContext = {
15
+ ...context,
16
+ messages: [...context.messages, ...prompts],
17
+ };
18
+ stream.push({ type: "agent_start" });
19
+ stream.push({ type: "turn_start" });
20
+ for (const prompt of prompts) {
21
+ stream.push({ type: "message_start", message: prompt });
22
+ stream.push({ type: "message_end", message: prompt });
23
+ }
24
+ await runLoop(currentContext, newMessages, config, signal, stream, streamFn);
25
+ })();
26
+ return stream;
27
+ }
28
+ /**
29
+ * Continue an agent loop from the current context without adding a new message.
30
+ * Used for retries - context already has user message or tool results.
31
+ *
32
+ * **Important:** The last message in context must convert to a `user` or `toolResult` message
33
+ * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.
34
+ * This cannot be validated here since `convertToLlm` is only called once per turn.
35
+ */
36
+ export function agentLoopContinue(context, config, signal, streamFn) {
37
+ if (context.messages.length === 0) {
38
+ throw new Error("Cannot continue: no messages in context");
39
+ }
40
+ if (context.messages[context.messages.length - 1].role === "assistant") {
41
+ throw new Error("Cannot continue from message role: assistant");
42
+ }
43
+ const stream = createAgentStream();
44
+ (async () => {
45
+ const newMessages = [];
46
+ const currentContext = { ...context };
47
+ stream.push({ type: "agent_start" });
48
+ stream.push({ type: "turn_start" });
49
+ await runLoop(currentContext, newMessages, config, signal, stream, streamFn);
50
+ })();
51
+ return stream;
52
+ }
53
+ function createAgentStream() {
54
+ return new EventStream((event) => event.type === "agent_end", (event) => (event.type === "agent_end" ? event.messages : []));
55
+ }
56
+ /**
57
+ * Main loop logic shared by agentLoop and agentLoopContinue.
58
+ */
59
+ async function runLoop(currentContext, newMessages, config, signal, stream, streamFn) {
60
+ let firstTurn = true;
61
+ // Check for steering messages at start (user may have typed while waiting)
62
+ let pendingMessages = (await config.getSteeringMessages?.()) || [];
63
+ // Outer loop: continues when queued follow-up messages arrive after agent would stop
64
+ while (true) {
65
+ let hasMoreToolCalls = true;
66
+ let steeringAfterTools = null;
67
+ // Inner loop: process tool calls and steering messages
68
+ while (hasMoreToolCalls || pendingMessages.length > 0) {
69
+ if (!firstTurn) {
70
+ stream.push({ type: "turn_start" });
71
+ }
72
+ else {
73
+ firstTurn = false;
74
+ }
75
+ // Process pending messages (inject before next assistant response)
76
+ if (pendingMessages.length > 0) {
77
+ for (const message of pendingMessages) {
78
+ stream.push({ type: "message_start", message });
79
+ stream.push({ type: "message_end", message });
80
+ currentContext.messages.push(message);
81
+ newMessages.push(message);
82
+ }
83
+ pendingMessages = [];
84
+ }
85
+ // Stream assistant response
86
+ const message = await streamAssistantResponse(currentContext, config, signal, stream, streamFn);
87
+ newMessages.push(message);
88
+ if (message.stopReason === "error" || message.stopReason === "aborted") {
89
+ stream.push({ type: "turn_end", message, toolResults: [] });
90
+ stream.push({ type: "agent_end", messages: newMessages });
91
+ stream.end(newMessages);
92
+ return;
93
+ }
94
+ // Check for tool calls
95
+ const toolCalls = message.content.filter((c) => c.type === "toolCall");
96
+ hasMoreToolCalls = toolCalls.length > 0;
97
+ const toolResults = [];
98
+ if (hasMoreToolCalls) {
99
+ const toolExecution = await executeToolCalls(currentContext.tools, message, signal, stream, config.getSteeringMessages);
100
+ toolResults.push(...toolExecution.toolResults);
101
+ steeringAfterTools = toolExecution.steeringMessages ?? null;
102
+ for (const result of toolResults) {
103
+ currentContext.messages.push(result);
104
+ newMessages.push(result);
105
+ }
106
+ }
107
+ stream.push({ type: "turn_end", message, toolResults });
108
+ // Get steering messages after turn completes
109
+ if (steeringAfterTools && steeringAfterTools.length > 0) {
110
+ pendingMessages = steeringAfterTools;
111
+ steeringAfterTools = null;
112
+ }
113
+ else {
114
+ pendingMessages = (await config.getSteeringMessages?.()) || [];
115
+ }
116
+ }
117
+ // Agent would stop here. Check for follow-up messages.
118
+ const followUpMessages = (await config.getFollowUpMessages?.()) || [];
119
+ if (followUpMessages.length > 0) {
120
+ // Set as pending so inner loop processes them
121
+ pendingMessages = followUpMessages;
122
+ continue;
123
+ }
124
+ // No more messages, exit
125
+ break;
126
+ }
127
+ stream.push({ type: "agent_end", messages: newMessages });
128
+ stream.end(newMessages);
129
+ }
130
+ /**
131
+ * Stream an assistant response from the LLM.
132
+ * This is where AgentMessage[] gets transformed to Message[] for the LLM.
133
+ */
134
+ async function streamAssistantResponse(context, config, signal, stream, streamFn) {
135
+ // Apply context transform if configured (AgentMessage[] → AgentMessage[])
136
+ let messages = context.messages;
137
+ if (config.transformContext) {
138
+ messages = await config.transformContext(messages, signal);
139
+ }
140
+ // Convert to LLM-compatible messages (AgentMessage[] → Message[])
141
+ const llmMessages = await config.convertToLlm(messages);
142
+ // Build LLM context
143
+ const llmContext = {
144
+ systemPrompt: context.systemPrompt,
145
+ messages: llmMessages,
146
+ tools: context.tools,
147
+ };
148
+ const streamFunction = streamFn || streamSimple;
149
+ // Resolve API key (important for expiring tokens)
150
+ const resolvedApiKey = (config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;
151
+ const response = await streamFunction(config.model, llmContext, {
152
+ ...config,
153
+ apiKey: resolvedApiKey,
154
+ signal,
155
+ });
156
+ let partialMessage = null;
157
+ let addedPartial = false;
158
+ for await (const event of response) {
159
+ switch (event.type) {
160
+ case "start":
161
+ partialMessage = event.partial;
162
+ context.messages.push(partialMessage);
163
+ addedPartial = true;
164
+ stream.push({ type: "message_start", message: { ...partialMessage } });
165
+ break;
166
+ case "text_start":
167
+ case "text_delta":
168
+ case "text_end":
169
+ case "thinking_start":
170
+ case "thinking_delta":
171
+ case "thinking_end":
172
+ case "toolcall_start":
173
+ case "toolcall_delta":
174
+ case "toolcall_end":
175
+ if (partialMessage) {
176
+ partialMessage = event.partial;
177
+ context.messages[context.messages.length - 1] = partialMessage;
178
+ stream.push({
179
+ type: "message_update",
180
+ assistantMessageEvent: event,
181
+ message: { ...partialMessage },
182
+ });
183
+ }
184
+ break;
185
+ case "done":
186
+ case "error": {
187
+ const finalMessage = await response.result();
188
+ if (addedPartial) {
189
+ context.messages[context.messages.length - 1] = finalMessage;
190
+ }
191
+ else {
192
+ context.messages.push(finalMessage);
193
+ }
194
+ if (!addedPartial) {
195
+ stream.push({ type: "message_start", message: { ...finalMessage } });
196
+ }
197
+ stream.push({ type: "message_end", message: finalMessage });
198
+ return finalMessage;
199
+ }
200
+ }
201
+ }
202
+ return await response.result();
203
+ }
204
+ /**
205
+ * Execute tool calls from an assistant message.
206
+ */
207
+ async function executeToolCalls(tools, assistantMessage, signal, stream, getSteeringMessages) {
208
+ const toolCalls = assistantMessage.content.filter((c) => c.type === "toolCall");
209
+ const results = [];
210
+ let steeringMessages;
211
+ for (let index = 0; index < toolCalls.length; index++) {
212
+ const toolCall = toolCalls[index];
213
+ const tool = tools?.find((t) => t.name === toolCall.name);
214
+ stream.push({
215
+ type: "tool_execution_start",
216
+ toolCallId: toolCall.id,
217
+ toolName: toolCall.name,
218
+ args: toolCall.arguments,
219
+ });
220
+ let result;
221
+ let isError = false;
222
+ try {
223
+ if (!tool)
224
+ throw new Error(`Tool ${toolCall.name} not found`);
225
+ const validatedArgs = validateToolArguments(tool, toolCall);
226
+ result = await tool.execute(toolCall.id, validatedArgs, signal, (partialResult) => {
227
+ stream.push({
228
+ type: "tool_execution_update",
229
+ toolCallId: toolCall.id,
230
+ toolName: toolCall.name,
231
+ args: toolCall.arguments,
232
+ partialResult,
233
+ });
234
+ });
235
+ }
236
+ catch (e) {
237
+ result = {
238
+ content: [{ type: "text", text: e instanceof Error ? e.message : String(e) }],
239
+ details: {},
240
+ };
241
+ isError = true;
242
+ }
243
+ stream.push({
244
+ type: "tool_execution_end",
245
+ toolCallId: toolCall.id,
246
+ toolName: toolCall.name,
247
+ result,
248
+ isError,
249
+ });
250
+ const toolResultMessage = {
251
+ role: "toolResult",
252
+ toolCallId: toolCall.id,
253
+ toolName: toolCall.name,
254
+ content: result.content,
255
+ details: result.details,
256
+ isError,
257
+ timestamp: Date.now(),
258
+ };
259
+ results.push(toolResultMessage);
260
+ stream.push({ type: "message_start", message: toolResultMessage });
261
+ stream.push({ type: "message_end", message: toolResultMessage });
262
+ // Check for steering messages - skip remaining tools if user interrupted
263
+ if (getSteeringMessages) {
264
+ const steering = await getSteeringMessages();
265
+ if (steering.length > 0) {
266
+ steeringMessages = steering;
267
+ const remainingCalls = toolCalls.slice(index + 1);
268
+ for (const skipped of remainingCalls) {
269
+ results.push(skipToolCall(skipped, stream));
270
+ }
271
+ break;
272
+ }
273
+ }
274
+ }
275
+ return { toolResults: results, steeringMessages };
276
+ }
277
+ function skipToolCall(toolCall, stream) {
278
+ const result = {
279
+ content: [{ type: "text", text: "Skipped due to queued user message." }],
280
+ details: {},
281
+ };
282
+ stream.push({
283
+ type: "tool_execution_start",
284
+ toolCallId: toolCall.id,
285
+ toolName: toolCall.name,
286
+ args: toolCall.arguments,
287
+ });
288
+ stream.push({
289
+ type: "tool_execution_end",
290
+ toolCallId: toolCall.id,
291
+ toolName: toolCall.name,
292
+ result,
293
+ isError: true,
294
+ });
295
+ const toolResultMessage = {
296
+ role: "toolResult",
297
+ toolCallId: toolCall.id,
298
+ toolName: toolCall.name,
299
+ content: result.content,
300
+ details: {},
301
+ isError: true,
302
+ timestamp: Date.now(),
303
+ };
304
+ stream.push({ type: "message_start", message: toolResultMessage });
305
+ stream.push({ type: "message_end", message: toolResultMessage });
306
+ return toolResultMessage;
307
+ }
308
+ //# sourceMappingURL=agent-loop.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-loop.js","sourceRoot":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OAAO,EAAE,gBAAgB,EAAE,CAAC;AAAA,CAClD;AAED,SAAS,YAAY,CACpB,QAA4E,EAC5E,MAA+C,EAC3B;IACpB,MAAM,MAAM,GAAyB;QACpC,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,qCAAqC,EAAE,CAAC;QACxE,OAAO,EAAE,EAAE;KACX,CAAC;IAEF,MAAM,CAAC,IAAI,CAAC;QACX,IAAI,EAAE,sBAAsB;QAC5B,UAAU,EAAE,QAAQ,CAAC,EAAE;QACvB,QAAQ,EAAE,QAAQ,CAAC,IAAI;QACvB,IAAI,EAAE,QAAQ,CAAC,SAAS;KACxB,CAAC,CAAC;IACH,MAAM,CAAC,IAAI,CAAC;QACX,IAAI,EAAE,oBAAoB;QAC1B,UAAU,EAAE,QAAQ,CAAC,EAAE;QACvB,QAAQ,EAAE,QAAQ,CAAC,IAAI;QACvB,MAAM;QACN,OAAO,EAAE,IAAI;KACb,CAAC,CAAC;IAEH,MAAM,iBAAiB,GAAsB;QAC5C,IAAI,EAAE,YAAY;QAClB,UAAU,EAAE,QAAQ,CAAC,EAAE;QACvB,QAAQ,EAAE,QAAQ,CAAC,IAAI;QACvB,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,OAAO,EAAE,EAAE;QACX,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACrB,CAAC;IAEF,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IACnE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAEjE,OAAO,iBAAiB,CAAC;AAAA,CACzB","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport {\n\ttype AssistantMessage,\n\ttype Context,\n\tEventStream,\n\tstreamSimple,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"@draht/ai\";\nimport type {\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolResult,\n\tStreamFn,\n} from \"./types.js\";\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\n\t(async () => {\n\t\tconst newMessages: AgentMessage[] = [...prompts];\n\t\tconst currentContext: AgentContext = {\n\t\t\t...context,\n\t\t\tmessages: [...context.messages, ...prompts],\n\t\t};\n\n\t\tstream.push({ type: \"agent_start\" });\n\t\tstream.push({ type: \"turn_start\" });\n\t\tfor (const prompt of prompts) {\n\t\t\tstream.push({ type: \"message_start\", message: prompt });\n\t\t\tstream.push({ type: \"message_end\", message: prompt });\n\t\t}\n\n\t\tawait runLoop(currentContext, newMessages, config, signal, stream, streamFn);\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst stream = createAgentStream();\n\n\t(async () => {\n\t\tconst newMessages: AgentMessage[] = [];\n\t\tconst currentContext: AgentContext = { ...context };\n\n\t\tstream.push({ type: \"agent_start\" });\n\t\tstream.push({ type: \"turn_start\" });\n\n\t\tawait runLoop(currentContext, newMessages, config, signal, stream, streamFn);\n\t})();\n\n\treturn stream;\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\",\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" ? event.messages : []),\n\t);\n}\n\n/**\n * Main loop logic shared by agentLoop and agentLoopContinue.\n */\nasync function runLoop(\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\tstream: EventStream<AgentEvent, AgentMessage[]>,\n\tstreamFn?: StreamFn,\n): Promise<void> {\n\tlet firstTurn = true;\n\t// Check for steering messages at start (user may have typed while waiting)\n\tlet pendingMessages: AgentMessage[] = (await config.getSteeringMessages?.()) || [];\n\n\t// Outer loop: continues when queued follow-up messages arrive after agent would stop\n\twhile (true) {\n\t\tlet hasMoreToolCalls = true;\n\t\tlet steeringAfterTools: AgentMessage[] | null = null;\n\n\t\t// Inner loop: process tool calls and steering messages\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\tif (!firstTurn) {\n\t\t\t\tstream.push({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\t// Process pending messages (inject before next assistant response)\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\tstream.push({ type: \"message_start\", message });\n\t\t\t\t\tstream.push({ type: \"message_end\", message });\n\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\tnewMessages.push(message);\n\t\t\t\t}\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\t// Stream assistant response\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, stream, streamFn);\n\t\t\tnewMessages.push(message);\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tstream.push({ type: \"turn_end\", message, toolResults: [] });\n\t\t\t\tstream.push({ type: \"agent_end\", messages: newMessages });\n\t\t\t\tstream.end(newMessages);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for tool calls\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\t\t\thasMoreToolCalls = toolCalls.length > 0;\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tif (hasMoreToolCalls) {\n\t\t\t\tconst toolExecution = await executeToolCalls(\n\t\t\t\t\tcurrentContext.tools,\n\t\t\t\t\tmessage,\n\t\t\t\t\tsignal,\n\t\t\t\t\tstream,\n\t\t\t\t\tconfig.getSteeringMessages,\n\t\t\t\t);\n\t\t\t\ttoolResults.push(...toolExecution.toolResults);\n\t\t\t\tsteeringAfterTools = toolExecution.steeringMessages ?? null;\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tnewMessages.push(result);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstream.push({ type: \"turn_end\", message, toolResults });\n\n\t\t\t// Get steering messages after turn completes\n\t\t\tif (steeringAfterTools && steeringAfterTools.length > 0) {\n\t\t\t\tpendingMessages = steeringAfterTools;\n\t\t\t\tsteeringAfterTools = null;\n\t\t\t} else {\n\t\t\t\tpendingMessages = (await config.getSteeringMessages?.()) || [];\n\t\t\t}\n\t\t}\n\n\t\t// Agent would stop here. Check for follow-up messages.\n\t\tconst followUpMessages = (await config.getFollowUpMessages?.()) || [];\n\t\tif (followUpMessages.length > 0) {\n\t\t\t// Set as pending so inner loop processes them\n\t\t\tpendingMessages = followUpMessages;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// No more messages, exit\n\t\tbreak;\n\t}\n\n\tstream.push({ type: \"agent_end\", messages: newMessages });\n\tstream.end(newMessages);\n}\n\n/**\n * Stream an assistant response from the LLM.\n * This is where AgentMessage[] gets transformed to Message[] for the LLM.\n */\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\tstream: EventStream<AgentEvent, AgentMessage[]>,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\t// Apply context transform if configured (AgentMessage[] → AgentMessage[])\n\tlet messages = context.messages;\n\tif (config.transformContext) {\n\t\tmessages = await config.transformContext(messages, signal);\n\t}\n\n\t// Convert to LLM-compatible messages (AgentMessage[] → Message[])\n\tconst llmMessages = await config.convertToLlm(messages);\n\n\t// Build LLM context\n\tconst llmContext: Context = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\tmessages: llmMessages,\n\t\ttools: context.tools,\n\t};\n\n\tconst streamFunction = streamFn || streamSimple;\n\n\t// Resolve API key (important for expiring tokens)\n\tconst resolvedApiKey =\n\t\t(config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;\n\n\tconst response = await streamFunction(config.model, llmContext, {\n\t\t...config,\n\t\tapiKey: resolvedApiKey,\n\t\tsignal,\n\t});\n\n\tlet partialMessage: AssistantMessage | null = null;\n\tlet addedPartial = false;\n\n\tfor await (const event of response) {\n\t\tswitch (event.type) {\n\t\t\tcase \"start\":\n\t\t\t\tpartialMessage = event.partial;\n\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\taddedPartial = true;\n\t\t\t\tstream.push({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\tbreak;\n\n\t\t\tcase \"text_start\":\n\t\t\tcase \"text_delta\":\n\t\t\tcase \"text_end\":\n\t\t\tcase \"thinking_start\":\n\t\t\tcase \"thinking_delta\":\n\t\t\tcase \"thinking_end\":\n\t\t\tcase \"toolcall_start\":\n\t\t\tcase \"toolcall_delta\":\n\t\t\tcase \"toolcall_end\":\n\t\t\t\tif (partialMessage) {\n\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"done\":\n\t\t\tcase \"error\": {\n\t\t\t\tconst finalMessage = await response.result();\n\t\t\t\tif (addedPartial) {\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t\t} else {\n\t\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\t}\n\t\t\t\tif (!addedPartial) {\n\t\t\t\t\tstream.push({ type: \"message_start\", message: { ...finalMessage } });\n\t\t\t\t}\n\t\t\t\tstream.push({ type: \"message_end\", message: finalMessage });\n\t\t\t\treturn finalMessage;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn await response.result();\n}\n\n/**\n * Execute tool calls from an assistant message.\n */\nasync function executeToolCalls(\n\ttools: AgentTool<any>[] | undefined,\n\tassistantMessage: AssistantMessage,\n\tsignal: AbortSignal | undefined,\n\tstream: EventStream<AgentEvent, AgentMessage[]>,\n\tgetSteeringMessages?: AgentLoopConfig[\"getSteeringMessages\"],\n): Promise<{ toolResults: ToolResultMessage[]; steeringMessages?: AgentMessage[] }> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\tconst results: ToolResultMessage[] = [];\n\tlet steeringMessages: AgentMessage[] | undefined;\n\n\tfor (let index = 0; index < toolCalls.length; index++) {\n\t\tconst toolCall = toolCalls[index];\n\t\tconst tool = tools?.find((t) => t.name === toolCall.name);\n\n\t\tstream.push({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tlet result: AgentToolResult<any>;\n\t\tlet isError = false;\n\n\t\ttry {\n\t\t\tif (!tool) throw new Error(`Tool ${toolCall.name} not found`);\n\n\t\t\tconst validatedArgs = validateToolArguments(tool, toolCall);\n\n\t\t\tresult = await tool.execute(toolCall.id, validatedArgs, signal, (partialResult) => {\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\targs: toolCall.arguments,\n\t\t\t\t\tpartialResult,\n\t\t\t\t});\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tresult = {\n\t\t\t\tcontent: [{ type: \"text\", text: e instanceof Error ? e.message : String(e) }],\n\t\t\t\tdetails: {},\n\t\t\t};\n\t\t\tisError = true;\n\t\t}\n\n\t\tstream.push({\n\t\t\ttype: \"tool_execution_end\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\tresult,\n\t\t\tisError,\n\t\t});\n\n\t\tconst toolResultMessage: ToolResultMessage = {\n\t\t\trole: \"toolResult\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\tcontent: result.content,\n\t\t\tdetails: result.details,\n\t\t\tisError,\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tresults.push(toolResultMessage);\n\t\tstream.push({ type: \"message_start\", message: toolResultMessage });\n\t\tstream.push({ type: \"message_end\", message: toolResultMessage });\n\n\t\t// Check for steering messages - skip remaining tools if user interrupted\n\t\tif (getSteeringMessages) {\n\t\t\tconst steering = await getSteeringMessages();\n\t\t\tif (steering.length > 0) {\n\t\t\t\tsteeringMessages = steering;\n\t\t\t\tconst remainingCalls = toolCalls.slice(index + 1);\n\t\t\t\tfor (const skipped of remainingCalls) {\n\t\t\t\t\tresults.push(skipToolCall(skipped, stream));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { toolResults: results, steeringMessages };\n}\n\nfunction skipToolCall(\n\ttoolCall: Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>,\n\tstream: EventStream<AgentEvent, AgentMessage[]>,\n): ToolResultMessage {\n\tconst result: AgentToolResult<any> = {\n\t\tcontent: [{ type: \"text\", text: \"Skipped due to queued user message.\" }],\n\t\tdetails: {},\n\t};\n\n\tstream.push({\n\t\ttype: \"tool_execution_start\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\targs: toolCall.arguments,\n\t});\n\tstream.push({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\tresult,\n\t\tisError: true,\n\t});\n\n\tconst toolResultMessage: ToolResultMessage = {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\tcontent: result.content,\n\t\tdetails: {},\n\t\tisError: true,\n\t\ttimestamp: Date.now(),\n\t};\n\n\tstream.push({ type: \"message_start\", message: toolResultMessage });\n\tstream.push({ type: \"message_end\", message: toolResultMessage });\n\n\treturn toolResultMessage;\n}\n"]}
@@ -0,0 +1,152 @@
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 ThinkingBudgets, type Transport } from "@draht/ai";
6
+ import type { AgentEvent, AgentMessage, AgentState, AgentTool, StreamFn, ThinkingLevel } from "./types.js";
7
+ 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
+ */
13
+ 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
+ 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
+ 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
+ getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
41
+ /**
42
+ * Custom token budgets for thinking levels (token-based providers only).
43
+ */
44
+ thinkingBudgets?: ThinkingBudgets;
45
+ /**
46
+ * Preferred transport for providers that support multiple transports.
47
+ */
48
+ transport?: Transport;
49
+ /**
50
+ * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
51
+ * If the server's requested delay exceeds this value, the request fails immediately,
52
+ * allowing higher-level retry logic to handle it with user visibility.
53
+ * Default: 60000 (60 seconds). Set to 0 to disable the cap.
54
+ */
55
+ maxRetryDelayMs?: number;
56
+ }
57
+ export declare class Agent {
58
+ private _state;
59
+ private listeners;
60
+ private abortController?;
61
+ private convertToLlm;
62
+ private transformContext?;
63
+ private steeringQueue;
64
+ private followUpQueue;
65
+ private steeringMode;
66
+ private followUpMode;
67
+ streamFn: StreamFn;
68
+ private _sessionId?;
69
+ getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
70
+ private runningPrompt?;
71
+ private resolveRunningPrompt?;
72
+ private _thinkingBudgets?;
73
+ private _transport;
74
+ private _maxRetryDelayMs?;
75
+ constructor(opts?: AgentOptions);
76
+ /**
77
+ * Get the current session ID used for provider caching.
78
+ */
79
+ get sessionId(): string | undefined;
80
+ /**
81
+ * Set the session ID for provider caching.
82
+ * Call this when switching sessions (new session, branch, resume).
83
+ */
84
+ set sessionId(value: string | undefined);
85
+ /**
86
+ * Get the current thinking budgets.
87
+ */
88
+ get thinkingBudgets(): ThinkingBudgets | undefined;
89
+ /**
90
+ * Set custom thinking budgets for token-based providers.
91
+ */
92
+ set thinkingBudgets(value: ThinkingBudgets | undefined);
93
+ /**
94
+ * Get the current preferred transport.
95
+ */
96
+ get transport(): Transport;
97
+ /**
98
+ * Set the preferred transport.
99
+ */
100
+ setTransport(value: Transport): void;
101
+ /**
102
+ * Get the current max retry delay in milliseconds.
103
+ */
104
+ get maxRetryDelayMs(): number | undefined;
105
+ /**
106
+ * Set the maximum delay to wait for server-requested retries.
107
+ * Set to 0 to disable the cap.
108
+ */
109
+ set maxRetryDelayMs(value: number | undefined);
110
+ get state(): AgentState;
111
+ subscribe(fn: (e: AgentEvent) => void): () => void;
112
+ setSystemPrompt(v: string): void;
113
+ setModel(m: Model<any>): void;
114
+ setThinkingLevel(l: ThinkingLevel): void;
115
+ setSteeringMode(mode: "all" | "one-at-a-time"): void;
116
+ getSteeringMode(): "all" | "one-at-a-time";
117
+ setFollowUpMode(mode: "all" | "one-at-a-time"): void;
118
+ getFollowUpMode(): "all" | "one-at-a-time";
119
+ setTools(t: AgentTool<any>[]): void;
120
+ replaceMessages(ms: AgentMessage[]): void;
121
+ appendMessage(m: AgentMessage): void;
122
+ /**
123
+ * Queue a steering message to interrupt the agent mid-run.
124
+ * Delivered after current tool execution, skips remaining tools.
125
+ */
126
+ steer(m: AgentMessage): void;
127
+ /**
128
+ * Queue a follow-up message to be processed after the agent finishes.
129
+ * Delivered only when agent has no more tool calls or steering messages.
130
+ */
131
+ followUp(m: AgentMessage): void;
132
+ clearSteeringQueue(): void;
133
+ clearFollowUpQueue(): void;
134
+ clearAllQueues(): void;
135
+ hasQueuedMessages(): boolean;
136
+ private dequeueSteeringMessages;
137
+ private dequeueFollowUpMessages;
138
+ clearMessages(): void;
139
+ abort(): void;
140
+ waitForIdle(): Promise<void>;
141
+ reset(): void;
142
+ /** Send a prompt with an AgentMessage */
143
+ prompt(message: AgentMessage | AgentMessage[]): Promise<void>;
144
+ prompt(input: string, images?: ImageContent[]): Promise<void>;
145
+ /**
146
+ * Continue from current context (used for retries and resuming queued messages).
147
+ */
148
+ continue(): Promise<void>;
149
+ private _runLoop;
150
+ private emit;
151
+ }
152
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +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,EAGV,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,MAAM,WAAW,CAAC;AAEnB,OAAO,KAAK,EAEX,UAAU,EAEV,YAAY,EACZ,UAAU,EACV,SAAS,EACT,QAAQ,EACR,aAAa,EACb,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,CAAC,QAAQ,EAAE,YAAY,EAAE,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC;IAE/F;;OAEG;IACH,YAAY,CAAC,EAAE,KAAK,GAAG,eAAe,CAAC;IAEvC;;OAEG;IACH,YAAY,CAAC,EAAE,KAAK,GAAG,eAAe,CAAC;IAEvC;;OAEG;IACH,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAEpB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,SAAS,CAAC,EAAE,CAAC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J;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;YAOa,QAAQ;IAqJtB,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\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@draht/ai\";\nimport { agentLoop, agentLoopContinue } from \"./agent-loop.js\";\nimport type {\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tStreamFn,\n\tThinkingLevel,\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 * 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\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 runningPrompt?: Promise<void>;\n\tprivate resolveRunningPrompt?: () => void;\n\tprivate _thinkingBudgets?: ThinkingBudgets;\n\tprivate _transport: Transport;\n\tprivate _maxRetryDelayMs?: number;\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._thinkingBudgets = opts.thinkingBudgets;\n\t\tthis._transport = opts.transport ?? \"sse\";\n\t\tthis._maxRetryDelayMs = opts.maxRetryDelayMs;\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 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 to interrupt the agent mid-run.\n\t * Delivered after current tool execution, skips remaining tools.\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\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\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\ttransport: this._transport,\n\t\t\tthinkingBudgets: this._thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this._maxRetryDelayMs,\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\tlet partial: AgentMessage | null = null;\n\n\t\ttry {\n\t\t\tconst stream = messages\n\t\t\t\t? agentLoop(messages, context, config, this.abortController.signal, this.streamFn)\n\t\t\t\t: agentLoopContinue(context, config, this.abortController.signal, this.streamFn);\n\n\t\t\tfor await (const event of stream) {\n\t\t\t\t// Update internal state based on events\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"message_start\":\n\t\t\t\t\t\tpartial = event.message;\n\t\t\t\t\t\tthis._state.streamMessage = event.message;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"message_update\":\n\t\t\t\t\t\tpartial = event.message;\n\t\t\t\t\t\tthis._state.streamMessage = event.message;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"message_end\":\n\t\t\t\t\t\tpartial = null;\n\t\t\t\t\t\tthis._state.streamMessage = null;\n\t\t\t\t\t\tthis.appendMessage(event.message);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"tool_execution_start\": {\n\t\t\t\t\t\tconst s = new Set(this._state.pendingToolCalls);\n\t\t\t\t\t\ts.add(event.toolCallId);\n\t\t\t\t\t\tthis._state.pendingToolCalls = s;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"tool_execution_end\": {\n\t\t\t\t\t\tconst s = new Set(this._state.pendingToolCalls);\n\t\t\t\t\t\ts.delete(event.toolCallId);\n\t\t\t\t\t\tthis._state.pendingToolCalls = s;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"turn_end\":\n\t\t\t\t\t\tif (event.message.role === \"assistant\" && (event.message as any).errorMessage) {\n\t\t\t\t\t\t\tthis._state.error = (event.message as any).errorMessage;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"agent_end\":\n\t\t\t\t\t\tthis._state.isStreaming = false;\n\t\t\t\t\t\tthis._state.streamMessage = null;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// Emit to listeners\n\t\t\t\tthis.emit(event);\n\t\t\t}\n\n\t\t\t// Handle any remaining partial message\n\t\t\tif (partial && partial.role === \"assistant\" && partial.content.length > 0) {\n\t\t\t\tconst onlyEmpty = !partial.content.some(\n\t\t\t\t\t(c) =>\n\t\t\t\t\t\t(c.type === \"thinking\" && c.thinking.trim().length > 0) ||\n\t\t\t\t\t\t(c.type === \"text\" && c.text.trim().length > 0) ||\n\t\t\t\t\t\t(c.type === \"toolCall\" && c.name.trim().length > 0),\n\t\t\t\t);\n\t\t\t\tif (!onlyEmpty) {\n\t\t\t\t\tthis.appendMessage(partial);\n\t\t\t\t} else {\n\t\t\t\t\tif (this.abortController?.signal.aborted) {\n\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t}\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;\n\t\t}\n\t}\n\n\tprivate emit(e: AgentEvent) {\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener(e);\n\t\t}\n\t}\n}\n"]}