agentblit 0.0.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/dist/index.js ADDED
@@ -0,0 +1,720 @@
1
+ // src/agent.ts
2
+ import OpenAI from "openai";
3
+ import { randomUUID as randomUUID2 } from "crypto";
4
+
5
+ // src/memory.ts
6
+ var ChatMemory = class {
7
+ messagesStore = [];
8
+ maxHistory;
9
+ summarizeFn;
10
+ constructor(options) {
11
+ const maxHistory = options?.maxHistory ?? 5;
12
+ if (maxHistory < 1) {
13
+ throw new Error("maxHistory must be at least 1");
14
+ }
15
+ this.maxHistory = maxHistory;
16
+ this.summarizeFn = options?.summarizeFn;
17
+ }
18
+ get messages() {
19
+ return [...this.messagesStore];
20
+ }
21
+ append(message) {
22
+ this.messagesStore.push(message);
23
+ }
24
+ extend(messages) {
25
+ this.messagesStore.push(...messages);
26
+ }
27
+ clear() {
28
+ this.messagesStore.length = 0;
29
+ }
30
+ async buildMessagesForLLM(systemPrompt) {
31
+ const out = [{ role: "system", content: systemPrompt }];
32
+ if (this.messagesStore.length <= this.maxHistory) {
33
+ out.push(...this.messagesStore);
34
+ return out;
35
+ }
36
+ const older = this.messagesStore.slice(0, -this.maxHistory);
37
+ const recent = this.messagesStore.slice(-this.maxHistory);
38
+ let summaryText;
39
+ if (!this.summarizeFn) {
40
+ summaryText = `[Earlier conversation truncated: ${older.length} message(s) not shown. Provide summarizeFn on Agent to compress older context with the LLM.]`;
41
+ } else {
42
+ summaryText = await this.summarizeFn(older);
43
+ }
44
+ out.push({
45
+ role: "system",
46
+ content: `Summary of earlier conversation:
47
+ ${summaryText}`
48
+ });
49
+ out.push(...recent);
50
+ return out;
51
+ }
52
+ };
53
+
54
+ // src/utils.ts
55
+ import process from "process";
56
+ import { randomUUID } from "crypto";
57
+ var LOGGER_PREFIX = "[agentblit]";
58
+ var DebugLogger = class {
59
+ constructor(enabled) {
60
+ this.enabled = enabled;
61
+ }
62
+ enabled;
63
+ log(message, ...args) {
64
+ if (!this.enabled) {
65
+ return;
66
+ }
67
+ console.debug(`${LOGGER_PREFIX} ${message}`, ...args);
68
+ }
69
+ logLLMRequest(model, messageCount, toolCount) {
70
+ this.log("LLM request model=%s messages=%s tools=%s", model, messageCount, toolCount);
71
+ }
72
+ logToolCalls(calls) {
73
+ this.log("Tool calls: %s", jsonDumpsSafe(calls));
74
+ }
75
+ logToolResult(toolCallId, ok, preview) {
76
+ this.log("Tool result id=%s ok=%s preview=%s", toolCallId, ok, preview.slice(0, 500));
77
+ }
78
+ };
79
+ function jsonDumpsSafe(obj) {
80
+ return JSON.stringify(obj, (_key, value) => {
81
+ if (value instanceof Error) {
82
+ return {
83
+ name: value.name,
84
+ message: value.message,
85
+ stack: value.stack
86
+ };
87
+ }
88
+ return value;
89
+ });
90
+ }
91
+ function extractParamNames(fn) {
92
+ const source = fn.toString();
93
+ const match = source.match(/\(([^)]*)\)/);
94
+ if (!match) {
95
+ return [];
96
+ }
97
+ const rawParams = match[1] ?? "";
98
+ return rawParams.split(",").map((segment) => segment.trim()).filter(Boolean).map((segment) => segment.replace(/=[\s\S]*$/, "").trim()).map((segment) => segment.replace(/^\.{3}/, "")).filter((segment) => segment !== "this");
99
+ }
100
+ function functionToToolSchema(fn, explicitSchema) {
101
+ if (explicitSchema) {
102
+ return explicitSchema;
103
+ }
104
+ const properties = Object.fromEntries(
105
+ extractParamNames(fn).map((name) => [name, { type: "string" }])
106
+ );
107
+ const required = Object.keys(properties);
108
+ return {
109
+ type: "object",
110
+ properties,
111
+ ...required.length > 0 ? { required } : {}
112
+ };
113
+ }
114
+ var TOOL_META = /* @__PURE__ */ Symbol.for("agentblit.tool.meta");
115
+ function setToolMetadata(fn, options) {
116
+ const metadata = {
117
+ name: options.name ?? fn.name,
118
+ description: options.description ?? "",
119
+ permissionMode: options.permissionMode ?? "always_allow",
120
+ inputSchema: options.inputSchema
121
+ };
122
+ fn[TOOL_META] = metadata;
123
+ return fn;
124
+ }
125
+ function getToolMetadata(fn) {
126
+ return fn[TOOL_META];
127
+ }
128
+ function nowIsoTimestamp() {
129
+ return (/* @__PURE__ */ new Date()).toISOString();
130
+ }
131
+ function randomId(prefix) {
132
+ return `${prefix}_${randomUUID().replace(/-/g, "")}`;
133
+ }
134
+ function readStdinLine(promptText) {
135
+ return new Promise((resolve) => {
136
+ process.stdout.write(promptText);
137
+ process.stdin.resume();
138
+ process.stdin.once("data", (chunk) => {
139
+ resolve(String(chunk).trim());
140
+ });
141
+ });
142
+ }
143
+
144
+ // src/tools.ts
145
+ function tool(arg1, arg2) {
146
+ if (typeof arg1 === "function") {
147
+ return setToolMetadata(arg1, arg2 ?? {});
148
+ }
149
+ return (fn) => setToolMetadata(fn, arg1);
150
+ }
151
+ var ToolRegistry = class {
152
+ baseUrl;
153
+ apiKey;
154
+ timeout;
155
+ remote = /* @__PURE__ */ new Map();
156
+ custom = /* @__PURE__ */ new Map();
157
+ constructor(options) {
158
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
159
+ this.apiKey = options.apiKey;
160
+ this.timeout = options.timeout ?? 3e4;
161
+ }
162
+ register(fn) {
163
+ const metadata = getToolMetadata(fn);
164
+ const name = metadata?.name ?? fn.name;
165
+ const description = metadata?.description ?? "";
166
+ const permissionMode = metadata?.permissionMode ?? "always_allow";
167
+ const inputSchema = functionToToolSchema(fn, metadata?.inputSchema);
168
+ this.custom.set(name, {
169
+ name,
170
+ description,
171
+ inputSchema,
172
+ permissionMode,
173
+ handler: fn
174
+ });
175
+ }
176
+ async refreshRemote() {
177
+ const url = `${this.baseUrl}/api/tools/list`;
178
+ const response = await fetch(url, {
179
+ method: "GET",
180
+ headers: { "X-API-Key": this.apiKey },
181
+ signal: AbortSignal.timeout(this.timeout)
182
+ });
183
+ if (!response.ok) {
184
+ throw new Error(
185
+ `AgentBlit request failed for GET '${url}': ${response.status} ${response.statusText}`
186
+ );
187
+ }
188
+ const data = await response.json();
189
+ if (!data.ok) {
190
+ throw new Error("tools/list returned ok=false");
191
+ }
192
+ this.remote.clear();
193
+ for (const toolItem of data.tools ?? []) {
194
+ const name = String(toolItem.name ?? "");
195
+ if (!name) {
196
+ continue;
197
+ }
198
+ this.remote.set(name, {
199
+ name,
200
+ description: String(toolItem.description ?? ""),
201
+ inputSchema: toolItem.inputSchema ?? {
202
+ type: "object",
203
+ properties: {}
204
+ },
205
+ permissionMode: String(toolItem.permissionMode ?? "always_allow") === "needs_approval" ? "needs_approval" : "always_allow",
206
+ outputSchema: toolItem.outputSchema
207
+ });
208
+ }
209
+ }
210
+ merged() {
211
+ const merged = new Map(this.remote);
212
+ for (const [name, def] of this.custom.entries()) {
213
+ merged.set(name, def);
214
+ }
215
+ return merged;
216
+ }
217
+ getDefinition(name) {
218
+ return this.merged().get(name);
219
+ }
220
+ toOpenAITools() {
221
+ return [...this.merged().values()].map((definition) => ({
222
+ type: "function",
223
+ function: {
224
+ name: definition.name,
225
+ description: definition.description,
226
+ parameters: definition.inputSchema
227
+ }
228
+ }));
229
+ }
230
+ async ensureApproval(definition, toolName, args, approvalCallback) {
231
+ if (definition.permissionMode !== "needs_approval") {
232
+ return true;
233
+ }
234
+ if (approvalCallback) {
235
+ return approvalCallback(toolName, args);
236
+ }
237
+ const answer = await readStdinLine(
238
+ `Approve tool "${toolName}" with args ${jsonDumpsSafe(args)}? [y/N]: `
239
+ );
240
+ return ["y", "yes"].includes(answer.toLowerCase());
241
+ }
242
+ async execute(toolCallId, toolName, argumentsJson, approvalCallback) {
243
+ const definition = this.getDefinition(toolName);
244
+ if (!definition) {
245
+ return jsonDumpsSafe({ error: `Unknown tool: ${toolName}` });
246
+ }
247
+ let args;
248
+ try {
249
+ args = argumentsJson ? JSON.parse(argumentsJson) : {};
250
+ } catch (error) {
251
+ return jsonDumpsSafe({ error: `Invalid JSON arguments: ${String(error)}` });
252
+ }
253
+ if (!await this.ensureApproval(definition, toolName, args, approvalCallback)) {
254
+ return jsonDumpsSafe({ error: "User denied approval for this tool call." });
255
+ }
256
+ if (definition.handler) {
257
+ try {
258
+ let result2;
259
+ try {
260
+ result2 = await definition.handler(...Object.values(args));
261
+ } catch {
262
+ result2 = await definition.handler(args);
263
+ }
264
+ return jsonDumpsSafe(result2);
265
+ } catch (error) {
266
+ return jsonDumpsSafe({ error: error instanceof Error ? error.message : String(error) });
267
+ }
268
+ }
269
+ const payload = {
270
+ tool_calls: [
271
+ {
272
+ id: toolCallId,
273
+ type: "function",
274
+ function: {
275
+ name: toolName,
276
+ arguments: jsonDumpsSafe(args)
277
+ }
278
+ }
279
+ ]
280
+ };
281
+ const url = `${this.baseUrl}/api/tools/call`;
282
+ const response = await fetch(url, {
283
+ method: "POST",
284
+ headers: {
285
+ "X-API-Key": this.apiKey,
286
+ "Content-Type": "application/json"
287
+ },
288
+ body: jsonDumpsSafe(payload),
289
+ signal: AbortSignal.timeout(this.timeout)
290
+ });
291
+ if (!response.ok) {
292
+ throw new Error(
293
+ `AgentBlit request failed for POST '${url}': ${response.status} ${response.statusText}`
294
+ );
295
+ }
296
+ const data = await response.json();
297
+ if (!data.ok) {
298
+ return jsonDumpsSafe({ error: data });
299
+ }
300
+ const result = (data.results ?? []).find((item) => item.tool_call_id === toolCallId);
301
+ if (!result) {
302
+ return jsonDumpsSafe({ error: "No result for tool_call_id" });
303
+ }
304
+ const toolResult = result.result;
305
+ if (!toolResult) {
306
+ return jsonDumpsSafe({ error: "Missing tool result payload" });
307
+ }
308
+ if (toolResult.isError) {
309
+ const text2 = (toolResult.content ?? []).map((part) => part.text ?? "").join("");
310
+ return jsonDumpsSafe({ error: text2 || "Tool error" });
311
+ }
312
+ if (typeof toolResult.structuredContent !== "undefined") {
313
+ return jsonDumpsSafe(toolResult.structuredContent);
314
+ }
315
+ const text = (toolResult.content ?? []).map((part) => part.text ?? "").join("");
316
+ return jsonDumpsSafe({ result: text });
317
+ }
318
+ };
319
+
320
+ // src/agent.ts
321
+ var VENDOR_BASE_URLS = {
322
+ openai: "https://api.openai.com/v1",
323
+ anthropic: "https://api.anthropic.com/v1",
324
+ gemini: "https://generativelanguage.googleapis.com/v1beta/openai",
325
+ openrouter: "https://openrouter.ai/api/v1"
326
+ };
327
+ var DEFAULT_TOOL_USAGE_INSTRUCTION = "Use tools when they help answer accurately.";
328
+ function resolveVendorAndModel(modelInput) {
329
+ const model = modelInput.trim();
330
+ if (!model || !model.includes("/")) {
331
+ throw new Error(
332
+ "model must be in the format 'vendor/model', for example 'openai/gpt-4o-mini'."
333
+ );
334
+ }
335
+ const [vendorRaw, ...rest] = model.split("/");
336
+ const vendor = (vendorRaw ?? "").trim().toLowerCase();
337
+ const providerModel = rest.join("/").trim();
338
+ if (!vendor || !providerModel) {
339
+ throw new Error(
340
+ "model must be in the format 'vendor/model', for example 'openai/gpt-4o-mini'."
341
+ );
342
+ }
343
+ return { vendor, model: providerModel };
344
+ }
345
+ function resolveLlmUrl(vendor) {
346
+ const url = VENDOR_BASE_URLS[vendor];
347
+ if (!url) {
348
+ const supported = Object.keys(VENDOR_BASE_URLS).sort().join(", ");
349
+ throw new Error(`Unsupported model vendor '${vendor}'. Supported vendors: ${supported}.`);
350
+ }
351
+ return url;
352
+ }
353
+ function composeSystemPrompt(systemPrompt) {
354
+ const userPrompt = systemPrompt.trim();
355
+ if (userPrompt.toLowerCase().includes(DEFAULT_TOOL_USAGE_INSTRUCTION.toLowerCase())) {
356
+ return userPrompt;
357
+ }
358
+ if (!userPrompt) {
359
+ return DEFAULT_TOOL_USAGE_INSTRUCTION;
360
+ }
361
+ return `${userPrompt}
362
+
363
+ ${DEFAULT_TOOL_USAGE_INSTRUCTION}`;
364
+ }
365
+ function formatMessagesForSummary(messages) {
366
+ return messages.map((message, index) => {
367
+ if (message.role === "assistant" && message.tool_calls) {
368
+ return `[${index}] assistant (tool_calls): ${jsonDumpsSafe(message.tool_calls)}`;
369
+ }
370
+ return `[${index}] ${message.role}: ${message.content ?? ""}`;
371
+ }).join("\n");
372
+ }
373
+ var Agent = class {
374
+ vendor;
375
+ model;
376
+ llmUrl;
377
+ agentId;
378
+ sessionId;
379
+ config;
380
+ memory;
381
+ client;
382
+ tools;
383
+ systemPrompt;
384
+ timeout;
385
+ debug;
386
+ approvalCallback;
387
+ maxToolRounds;
388
+ eventBaseUrl;
389
+ eventApiKey;
390
+ pendingCustomEvents = [];
391
+ agentInitSent = false;
392
+ toolsSignature;
393
+ constructor(options) {
394
+ const agentblitApiKey = options.agentblitApiKey.trim();
395
+ if (!agentblitApiKey) {
396
+ throw new Error("agentblitApiKey is required");
397
+ }
398
+ const maxHistory = options.maxHistory ?? 5;
399
+ if (maxHistory < 1) {
400
+ throw new Error("maxHistory must be at least 1");
401
+ }
402
+ const maxToolRounds = options.maxToolRounds ?? 25;
403
+ if (maxToolRounds < 1) {
404
+ throw new Error("maxToolRounds must be at least 1");
405
+ }
406
+ const { vendor, model } = resolveVendorAndModel(options.model);
407
+ const llmUrl = resolveLlmUrl(vendor);
408
+ const timeoutSeconds = options.timeout ?? 30;
409
+ const timeoutMs = timeoutSeconds * 1e3;
410
+ const agentblitUrl = (options.agentblitUrl ?? "https://console.agentblit.com").replace(/\/$/, "");
411
+ const systemPrompt = composeSystemPrompt(options.systemPrompt ?? "");
412
+ this.vendor = vendor;
413
+ this.model = model;
414
+ this.llmUrl = llmUrl;
415
+ this.systemPrompt = systemPrompt;
416
+ this.timeout = timeoutMs;
417
+ this.approvalCallback = options.approvalCallback;
418
+ this.maxToolRounds = maxToolRounds;
419
+ this.agentId = randomUUID2();
420
+ this.sessionId = randomUUID2();
421
+ this.eventBaseUrl = agentblitUrl;
422
+ this.eventApiKey = agentblitApiKey;
423
+ this.debug = new DebugLogger(Boolean(options.debug));
424
+ this.client = new OpenAI({
425
+ apiKey: options.apiKey,
426
+ baseURL: llmUrl,
427
+ timeout: timeoutMs
428
+ });
429
+ this.tools = new ToolRegistry({
430
+ baseUrl: agentblitUrl,
431
+ apiKey: agentblitApiKey,
432
+ timeout: timeoutMs
433
+ });
434
+ for (const customTool of options.customTools ?? []) {
435
+ this.registerTool(customTool);
436
+ }
437
+ this.memory = new ChatMemory({
438
+ maxHistory,
439
+ summarizeFn: (older) => this.summarizeOlderMessages(older)
440
+ });
441
+ this.config = Object.freeze({
442
+ model: this.model,
443
+ vendor: this.vendor,
444
+ llmUrl: this.llmUrl,
445
+ agentblitUrl: this.eventBaseUrl,
446
+ systemPrompt: this.systemPrompt,
447
+ maxHistory,
448
+ debug: Boolean(options.debug),
449
+ timeout: timeoutSeconds,
450
+ agentId: this.agentId,
451
+ sessionId: this.sessionId
452
+ });
453
+ }
454
+ registerTool(fn) {
455
+ this.tools.register(fn);
456
+ }
457
+ track(eventType, properties) {
458
+ this.pendingCustomEvents.push(this.makeEvent({ eventType, data: properties }));
459
+ }
460
+ makeEvent(input) {
461
+ return {
462
+ id: randomId("evt"),
463
+ session_id: this.sessionId,
464
+ agent_id: this.agentId,
465
+ timestamp: nowIsoTimestamp(),
466
+ type: input.eventType,
467
+ data: input.data,
468
+ tokens: Math.max(0, Math.trunc(input.tokens ?? 0)),
469
+ latency_ms: Math.max(0, Math.trunc(input.latencyMs ?? 0))
470
+ };
471
+ }
472
+ async flushEvents(events) {
473
+ if (events.length === 0) {
474
+ return;
475
+ }
476
+ const url = `${this.eventBaseUrl}/api/events/batch`;
477
+ this.debug.log("Event batch send start url=%s count=%s", url, events.length);
478
+ try {
479
+ const response = await fetch(url, {
480
+ method: "POST",
481
+ headers: {
482
+ "X-API-Key": this.eventApiKey,
483
+ "Content-Type": "application/json"
484
+ },
485
+ body: jsonDumpsSafe({ events }),
486
+ signal: AbortSignal.timeout(this.timeout)
487
+ });
488
+ if (!response.ok) {
489
+ const body = (await response.text()).slice(0, 1e3);
490
+ this.debug.log(
491
+ "Failed to send events batch status=%s body=%s",
492
+ response.status,
493
+ body
494
+ );
495
+ return;
496
+ }
497
+ this.debug.log("Event batch send success status=%s count=%s", response.status, events.length);
498
+ } catch (error) {
499
+ this.debug.log("Failed to send events batch: %s", String(error));
500
+ }
501
+ }
502
+ extractLlmEventMessages(messages) {
503
+ if (messages.length === 0) {
504
+ return [];
505
+ }
506
+ const summaryMessage = messages.find(
507
+ (message) => message.role === "system" && typeof message.content === "string" && message.content.startsWith("Summary of earlier conversation:")
508
+ );
509
+ const lastMessage = messages[messages.length - 1];
510
+ if (!lastMessage) {
511
+ return [];
512
+ }
513
+ if (!summaryMessage) {
514
+ return [lastMessage];
515
+ }
516
+ if (summaryMessage === lastMessage) {
517
+ return [summaryMessage];
518
+ }
519
+ return [summaryMessage, lastMessage];
520
+ }
521
+ async summarizeOlderMessages(older) {
522
+ const text = formatMessagesForSummary(older);
523
+ this.debug.log("Summarizing %s older messages", older.length);
524
+ const response = await this.client.chat.completions.create({
525
+ model: this.model,
526
+ messages: [
527
+ {
528
+ role: "system",
529
+ content: "Summarize the conversation excerpt below for use as memory. Preserve key facts, decisions, and tool outcomes. Be concise."
530
+ },
531
+ { role: "user", content: text }
532
+ ],
533
+ temperature: 0.2
534
+ });
535
+ return response.choices[0]?.message?.content?.trim() ?? "";
536
+ }
537
+ async *run(userMessage) {
538
+ const events = [...this.pendingCustomEvents];
539
+ this.pendingCustomEvents.length = 0;
540
+ try {
541
+ this.memory.append({ role: "user", content: userMessage });
542
+ await this.tools.refreshRemote();
543
+ const openaiTools = this.tools.toOpenAITools();
544
+ const toolsSignature = jsonDumpsSafe(openaiTools);
545
+ if (!this.agentInitSent) {
546
+ events.push(
547
+ this.makeEvent({
548
+ eventType: "agent_init",
549
+ data: { system_prompt: this.systemPrompt, tools: openaiTools }
550
+ })
551
+ );
552
+ this.agentInitSent = true;
553
+ this.toolsSignature = toolsSignature;
554
+ } else if (toolsSignature !== this.toolsSignature) {
555
+ events.push(this.makeEvent({ eventType: "tools_updated", data: { tools: openaiTools } }));
556
+ this.toolsSignature = toolsSignature;
557
+ }
558
+ events.push(
559
+ this.makeEvent({
560
+ eventType: "user_prompt",
561
+ data: { request: { message: userMessage }, response: null }
562
+ })
563
+ );
564
+ let finishedNormally = false;
565
+ for (let round = 0; round < this.maxToolRounds; round += 1) {
566
+ const messages = await this.memory.buildMessagesForLLM(this.systemPrompt);
567
+ this.debug.logLLMRequest(this.model, messages.length, openaiTools.length);
568
+ const llmRequest = {
569
+ model: this.model,
570
+ messages,
571
+ stream: true,
572
+ ...openaiTools.length > 0 ? { tools: openaiTools } : {},
573
+ ...this.vendor === "openai" || this.vendor === "openrouter" ? { stream_options: { include_usage: true } } : {}
574
+ };
575
+ const llmEventRequestData = {
576
+ model: this.model,
577
+ messages: this.extractLlmEventMessages(messages),
578
+ stream: true
579
+ };
580
+ const startedAt = Date.now();
581
+ const stream = await this.client.chat.completions.create(
582
+ llmRequest
583
+ );
584
+ const contentParts = [];
585
+ const toolCallsMap = /* @__PURE__ */ new Map();
586
+ let finishReason = null;
587
+ let llmTotalTokens = 0;
588
+ for await (const chunk of stream) {
589
+ if (chunk.usage?.total_tokens) {
590
+ llmTotalTokens = chunk.usage.total_tokens;
591
+ }
592
+ const choice = chunk.choices?.[0];
593
+ if (!choice) {
594
+ continue;
595
+ }
596
+ if (choice.finish_reason) {
597
+ finishReason = choice.finish_reason;
598
+ }
599
+ const delta = choice.delta;
600
+ if (!delta) {
601
+ continue;
602
+ }
603
+ if (delta.content) {
604
+ contentParts.push(delta.content);
605
+ yield delta.content;
606
+ }
607
+ for (const toolCall of delta.tool_calls ?? []) {
608
+ const index = toolCall.index ?? 0;
609
+ const existing = toolCallsMap.get(index) ?? { id: "", name: "", arguments: "" };
610
+ if (toolCall.id) {
611
+ existing.id = toolCall.id;
612
+ }
613
+ if (toolCall.function?.name) {
614
+ existing.name = toolCall.function.name;
615
+ }
616
+ if (toolCall.function?.arguments) {
617
+ existing.arguments += toolCall.function.arguments;
618
+ }
619
+ toolCallsMap.set(index, existing);
620
+ }
621
+ }
622
+ const assistantContent = contentParts.join("") || null;
623
+ const llmLatencyMs = Date.now() - startedAt;
624
+ const toolCalls = [...toolCallsMap.entries()].sort(([a], [b]) => a - b).map(([, call]) => ({
625
+ id: call.id,
626
+ type: "function",
627
+ function: {
628
+ name: call.name,
629
+ arguments: call.arguments || "{}"
630
+ }
631
+ }));
632
+ events.push(
633
+ this.makeEvent({
634
+ eventType: "llm_call",
635
+ data: {
636
+ request: llmEventRequestData,
637
+ response: {
638
+ finish_reason: finishReason,
639
+ content: assistantContent,
640
+ tool_calls: toolCalls
641
+ }
642
+ },
643
+ tokens: llmTotalTokens,
644
+ latencyMs: llmLatencyMs
645
+ })
646
+ );
647
+ if (finishReason === "tool_calls" || toolCalls.length > 0) {
648
+ this.debug.logToolCalls(toolCalls);
649
+ this.memory.append({
650
+ role: "assistant",
651
+ content: assistantContent,
652
+ tool_calls: toolCalls
653
+ });
654
+ for (const toolCall of toolCalls) {
655
+ const toolStartedAt = Date.now();
656
+ const result = await this.tools.execute(
657
+ toolCall.id,
658
+ toolCall.function.name,
659
+ toolCall.function.arguments,
660
+ this.approvalCallback
661
+ );
662
+ const toolLatencyMs = Date.now() - toolStartedAt;
663
+ this.debug.logToolResult(toolCall.id, true, result);
664
+ let parsedResponse;
665
+ try {
666
+ parsedResponse = JSON.parse(result);
667
+ } catch {
668
+ parsedResponse = { raw: result };
669
+ }
670
+ events.push(
671
+ this.makeEvent({
672
+ eventType: "tool_call",
673
+ data: {
674
+ request: toolCall,
675
+ response: parsedResponse
676
+ },
677
+ latencyMs: toolLatencyMs
678
+ })
679
+ );
680
+ this.memory.append({
681
+ role: "tool",
682
+ tool_call_id: toolCall.id,
683
+ content: result
684
+ });
685
+ }
686
+ continue;
687
+ }
688
+ this.memory.append({
689
+ role: "assistant",
690
+ content: assistantContent ?? ""
691
+ });
692
+ finishedNormally = true;
693
+ break;
694
+ }
695
+ if (!finishedNormally) {
696
+ throw new Error(
697
+ `Exceeded maxToolRounds (${this.maxToolRounds}); increase maxToolRounds or simplify the task.`
698
+ );
699
+ }
700
+ } catch (error) {
701
+ events.push(
702
+ this.makeEvent({
703
+ eventType: "agent_loop_error",
704
+ data: { error: error instanceof Error ? error.message : String(error) }
705
+ })
706
+ );
707
+ throw error;
708
+ } finally {
709
+ this.debug.log("Queueing event flush count=%s", events.length);
710
+ await this.flushEvents(events);
711
+ }
712
+ }
713
+ };
714
+ export {
715
+ Agent,
716
+ ChatMemory,
717
+ ToolRegistry,
718
+ tool
719
+ };
720
+ //# sourceMappingURL=index.js.map