@anvia/core 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/agent/index.d.ts +4 -4
  2. package/dist/agent/index.js +6 -5
  3. package/dist/{agent-0UeJ9Rad.d.ts → agent-B-ls5y_g.d.ts} +2 -15
  4. package/dist/{chunk-I2HOMD3R.js → chunk-35GF7P43.js} +3 -3
  5. package/dist/{chunk-TILE6Z2N.js → chunk-DUP7FMAF.js} +2 -2
  6. package/dist/{chunk-A7VDIZQN.js → chunk-EFGX3EX5.js} +5 -14
  7. package/dist/chunk-EFGX3EX5.js.map +1 -0
  8. package/dist/{chunk-PP4VIN3Y.js → chunk-LGETU3RG.js} +3 -3
  9. package/dist/{chunk-6U6PZ5MD.js → chunk-MOICCK3J.js} +6 -15
  10. package/dist/chunk-MOICCK3J.js.map +1 -0
  11. package/dist/{chunk-TP32W7XT.js → chunk-N7NMSGZI.js} +597 -555
  12. package/dist/chunk-N7NMSGZI.js.map +1 -0
  13. package/dist/chunk-OIMLU4SF.js +20 -0
  14. package/dist/chunk-OIMLU4SF.js.map +1 -0
  15. package/dist/{chunk-65QV627O.js → chunk-P425B6GR.js} +31 -2
  16. package/dist/chunk-P425B6GR.js.map +1 -0
  17. package/dist/embeddings/index.d.ts +4 -24
  18. package/dist/embeddings/index.js +2 -1
  19. package/dist/evals/index.d.ts +23 -19
  20. package/dist/evals/index.js +92 -90
  21. package/dist/evals/index.js.map +1 -1
  22. package/dist/extractor/index.d.ts +3 -3
  23. package/dist/extractor/index.js +7 -6
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +7 -6
  26. package/dist/internal/agent.d.ts +3 -3
  27. package/dist/internal/agent.js +5 -4
  28. package/dist/loaders/index.d.ts +20 -12
  29. package/dist/loaders/index.js +107 -96
  30. package/dist/loaders/index.js.map +1 -1
  31. package/dist/mcp/index.js +10 -1
  32. package/dist/mcp/index.js.map +1 -1
  33. package/dist/{middleware-BQ7fkEEe.d.ts → middleware-CGiEIaBx.d.ts} +1 -1
  34. package/dist/pipeline/index.d.ts +5 -3
  35. package/dist/pipeline/index.js +156 -160
  36. package/dist/pipeline/index.js.map +1 -1
  37. package/dist/skills/index.js +5 -4
  38. package/dist/tool/index.d.ts +2 -2
  39. package/dist/tool/index.js +4 -3
  40. package/dist/types-IB2e9u5M.d.ts +25 -0
  41. package/dist/vector-store/index.d.ts +4 -1
  42. package/dist/vector-store/index.js +3 -2
  43. package/package.json +1 -1
  44. package/dist/chunk-65QV627O.js.map +0 -1
  45. package/dist/chunk-6U6PZ5MD.js.map +0 -1
  46. package/dist/chunk-A7VDIZQN.js.map +0 -1
  47. package/dist/chunk-TP32W7XT.js.map +0 -1
  48. /package/dist/{chunk-I2HOMD3R.js.map → chunk-35GF7P43.js.map} +0 -0
  49. /package/dist/{chunk-TILE6Z2N.js.map → chunk-DUP7FMAF.js.map} +0 -0
  50. /package/dist/{chunk-PP4VIN3Y.js.map → chunk-LGETU3RG.js.map} +0 -0
@@ -7,10 +7,10 @@ import {
7
7
  import {
8
8
  ToolSet,
9
9
  toolResultContentToText
10
- } from "./chunk-I2HOMD3R.js";
10
+ } from "./chunk-35GF7P43.js";
11
11
  import {
12
12
  createTool
13
- } from "./chunk-65QV627O.js";
13
+ } from "./chunk-P425B6GR.js";
14
14
  import {
15
15
  CompletionRequestBuilder,
16
16
  Message,
@@ -19,6 +19,9 @@ import {
19
19
  assertCompletionRequestSupported,
20
20
  textFromAssistantContent
21
21
  } from "./chunk-6GJDBBDC.js";
22
+ import {
23
+ mapWithConcurrency
24
+ } from "./chunk-OIMLU4SF.js";
22
25
 
23
26
  // src/agent/errors.ts
24
27
  var MaxTurnsError = class extends Error {
@@ -87,6 +90,86 @@ var toolCallControl = {
87
90
  // src/agent/agent.ts
88
91
  import { z } from "zod";
89
92
 
93
+ // src/agent/ids.ts
94
+ function normalizeAgentId(id) {
95
+ if (typeof id !== "string") {
96
+ throw new TypeError("Agent id must be a string.");
97
+ }
98
+ const normalized = id.trim();
99
+ if (normalized.length === 0) {
100
+ throw new TypeError("Agent id must be a non-empty string.");
101
+ }
102
+ return normalized;
103
+ }
104
+
105
+ // src/internal/async-queue.ts
106
+ function createAsyncQueue() {
107
+ const values = [];
108
+ const waiters = [];
109
+ let closed = false;
110
+ let error;
111
+ function flush() {
112
+ while (waiters.length > 0 && values.length > 0) {
113
+ const waiter = waiters.shift();
114
+ const value = values.shift();
115
+ if (waiter !== void 0) {
116
+ waiter.resolve({ value, done: false });
117
+ }
118
+ }
119
+ if (values.length > 0 || waiters.length === 0 || !closed) {
120
+ return;
121
+ }
122
+ while (waiters.length > 0) {
123
+ const waiter = waiters.shift();
124
+ if (waiter === void 0) {
125
+ continue;
126
+ }
127
+ if (error !== void 0) {
128
+ waiter.reject(error);
129
+ } else {
130
+ waiter.resolve({ value: void 0, done: true });
131
+ }
132
+ }
133
+ }
134
+ return {
135
+ enqueue(value) {
136
+ if (closed) {
137
+ return;
138
+ }
139
+ values.push(value);
140
+ flush();
141
+ },
142
+ close() {
143
+ closed = true;
144
+ flush();
145
+ },
146
+ throw(thrown) {
147
+ closed = true;
148
+ error = thrown;
149
+ flush();
150
+ },
151
+ [Symbol.asyncIterator]() {
152
+ return {
153
+ next() {
154
+ if (values.length > 0) {
155
+ const value = values.shift();
156
+ return Promise.resolve({ value, done: false });
157
+ }
158
+ if (error !== void 0) {
159
+ return Promise.reject(error);
160
+ }
161
+ if (closed) {
162
+ return Promise.resolve({ value: void 0, done: true });
163
+ }
164
+ return new Promise((resolve, reject) => {
165
+ waiters.push({ resolve, reject });
166
+ });
167
+ }
168
+ };
169
+ }
170
+ };
171
+ }
172
+
90
173
  // src/observability/group.ts
91
174
  async function startAgentRunObservers(registrations, args, failOnObserverError) {
92
175
  const runObservers = [];
@@ -255,6 +338,158 @@ var ActiveToolObservers = class {
255
338
  }
256
339
  };
257
340
 
341
+ // src/agent/request-memory.ts
342
+ var PromptRequestMemory = class {
343
+ constructor(agent, memoryContext, initialHistory) {
344
+ this.agent = agent;
345
+ this.memoryContext = memoryContext;
346
+ this.initialHistory = initialHistory;
347
+ }
348
+ agent;
349
+ memoryContext;
350
+ initialHistory;
351
+ memoryPolicy() {
352
+ return this.memory()?.options.savePolicy;
353
+ }
354
+ pendingTurnMessages(newMessages) {
355
+ return this.memoryPolicy() === "turn" ? [...newMessages] : [];
356
+ }
357
+ async prepareRun(runId, newMessages) {
358
+ const memory = this.memory();
359
+ if (memory === void 0 || this.memoryContext === void 0) {
360
+ return this.initialHistory;
361
+ }
362
+ const memoryHistory = await memory.store.load(this.memoryContext);
363
+ const chatHistory = [...memoryHistory, ...this.initialHistory];
364
+ if (memory.options.savePolicy === "message") {
365
+ await memory.store.append({
366
+ context: this.memoryContext,
367
+ runId,
368
+ turn: 1,
369
+ messages: newMessages
370
+ });
371
+ }
372
+ return chatHistory;
373
+ }
374
+ async commitMessages(runId, turn, messages, pendingTurnMessages) {
375
+ const memory = this.memory();
376
+ if (memory === void 0 || this.memoryContext === void 0 || messages.length === 0) {
377
+ return;
378
+ }
379
+ if (memory.options.savePolicy === "message") {
380
+ await memory.store.append({
381
+ context: this.memoryContext,
382
+ runId,
383
+ turn,
384
+ messages
385
+ });
386
+ } else if (memory.options.savePolicy === "turn") {
387
+ pendingTurnMessages.push(...messages);
388
+ }
389
+ }
390
+ async commitCompletedTurn(runId, turn, pendingTurnMessages) {
391
+ const memory = this.memory();
392
+ if (memory === void 0 || this.memoryContext === void 0 || memory.options.savePolicy !== "turn" || pendingTurnMessages.length === 0) {
393
+ return;
394
+ }
395
+ await memory.store.append({
396
+ context: this.memoryContext,
397
+ runId,
398
+ turn,
399
+ messages: [...pendingTurnMessages]
400
+ });
401
+ pendingTurnMessages.length = 0;
402
+ }
403
+ async commitCompletedRun(runId, turn, newMessages, pendingTurnMessages) {
404
+ await this.commitCompletedTurn(runId, turn, pendingTurnMessages);
405
+ const memory = this.memory();
406
+ if (memory === void 0 || this.memoryContext === void 0 || memory.options.savePolicy !== "run") {
407
+ return;
408
+ }
409
+ await memory.store.append({
410
+ context: this.memoryContext,
411
+ runId,
412
+ turn,
413
+ messages: [...newMessages]
414
+ });
415
+ }
416
+ async recordError(runId, error, newMessages) {
417
+ const memory = this.memory();
418
+ if (memory === void 0 || this.memoryContext === void 0) {
419
+ return;
420
+ }
421
+ await memory.store.recordError?.({
422
+ context: this.memoryContext,
423
+ runId,
424
+ error,
425
+ messages: [...newMessages]
426
+ });
427
+ }
428
+ memory() {
429
+ return this.memoryContext === void 0 ? void 0 : this.agent.memory;
430
+ }
431
+ };
432
+
433
+ // src/agent/retrieval.ts
434
+ async function fetchDynamicContext(agent, ragText) {
435
+ if (ragText === void 0 || ragText.length === 0 || agent.dynamicContexts.length === 0) {
436
+ return [];
437
+ }
438
+ const documents = [];
439
+ for (const registration of agent.dynamicContexts) {
440
+ const results = await registration.index.search({
441
+ query: ragText,
442
+ topK: registration.options.topK,
443
+ threshold: registration.options.threshold,
444
+ filter: registration.options.filter
445
+ });
446
+ for (const result of results) {
447
+ const formatted = registration.options.format?.(result);
448
+ if (formatted !== void 0) {
449
+ documents.push(formatted);
450
+ } else {
451
+ const metadata = formatMetadata(result.metadata);
452
+ documents.push({
453
+ id: result.id,
454
+ text: typeof result.document === "string" ? result.document : JSON.stringify(result.document, null, 2),
455
+ ...metadata === void 0 ? {} : { additionalProps: metadata }
456
+ });
457
+ }
458
+ }
459
+ }
460
+ return documents;
461
+ }
462
+ async function fetchToolDefinitions(agent, ragText) {
463
+ const staticDefinitions = await agent.toolSet.getToolDefinitions(ragText);
464
+ if (ragText === void 0 || ragText.length === 0 || agent.dynamicTools.length === 0) {
465
+ return staticDefinitions;
466
+ }
467
+ const definitions = [...staticDefinitions];
468
+ const names = new Set(staticDefinitions.map((definition) => definition.name));
469
+ for (const registration of agent.dynamicTools) {
470
+ const results = await registration.index.search({
471
+ query: ragText,
472
+ topK: registration.options.topK,
473
+ threshold: registration.options.threshold,
474
+ filter: registration.options.filter
475
+ });
476
+ for (const result of results) {
477
+ if (names.has(result.document.toolName)) {
478
+ continue;
479
+ }
480
+ names.add(result.document.toolName);
481
+ definitions.push(result.document.definition);
482
+ }
483
+ }
484
+ return definitions;
485
+ }
486
+ function formatMetadata(metadata) {
487
+ if (metadata === void 0) {
488
+ return void 0;
489
+ }
490
+ return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, String(value)]));
491
+ }
492
+
258
493
  // src/agent/utils.ts
259
494
  function isStreamingCompletionModel(model) {
260
495
  return "streamCompletion" in model && typeof model.streamCompletion === "function";
@@ -278,23 +513,6 @@ function parseJsonValue(text) {
278
513
  return text;
279
514
  }
280
515
  }
281
- async function mapWithConcurrency(items, concurrency, mapper) {
282
- const results = [];
283
- let next = 0;
284
- async function worker() {
285
- while (next < items.length) {
286
- const index = next;
287
- next += 1;
288
- const item = items[index];
289
- if (item !== void 0) {
290
- results[index] = await mapper(item);
291
- }
292
- }
293
- }
294
- const workerCount = Math.min(concurrency, items.length);
295
- await Promise.all(Array.from({ length: workerCount }, () => worker()));
296
- return results;
297
- }
298
516
 
299
517
  // src/agent/stream-accumulator.ts
300
518
  var CompletionStreamAccumulator = class _CompletionStreamAccumulator {
@@ -524,95 +742,300 @@ function isEmptyToolArguments(value) {
524
742
  return false;
525
743
  }
526
744
 
527
- // src/agent/request.ts
745
+ // src/agent/tool-execution.ts
528
746
  var MCP_TOOL_METADATA_KEY = /* @__PURE__ */ Symbol.for("anvia.mcp.tool.metadata");
529
- var PromptRequest = class _PromptRequest {
530
- constructor(agent, promptMessage, initialHistory = [], memoryContext = void 0) {
747
+ var ToolCallExecutor = class {
748
+ constructor(agent, activeHook, concurrency, requestToolMiddlewares, cancel) {
531
749
  this.agent = agent;
532
- this.promptMessage = promptMessage;
533
- this.initialHistory = initialHistory;
534
- this.memoryContext = memoryContext;
535
- this.chatHistory = initialHistory;
536
- this.maxTurnCount = agent.defaultMaxTurns ?? 0;
537
- this.activeHook = agent.hook;
750
+ this.activeHook = activeHook;
751
+ this.concurrency = concurrency;
752
+ this.requestToolMiddlewares = requestToolMiddlewares;
753
+ this.cancel = cancel;
538
754
  }
539
755
  agent;
540
- promptMessage;
541
- initialHistory;
542
- memoryContext;
543
- chatHistory;
544
- maxTurnCount;
545
756
  activeHook;
546
- concurrency = 1;
547
- traceOptions;
548
- requestToolMiddlewares = [];
549
- static fromAgent(agent, prompt, options = {}) {
550
- const normalized = normalizePromptInput(prompt);
551
- return new _PromptRequest(agent, normalized.prompt, normalized.history, options.memoryContext);
552
- }
553
- maxTurns(maxTurns) {
554
- this.maxTurnCount = maxTurns;
555
- return this;
556
- }
557
- requestHook(hook) {
558
- this.activeHook = hook;
559
- return this;
560
- }
561
- withToolConcurrency(concurrency) {
562
- this.concurrency = Math.max(1, concurrency);
563
- return this;
564
- }
565
- withToolMiddleware(middleware) {
566
- this.requestToolMiddlewares.push(middleware);
567
- return this;
568
- }
569
- withToolMiddlewares(middlewares) {
570
- this.requestToolMiddlewares.push(...middlewares);
571
- return this;
572
- }
573
- withTrace(trace) {
574
- this.traceOptions = trace;
575
- return this;
576
- }
577
- async send() {
578
- const runId = globalThis.crypto.randomUUID();
579
- const newMessages = [this.promptMessage];
580
- await this.prepareMemoryRun(runId, newMessages);
581
- const pendingTurnMessages = this.memoryPolicy() === "turn" ? [...newMessages] : [];
582
- let usage = Usage.empty();
583
- let currentTurns = 0;
584
- let lastPrompt = this.promptMessage;
585
- const runObservers = await this.startRunObservers();
586
- try {
587
- while (currentTurns <= this.maxTurnCount + 1) {
588
- const prompt = newMessages.at(-1);
589
- if (prompt === void 0) {
590
- throw new Error("PromptRequest requires at least one message");
591
- }
592
- lastPrompt = prompt;
593
- currentTurns += 1;
594
- const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];
595
- await this.runCompletionCallHook(prompt, historyForRequest, newMessages);
596
- const ragText = extractRagText(prompt);
597
- const dynamicContext = await this.fetchDynamicContext(ragText);
598
- const toolDefs = await this.fetchToolDefinitions(ragText);
599
- const request = new CompletionRequestBuilder(this.agent.model, prompt).instructions(this.agent.instructions).messages(historyForRequest).documents([...this.agent.staticContext, ...dynamicContext]).tools(toolDefs).temperature(this.agent.temperature).maxTokens(this.agent.maxTokens).additionalParams(this.agent.additionalParams).toolChoice(this.agent.toolChoice).outputSchema(this.agent.outputSchema).build();
600
- const response = await this.runCompletion(request, currentTurns, runObservers);
601
- usage = Usage.add(usage, response.usage);
602
- await this.runCompletionResponseHook(prompt, response, newMessages);
603
- const assistantMessage = Message.assistant(response.choice, response.messageId);
604
- newMessages.push(assistantMessage);
605
- await this.commitMemoryMessages(
606
- runId,
607
- currentTurns,
608
- [assistantMessage],
609
- pendingTurnMessages
610
- );
611
- const toolCalls = response.choice.filter(
757
+ concurrency;
758
+ requestToolMiddlewares;
759
+ cancel;
760
+ async execute(toolCalls, onResult, onStreamEvent, observation) {
761
+ return mapWithConcurrency(toolCalls, this.concurrency, async (toolCall) => {
762
+ const args = JSON.stringify(toolCall.function.arguments ?? {});
763
+ const internalCallId = globalThis.crypto.randomUUID();
764
+ const hookArgs = {
765
+ toolName: toolCall.function.name,
766
+ internalCallId,
767
+ args
768
+ };
769
+ if (toolCall.callId !== void 0) {
770
+ hookArgs.toolCallId = toolCall.callId;
771
+ }
772
+ const tool = this.agent.getTool(toolCall.function.name);
773
+ const toolDefinition = observation?.toolDefinitions?.find(
774
+ (definition) => definition.name === toolCall.function.name
775
+ );
776
+ const toolMetadata = toolTraceMetadata(tool);
777
+ const toolObservers = await observation?.runObservers.startTool({
778
+ turn: observation.turn,
779
+ toolCall,
780
+ toolName: toolCall.function.name,
781
+ internalCallId,
782
+ args,
783
+ toolCallId: toolCall.callId,
784
+ ...toolDefinition === void 0 ? {} : { toolDefinition },
785
+ ...toolMetadata === void 0 ? {} : { toolMetadata }
786
+ });
787
+ const callAction = await this.activeHook?.onToolCall?.({
788
+ ...hookArgs,
789
+ tool: toolCallControl
790
+ });
791
+ if (callAction?.type === "terminate") {
792
+ await recordToolError(
793
+ toolObservers,
794
+ observation?.turn,
795
+ toolCall,
796
+ internalCallId,
797
+ args,
798
+ callAction.reason
799
+ );
800
+ throw this.cancel(callAction.reason);
801
+ }
802
+ if (callAction?.type === "approval_request") {
803
+ const reason = `Tool approval was requested for ${toolCall.function.name}, but no approval handler is installed.`;
804
+ await recordToolError(
805
+ toolObservers,
806
+ observation?.turn,
807
+ toolCall,
808
+ internalCallId,
809
+ args,
810
+ reason
811
+ );
812
+ throw this.cancel(reason);
813
+ }
814
+ let output;
815
+ let skipped = false;
816
+ if (callAction?.type === "skip") {
817
+ output = callAction.reason;
818
+ skipped = true;
819
+ } else {
820
+ try {
821
+ output = await this.agent.callTool(toolCall.function.name, args, {
822
+ emitStreamEvent: async (event) => {
823
+ await toolObservers?.streamEvent({
824
+ turn: observation?.turn ?? 0,
825
+ toolCall,
826
+ toolName: toolCall.function.name,
827
+ internalCallId,
828
+ args,
829
+ ...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId },
830
+ event
831
+ });
832
+ const payload = agentToolEventPayload(toolCall, internalCallId, event);
833
+ if (payload !== void 0) {
834
+ onStreamEvent?.(payload);
835
+ }
836
+ }
837
+ });
838
+ } catch (error) {
839
+ output = error instanceof Error ? error.toString() : String(error);
840
+ }
841
+ }
842
+ let result = toolOutputToText(output);
843
+ let structuredResult = toolOutputToStructuredResult(output);
844
+ if (this.agent.shouldApplyToolMiddleware(toolCall.function.name)) {
845
+ const middlewareReplacement = await this.runToolResultMiddlewares({
846
+ ...hookArgs,
847
+ result,
848
+ originalResult: result,
849
+ structuredResult,
850
+ originalStructuredResult: structuredResult,
851
+ turn: observation?.turn ?? 0
852
+ });
853
+ if (middlewareReplacement !== void 0) {
854
+ output = middlewareReplacement;
855
+ result = middlewareReplacement;
856
+ structuredResult = void 0;
857
+ }
858
+ }
859
+ const resultAction = await this.activeHook?.onToolResult?.({
860
+ ...hookArgs,
861
+ result,
862
+ structuredResult,
863
+ run: runControl
864
+ });
865
+ await toolObservers?.end({
866
+ turn: observation?.turn ?? 0,
867
+ toolCall,
868
+ toolName: toolCall.function.name,
869
+ internalCallId,
870
+ args,
871
+ result,
872
+ structuredResult,
873
+ skipped,
874
+ toolCallId: toolCall.callId
875
+ });
876
+ if (resultAction?.type === "terminate") {
877
+ throw this.cancel(resultAction.reason);
878
+ }
879
+ const resultPayload = {
880
+ type: "tool_result",
881
+ toolName: toolCall.function.name,
882
+ internalCallId,
883
+ args,
884
+ result,
885
+ structuredResult
886
+ };
887
+ if (toolCall.callId !== void 0) {
888
+ resultPayload.toolCallId = toolCall.callId;
889
+ }
890
+ onResult?.(resultPayload);
891
+ return ToolContent.toolResult(toolCall.id, output, toolCall.callId);
892
+ });
893
+ }
894
+ async runToolResultMiddlewares(args) {
895
+ let result = args.result;
896
+ let replaced = false;
897
+ for (const middleware of [...this.agent.toolMiddlewares, ...this.requestToolMiddlewares]) {
898
+ const replacement = await middleware.onResult?.({
899
+ ...args,
900
+ result
901
+ });
902
+ if (replacement !== void 0) {
903
+ result = replacement;
904
+ replaced = true;
905
+ }
906
+ }
907
+ return replaced ? result : void 0;
908
+ }
909
+ };
910
+ function toolTraceMetadata(tool) {
911
+ if (tool === void 0) {
912
+ return void 0;
913
+ }
914
+ const metadata = tool[MCP_TOOL_METADATA_KEY];
915
+ const mcpMetadata = typeof metadata === "object" && metadata !== null ? metadata : void 0;
916
+ return {
917
+ approvalRequired: tool.approval !== void 0,
918
+ ...typeof mcpMetadata?.serverName === "string" && mcpMetadata.serverName.length > 0 ? { mcpServerName: mcpMetadata.serverName } : {}
919
+ };
920
+ }
921
+ async function recordToolError(toolObservers, turn, toolCall, internalCallId, args, error) {
922
+ await toolObservers?.error({
923
+ turn: turn ?? 0,
924
+ toolCall,
925
+ toolName: toolCall.function.name,
926
+ internalCallId,
927
+ args,
928
+ error,
929
+ toolCallId: toolCall.callId
930
+ });
931
+ }
932
+ function toolOutputToText(output) {
933
+ return typeof output === "string" ? output : toolResultContentToText(output);
934
+ }
935
+ function toolOutputToStructuredResult(output) {
936
+ return typeof output === "string" ? void 0 : output;
937
+ }
938
+ function agentToolEventPayload(toolCall, internalCallId, event) {
939
+ if (typeof event.agentId !== "string" || event.agentId.length === 0) {
940
+ return void 0;
941
+ }
942
+ return {
943
+ type: "agent_tool_event",
944
+ toolName: toolCall.function.name,
945
+ ...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId },
946
+ internalCallId,
947
+ agentId: event.agentId,
948
+ ...event.agentName === void 0 ? {} : { agentName: event.agentName },
949
+ event: event.event
950
+ };
951
+ }
952
+
953
+ // src/agent/request.ts
954
+ var PromptRequest = class _PromptRequest {
955
+ constructor(agent, promptMessage, initialHistory = [], memoryContext = void 0) {
956
+ this.agent = agent;
957
+ this.promptMessage = promptMessage;
958
+ this.chatHistory = initialHistory;
959
+ this.maxTurnCount = agent.defaultMaxTurns ?? 0;
960
+ this.activeHook = agent.hook;
961
+ this.memoryRecorder = new PromptRequestMemory(agent, memoryContext, initialHistory);
962
+ }
963
+ agent;
964
+ promptMessage;
965
+ chatHistory;
966
+ maxTurnCount;
967
+ activeHook;
968
+ concurrency = 1;
969
+ traceOptions;
970
+ requestToolMiddlewares = [];
971
+ memoryRecorder;
972
+ static fromAgent(agent, prompt, options = {}) {
973
+ const normalized = normalizePromptInput(prompt);
974
+ return new _PromptRequest(agent, normalized.prompt, normalized.history, options.memoryContext);
975
+ }
976
+ maxTurns(maxTurns) {
977
+ this.maxTurnCount = maxTurns;
978
+ return this;
979
+ }
980
+ requestHook(hook) {
981
+ this.activeHook = hook;
982
+ return this;
983
+ }
984
+ withToolConcurrency(concurrency) {
985
+ this.concurrency = Math.max(1, concurrency);
986
+ return this;
987
+ }
988
+ withToolMiddleware(middleware) {
989
+ this.requestToolMiddlewares.push(middleware);
990
+ return this;
991
+ }
992
+ withToolMiddlewares(middlewares) {
993
+ this.requestToolMiddlewares.push(...middlewares);
994
+ return this;
995
+ }
996
+ withTrace(trace) {
997
+ this.traceOptions = trace;
998
+ return this;
999
+ }
1000
+ async send() {
1001
+ const runId = globalThis.crypto.randomUUID();
1002
+ const newMessages = [this.promptMessage];
1003
+ this.chatHistory = await this.memoryRecorder.prepareRun(runId, newMessages);
1004
+ const pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);
1005
+ let usage = Usage.empty();
1006
+ let currentTurns = 0;
1007
+ let lastPrompt = this.promptMessage;
1008
+ const runObservers = await this.startRunObservers();
1009
+ try {
1010
+ while (currentTurns <= this.maxTurnCount + 1) {
1011
+ const prompt = newMessages.at(-1);
1012
+ if (prompt === void 0) {
1013
+ throw new Error("PromptRequest requires at least one message");
1014
+ }
1015
+ lastPrompt = prompt;
1016
+ currentTurns += 1;
1017
+ const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];
1018
+ await this.runCompletionCallHook(prompt, historyForRequest, newMessages);
1019
+ const ragText = extractRagText(prompt);
1020
+ const dynamicContext = await fetchDynamicContext(this.agent, ragText);
1021
+ const toolDefs = await fetchToolDefinitions(this.agent, ragText);
1022
+ const request = new CompletionRequestBuilder(this.agent.model, prompt).instructions(this.agent.instructions).messages(historyForRequest).documents([...this.agent.staticContext, ...dynamicContext]).tools(toolDefs).temperature(this.agent.temperature).maxTokens(this.agent.maxTokens).additionalParams(this.agent.additionalParams).toolChoice(this.agent.toolChoice).outputSchema(this.agent.outputSchema).build();
1023
+ const response = await this.runCompletion(request, currentTurns, runObservers);
1024
+ usage = Usage.add(usage, response.usage);
1025
+ await this.runCompletionResponseHook(prompt, response, newMessages);
1026
+ const assistantMessage = Message.assistant(response.choice, response.messageId);
1027
+ newMessages.push(assistantMessage);
1028
+ await this.memoryRecorder.commitMessages(
1029
+ runId,
1030
+ currentTurns,
1031
+ [assistantMessage],
1032
+ pendingTurnMessages
1033
+ );
1034
+ const toolCalls = response.choice.filter(
612
1035
  (item) => item.type === "tool_call"
613
1036
  );
614
1037
  if (toolCalls.length === 0) {
615
- await this.commitCompletedMemoryRun(
1038
+ await this.memoryRecorder.commitCompletedRun(
616
1039
  runId,
617
1040
  currentTurns,
618
1041
  newMessages,
@@ -640,13 +1063,18 @@ var PromptRequest = class _PromptRequest {
640
1063
  );
641
1064
  const toolMessage = Message.tool(toolResults);
642
1065
  newMessages.push(toolMessage);
643
- await this.commitMemoryMessages(runId, currentTurns, [toolMessage], pendingTurnMessages);
644
- await this.commitCompletedMemoryTurn(runId, currentTurns, pendingTurnMessages);
1066
+ await this.memoryRecorder.commitMessages(
1067
+ runId,
1068
+ currentTurns,
1069
+ [toolMessage],
1070
+ pendingTurnMessages
1071
+ );
1072
+ await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
645
1073
  }
646
1074
  throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);
647
1075
  } catch (error) {
648
1076
  await runObservers.error({ error, usage, messages: [...newMessages] });
649
- await this.recordMemoryError(runId, error, newMessages);
1077
+ await this.memoryRecorder.recordError(runId, error, newMessages);
650
1078
  throw error;
651
1079
  }
652
1080
  }
@@ -656,8 +1084,8 @@ var PromptRequest = class _PromptRequest {
656
1084
  }
657
1085
  const runId = globalThis.crypto.randomUUID();
658
1086
  const newMessages = [this.promptMessage];
659
- await this.prepareMemoryRun(runId, newMessages);
660
- const pendingTurnMessages = this.memoryPolicy() === "turn" ? [...newMessages] : [];
1087
+ this.chatHistory = await this.memoryRecorder.prepareRun(runId, newMessages);
1088
+ const pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);
661
1089
  let usage = Usage.empty();
662
1090
  let currentTurns = 0;
663
1091
  let lastPrompt = this.promptMessage;
@@ -683,8 +1111,8 @@ var PromptRequest = class _PromptRequest {
683
1111
  });
684
1112
  await this.runCompletionCallHook(prompt, historyForRequest, newMessages);
685
1113
  const ragText = extractRagText(prompt);
686
- const dynamicContext = await this.fetchDynamicContext(ragText);
687
- const toolDefs = await this.fetchToolDefinitions(ragText);
1114
+ const dynamicContext = await fetchDynamicContext(this.agent, ragText);
1115
+ const toolDefs = await fetchToolDefinitions(this.agent, ragText);
688
1116
  const request = new CompletionRequestBuilder(this.agent.model, prompt).instructions(this.agent.instructions).messages(historyForRequest).documents([...this.agent.staticContext, ...dynamicContext]).tools(toolDefs).temperature(this.agent.temperature).maxTokens(this.agent.maxTokens).additionalParams(this.agent.additionalParams).toolChoice(this.agent.toolChoice).outputSchema(this.agent.outputSchema).build();
689
1117
  assertCompletionRequestSupported(this.agent.model, request, { streaming: true });
690
1118
  const providerRequest = this.providerTraceRequest(request, { stream: true });
@@ -728,7 +1156,7 @@ var PromptRequest = class _PromptRequest {
728
1156
  await this.runCompletionResponseHook(prompt, response, newMessages);
729
1157
  const assistantMessage = Message.assistant(response.choice, response.messageId);
730
1158
  newMessages.push(assistantMessage);
731
- await this.commitMemoryMessages(
1159
+ await this.memoryRecorder.commitMessages(
732
1160
  runId,
733
1161
  currentTurns,
734
1162
  [assistantMessage],
@@ -743,7 +1171,7 @@ var PromptRequest = class _PromptRequest {
743
1171
  yield await emit({ type: "turn_end", turn: currentTurns, response });
744
1172
  if (toolCalls.length === 0) {
745
1173
  const output = textFromAssistantContent(response.choice);
746
- await this.commitCompletedMemoryRun(
1174
+ await this.memoryRecorder.commitCompletedRun(
747
1175
  runId,
748
1176
  currentTurns,
749
1177
  newMessages,
@@ -782,214 +1210,69 @@ var PromptRequest = class _PromptRequest {
782
1210
  );
783
1211
  for await (const result of toolResultEvents) {
784
1212
  yield await emit({ turn: currentTurns, ...result });
785
- }
786
- const toolResults = await toolResultsPromise;
787
- const toolMessage = Message.tool(toolResults);
788
- newMessages.push(toolMessage);
789
- await this.commitMemoryMessages(runId, currentTurns, [toolMessage], pendingTurnMessages);
790
- await this.commitCompletedMemoryTurn(runId, currentTurns, pendingTurnMessages);
791
- }
792
- throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);
793
- } catch (error) {
794
- await runObservers.error({ error, usage, messages: [...newMessages] });
795
- await this.recordMemoryError(runId, error, newMessages);
796
- yield await emit({ type: "error", error });
797
- throw error;
798
- }
799
- }
800
- readableStream() {
801
- return toReadableStream(this.stream());
802
- }
803
- async runCompletion(request, turn, runObservers) {
804
- assertCompletionRequestSupported(this.agent.model, request);
805
- const providerRequest = this.providerTraceRequest(request);
806
- const generationObservers = await runObservers.startGeneration({
807
- turn,
808
- request,
809
- ...providerRequest === void 0 ? {} : { providerRequest },
810
- modelInfo: {
811
- provider: this.agent.model.provider,
812
- defaultModel: this.agent.model.defaultModel,
813
- capabilities: this.agent.model.capabilities
814
- }
815
- });
816
- try {
817
- const response = await this.agent.model.completion(request);
818
- await generationObservers.end({ turn, response });
819
- return response;
820
- } catch (error) {
821
- await generationObservers.error({ turn, error });
822
- throw error;
823
- }
824
- }
825
- providerTraceRequest(request, options = {}) {
826
- try {
827
- return this.agent.model.traceRequest?.(request, options);
828
- } catch (error) {
829
- return {
830
- error: error instanceof Error ? error.message : String(error)
831
- };
832
- }
833
- }
834
- toolTraceMetadata(tool) {
835
- if (tool === void 0) {
836
- return void 0;
837
- }
838
- const metadata = tool[MCP_TOOL_METADATA_KEY];
839
- const mcpMetadata = typeof metadata === "object" && metadata !== null ? metadata : void 0;
840
- return {
841
- approvalRequired: tool.approval !== void 0,
842
- ...typeof mcpMetadata?.serverName === "string" && mcpMetadata.serverName.length > 0 ? { mcpServerName: mcpMetadata.serverName } : {}
843
- };
844
- }
845
- async executeToolCalls(toolCalls, newMessages, onResult, onStreamEvent, observation) {
846
- return mapWithConcurrency(toolCalls, this.concurrency, async (toolCall) => {
847
- const args = JSON.stringify(toolCall.function.arguments ?? {});
848
- const internalCallId = globalThis.crypto.randomUUID();
849
- const hookArgs = {
850
- toolName: toolCall.function.name,
851
- internalCallId,
852
- args
853
- };
854
- if (toolCall.callId !== void 0) {
855
- hookArgs.toolCallId = toolCall.callId;
856
- }
857
- const tool = this.agent.getTool(toolCall.function.name);
858
- const toolDefinition = observation?.toolDefinitions?.find(
859
- (definition) => definition.name === toolCall.function.name
860
- );
861
- const toolMetadata = this.toolTraceMetadata(tool);
862
- const toolObservers = await observation?.runObservers.startTool({
863
- turn: observation.turn,
864
- toolCall,
865
- toolName: toolCall.function.name,
866
- internalCallId,
867
- args,
868
- toolCallId: toolCall.callId,
869
- ...toolDefinition === void 0 ? {} : { toolDefinition },
870
- ...toolMetadata === void 0 ? {} : { toolMetadata }
871
- });
872
- const callAction = await this.activeHook?.onToolCall?.({
873
- ...hookArgs,
874
- tool: toolCallControl
875
- });
876
- if (callAction?.type === "terminate") {
877
- await this.recordToolError(
878
- toolObservers,
879
- observation?.turn,
880
- toolCall,
881
- internalCallId,
882
- args,
883
- callAction.reason
884
- );
885
- throw this.cancelled(newMessages, callAction.reason);
886
- }
887
- if (callAction?.type === "approval_request") {
888
- const reason = `Tool approval was requested for ${toolCall.function.name}, but no approval handler is installed.`;
889
- await this.recordToolError(
890
- toolObservers,
891
- observation?.turn,
892
- toolCall,
893
- internalCallId,
894
- args,
895
- reason
896
- );
897
- throw this.cancelled(newMessages, reason);
898
- }
899
- let output;
900
- let skipped = false;
901
- if (callAction?.type === "skip") {
902
- output = callAction.reason;
903
- skipped = true;
904
- } else {
905
- try {
906
- output = await this.agent.callTool(toolCall.function.name, args, {
907
- emitStreamEvent: async (event) => {
908
- await toolObservers?.streamEvent({
909
- turn: observation?.turn ?? 0,
910
- toolCall,
911
- toolName: toolCall.function.name,
912
- internalCallId,
913
- args,
914
- ...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId },
915
- event
916
- });
917
- const payload = agentToolEventPayload(toolCall, internalCallId, event);
918
- if (payload !== void 0) {
919
- onStreamEvent?.(payload);
920
- }
921
- }
922
- });
923
- } catch (error) {
924
- output = error instanceof Error ? error.toString() : String(error);
925
- }
926
- }
927
- let result = toolOutputToText(output);
928
- let structuredResult = toolOutputToStructuredResult(output);
929
- if (this.agent.shouldApplyToolMiddleware(toolCall.function.name)) {
930
- const middlewareReplacement = await this.runToolResultMiddlewares({
931
- ...hookArgs,
932
- result,
933
- originalResult: result,
934
- structuredResult,
935
- originalStructuredResult: structuredResult,
936
- turn: observation?.turn ?? 0
937
- });
938
- if (middlewareReplacement !== void 0) {
939
- output = middlewareReplacement;
940
- result = middlewareReplacement;
941
- structuredResult = void 0;
942
- }
943
- }
944
- const resultAction = await this.activeHook?.onToolResult?.({
945
- ...hookArgs,
946
- result,
947
- structuredResult,
948
- run: runControl
949
- });
950
- await toolObservers?.end({
951
- turn: observation?.turn ?? 0,
952
- toolCall,
953
- toolName: toolCall.function.name,
954
- internalCallId,
955
- args,
956
- result,
957
- structuredResult,
958
- skipped,
959
- toolCallId: toolCall.callId
960
- });
961
- if (resultAction?.type === "terminate") {
962
- throw this.cancelled(newMessages, resultAction.reason);
1213
+ }
1214
+ const toolResults = await toolResultsPromise;
1215
+ const toolMessage = Message.tool(toolResults);
1216
+ newMessages.push(toolMessage);
1217
+ await this.memoryRecorder.commitMessages(
1218
+ runId,
1219
+ currentTurns,
1220
+ [toolMessage],
1221
+ pendingTurnMessages
1222
+ );
1223
+ await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
963
1224
  }
964
- const resultPayload = {
965
- type: "tool_result",
966
- toolName: toolCall.function.name,
967
- internalCallId,
968
- args,
969
- result,
970
- structuredResult
971
- };
972
- if (toolCall.callId !== void 0) {
973
- resultPayload.toolCallId = toolCall.callId;
1225
+ throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);
1226
+ } catch (error) {
1227
+ await runObservers.error({ error, usage, messages: [...newMessages] });
1228
+ await this.memoryRecorder.recordError(runId, error, newMessages);
1229
+ yield await emit({ type: "error", error });
1230
+ throw error;
1231
+ }
1232
+ }
1233
+ readableStream() {
1234
+ return toReadableStream(this.stream());
1235
+ }
1236
+ async runCompletion(request, turn, runObservers) {
1237
+ assertCompletionRequestSupported(this.agent.model, request);
1238
+ const providerRequest = this.providerTraceRequest(request);
1239
+ const generationObservers = await runObservers.startGeneration({
1240
+ turn,
1241
+ request,
1242
+ ...providerRequest === void 0 ? {} : { providerRequest },
1243
+ modelInfo: {
1244
+ provider: this.agent.model.provider,
1245
+ defaultModel: this.agent.model.defaultModel,
1246
+ capabilities: this.agent.model.capabilities
974
1247
  }
975
- onResult?.(resultPayload);
976
- return ToolContent.toolResult(toolCall.id, output, toolCall.callId);
977
1248
  });
1249
+ try {
1250
+ const response = await this.agent.model.completion(request);
1251
+ await generationObservers.end({ turn, response });
1252
+ return response;
1253
+ } catch (error) {
1254
+ await generationObservers.error({ turn, error });
1255
+ throw error;
1256
+ }
978
1257
  }
979
- async runToolResultMiddlewares(args) {
980
- let result = args.result;
981
- let replaced = false;
982
- for (const middleware of [...this.agent.toolMiddlewares, ...this.requestToolMiddlewares]) {
983
- const replacement = await middleware.onResult?.({
984
- ...args,
985
- result
986
- });
987
- if (replacement !== void 0) {
988
- result = replacement;
989
- replaced = true;
990
- }
1258
+ providerTraceRequest(request, options = {}) {
1259
+ try {
1260
+ return this.agent.model.traceRequest?.(request, options);
1261
+ } catch (error) {
1262
+ return {
1263
+ error: error instanceof Error ? error.message : String(error)
1264
+ };
991
1265
  }
992
- return replaced ? result : void 0;
1266
+ }
1267
+ async executeToolCalls(toolCalls, newMessages, onResult, onStreamEvent, observation) {
1268
+ const executor = new ToolCallExecutor(
1269
+ this.agent,
1270
+ this.activeHook,
1271
+ this.concurrency,
1272
+ this.requestToolMiddlewares,
1273
+ (reason) => this.cancelled(newMessages, reason)
1274
+ );
1275
+ return executor.execute(toolCalls, onResult, onStreamEvent, observation);
993
1276
  }
994
1277
  async startRunObservers() {
995
1278
  const failOnObserverError = this.traceOptions?.failOnObserverError === true || this.agent.observers.some((registration) => registration.failOnObserverError === true);
@@ -1031,69 +1314,6 @@ var PromptRequest = class _PromptRequest {
1031
1314
  event
1032
1315
  });
1033
1316
  }
1034
- async fetchDynamicContext(ragText) {
1035
- if (ragText === void 0 || ragText.length === 0 || this.agent.dynamicContexts.length === 0) {
1036
- return [];
1037
- }
1038
- const documents = [];
1039
- for (const registration of this.agent.dynamicContexts) {
1040
- const results = await registration.index.search({
1041
- query: ragText,
1042
- topK: registration.options.topK,
1043
- threshold: registration.options.threshold,
1044
- filter: registration.options.filter
1045
- });
1046
- for (const result of results) {
1047
- const formatted = registration.options.format?.(result);
1048
- if (formatted !== void 0) {
1049
- documents.push(formatted);
1050
- } else {
1051
- const metadata = formatMetadata(result.metadata);
1052
- documents.push({
1053
- id: result.id,
1054
- text: typeof result.document === "string" ? result.document : JSON.stringify(result.document, null, 2),
1055
- ...metadata === void 0 ? {} : { additionalProps: metadata }
1056
- });
1057
- }
1058
- }
1059
- }
1060
- return documents;
1061
- }
1062
- async fetchToolDefinitions(ragText) {
1063
- const staticDefinitions = await this.agent.toolSet.getToolDefinitions(ragText);
1064
- if (ragText === void 0 || ragText.length === 0 || this.agent.dynamicTools.length === 0) {
1065
- return staticDefinitions;
1066
- }
1067
- const definitions = [...staticDefinitions];
1068
- const names = new Set(staticDefinitions.map((definition) => definition.name));
1069
- for (const registration of this.agent.dynamicTools) {
1070
- const results = await registration.index.search({
1071
- query: ragText,
1072
- topK: registration.options.topK,
1073
- threshold: registration.options.threshold,
1074
- filter: registration.options.filter
1075
- });
1076
- for (const result of results) {
1077
- if (names.has(result.document.toolName)) {
1078
- continue;
1079
- }
1080
- names.add(result.document.toolName);
1081
- definitions.push(result.document.definition);
1082
- }
1083
- }
1084
- return definitions;
1085
- }
1086
- async recordToolError(toolObservers, turn, toolCall, internalCallId, args, error) {
1087
- await toolObservers?.error({
1088
- turn: turn ?? 0,
1089
- toolCall,
1090
- toolName: toolCall.function.name,
1091
- internalCallId,
1092
- args,
1093
- error,
1094
- toolCallId: toolCall.callId
1095
- });
1096
- }
1097
1317
  async runCompletionCallHook(prompt, history, newMessages) {
1098
1318
  const action = await this.activeHook?.onCompletionCall?.({
1099
1319
  prompt,
@@ -1117,83 +1337,6 @@ var PromptRequest = class _PromptRequest {
1117
1337
  cancelled(newMessages, reason) {
1118
1338
  return new PromptCancelledError([...this.chatHistory, ...newMessages], reason);
1119
1339
  }
1120
- memory() {
1121
- return this.memoryContext === void 0 ? void 0 : this.agent.memory;
1122
- }
1123
- memoryPolicy() {
1124
- return this.memory()?.options.savePolicy;
1125
- }
1126
- async prepareMemoryRun(runId, newMessages) {
1127
- const memory = this.memory();
1128
- if (memory === void 0 || this.memoryContext === void 0) {
1129
- this.chatHistory = this.initialHistory;
1130
- return;
1131
- }
1132
- const memoryHistory = await memory.store.load(this.memoryContext);
1133
- this.chatHistory = [...memoryHistory, ...this.initialHistory];
1134
- if (memory.options.savePolicy === "message") {
1135
- await memory.store.append({
1136
- context: this.memoryContext,
1137
- runId,
1138
- turn: 1,
1139
- messages: newMessages
1140
- });
1141
- }
1142
- }
1143
- async commitMemoryMessages(runId, turn, messages, pendingTurnMessages) {
1144
- const memory = this.memory();
1145
- if (memory === void 0 || this.memoryContext === void 0 || messages.length === 0) {
1146
- return;
1147
- }
1148
- if (memory.options.savePolicy === "message") {
1149
- await memory.store.append({
1150
- context: this.memoryContext,
1151
- runId,
1152
- turn,
1153
- messages
1154
- });
1155
- } else if (memory.options.savePolicy === "turn") {
1156
- pendingTurnMessages.push(...messages);
1157
- }
1158
- }
1159
- async commitCompletedMemoryTurn(runId, turn, pendingTurnMessages) {
1160
- const memory = this.memory();
1161
- if (memory === void 0 || this.memoryContext === void 0 || memory.options.savePolicy !== "turn" || pendingTurnMessages.length === 0) {
1162
- return;
1163
- }
1164
- await memory.store.append({
1165
- context: this.memoryContext,
1166
- runId,
1167
- turn,
1168
- messages: [...pendingTurnMessages]
1169
- });
1170
- pendingTurnMessages.length = 0;
1171
- }
1172
- async commitCompletedMemoryRun(runId, turn, newMessages, pendingTurnMessages) {
1173
- await this.commitCompletedMemoryTurn(runId, turn, pendingTurnMessages);
1174
- const memory = this.memory();
1175
- if (memory === void 0 || this.memoryContext === void 0 || memory.options.savePolicy !== "run") {
1176
- return;
1177
- }
1178
- await memory.store.append({
1179
- context: this.memoryContext,
1180
- runId,
1181
- turn,
1182
- messages: [...newMessages]
1183
- });
1184
- }
1185
- async recordMemoryError(runId, error, newMessages) {
1186
- const memory = this.memory();
1187
- if (memory === void 0 || this.memoryContext === void 0) {
1188
- return;
1189
- }
1190
- await memory.store.recordError?.({
1191
- context: this.memoryContext,
1192
- runId,
1193
- error,
1194
- messages: [...newMessages]
1195
- });
1196
- }
1197
1340
  };
1198
1341
  function normalizePromptInput(prompt) {
1199
1342
  if (typeof prompt === "string") {
@@ -1214,92 +1357,6 @@ function normalizePromptInput(prompt) {
1214
1357
  history: prompt.slice(0, -1)
1215
1358
  };
1216
1359
  }
1217
- function toolOutputToText(output) {
1218
- return typeof output === "string" ? output : toolResultContentToText(output);
1219
- }
1220
- function toolOutputToStructuredResult(output) {
1221
- return typeof output === "string" ? void 0 : output;
1222
- }
1223
- function agentToolEventPayload(toolCall, internalCallId, event) {
1224
- if (typeof event.agentId !== "string" || event.agentId.length === 0) {
1225
- return void 0;
1226
- }
1227
- return {
1228
- type: "agent_tool_event",
1229
- toolName: toolCall.function.name,
1230
- ...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId },
1231
- internalCallId,
1232
- agentId: event.agentId,
1233
- ...event.agentName === void 0 ? {} : { agentName: event.agentName },
1234
- event: event.event
1235
- };
1236
- }
1237
- function createAsyncQueue() {
1238
- const values = [];
1239
- const waiters = [];
1240
- let closed = false;
1241
- let error;
1242
- function flush() {
1243
- while (waiters.length > 0 && values.length > 0) {
1244
- const waiter = waiters.shift();
1245
- const value = values.shift();
1246
- if (waiter !== void 0) {
1247
- waiter.resolve({ value, done: false });
1248
- }
1249
- }
1250
- if (values.length > 0 || waiters.length === 0 || !closed) {
1251
- return;
1252
- }
1253
- while (waiters.length > 0) {
1254
- const waiter = waiters.shift();
1255
- if (waiter === void 0) {
1256
- continue;
1257
- }
1258
- if (error !== void 0) {
1259
- waiter.reject(error);
1260
- } else {
1261
- waiter.resolve({ value: void 0, done: true });
1262
- }
1263
- }
1264
- }
1265
- return {
1266
- enqueue(value) {
1267
- if (closed) {
1268
- return;
1269
- }
1270
- values.push(value);
1271
- flush();
1272
- },
1273
- close() {
1274
- closed = true;
1275
- flush();
1276
- },
1277
- throw(thrown) {
1278
- closed = true;
1279
- error = thrown;
1280
- flush();
1281
- },
1282
- [Symbol.asyncIterator]() {
1283
- return {
1284
- next() {
1285
- if (values.length > 0) {
1286
- const value = values.shift();
1287
- return Promise.resolve({ value, done: false });
1288
- }
1289
- if (error !== void 0) {
1290
- return Promise.reject(error);
1291
- }
1292
- if (closed) {
1293
- return Promise.resolve({ value: void 0, done: true });
1294
- }
1295
- return new Promise((resolve, reject) => {
1296
- waiters.push({ resolve, reject });
1297
- });
1298
- }
1299
- };
1300
- }
1301
- };
1302
- }
1303
1360
  function addTurn(turn, event) {
1304
1361
  if (event.type === "text_delta") {
1305
1362
  return { type: "text_delta", turn, delta: event.delta };
@@ -1316,12 +1373,6 @@ function addTurn(turn, event) {
1316
1373
  function isGenerationDeltaEvent(type) {
1317
1374
  return type === "text_delta" || type === "reasoning_delta" || type === "tool_call_delta" || type === "tool_call";
1318
1375
  }
1319
- function formatMetadata(metadata) {
1320
- if (metadata === void 0) {
1321
- return void 0;
1322
- }
1323
- return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, String(value)]));
1324
- }
1325
1376
 
1326
1377
  // src/agent/agent.ts
1327
1378
  var DEFAULT_MAX_TURNS = 20;
@@ -1477,18 +1528,9 @@ function dynamicToolSetFromIndex(index) {
1477
1528
  const maybeIndex = index;
1478
1529
  return maybeIndex.toolSet instanceof ToolSet ? maybeIndex.toolSet : void 0;
1479
1530
  }
1480
- function normalizeAgentId(id) {
1481
- if (typeof id !== "string") {
1482
- throw new TypeError("Agent id must be a string.");
1483
- }
1484
- const normalized = id.trim();
1485
- if (normalized.length === 0) {
1486
- throw new TypeError("Agent id must be a non-empty string.");
1487
- }
1488
- return normalized;
1489
- }
1490
1531
 
1491
1532
  export {
1533
+ normalizeAgentId,
1492
1534
  MaxTurnsError,
1493
1535
  PromptCancelledError,
1494
1536
  createHook,
@@ -1501,4 +1543,4 @@ export {
1501
1543
  Agent,
1502
1544
  AgentSession
1503
1545
  };
1504
- //# sourceMappingURL=chunk-TP32W7XT.js.map
1546
+ //# sourceMappingURL=chunk-N7NMSGZI.js.map