@anvia/core 1.0.0-rc.1 → 1.0.0-rc.3

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 (151) hide show
  1. package/README.md +344 -85
  2. package/dist/agent/index.d.ts +33 -18
  3. package/dist/agent/index.js +42 -17
  4. package/dist/agent-CXScUOpX.d.ts +150 -0
  5. package/dist/{chunk-R2LJSQUW.js → chunk-3CMWKK32.js} +260 -104
  6. package/dist/chunk-3CMWKK32.js.map +1 -0
  7. package/dist/chunk-3RM57ZT2.js +31 -0
  8. package/dist/chunk-3RM57ZT2.js.map +1 -0
  9. package/dist/chunk-5MK3BISB.js +704 -0
  10. package/dist/chunk-5MK3BISB.js.map +1 -0
  11. package/dist/chunk-AI5JMUW7.js +45 -0
  12. package/dist/chunk-AI5JMUW7.js.map +1 -0
  13. package/dist/{chunk-FNQB2JEH.js → chunk-AZB6N7P4.js} +94 -65
  14. package/dist/chunk-AZB6N7P4.js.map +1 -0
  15. package/dist/chunk-BEYBU7VJ.js +53 -0
  16. package/dist/chunk-BEYBU7VJ.js.map +1 -0
  17. package/dist/chunk-BY4OMNIU.js +4699 -0
  18. package/dist/chunk-BY4OMNIU.js.map +1 -0
  19. package/dist/chunk-D2ECOWN5.js +515 -0
  20. package/dist/chunk-D2ECOWN5.js.map +1 -0
  21. package/dist/{chunk-A3UBYTJT.js → chunk-FN7HLLAZ.js} +60 -6
  22. package/dist/chunk-FN7HLLAZ.js.map +1 -0
  23. package/dist/chunk-GKDERULJ.js +50 -0
  24. package/dist/chunk-GKDERULJ.js.map +1 -0
  25. package/dist/chunk-GQL5KRAH.js +331 -0
  26. package/dist/chunk-GQL5KRAH.js.map +1 -0
  27. package/dist/{chunk-5XKDW36Z.js → chunk-KFR4CDGK.js} +70 -75
  28. package/dist/chunk-KFR4CDGK.js.map +1 -0
  29. package/dist/chunk-KV6QCRQ4.js +171 -0
  30. package/dist/chunk-KV6QCRQ4.js.map +1 -0
  31. package/dist/{chunk-DMPUP4R3.js → chunk-LXMAFD23.js} +5 -5
  32. package/dist/{chunk-I6G7BC42.js → chunk-MGNTXGTX.js} +2 -6
  33. package/dist/chunk-MGNTXGTX.js.map +1 -0
  34. package/dist/chunk-PK5LKOFL.js +239 -0
  35. package/dist/chunk-PK5LKOFL.js.map +1 -0
  36. package/dist/chunk-QOUPWOGW.js +29 -0
  37. package/dist/chunk-QOUPWOGW.js.map +1 -0
  38. package/dist/chunk-TRQ3XRFD.js +54 -0
  39. package/dist/chunk-TRQ3XRFD.js.map +1 -0
  40. package/dist/chunk-VKYZZXP5.js +323 -0
  41. package/dist/chunk-VKYZZXP5.js.map +1 -0
  42. package/dist/chunk-ZCPOIDAQ.js +127 -0
  43. package/dist/chunk-ZCPOIDAQ.js.map +1 -0
  44. package/dist/client-DvUatElp.d.ts +84 -0
  45. package/dist/completion/index.d.ts +5 -4
  46. package/dist/completion/index.js +25 -28
  47. package/dist/documents/index.d.ts +34 -0
  48. package/dist/documents/index.js +315 -0
  49. package/dist/documents/index.js.map +1 -0
  50. package/dist/{dynamic-tools-i9woysFa.d.ts → dynamic-tools-AEBOTgu1.d.ts} +21 -9
  51. package/dist/embeddings/index.d.ts +11 -9
  52. package/dist/embeddings/index.js +3 -3
  53. package/dist/evals/index.d.ts +53 -25
  54. package/dist/evals/index.js +153 -103
  55. package/dist/evals/index.js.map +1 -1
  56. package/dist/extractor/index.d.ts +23 -26
  57. package/dist/extractor/index.js +7 -8
  58. package/dist/guardrails/index.d.ts +7 -129
  59. package/dist/guardrails/index.js +1 -1
  60. package/dist/image-generation/index.d.ts +18 -16
  61. package/dist/image-generation/index.js +2 -2
  62. package/dist/index.d.ts +26 -23
  63. package/dist/index.js +71 -48
  64. package/dist/interactions-csssHYcN.d.ts +174 -0
  65. package/dist/internal/agent.d.ts +36 -29
  66. package/dist/internal/agent.js +48 -15
  67. package/dist/internal/agent.js.map +1 -1
  68. package/dist/mcp/index.d.ts +19 -13
  69. package/dist/mcp/index.js +14 -348
  70. package/dist/mcp/index.js.map +1 -1
  71. package/dist/memory/index.d.ts +20 -6
  72. package/dist/memory/index.js +10 -10
  73. package/dist/message-schema-B2M7AYzR.d.ts +52 -0
  74. package/dist/model-call-options-CZkSw_xN.d.ts +6 -0
  75. package/dist/model-listing/index.d.ts +3 -1
  76. package/dist/observability/index.d.ts +21 -6
  77. package/dist/observability/index.js +8 -5
  78. package/dist/observability/index.js.map +1 -1
  79. package/dist/pipeline/index.d.ts +106 -57
  80. package/dist/pipeline/index.js +419 -236
  81. package/dist/pipeline/index.js.map +1 -1
  82. package/dist/{retry-D3Ruy-ba.d.ts → retry-CjvSlKGW.d.ts} +2 -1
  83. package/dist/skills/index.d.ts +5 -4
  84. package/dist/skills/index.js +8 -7
  85. package/dist/speech-generation/index.d.ts +37 -0
  86. package/dist/speech-generation/index.js +8 -0
  87. package/dist/text-C_6eKrbC.d.ts +32 -0
  88. package/dist/{think-tool-DZqZj2LV.d.ts → think-tool-D8frXxwV.d.ts} +16 -2
  89. package/dist/tool/index.d.ts +9 -7
  90. package/dist/tool/index.js +12 -10
  91. package/dist/{tool-C_8GudXn.d.ts → tool-r62gf3QY.d.ts} +17 -8
  92. package/dist/transcription/index.d.ts +23 -14
  93. package/dist/transcription/index.js +2 -2
  94. package/dist/types-C3gv9EX6.d.ts +130 -0
  95. package/dist/{index-DxB74ybJ.d.ts → types-CElwurHZ.d.ts} +139 -88
  96. package/dist/types-CIPaIbZo.d.ts +105 -0
  97. package/dist/types-Cr4uiYo5.d.ts +99 -0
  98. package/dist/types-D9rKQ_as.d.ts +341 -0
  99. package/dist/types-DbolvLtZ.d.ts +155 -0
  100. package/dist/{types-DhQfwiZn.d.ts → types-RT3cuyRk.d.ts} +1 -1
  101. package/dist/vector-store/index.d.ts +33 -34
  102. package/dist/vector-store/index.js +7 -6
  103. package/package.json +10 -14
  104. package/dist/agent-DGYY_onS.d.ts +0 -145
  105. package/dist/audio-generation/index.d.ts +0 -31
  106. package/dist/audio-generation/index.js +0 -8
  107. package/dist/chunk-5XKDW36Z.js.map +0 -1
  108. package/dist/chunk-6WGGTJE6.js +0 -139
  109. package/dist/chunk-6WGGTJE6.js.map +0 -1
  110. package/dist/chunk-A3UBYTJT.js.map +0 -1
  111. package/dist/chunk-ADH7NNCS.js +0 -512
  112. package/dist/chunk-ADH7NNCS.js.map +0 -1
  113. package/dist/chunk-DZ3CKYTH.js +0 -267
  114. package/dist/chunk-DZ3CKYTH.js.map +0 -1
  115. package/dist/chunk-FNQB2JEH.js.map +0 -1
  116. package/dist/chunk-I6G7BC42.js.map +0 -1
  117. package/dist/chunk-IL3ZSNJI.js +0 -3748
  118. package/dist/chunk-IL3ZSNJI.js.map +0 -1
  119. package/dist/chunk-J6GNQART.js +0 -122
  120. package/dist/chunk-J6GNQART.js.map +0 -1
  121. package/dist/chunk-M3IOWB4Y.js +0 -280
  122. package/dist/chunk-M3IOWB4Y.js.map +0 -1
  123. package/dist/chunk-QY5GZ7HR.js +0 -39
  124. package/dist/chunk-QY5GZ7HR.js.map +0 -1
  125. package/dist/chunk-R2LJSQUW.js.map +0 -1
  126. package/dist/chunk-RFDVKCIE.js +0 -12
  127. package/dist/chunk-RFDVKCIE.js.map +0 -1
  128. package/dist/chunk-RMUBRRSK.js +0 -34
  129. package/dist/chunk-RMUBRRSK.js.map +0 -1
  130. package/dist/chunk-RXKHOYEH.js +0 -466
  131. package/dist/chunk-RXKHOYEH.js.map +0 -1
  132. package/dist/chunk-XDRSPSR7.js +0 -38
  133. package/dist/chunk-XDRSPSR7.js.map +0 -1
  134. package/dist/chunk-XWUC7CIT.js +0 -1
  135. package/dist/chunk-XWUC7CIT.js.map +0 -1
  136. package/dist/errors-CYKUcU89.d.ts +0 -17
  137. package/dist/json-Zo7K3xmt.d.ts +0 -40
  138. package/dist/loaders/index.d.ts +0 -86
  139. package/dist/loaders/index.js +0 -299
  140. package/dist/loaders/index.js.map +0 -1
  141. package/dist/middleware-KynLg_RW.d.ts +0 -56
  142. package/dist/types-B3A4YxaA.d.ts +0 -354
  143. package/dist/types-BBEGKB9m.d.ts +0 -119
  144. package/dist/types-DT3nEemY.d.ts +0 -79
  145. package/dist/types-DulRCYdB.d.ts +0 -70
  146. package/dist/types-p55Jc-sr.d.ts +0 -47
  147. package/dist/ui/index.d.ts +0 -107
  148. package/dist/ui/index.js +0 -10
  149. package/dist/ui/index.js.map +0 -1
  150. /package/dist/{chunk-DMPUP4R3.js.map → chunk-LXMAFD23.js.map} +0 -0
  151. /package/dist/{audio-generation → speech-generation}/index.js.map +0 -0
@@ -1,3748 +0,0 @@
1
- import {
2
- isSkillTool
3
- } from "./chunk-YK4WAAS4.js";
4
- import {
5
- assertFiniteSearchThreshold,
6
- assertPositiveSearchLimit,
7
- isToolIndex
8
- } from "./chunk-6WGGTJE6.js";
9
- import {
10
- ToolNotFoundError,
11
- assertToolApprovalRequirement,
12
- createTool,
13
- parseToolArgs,
14
- prepareToolCall,
15
- toolMayRequireApproval,
16
- toolResultContentToText
17
- } from "./chunk-R2LJSQUW.js";
18
- import {
19
- MemoryCompactionConflictError,
20
- MemoryCompactionError,
21
- createMemoryCompactionSummary,
22
- cumulativeCompactedMessageCount,
23
- resolveMemoryOptions
24
- } from "./chunk-5XKDW36Z.js";
25
- import {
26
- mapWithConcurrency
27
- } from "./chunk-DZ3CKYTH.js";
28
- import {
29
- createCompletionRequest,
30
- isStreamingCompletionModel
31
- } from "./chunk-M3IOWB4Y.js";
32
- import {
33
- toProviderJsonSchema
34
- } from "./chunk-RFDVKCIE.js";
35
- import {
36
- AssistantContent,
37
- Message,
38
- ToolContent,
39
- Usage,
40
- assertCompletionRequestSupported,
41
- getAssistantGenerationMetadata,
42
- isProviderTool,
43
- textFromAssistantContent
44
- } from "./chunk-ADH7NNCS.js";
45
- import {
46
- resolveRetryOptions,
47
- retryDelayMs,
48
- retryErrorAttributes,
49
- waitForRetry
50
- } from "./chunk-A3UBYTJT.js";
51
- import {
52
- appendGuardrailPolicies,
53
- hasEnforcedOutputGuardrails,
54
- runInputGuardrails,
55
- runOutputGuardrails
56
- } from "./chunk-FNQB2JEH.js";
57
-
58
- // src/agent/errors.ts
59
- var MaxTurnsError = class extends Error {
60
- constructor(maxTurns, chatHistory, prompt) {
61
- super(`Reached max turn limit: ${maxTurns}`);
62
- this.maxTurns = maxTurns;
63
- this.chatHistory = chatHistory;
64
- this.prompt = prompt;
65
- this.name = "MaxTurnsError";
66
- }
67
- maxTurns;
68
- chatHistory;
69
- prompt;
70
- };
71
- var AgentRunCancelledError = class extends Error {
72
- constructor(chatHistory, reason) {
73
- super(`Agent run cancelled: ${reason}`);
74
- this.chatHistory = chatHistory;
75
- this.reason = reason;
76
- this.name = "AgentRunCancelledError";
77
- }
78
- chatHistory;
79
- reason;
80
- };
81
-
82
- // src/agent/tool-state.ts
83
- var agentToolStates = /* @__PURE__ */ new WeakMap();
84
- function registerAgentToolState(agent, publicState, toolsByName) {
85
- agentToolStates.set(agent, { publicState, toolsByName });
86
- }
87
- function getAgentToolState(agent) {
88
- return getStoredAgentToolState(agent).publicState;
89
- }
90
- function getRegisteredAgentTool(agent, toolName) {
91
- return getStoredAgentToolState(agent).toolsByName.get(toolName);
92
- }
93
- function getStoredAgentToolState(agent) {
94
- const state = agentToolStates.get(agent);
95
- if (state === void 0) {
96
- throw new TypeError("Agent tool state is unavailable.");
97
- }
98
- return state;
99
- }
100
-
101
- // src/hooks/control.ts
102
- function createHook(hook) {
103
- return hook;
104
- }
105
- function cancelRun(reason) {
106
- return { type: "terminate", reason };
107
- }
108
- function skipTool(reason) {
109
- return { type: "skip", reason };
110
- }
111
- function requestToolApproval(options = {}) {
112
- const action = {
113
- type: "approval_request"
114
- };
115
- if (options.reason !== void 0) {
116
- action.reason = options.reason;
117
- }
118
- if (options.rejectMessage !== void 0) {
119
- action.rejectMessage = options.rejectMessage;
120
- }
121
- return action;
122
- }
123
- var runControl = {
124
- continue() {
125
- return { type: "continue" };
126
- },
127
- cancel(reason) {
128
- return cancelRun(reason);
129
- }
130
- };
131
- var toolCallControl = {
132
- run() {
133
- return { type: "continue" };
134
- },
135
- skip(reason) {
136
- return skipTool(reason);
137
- },
138
- cancel(reason) {
139
- return { type: "terminate", reason };
140
- },
141
- requestApproval(options) {
142
- return requestToolApproval(options);
143
- }
144
- };
145
-
146
- // src/internal/agent-runtime/approval-details.ts
147
- var approvalDetails = /* @__PURE__ */ new WeakMap();
148
- function registerAgentApprovalRequestDetails(approval, request) {
149
- approvalDetails.set(approval, request);
150
- }
151
- function getAgentApprovalRequestDetails(approval) {
152
- return approvalDetails.get(approval);
153
- }
154
-
155
- // src/agent/context-index.ts
156
- function createContextIndex(index, options) {
157
- const topK = assertPositiveSearchLimit(options.topK);
158
- const threshold = assertFiniteSearchThreshold(options.threshold);
159
- return Object.freeze({
160
- ...options,
161
- topK,
162
- ...threshold === void 0 ? {} : { threshold },
163
- kind: "context-index",
164
- index
165
- });
166
- }
167
- function isContextIndex(value) {
168
- if (typeof value !== "object" || value === null) {
169
- return false;
170
- }
171
- const candidate = value;
172
- if (candidate.kind !== "context-index" || typeof candidate.index !== "object") {
173
- return false;
174
- }
175
- return candidate.index !== null && typeof candidate.index.search === "function";
176
- }
177
-
178
- // src/internal/agent-runtime/run-options.ts
179
- var internalAgentRunOptions = /* @__PURE__ */ Symbol("internalAgentRunOptions");
180
- function withInternalAgentRunOptions(options, internal) {
181
- return {
182
- ...options,
183
- [internalAgentRunOptions]: internal
184
- };
185
- }
186
- function getInternalAgentRunOptions(options) {
187
- return options[internalAgentRunOptions];
188
- }
189
-
190
- // src/agent/agent.ts
191
- import { z } from "zod";
192
-
193
- // src/agent/lifecycle.ts
194
- function composeAgentLifecycle(first, second) {
195
- if (first === void 0) return second;
196
- if (second === void 0) return first;
197
- return {
198
- async onStart(event) {
199
- await first.onStart?.(lifecycleSnapshot(event));
200
- await second.onStart?.(lifecycleSnapshot(event));
201
- },
202
- async onStepFinish(event) {
203
- await first.onStepFinish?.(lifecycleSnapshot(event));
204
- await second.onStepFinish?.(lifecycleSnapshot(event));
205
- },
206
- async onToolStart(event) {
207
- await first.onToolStart?.(lifecycleSnapshot(event));
208
- await second.onToolStart?.(lifecycleSnapshot(event));
209
- },
210
- async onToolFinish(event) {
211
- await first.onToolFinish?.(lifecycleSnapshot(event));
212
- await second.onToolFinish?.(lifecycleSnapshot(event));
213
- },
214
- async onFinish(event) {
215
- await first.onFinish?.(lifecycleSnapshot(event));
216
- await second.onFinish?.(lifecycleSnapshot(event));
217
- },
218
- async onError(event) {
219
- await first.onError?.(lifecycleSnapshot(event));
220
- await second.onError?.(lifecycleSnapshot(event));
221
- }
222
- };
223
- }
224
- function lifecycleSnapshot(value) {
225
- try {
226
- return globalThis.structuredClone(value);
227
- } catch {
228
- return cloneLifecycleFallback(value, /* @__PURE__ */ new WeakMap());
229
- }
230
- }
231
- function cloneLifecycleFallback(value, seen) {
232
- if (typeof value !== "object" || value === null) {
233
- return value;
234
- }
235
- const existing = seen.get(value);
236
- if (existing !== void 0) {
237
- return existing;
238
- }
239
- if (Array.isArray(value)) {
240
- const clone2 = [];
241
- seen.set(value, clone2);
242
- clone2.push(...value.map((item) => cloneLifecycleFallback(item, seen)));
243
- return clone2;
244
- }
245
- if (Object.getPrototypeOf(value) !== Object.prototype) {
246
- return value;
247
- }
248
- const clone = {};
249
- seen.set(value, clone);
250
- for (const [key, item] of Object.entries(value)) {
251
- clone[key] = cloneLifecycleFallback(item, seen);
252
- }
253
- return clone;
254
- }
255
-
256
- // src/observability/snapshot.ts
257
- function observerSnapshot(value) {
258
- if (containsError(value, /* @__PURE__ */ new WeakSet())) {
259
- return cloneObserverFallback(value, /* @__PURE__ */ new WeakMap());
260
- }
261
- try {
262
- return globalThis.structuredClone(value);
263
- } catch {
264
- return cloneObserverFallback(value, /* @__PURE__ */ new WeakMap());
265
- }
266
- }
267
- function cloneObserverFallback(value, seen) {
268
- if (typeof value !== "object" || value === null) {
269
- return value;
270
- }
271
- const existing = seen.get(value);
272
- if (existing !== void 0) {
273
- return existing;
274
- }
275
- if (Array.isArray(value)) {
276
- const clone2 = [];
277
- seen.set(value, clone2);
278
- clone2.push(...value.map((item) => cloneObserverFallback(item, seen)));
279
- return clone2;
280
- }
281
- if (value instanceof Date) {
282
- return new Date(value.getTime());
283
- }
284
- if (value instanceof Error) {
285
- const clone2 = Object.create(Object.getPrototypeOf(value));
286
- seen.set(value, clone2);
287
- Object.defineProperties(clone2, {
288
- name: { configurable: true, writable: true, value: value.name },
289
- message: { configurable: true, writable: true, value: value.message }
290
- });
291
- if (value.stack !== void 0) {
292
- Object.defineProperty(clone2, "stack", {
293
- configurable: true,
294
- writable: true,
295
- value: value.stack
296
- });
297
- }
298
- if (value.cause !== void 0) {
299
- Object.defineProperty(clone2, "cause", {
300
- configurable: true,
301
- writable: true,
302
- value: cloneObserverFallback(value.cause, seen)
303
- });
304
- }
305
- for (const key of Object.getOwnPropertyNames(value)) {
306
- if (key === "name" || key === "message" || key === "stack" || key === "cause") continue;
307
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
308
- if (descriptor === void 0) continue;
309
- if ("value" in descriptor) {
310
- descriptor.value = cloneObserverFallback(descriptor.value, seen);
311
- }
312
- Object.defineProperty(clone2, key, descriptor);
313
- }
314
- return clone2;
315
- }
316
- if (Object.getPrototypeOf(value) !== Object.prototype) {
317
- return value;
318
- }
319
- const clone = {};
320
- seen.set(value, clone);
321
- for (const [key, item] of Object.entries(value)) {
322
- clone[key] = cloneObserverFallback(item, seen);
323
- }
324
- return clone;
325
- }
326
- function containsError(value, seen) {
327
- if (typeof value !== "object" || value === null) return false;
328
- if (value instanceof Error) return true;
329
- if (seen.has(value)) return false;
330
- seen.add(value);
331
- if (Array.isArray(value)) {
332
- return value.some((item) => containsError(item, seen));
333
- }
334
- if (Object.getPrototypeOf(value) !== Object.prototype) return false;
335
- return Object.values(value).some((item) => containsError(item, seen));
336
- }
337
-
338
- // src/observability/group.ts
339
- async function startAgentRunObservers(registrations, args, failOnObserverError) {
340
- const runObservers = [];
341
- for (const registration of registrations) {
342
- try {
343
- const runObserver = await registration.observer.startRun(observerSnapshot(args));
344
- if (runObserver !== void 0) {
345
- runObservers.push(runObserver);
346
- }
347
- } catch (error) {
348
- if (failOnObserverError || registration.failOnObserverError === true) {
349
- throw error;
350
- }
351
- }
352
- }
353
- return new ActiveAgentRunObservers(runObservers, failOnObserverError);
354
- }
355
- var ActiveAgentRunObservers = class {
356
- constructor(runObservers, failOnObserverError) {
357
- this.runObservers = runObservers;
358
- this.failOnObserverError = failOnObserverError;
359
- this.trace = runObservers.find((observer) => observer.trace !== void 0)?.trace;
360
- }
361
- runObservers;
362
- failOnObserverError;
363
- trace;
364
- async startGeneration(args) {
365
- const generationObservers = [];
366
- for (const runObserver of this.runObservers) {
367
- if (runObserver.startGeneration === void 0) {
368
- continue;
369
- }
370
- try {
371
- const generationObserver = await runObserver.startGeneration(observerSnapshot(args));
372
- if (generationObserver !== void 0) {
373
- generationObservers.push(generationObserver);
374
- }
375
- } catch (error) {
376
- this.handleError(error);
377
- }
378
- }
379
- return new ActiveGenerationObservers(generationObservers, this.failOnObserverError);
380
- }
381
- async startTool(args) {
382
- const toolObservers = [];
383
- for (const runObserver of this.runObservers) {
384
- if (runObserver.startTool === void 0) {
385
- continue;
386
- }
387
- try {
388
- const toolObserver = await runObserver.startTool(observerSnapshot(args));
389
- if (toolObserver !== void 0) {
390
- toolObservers.push(toolObserver);
391
- }
392
- } catch (error) {
393
- this.handleError(error);
394
- }
395
- }
396
- return new ActiveToolObservers(toolObservers, this.failOnObserverError);
397
- }
398
- async end(args) {
399
- for (const runObserver of this.runObservers) {
400
- try {
401
- await runObserver.end(observerSnapshot(args));
402
- } catch (error) {
403
- this.handleError(error);
404
- }
405
- }
406
- }
407
- async error(args) {
408
- for (const runObserver of this.runObservers) {
409
- if (runObserver.error === void 0) {
410
- continue;
411
- }
412
- try {
413
- await runObserver.error(observerSnapshot(args));
414
- } catch (error) {
415
- this.handleError(error);
416
- }
417
- }
418
- }
419
- async event(args) {
420
- for (const runObserver of this.runObservers) {
421
- if (runObserver.event === void 0) {
422
- continue;
423
- }
424
- try {
425
- await runObserver.event(observerSnapshot(args));
426
- } catch (error) {
427
- this.handleError(error);
428
- }
429
- }
430
- }
431
- handleError(error) {
432
- if (this.failOnObserverError) {
433
- throw error;
434
- }
435
- }
436
- };
437
- var ActiveGenerationObservers = class {
438
- constructor(generationObservers, failOnObserverError) {
439
- this.generationObservers = generationObservers;
440
- this.failOnObserverError = failOnObserverError;
441
- }
442
- generationObservers;
443
- failOnObserverError;
444
- async end(args) {
445
- for (const observer of this.generationObservers) {
446
- try {
447
- await observer.end(observerSnapshot(args));
448
- } catch (error) {
449
- this.handleError(error);
450
- }
451
- }
452
- }
453
- async error(args) {
454
- for (const observer of this.generationObservers) {
455
- if (observer.error === void 0) {
456
- continue;
457
- }
458
- try {
459
- await observer.error(observerSnapshot(args));
460
- } catch (error) {
461
- this.handleError(error);
462
- }
463
- }
464
- }
465
- async update(args) {
466
- for (const observer of this.generationObservers) {
467
- if (observer.update === void 0) {
468
- continue;
469
- }
470
- try {
471
- await observer.update(observerSnapshot(args));
472
- } catch (error) {
473
- this.handleError(error);
474
- }
475
- }
476
- }
477
- handleError(error) {
478
- if (this.failOnObserverError) {
479
- throw error;
480
- }
481
- }
482
- };
483
- var ActiveToolObservers = class {
484
- constructor(toolObservers, failOnObserverError) {
485
- this.toolObservers = toolObservers;
486
- this.failOnObserverError = failOnObserverError;
487
- }
488
- toolObservers;
489
- failOnObserverError;
490
- async streamEvent(args) {
491
- for (const observer of this.toolObservers) {
492
- if (observer.streamEvent === void 0) {
493
- continue;
494
- }
495
- try {
496
- await observer.streamEvent(observerSnapshot(args));
497
- } catch (error) {
498
- this.handleError(error);
499
- }
500
- }
501
- }
502
- async end(args) {
503
- for (const observer of this.toolObservers) {
504
- try {
505
- await observer.end(observerSnapshot(args));
506
- } catch (error) {
507
- this.handleError(error);
508
- }
509
- }
510
- }
511
- async error(args) {
512
- for (const observer of this.toolObservers) {
513
- if (observer.error === void 0) {
514
- continue;
515
- }
516
- try {
517
- await observer.error(observerSnapshot(args));
518
- } catch (error) {
519
- this.handleError(error);
520
- }
521
- }
522
- }
523
- handleError(error) {
524
- if (this.failOnObserverError) {
525
- throw error;
526
- }
527
- }
528
- };
529
-
530
- // src/internal/async-queue.ts
531
- function createAsyncQueue() {
532
- const values = [];
533
- const waiters = [];
534
- let closed = false;
535
- let error;
536
- function flush() {
537
- while (waiters.length > 0 && values.length > 0) {
538
- const waiter = waiters.shift();
539
- const value = values.shift();
540
- if (waiter !== void 0) {
541
- waiter.resolve({ value, done: false });
542
- }
543
- }
544
- if (values.length > 0 || waiters.length === 0 || !closed) {
545
- return;
546
- }
547
- while (waiters.length > 0) {
548
- const waiter = waiters.shift();
549
- if (waiter === void 0) {
550
- continue;
551
- }
552
- if (error !== void 0) {
553
- waiter.reject(error);
554
- } else {
555
- waiter.resolve({ value: void 0, done: true });
556
- }
557
- }
558
- }
559
- return {
560
- enqueue(value) {
561
- if (closed) {
562
- return;
563
- }
564
- values.push(value);
565
- flush();
566
- },
567
- close() {
568
- closed = true;
569
- flush();
570
- },
571
- throw(thrown) {
572
- closed = true;
573
- error = thrown;
574
- flush();
575
- },
576
- [Symbol.asyncIterator]() {
577
- return {
578
- next() {
579
- if (values.length > 0) {
580
- const value = values.shift();
581
- return Promise.resolve({ value, done: false });
582
- }
583
- if (error !== void 0) {
584
- return Promise.reject(error);
585
- }
586
- if (closed) {
587
- return Promise.resolve({ value: void 0, done: true });
588
- }
589
- return new Promise((resolve, reject) => {
590
- waiters.push({ resolve, reject });
591
- });
592
- }
593
- };
594
- }
595
- };
596
- }
597
-
598
- // src/internal/rag-text.ts
599
- function extractRagText(message) {
600
- if (message.role === "user") {
601
- return message.content.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n");
602
- }
603
- if (message.role === "tool") {
604
- return message.content.flatMap((item) => item.content.flatMap((part) => part.type === "text" ? [part.text] : [])).join("\n");
605
- }
606
- return void 0;
607
- }
608
-
609
- // src/internal/agent-runtime/memory.ts
610
- var AgentRunMemory = class {
611
- constructor(agent, memoryContext, initialHistory) {
612
- this.agent = agent;
613
- this.memoryContext = memoryContext;
614
- this.initialHistory = initialHistory;
615
- }
616
- agent;
617
- memoryContext;
618
- initialHistory;
619
- memoryPolicy() {
620
- return this.memory()?.options.savePolicy;
621
- }
622
- pendingTurnMessages(newMessages) {
623
- return this.memoryPolicy() === "turn" ? [...newMessages] : [];
624
- }
625
- async prepareHistory(runId, incomingMessageCount) {
626
- const memory = this.memory();
627
- if (memory === void 0 || this.memoryContext === void 0) {
628
- return {
629
- history: this.initialHistory,
630
- usage: Usage.empty()
631
- };
632
- }
633
- const preparation = await this.prepareStoredHistory(memory, runId, incomingMessageCount);
634
- const memoryHistory = preparation.history;
635
- const chatHistory = [...memoryHistory, ...this.initialHistory];
636
- return {
637
- ...preparation,
638
- history: chatHistory
639
- };
640
- }
641
- async commitAcceptedInput(runId, messages) {
642
- const memory = this.memory();
643
- if (memory === void 0 || this.memoryContext === void 0 || memory.options.savePolicy !== "message" || messages.length === 0) {
644
- return;
645
- }
646
- await memory.store.append({
647
- context: this.memoryContext,
648
- runId,
649
- turn: 1,
650
- messages
651
- });
652
- }
653
- async commitMessages(runId, turn, messages, pendingTurnMessages) {
654
- const memory = this.memory();
655
- if (memory === void 0 || this.memoryContext === void 0 || messages.length === 0) {
656
- return;
657
- }
658
- if (memory.options.savePolicy === "message") {
659
- await memory.store.append({
660
- context: this.memoryContext,
661
- runId,
662
- turn,
663
- messages
664
- });
665
- } else if (memory.options.savePolicy === "turn") {
666
- pendingTurnMessages.push(...messages);
667
- }
668
- }
669
- async commitCompletedTurn(runId, turn, pendingTurnMessages) {
670
- const memory = this.memory();
671
- if (memory === void 0 || this.memoryContext === void 0 || memory.options.savePolicy !== "turn" || pendingTurnMessages.length === 0) {
672
- return;
673
- }
674
- await memory.store.append({
675
- context: this.memoryContext,
676
- runId,
677
- turn,
678
- messages: [...pendingTurnMessages]
679
- });
680
- pendingTurnMessages.length = 0;
681
- }
682
- async commitCompletedRun(runId, turn, newMessages, pendingTurnMessages) {
683
- await this.commitCompletedTurn(runId, turn, pendingTurnMessages);
684
- const memory = this.memory();
685
- if (memory === void 0 || this.memoryContext === void 0 || memory.options.savePolicy !== "run") {
686
- return;
687
- }
688
- await memory.store.append({
689
- context: this.memoryContext,
690
- runId,
691
- turn,
692
- messages: [...newMessages]
693
- });
694
- }
695
- async recordError(runId, error, newMessages) {
696
- const memory = this.memory();
697
- if (memory === void 0 || this.memoryContext === void 0) {
698
- return;
699
- }
700
- await memory.store.recordError?.({
701
- context: this.memoryContext,
702
- runId,
703
- error,
704
- messages: [...newMessages]
705
- });
706
- }
707
- memory() {
708
- return this.memoryContext === void 0 ? void 0 : this.agent.memory;
709
- }
710
- async prepareStoredHistory(memory, runId, incomingMessageCount) {
711
- const context = this.memoryContext;
712
- if (context === void 0) {
713
- return { history: [], usage: Usage.empty() };
714
- }
715
- const options = memory.options.compaction;
716
- const capability = memory.store.compaction;
717
- if (options === void 0 || capability === void 0) {
718
- return {
719
- history: await memory.store.load(context),
720
- usage: Usage.empty()
721
- };
722
- }
723
- let usage = Usage.empty();
724
- let conflictRetries = 0;
725
- for (let attempt = 0; attempt <= options.conflictRetries; attempt += 1) {
726
- const snapshot = await capability.load(context);
727
- const compactedMessageCount = compactedPrefixLength(
728
- snapshot.messages,
729
- incomingMessageCount,
730
- options.maxMessages,
731
- options.keepRecentUserTurns
732
- );
733
- if (compactedMessageCount === 0) {
734
- return { history: snapshot.messages, usage };
735
- }
736
- const prefix = snapshot.messages.slice(0, compactedMessageCount);
737
- let result;
738
- try {
739
- result = await options.compactor({
740
- context,
741
- messages: prefix
742
- });
743
- } catch (error) {
744
- throw remappedCompactorError(error, usage);
745
- }
746
- if (result.usage !== void 0) {
747
- usage = Usage.add(usage, result.usage);
748
- }
749
- const summaryText = result.summary.trim();
750
- if (summaryText.length === 0) {
751
- throw new MemoryCompactionError("Memory compactor returned an empty summary.", {
752
- usage
753
- });
754
- }
755
- const summary = createMemoryCompactionSummary(
756
- summaryText,
757
- cumulativeCompactedMessageCount(prefix)
758
- );
759
- let commit;
760
- try {
761
- commit = await capability.commit({
762
- context,
763
- revision: snapshot.revision,
764
- compactedMessageCount,
765
- summary,
766
- runId: `memory-compaction:${runId}:${attempt + 1}`
767
- });
768
- } catch (error) {
769
- throw new MemoryCompactionError("Memory compaction store commit failed.", {
770
- cause: error,
771
- usage
772
- });
773
- }
774
- if (commit === "committed") {
775
- const retained = snapshot.messages.slice(compactedMessageCount);
776
- return {
777
- history: [summary, ...retained],
778
- usage,
779
- compaction: {
780
- originalMessageCount: snapshot.messages.length,
781
- compactedMessageCount,
782
- retainedMessageCount: retained.length,
783
- conflictRetries
784
- }
785
- };
786
- }
787
- conflictRetries += 1;
788
- }
789
- throw new MemoryCompactionConflictError(options.conflictRetries + 1, usage);
790
- }
791
- };
792
- function compactedPrefixLength(messages, incomingMessageCount, maxMessages, keepRecentUserTurns) {
793
- if (messages.length + incomingMessageCount <= maxMessages) {
794
- return 0;
795
- }
796
- const userMessageIndexes = messages.flatMap(
797
- (message, index) => message.role === "user" ? [index] : []
798
- );
799
- if (userMessageIndexes.length <= keepRecentUserTurns) {
800
- return 0;
801
- }
802
- return userMessageIndexes[userMessageIndexes.length - keepRecentUserTurns] ?? 0;
803
- }
804
- function remappedCompactorError(error, usage) {
805
- if (error instanceof MemoryCompactionError) {
806
- const mergedUsage = error.usage === void 0 ? usage : isEmptyUsage(usage) ? error.usage : Usage.add(usage, error.usage);
807
- if (mergedUsage === error.usage || error.usage === void 0 && isEmptyUsage(usage)) {
808
- return error;
809
- }
810
- return new MemoryCompactionError(error.message, {
811
- cause: error,
812
- usage: mergedUsage
813
- });
814
- }
815
- return new MemoryCompactionError("Memory compactor failed.", {
816
- cause: error,
817
- usage
818
- });
819
- }
820
- function isEmptyUsage(usage) {
821
- return usage.inputTokens === 0 && usage.outputTokens === 0 && usage.totalTokens === 0 && usage.cachedInputTokens === 0 && usage.cacheCreationInputTokens === 0;
822
- }
823
-
824
- // src/internal/agent-runtime/retrieval.ts
825
- async function fetchContextDocuments(agent, ragText) {
826
- const documents = [];
827
- for (const input of agent.context) {
828
- if (!isContextIndex(input)) {
829
- documents.push(input);
830
- continue;
831
- }
832
- if (ragText === void 0 || ragText.length === 0) {
833
- continue;
834
- }
835
- const results = await input.index.search({
836
- query: ragText,
837
- topK: input.topK,
838
- threshold: input.threshold,
839
- filter: input.filter
840
- });
841
- for (const result of results) {
842
- const formatted = input.format?.(result);
843
- if (formatted !== void 0) {
844
- documents.push(formatted);
845
- } else {
846
- const metadata = formatMetadata(result.metadata);
847
- const document = {
848
- id: result.id,
849
- text: typeof result.document === "string" ? result.document : JSON.stringify(result.document, null, 2)
850
- };
851
- if (metadata !== void 0) {
852
- document.additionalProps = metadata;
853
- }
854
- documents.push(document);
855
- }
856
- }
857
- }
858
- return documents;
859
- }
860
- async function fetchToolDefinitions(agent, ragText) {
861
- const state = getAgentToolState(agent);
862
- const staticDefinitions = await Promise.all(
863
- state.staticTools.map((tool) => tool.definition(ragText ?? ""))
864
- );
865
- if (ragText === void 0 || ragText.length === 0 || state.toolIndexes.length === 0) {
866
- return staticDefinitions;
867
- }
868
- const definitions = [...staticDefinitions];
869
- const names = new Set(staticDefinitions.map((definition) => definition.name));
870
- for (const index of state.toolIndexes) {
871
- const results = await index.search({
872
- query: ragText,
873
- topK: index.topK,
874
- threshold: index.threshold,
875
- filter: index.filter
876
- });
877
- for (const result of results) {
878
- const toolName = result.document.toolName;
879
- if (names.has(toolName)) {
880
- continue;
881
- }
882
- const tool = index.tools.find((candidate) => candidate.name === toolName);
883
- if (tool === void 0) {
884
- continue;
885
- }
886
- names.add(toolName);
887
- definitions.push(await tool.definition(ragText));
888
- }
889
- }
890
- return definitions;
891
- }
892
- function formatMetadata(metadata) {
893
- if (metadata === void 0) {
894
- return void 0;
895
- }
896
- return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, String(value)]));
897
- }
898
-
899
- // src/internal/agent-runtime/run-validation.ts
900
- function assertNonnegativeSafeInteger(value, name) {
901
- if (!Number.isSafeInteger(value) || value < 0) {
902
- throw new TypeError(`${name} must be a nonnegative safe integer.`);
903
- }
904
- return value;
905
- }
906
- function assertPositiveSafeInteger(value, name) {
907
- if (!Number.isSafeInteger(value) || value <= 0) {
908
- throw new TypeError(`${name} must be a positive safe integer.`);
909
- }
910
- return value;
911
- }
912
-
913
- // src/internal/agent-runtime/stream-accumulator.ts
914
- var CompletionStreamAccumulator = class {
915
- orderedParts = [];
916
- textParts = /* @__PURE__ */ new Map();
917
- reasoningByKey = /* @__PURE__ */ new Map();
918
- reasoningKeyById = /* @__PURE__ */ new Map();
919
- toolCalls = /* @__PURE__ */ new Map();
920
- sources = /* @__PURE__ */ new Map();
921
- providerToolCalls = /* @__PURE__ */ new Map();
922
- finalResponse;
923
- messageId;
924
- nextTextKey = 0;
925
- nextReasoningKey = 0;
926
- accept(event) {
927
- if (event.type === "text_delta") {
928
- this.appendText(event.delta);
929
- return { type: "text_delta", delta: event.delta };
930
- }
931
- if (event.type === "reasoning_delta") {
932
- const reasoning = this.reasoningStateForEvent(event);
933
- this.appendReasoning(reasoning, event);
934
- return reasoningDeltaEvent(event);
935
- }
936
- if (event.type === "tool_call_delta") {
937
- const toolCall = this.toolCallStateForId(event.id);
938
- if (event.callId !== void 0 && event.callId.length > 0) toolCall.callId = event.callId;
939
- if (event.name !== void 0 && event.name.length > 0) toolCall.name = event.name;
940
- if (event.signature !== void 0) toolCall.signature = event.signature;
941
- if (event.argumentsDelta !== void 0) {
942
- if (event.argumentsMode === "replace") {
943
- toolCall.argumentsText = event.argumentsDelta;
944
- } else {
945
- toolCall.argumentsText += event.argumentsDelta;
946
- }
947
- }
948
- return void 0;
949
- }
950
- if (event.type === "tool_call") {
951
- this.upsertToolCall(event.toolCall);
952
- return { type: "tool_call", toolCall: event.toolCall };
953
- }
954
- if (event.type === "source") {
955
- this.sources.set(sourceKey(event.source), event.source);
956
- return { type: "source", source: event.source };
957
- }
958
- if (event.type === "provider_tool_call") {
959
- this.providerToolCalls.set(event.toolCall.id, event.toolCall);
960
- return { type: "provider_tool_call", toolCall: event.toolCall };
961
- }
962
- if (event.type === "message_id") {
963
- this.messageId = event.id;
964
- return void 0;
965
- }
966
- if (event.type === "final") {
967
- this.finalResponse = event.response;
968
- return void 0;
969
- }
970
- return void 0;
971
- }
972
- response() {
973
- const accumulatedResponse = this.buildAccumulatedResponse();
974
- if (this.finalResponse !== void 0) {
975
- if (accumulatedResponse.choice.length === 0) {
976
- return this.withAccumulatedArtifacts(this.finalResponse, accumulatedResponse);
977
- }
978
- return this.mergeFinalResponse(accumulatedResponse, this.finalResponse);
979
- }
980
- return accumulatedResponse;
981
- }
982
- buildAccumulatedResponse() {
983
- const choice = [];
984
- for (const part of this.orderedParts) {
985
- if (part.type === "text") {
986
- const text = this.textParts.get(part.key) ?? "";
987
- if (text.length > 0) {
988
- choice.push({ type: "text", text });
989
- }
990
- continue;
991
- }
992
- if (part.type === "reasoning") {
993
- const reasoning = this.reasoningByKey.get(part.key);
994
- if (reasoning !== void 0) {
995
- choice.push(reasoningContent(reasoning));
996
- }
997
- continue;
998
- }
999
- const toolCall = this.toolCalls.get(part.key);
1000
- if (toolCall !== void 0) {
1001
- choice.push(
1002
- toolCallContent(toolCall, matchingFinalToolCall(toolCall, this.finalResponse?.choice))
1003
- );
1004
- }
1005
- }
1006
- const response = {
1007
- choice,
1008
- usage: Usage.empty(),
1009
- rawResponse: void 0
1010
- };
1011
- if (this.messageId !== void 0) {
1012
- response.messageId = this.messageId;
1013
- }
1014
- const sources = [...this.sources.values()];
1015
- if (sources.length > 0) {
1016
- response.sources = sources;
1017
- }
1018
- const providerToolCalls = [...this.providerToolCalls.values()];
1019
- if (providerToolCalls.length > 0) {
1020
- response.providerToolCalls = providerToolCalls;
1021
- }
1022
- return response;
1023
- }
1024
- upsertToolCall(toolCall) {
1025
- if (!this.toolCalls.has(toolCall.id)) {
1026
- this.orderedParts.push({ type: "tool_call", key: toolCall.id });
1027
- }
1028
- const partial = {
1029
- id: toolCall.id,
1030
- name: toolCall.function.name,
1031
- argumentsText: JSON.stringify(toolCall.function.arguments ?? {})
1032
- };
1033
- if (toolCall.callId !== void 0) {
1034
- partial.callId = toolCall.callId;
1035
- }
1036
- if (toolCall.signature !== void 0) {
1037
- partial.signature = toolCall.signature;
1038
- }
1039
- if (toolCall.additionalParams !== void 0) {
1040
- partial.additionalParams = toolCall.additionalParams;
1041
- }
1042
- this.toolCalls.set(toolCall.id, partial);
1043
- }
1044
- mergeFinalResponse(accumulatedResponse, finalResponse) {
1045
- if (finalResponse.choice.length === 0) {
1046
- const mergedResponse = {
1047
- ...accumulatedResponse,
1048
- usage: finalResponse.usage,
1049
- rawResponse: finalResponse.rawResponse
1050
- };
1051
- if (finalResponse.messageId !== void 0) {
1052
- mergedResponse.messageId = finalResponse.messageId;
1053
- }
1054
- return this.withAccumulatedArtifacts(mergedResponse, accumulatedResponse);
1055
- }
1056
- const finalById = /* @__PURE__ */ new Map();
1057
- const finalByCallId = /* @__PURE__ */ new Map();
1058
- for (const content of finalResponse.choice) {
1059
- if (content.type !== "tool_call") {
1060
- continue;
1061
- }
1062
- finalById.set(content.id, content);
1063
- if (content.callId !== void 0) {
1064
- finalByCallId.set(content.callId, content);
1065
- }
1066
- }
1067
- const matchedFinalToolCalls = /* @__PURE__ */ new Set();
1068
- const choice = accumulatedResponse.choice.map((content) => {
1069
- if (content.type !== "tool_call") {
1070
- return content;
1071
- }
1072
- const finalToolCall = finalById.get(content.id) ?? (content.callId === void 0 ? void 0 : finalByCallId.get(content.callId));
1073
- if (finalToolCall === void 0) {
1074
- return content;
1075
- }
1076
- matchedFinalToolCalls.add(finalToolCall);
1077
- return mergeFinalToolCall(content, finalToolCall);
1078
- });
1079
- for (const content of finalResponse.choice) {
1080
- if (content.type !== "tool_call") {
1081
- continue;
1082
- }
1083
- if (!matchedFinalToolCalls.has(content)) {
1084
- choice.push(content);
1085
- }
1086
- }
1087
- return this.withAccumulatedArtifacts({ ...finalResponse, choice }, accumulatedResponse);
1088
- }
1089
- appendText(delta) {
1090
- const lastPart = this.orderedParts.at(-1);
1091
- const key = lastPart?.type === "text" ? lastPart.key : this.createTextKey();
1092
- if (lastPart?.type !== "text") {
1093
- this.orderedParts.push({ type: "text", key });
1094
- }
1095
- this.textParts.set(key, `${this.textParts.get(key) ?? ""}${delta}`);
1096
- }
1097
- reasoningStateForEvent(event) {
1098
- if (event.id !== void 0) {
1099
- const existingKey = this.reasoningKeyById.get(event.id);
1100
- if (existingKey !== void 0) {
1101
- const existing = this.reasoningByKey.get(existingKey);
1102
- if (existing !== void 0) {
1103
- return existing;
1104
- }
1105
- }
1106
- const key2 = this.createReasoningKey();
1107
- const reasoning2 = { id: event.id, text: "" };
1108
- this.reasoningKeyById.set(event.id, key2);
1109
- this.reasoningByKey.set(key2, reasoning2);
1110
- this.orderedParts.push({ type: "reasoning", key: key2 });
1111
- return reasoning2;
1112
- }
1113
- const lastPart = this.orderedParts.at(-1);
1114
- if (lastPart?.type === "reasoning") {
1115
- const lastReasoning = this.reasoningByKey.get(lastPart.key);
1116
- if (lastReasoning !== void 0 && lastReasoning.id === void 0) {
1117
- return lastReasoning;
1118
- }
1119
- }
1120
- const key = this.createReasoningKey();
1121
- const reasoning = { text: "" };
1122
- this.reasoningByKey.set(key, reasoning);
1123
- this.orderedParts.push({ type: "reasoning", key });
1124
- return reasoning;
1125
- }
1126
- toolCallStateForId(id) {
1127
- const existing = this.toolCalls.get(id);
1128
- if (existing !== void 0) {
1129
- return existing;
1130
- }
1131
- const toolCall = {
1132
- id,
1133
- name: "",
1134
- argumentsText: ""
1135
- };
1136
- this.toolCalls.set(id, toolCall);
1137
- this.orderedParts.push({ type: "tool_call", key: id });
1138
- return toolCall;
1139
- }
1140
- withMessageIdFallback(response, accumulatedResponse) {
1141
- if (response.messageId !== void 0 || accumulatedResponse.messageId === void 0) {
1142
- return response;
1143
- }
1144
- return { ...response, messageId: accumulatedResponse.messageId };
1145
- }
1146
- withAccumulatedArtifacts(response, accumulatedResponse) {
1147
- const withMessageId = this.withMessageIdFallback(response, accumulatedResponse);
1148
- const sources = mergeSources(accumulatedResponse.sources, response.sources);
1149
- const providerToolCalls = mergeProviderToolCalls(
1150
- accumulatedResponse.providerToolCalls,
1151
- response.providerToolCalls
1152
- );
1153
- return {
1154
- ...withMessageId,
1155
- ...sources.length === 0 ? {} : { sources },
1156
- ...providerToolCalls.length === 0 ? {} : { providerToolCalls }
1157
- };
1158
- }
1159
- createTextKey() {
1160
- this.nextTextKey += 1;
1161
- return `text_${this.nextTextKey.toString()}`;
1162
- }
1163
- createReasoningKey() {
1164
- this.nextReasoningKey += 1;
1165
- return `reasoning_${this.nextReasoningKey.toString()}`;
1166
- }
1167
- appendReasoning(reasoning, event) {
1168
- const contentType = event.contentType ?? "text";
1169
- if (contentType === "text" || contentType === "summary") {
1170
- reasoning.text += event.delta;
1171
- }
1172
- if (event.contentType === void 0 && event.signature === void 0) {
1173
- return;
1174
- }
1175
- reasoning.content ??= [];
1176
- const last = reasoning.content.at(-1);
1177
- if (contentType === "text") {
1178
- if (last?.type === "text") {
1179
- last.text += event.delta;
1180
- if (event.signature !== void 0) {
1181
- last.signature = event.signature;
1182
- }
1183
- } else {
1184
- reasoning.content.push(
1185
- event.signature === void 0 ? { type: "text", text: event.delta } : { type: "text", text: event.delta, signature: event.signature }
1186
- );
1187
- }
1188
- return;
1189
- }
1190
- if (contentType === "summary") {
1191
- if (last?.type === "summary") {
1192
- last.text += event.delta;
1193
- } else {
1194
- reasoning.content.push({ type: "summary", text: event.delta });
1195
- }
1196
- return;
1197
- }
1198
- if (contentType === "encrypted") {
1199
- reasoning.content.push({ type: "encrypted", data: event.delta });
1200
- return;
1201
- }
1202
- reasoning.content.push({ type: "redacted", data: event.delta });
1203
- }
1204
- };
1205
- function sourceKey(source) {
1206
- return `${source.url}\0${source.startIndex ?? ""}\0${source.endIndex ?? ""}`;
1207
- }
1208
- function mergeSources(accumulated, final) {
1209
- const sources = /* @__PURE__ */ new Map();
1210
- for (const source of [...accumulated ?? [], ...final ?? []]) {
1211
- sources.set(sourceKey(source), source);
1212
- }
1213
- return [...sources.values()];
1214
- }
1215
- function mergeProviderToolCalls(accumulated, final) {
1216
- const toolCalls = /* @__PURE__ */ new Map();
1217
- for (const toolCall of [...accumulated ?? [], ...final ?? []]) {
1218
- toolCalls.set(toolCall.id, toolCall);
1219
- }
1220
- return [...toolCalls.values()];
1221
- }
1222
- function reasoningContent(reasoning) {
1223
- const content = reasoning.content === void 0 ? { type: "reasoning", text: reasoning.text } : { type: "reasoning", text: reasoning.text, content: reasoning.content };
1224
- return reasoning.id === void 0 ? content : { ...content, id: reasoning.id };
1225
- }
1226
- function toolCallContent(toolCall, finalToolCall) {
1227
- const argumentsValue = finalToolCall !== void 0 && !isEmptyToolArguments(finalToolCall.function.arguments) ? finalToolCall.function.arguments : parseToolArguments(toolCall.id, toolCall.argumentsText);
1228
- const content = {
1229
- type: "tool_call",
1230
- id: toolCall.id,
1231
- function: {
1232
- name: toolCall.name,
1233
- arguments: argumentsValue
1234
- }
1235
- };
1236
- if (toolCall.callId !== void 0) {
1237
- content.callId = toolCall.callId;
1238
- }
1239
- if (toolCall.signature !== void 0) {
1240
- content.signature = toolCall.signature;
1241
- }
1242
- if (toolCall.additionalParams !== void 0) {
1243
- content.additionalParams = toolCall.additionalParams;
1244
- }
1245
- return content;
1246
- }
1247
- function matchingFinalToolCall(accumulated, finalChoice) {
1248
- const byId = finalChoice?.find(
1249
- (content) => content.type === "tool_call" && content.id === accumulated.id
1250
- );
1251
- if (byId !== void 0 || accumulated.callId === void 0) {
1252
- return byId;
1253
- }
1254
- return finalChoice?.find(
1255
- (content) => content.type === "tool_call" && content.callId === accumulated.callId
1256
- );
1257
- }
1258
- function mergeFinalToolCall(accumulated, finalToolCall) {
1259
- const argumentsValue = isEmptyToolArguments(finalToolCall.function.arguments) ? accumulated.function.arguments : finalToolCall.function.arguments;
1260
- return {
1261
- ...accumulated,
1262
- ...finalToolCall,
1263
- function: {
1264
- ...accumulated.function,
1265
- ...finalToolCall.function,
1266
- arguments: argumentsValue
1267
- }
1268
- };
1269
- }
1270
- function reasoningDeltaEvent(event) {
1271
- const mapped = { type: "reasoning_delta", delta: event.delta };
1272
- if (event.id !== void 0) mapped.id = event.id;
1273
- if (event.contentType !== void 0) mapped.contentType = event.contentType;
1274
- if (event.signature !== void 0) mapped.signature = event.signature;
1275
- return mapped;
1276
- }
1277
- function isEmptyToolArguments(value) {
1278
- if (value === void 0 || value === null) {
1279
- return true;
1280
- }
1281
- if (typeof value === "string") {
1282
- return value.trim().length === 0;
1283
- }
1284
- if (Array.isArray(value)) {
1285
- return value.length === 0;
1286
- }
1287
- if (typeof value === "object") {
1288
- return Object.values(value).every((item) => item === void 0);
1289
- }
1290
- return false;
1291
- }
1292
- function parseToolArguments(toolCallId, text) {
1293
- if (text.trim().length === 0) {
1294
- return {};
1295
- }
1296
- try {
1297
- return JSON.parse(text);
1298
- } catch {
1299
- throw new Error(
1300
- `Completion returned tool call "${toolCallId}" with malformed JSON arguments; this indicates invalid provider output or incomplete stream assembly.`
1301
- );
1302
- }
1303
- }
1304
-
1305
- // src/internal/agent-runtime/stream-events.ts
1306
- function addTurn(turn, event) {
1307
- if (event.type === "text_delta") {
1308
- return { type: "text_delta", turn, delta: event.delta };
1309
- }
1310
- if (event.type === "reasoning_delta") {
1311
- const mapped = { type: "reasoning_delta", turn, delta: event.delta };
1312
- if (event.id !== void 0) mapped.id = event.id;
1313
- if (event.contentType !== void 0) mapped.contentType = event.contentType;
1314
- if (event.signature !== void 0) mapped.signature = event.signature;
1315
- return mapped;
1316
- }
1317
- if (event.type === "source") {
1318
- return { type: "source", turn, source: event.source };
1319
- }
1320
- if (event.type === "provider_tool_call") {
1321
- return { type: "provider_tool_call", turn, toolCall: event.toolCall };
1322
- }
1323
- return { type: "tool_call", turn, toolCall: event.toolCall };
1324
- }
1325
- function addTurnToToolCallDelta(turn, event) {
1326
- const mapped = {
1327
- type: "tool_call_delta",
1328
- turn,
1329
- id: event.id
1330
- };
1331
- if (event.callId !== void 0) mapped.callId = event.callId;
1332
- if (event.name !== void 0) mapped.name = event.name;
1333
- if (event.argumentsDelta !== void 0) mapped.argumentsDelta = event.argumentsDelta;
1334
- if (event.argumentsMode !== void 0) mapped.argumentsMode = event.argumentsMode;
1335
- if (event.signature !== void 0) mapped.signature = event.signature;
1336
- return mapped;
1337
- }
1338
- function isGenerationDeltaEvent(type) {
1339
- return type === "text_delta" || type === "reasoning_delta" || type === "tool_call_delta" || type === "tool_call" || type === "source" || type === "provider_tool_call";
1340
- }
1341
-
1342
- // src/internal/agent-runtime/tool-execution.ts
1343
- var MCP_TOOL_METADATA_KEY = /* @__PURE__ */ Symbol.for("anvia.mcp.tool.metadata");
1344
- var ToolCallExecutor = class {
1345
- constructor(agent, activeHook, approvalHandler, lifecycle, runContext, concurrency, requestMiddlewares, includeToolCallDeltas, cancel) {
1346
- this.agent = agent;
1347
- this.activeHook = activeHook;
1348
- this.approvalHandler = approvalHandler;
1349
- this.lifecycle = lifecycle;
1350
- this.runContext = runContext;
1351
- this.concurrency = concurrency;
1352
- this.requestMiddlewares = requestMiddlewares;
1353
- this.includeToolCallDeltas = includeToolCallDeltas;
1354
- this.cancel = cancel;
1355
- }
1356
- agent;
1357
- activeHook;
1358
- approvalHandler;
1359
- lifecycle;
1360
- runContext;
1361
- concurrency;
1362
- requestMiddlewares;
1363
- includeToolCallDeltas;
1364
- cancel;
1365
- async execute(toolCalls, onResult, onStreamEvent, observation) {
1366
- for (const toolCall of toolCalls) {
1367
- if (toolCall.function.name.length === 0) {
1368
- throw new Error(
1369
- `Completion returned tool call "${toolCall.id}" with an empty function name; this indicates invalid provider output or provider mapping.`
1370
- );
1371
- }
1372
- }
1373
- return mapWithConcurrency(toolCalls, this.concurrency, async (toolCall) => {
1374
- const args = JSON.stringify(toolCall.function.arguments ?? {});
1375
- const internalCallId = globalThis.crypto.randomUUID();
1376
- const hookArgs = {
1377
- toolName: toolCall.function.name,
1378
- internalCallId,
1379
- args
1380
- };
1381
- if (toolCall.callId !== void 0) {
1382
- hookArgs.toolCallId = toolCall.callId;
1383
- }
1384
- const tool = this.agent.getTool(toolCall.function.name);
1385
- const toolDefinition = observation?.toolDefinitions?.find(
1386
- (definition) => definition.name === toolCall.function.name
1387
- );
1388
- const toolMetadata = toolTraceMetadata(tool);
1389
- const toolStartArgs = {
1390
- turn: observation?.turn ?? 0,
1391
- toolCall,
1392
- toolName: toolCall.function.name,
1393
- internalCallId,
1394
- args,
1395
- ...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId },
1396
- ...toolDefinition === void 0 ? {} : { toolDefinition },
1397
- ...toolMetadata === void 0 ? {} : { toolMetadata }
1398
- };
1399
- const toolObservers = await observation?.runObservers.startTool(toolStartArgs);
1400
- const toolObservation = new ToolObserverScope(toolObservers);
1401
- let output;
1402
- let skipped = false;
1403
- let toolExecutionFailed = false;
1404
- let effectiveArgs = args;
1405
- try {
1406
- const callAction = await this.activeHook?.onToolCall?.({
1407
- ...hookArgs,
1408
- tool: toolCallControl
1409
- });
1410
- if (callAction?.type === "terminate") {
1411
- throw this.cancel(callAction.reason);
1412
- }
1413
- if (callAction?.type === "skip") {
1414
- output = callAction.reason;
1415
- skipped = true;
1416
- } else {
1417
- try {
1418
- effectiveArgs = await this.runToolInputMiddlewares({
1419
- ...hookArgs,
1420
- turn: observation?.turn ?? 0,
1421
- originalArgs: args
1422
- });
1423
- hookArgs.args = effectiveArgs;
1424
- let prepared;
1425
- try {
1426
- prepared = this.prepareToolCall(tool, toolCall.function.name, effectiveArgs);
1427
- } catch (error) {
1428
- const outcome = await this.handleToolError(
1429
- toolCall,
1430
- hookArgs,
1431
- effectiveArgs,
1432
- error,
1433
- toolObservation,
1434
- observation
1435
- );
1436
- output = outcome.output;
1437
- toolExecutionFailed = outcome.failed;
1438
- }
1439
- if (prepared !== void 0) {
1440
- const approvalContext = createApprovalContext(
1441
- prepared.input,
1442
- hookArgs,
1443
- this.agent,
1444
- this.runContext
1445
- );
1446
- const approvalDecision = callAction?.type === "approval_request" ? await this.requestApproval(approvalContext, callAction, observation) : await this.evaluateToolApproval(tool, approvalContext, observation) ?? {
1447
- approved: true
1448
- };
1449
- if (!approvalDecision.approved) {
1450
- output = approvalDecision.result;
1451
- skipped = true;
1452
- } else {
1453
- const step = observation?.turn ?? 0;
1454
- const lifecycleEvent = {
1455
- runId: this.runContext.runId,
1456
- step,
1457
- toolName: toolCall.function.name,
1458
- input: lifecycleSnapshot(prepared.input),
1459
- ...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId }
1460
- };
1461
- await this.lifecycle?.onToolStart?.(lifecycleEvent);
1462
- const startedAt = Date.now();
1463
- const outcome = await this.runApprovedToolCall(
1464
- prepared,
1465
- toolCall,
1466
- hookArgs,
1467
- effectiveArgs,
1468
- toolObservation,
1469
- observation,
1470
- onStreamEvent
1471
- );
1472
- output = outcome.output;
1473
- toolExecutionFailed = outcome.failed;
1474
- const durationMs = Date.now() - startedAt;
1475
- await this.lifecycle?.onToolFinish?.(
1476
- outcome.failed ? {
1477
- ...lifecycleEvent,
1478
- durationMs,
1479
- success: false,
1480
- error: lifecycleSnapshot(outcome.error)
1481
- } : {
1482
- ...lifecycleEvent,
1483
- durationMs,
1484
- success: true,
1485
- output: lifecycleSnapshot(output)
1486
- }
1487
- );
1488
- }
1489
- }
1490
- } catch (error) {
1491
- await toolObservation.error(
1492
- toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
1493
- );
1494
- throw error;
1495
- }
1496
- }
1497
- if (output === void 0) {
1498
- throw new Error(`Tool "${toolCall.function.name}" did not produce an execution result.`);
1499
- }
1500
- let result = toolOutputToText(output);
1501
- let structuredResult = toolOutputToStructuredResult(output);
1502
- if (!isSkillTool(tool)) {
1503
- const middlewareReplacement = await this.runToolResultMiddlewares({
1504
- ...hookArgs,
1505
- args: effectiveArgs,
1506
- result,
1507
- originalResult: result,
1508
- structuredResult,
1509
- originalStructuredResult: structuredResult,
1510
- turn: observation?.turn ?? 0
1511
- });
1512
- if (middlewareReplacement !== void 0) {
1513
- output = middlewareReplacement;
1514
- result = toolOutputToText(middlewareReplacement);
1515
- structuredResult = toolOutputToStructuredResult(middlewareReplacement);
1516
- }
1517
- }
1518
- const resultAction = await this.activeHook?.onToolResult?.({
1519
- ...hookArgs,
1520
- args: effectiveArgs,
1521
- result,
1522
- structuredResult,
1523
- run: runControl
1524
- });
1525
- if (!toolExecutionFailed) {
1526
- await toolObservation.end({
1527
- turn: observation?.turn ?? 0,
1528
- toolCall,
1529
- toolName: toolCall.function.name,
1530
- internalCallId,
1531
- args: effectiveArgs,
1532
- result,
1533
- structuredResult,
1534
- skipped,
1535
- toolCallId: toolCall.callId
1536
- });
1537
- }
1538
- if (resultAction?.type === "terminate") {
1539
- throw this.cancel(resultAction.reason);
1540
- }
1541
- const resultPayload = {
1542
- type: "tool_result",
1543
- toolName: toolCall.function.name,
1544
- internalCallId,
1545
- args: effectiveArgs,
1546
- result,
1547
- structuredResult
1548
- };
1549
- if (toolCall.callId !== void 0) {
1550
- resultPayload.toolCallId = toolCall.callId;
1551
- }
1552
- onResult?.(resultPayload);
1553
- return ToolContent.toolResult(toolCall.id, output, {
1554
- callId: toolCall.callId,
1555
- toolName: toolCall.function.name
1556
- });
1557
- } catch (error) {
1558
- await toolObservation.error(
1559
- toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
1560
- );
1561
- throw error;
1562
- }
1563
- });
1564
- }
1565
- async runApprovedToolCall(prepared, toolCall, hookArgs, effectiveArgs, toolObservation, observation, onStreamEvent) {
1566
- try {
1567
- const toolContext = {
1568
- emitStreamEvent: async (event) => {
1569
- const streamEventArgs = {
1570
- turn: observation?.turn ?? 0,
1571
- toolCall,
1572
- toolName: toolCall.function.name,
1573
- internalCallId: hookArgs.internalCallId,
1574
- args: effectiveArgs,
1575
- event,
1576
- ...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId }
1577
- };
1578
- await toolObservation.streamEvent(streamEventArgs);
1579
- const payload = agentToolEventPayload(toolCall, hookArgs.internalCallId, event);
1580
- if (payload !== void 0) {
1581
- onStreamEvent?.(payload);
1582
- }
1583
- }
1584
- };
1585
- toolContext.includeToolCallDeltas = this.includeToolCallDeltas;
1586
- return {
1587
- output: await prepared.call(toolContext),
1588
- failed: false
1589
- };
1590
- } catch (error) {
1591
- return this.handleToolError(
1592
- toolCall,
1593
- hookArgs,
1594
- effectiveArgs,
1595
- error,
1596
- toolObservation,
1597
- observation
1598
- );
1599
- }
1600
- }
1601
- prepareToolCall(tool, toolName, args) {
1602
- if (tool !== void 0) {
1603
- return prepareToolCall(tool, args);
1604
- }
1605
- const input = parseToolArgs(args);
1606
- return {
1607
- input,
1608
- call: (context) => this.agent.callTool(toolName, args, context)
1609
- };
1610
- }
1611
- async handleToolError(toolCall, hookArgs, args, error, toolObservation, observation) {
1612
- const errorAction = await this.activeHook?.onToolError?.({
1613
- ...hookArgs,
1614
- args,
1615
- error,
1616
- run: runControl
1617
- });
1618
- await toolObservation.error(
1619
- toolErrorArgs(observation?.turn ?? 0, toolCall, hookArgs.internalCallId, args, error)
1620
- );
1621
- if (errorAction?.type === "terminate") {
1622
- throw this.cancel(errorAction.reason);
1623
- }
1624
- return {
1625
- output: error instanceof Error ? error.toString() : String(error),
1626
- failed: true,
1627
- error
1628
- };
1629
- }
1630
- async runToolResultMiddlewares(args) {
1631
- let result = args.result;
1632
- let structuredResult = args.structuredResult;
1633
- let replaced = false;
1634
- for (const middleware of this.activeMiddlewares()) {
1635
- const outputReplacement = await middleware.onToolOutput?.({
1636
- ...args,
1637
- result,
1638
- structuredResult
1639
- });
1640
- if (outputReplacement !== void 0) {
1641
- const normalized = normalizeToolOutputMiddlewareResult(outputReplacement);
1642
- if (normalized.result !== void 0) {
1643
- result = normalized.result;
1644
- structuredResult = void 0;
1645
- }
1646
- if (normalized.structuredResult !== void 0) {
1647
- structuredResult = normalized.structuredResult;
1648
- result = toolResultContentToText(normalized.structuredResult);
1649
- }
1650
- replaced = true;
1651
- }
1652
- }
1653
- return replaced ? structuredResult ?? result : void 0;
1654
- }
1655
- async runToolInputMiddlewares(args) {
1656
- let current = args.args;
1657
- for (const middleware of this.activeMiddlewares()) {
1658
- const replacement = await middleware.onToolInput?.({
1659
- ...args,
1660
- args: current
1661
- });
1662
- if (replacement?.args !== void 0) {
1663
- current = typeof replacement.args === "string" ? replacement.args : JSON.stringify(replacement.args);
1664
- }
1665
- }
1666
- return current;
1667
- }
1668
- activeMiddlewares() {
1669
- return [...this.agent.middlewares, ...this.requestMiddlewares];
1670
- }
1671
- async evaluateToolApproval(tool, context, observation) {
1672
- const requirement = tool?.requiresApproval;
1673
- if (requirement === void 0) return void 0;
1674
- const resolved = typeof requirement === "function" ? await requirement(context.args, context) : requirement;
1675
- assertToolApprovalRequirement(resolved, { allowFunction: false });
1676
- if (resolved === false) return { approved: true };
1677
- const reason = resolved === true ? void 0 : resolved.reason;
1678
- return this.requestApproval(context, reason === void 0 ? {} : { reason }, observation);
1679
- }
1680
- async requestApproval(context, options, observation) {
1681
- const request = {
1682
- ...context,
1683
- id: globalThis.crypto.randomUUID()
1684
- };
1685
- if (options.reason !== void 0) {
1686
- request.reason = options.reason;
1687
- }
1688
- if (options.rejectMessage !== void 0) {
1689
- request.rejectMessage = options.rejectMessage;
1690
- }
1691
- await observation?.runObservers.event({
1692
- name: "tool.approval_requested",
1693
- attributes: approvalEventAttributes(request, observation.turn)
1694
- });
1695
- let decision;
1696
- try {
1697
- decision = await this.approvalHandler(request);
1698
- } catch (error) {
1699
- await observation?.runObservers.event({
1700
- name: "tool.approval_failed",
1701
- level: "ERROR",
1702
- attributes: {
1703
- ...approvalEventAttributes(request, observation.turn),
1704
- errorName: error instanceof Error ? error.name : typeof error
1705
- }
1706
- });
1707
- throw error;
1708
- }
1709
- await observation?.runObservers.event({
1710
- name: "tool.approval_resolved",
1711
- attributes: {
1712
- ...approvalEventAttributes(request, observation.turn),
1713
- approved: decision.approved,
1714
- ...decision.reason === void 0 ? {} : { decisionReason: decision.reason }
1715
- }
1716
- });
1717
- if (decision.approved) {
1718
- return { approved: true };
1719
- }
1720
- return {
1721
- approved: false,
1722
- result: decision.reason ?? request.rejectMessage ?? "Tool approval was rejected."
1723
- };
1724
- }
1725
- };
1726
- function createApprovalContext(input, hookArgs, agent, run) {
1727
- const approvalRun = {
1728
- agentId: agent.id,
1729
- runId: run.runId
1730
- };
1731
- if (run.sessionId !== void 0) {
1732
- approvalRun.sessionId = run.sessionId;
1733
- }
1734
- if (run.metadata !== void 0) {
1735
- approvalRun.metadata = run.metadata;
1736
- }
1737
- const context = {
1738
- toolName: hookArgs.toolName,
1739
- args: lifecycleSnapshot(input),
1740
- rawArgs: hookArgs.args,
1741
- internalCallId: hookArgs.internalCallId,
1742
- run: approvalRun
1743
- };
1744
- if (hookArgs.toolCallId !== void 0) {
1745
- context.toolCallId = hookArgs.toolCallId;
1746
- }
1747
- return context;
1748
- }
1749
- function approvalEventAttributes(request, turn) {
1750
- return {
1751
- turn,
1752
- approvalId: request.id,
1753
- toolName: request.toolName,
1754
- toolCallId: request.toolCallId,
1755
- internalCallId: request.internalCallId,
1756
- reason: request.reason
1757
- };
1758
- }
1759
- function normalizeToolOutputMiddlewareResult(result) {
1760
- if (typeof result === "string") {
1761
- return { result };
1762
- }
1763
- return result ?? {};
1764
- }
1765
- function toolTraceMetadata(tool) {
1766
- if (tool === void 0) {
1767
- return void 0;
1768
- }
1769
- const metadata = tool[MCP_TOOL_METADATA_KEY];
1770
- const mcpMetadata = typeof metadata === "object" && metadata !== null ? metadata : void 0;
1771
- const result = {
1772
- approvalRequired: toolMayRequireApproval(tool.requiresApproval)
1773
- };
1774
- if (typeof mcpMetadata?.serverName === "string" && mcpMetadata.serverName.length > 0) {
1775
- result.mcpServerName = mcpMetadata.serverName;
1776
- }
1777
- return result;
1778
- }
1779
- function toolErrorArgs(turn, toolCall, internalCallId, args, error) {
1780
- const observerArgs = {
1781
- turn,
1782
- toolCall,
1783
- toolName: toolCall.function.name,
1784
- internalCallId,
1785
- args,
1786
- error,
1787
- ...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId }
1788
- };
1789
- return observerArgs;
1790
- }
1791
- var ToolObserverScope = class {
1792
- constructor(observers) {
1793
- this.observers = observers;
1794
- }
1795
- observers;
1796
- terminal = false;
1797
- streamEvent(args) {
1798
- return this.observers?.streamEvent(args);
1799
- }
1800
- async end(args) {
1801
- if (this.terminal) return;
1802
- this.terminal = true;
1803
- await this.observers?.end(args);
1804
- }
1805
- async error(args) {
1806
- if (this.terminal) return;
1807
- this.terminal = true;
1808
- await this.observers?.error(args);
1809
- }
1810
- };
1811
- function toolOutputToText(output) {
1812
- return typeof output === "string" ? output : toolResultContentToText(output);
1813
- }
1814
- function toolOutputToStructuredResult(output) {
1815
- return typeof output === "string" ? void 0 : output;
1816
- }
1817
- function agentToolEventPayload(toolCall, internalCallId, event) {
1818
- if (typeof event.agentId !== "string" || event.agentId.length === 0) {
1819
- return void 0;
1820
- }
1821
- const payload = {
1822
- type: "agent_tool_event",
1823
- toolName: toolCall.function.name,
1824
- internalCallId,
1825
- agentId: event.agentId,
1826
- event: event.event
1827
- };
1828
- if (toolCall.callId !== void 0) {
1829
- payload.toolCallId = toolCall.callId;
1830
- }
1831
- if (event.agentName !== void 0) {
1832
- payload.agentName = event.agentName;
1833
- }
1834
- return payload;
1835
- }
1836
-
1837
- // src/internal/agent-runtime/agent-run.ts
1838
- function deferredSignal() {
1839
- let resolve = () => {
1840
- };
1841
- const promise = new Promise((done) => {
1842
- resolve = done;
1843
- });
1844
- return { promise, resolve };
1845
- }
1846
- async function settleFailureCleanup(operations) {
1847
- for (const operation of operations) {
1848
- try {
1849
- await operation();
1850
- } catch {
1851
- }
1852
- }
1853
- }
1854
- var AgentRun = class _AgentRun {
1855
- constructor(agent, promptMessage, initialHistory = [], options = {}) {
1856
- this.agent = agent;
1857
- this.promptMessage = promptMessage;
1858
- this.chatHistory = initialHistory;
1859
- this.maxTurnCount = assertNonnegativeSafeInteger(
1860
- options.maxTurns ?? agent.defaultMaxTurns ?? 0,
1861
- "maxTurns"
1862
- );
1863
- const internalOptions = getInternalAgentRunOptions(options);
1864
- this.activeHook = internalOptions?.hook;
1865
- this.requestedRunId = normalizeRequestedRunId(internalOptions?.runId);
1866
- this.activeLifecycle = composeAgentLifecycle(agent.lifecycle, options.lifecycle);
1867
- this.guardrailPolicies = options.guardrails === void 0 ? [...agent.guardrails] : appendGuardrailPolicies([...agent.guardrails], options.guardrails);
1868
- const configuredConcurrency = assertPositiveSafeInteger(
1869
- options.toolConcurrency ?? 1,
1870
- "toolConcurrency"
1871
- );
1872
- this.concurrency = this.activeHook !== void 0 || agent.tools.some((tool) => toolMayRequireApproval(tool.requiresApproval)) ? 1 : configuredConcurrency;
1873
- this.traceOptions = options.trace;
1874
- this.completionRetryOptions = options.retries === void 0 ? void 0 : resolveRetryOptions(options.retries);
1875
- this.requestMiddlewares = [...options.middlewares ?? []];
1876
- this.memoryContext = options.memoryContext;
1877
- this.memoryRecorder = new AgentRunMemory(agent, options.memoryContext, initialHistory);
1878
- }
1879
- agent;
1880
- promptMessage;
1881
- chatHistory;
1882
- maxTurnCount;
1883
- activeHook;
1884
- activeLifecycle;
1885
- guardrailPolicies;
1886
- guardrailDecisions = [];
1887
- concurrency;
1888
- traceOptions;
1889
- completionRetryOptions;
1890
- requestMiddlewares;
1891
- steeringMessages = [];
1892
- runState = "idle";
1893
- memoryRecorder;
1894
- memoryContext;
1895
- pendingApproval;
1896
- approvalSignal = deferredSignal();
1897
- activeRunId;
1898
- requestedRunId;
1899
- currentUsage = Usage.empty();
1900
- currentMessages = [];
1901
- cancellationError;
1902
- activeGeneration;
1903
- static fromAgent(agent, input, options = {}) {
1904
- const normalized = normalizeAgentInput(input);
1905
- return new _AgentRun(agent, normalized.prompt, normalized.history, options);
1906
- }
1907
- steer(input) {
1908
- if (this.isTerminal() || this.cancellationError !== void 0) {
1909
- return false;
1910
- }
1911
- this.steeringMessages.push(...normalizeSteeringInput(input));
1912
- return true;
1913
- }
1914
- waitForApproval() {
1915
- return this.pendingApproval === void 0 ? this.approvalSignal.promise : Promise.resolve();
1916
- }
1917
- approvalResult() {
1918
- const snapshot = this.approvalSnapshot();
1919
- return { status: "approval_required", ...snapshot };
1920
- }
1921
- approvalEvent() {
1922
- const snapshot = this.approvalSnapshot();
1923
- return { type: "approval_required", ...snapshot };
1924
- }
1925
- resolveApproval(decision) {
1926
- const pending = this.pendingApproval;
1927
- if (pending === void 0) {
1928
- throw new TypeError("Agent run has no pending tool approval.");
1929
- }
1930
- this.pendingApproval = void 0;
1931
- this.approvalSignal = deferredSignal();
1932
- pending.resolve(decision);
1933
- }
1934
- cancel(reason) {
1935
- if (this.isTerminal() || this.cancellationError !== void 0) {
1936
- return;
1937
- }
1938
- const messages = this.currentMessages.length === 0 ? [this.promptMessage] : [...this.currentMessages];
1939
- const error = new AgentRunCancelledError([...this.chatHistory, ...messages], reason);
1940
- this.cancellationError = error;
1941
- const pending = this.pendingApproval;
1942
- if (pending !== void 0) {
1943
- this.pendingApproval = void 0;
1944
- this.approvalSignal = deferredSignal();
1945
- pending.reject(error);
1946
- }
1947
- }
1948
- async generate() {
1949
- this.startRun();
1950
- const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();
1951
- this.activeRunId = runId;
1952
- let usage = Usage.empty();
1953
- let currentTurns = 0;
1954
- let lastPrompt = this.promptMessage;
1955
- let newMessages = [this.promptMessage];
1956
- let runObservers;
1957
- try {
1958
- const memoryPreparation = await this.memoryRecorder.prepareHistory(runId, newMessages.length);
1959
- this.chatHistory = memoryPreparation.history;
1960
- usage = Usage.add(usage, memoryPreparation.usage);
1961
- runObservers = await this.startRunObservers(runId);
1962
- await this.recordMemoryCompaction(memoryPreparation, runObservers);
1963
- await this.activeLifecycle?.onStart?.({
1964
- runId,
1965
- input: lifecycleSnapshot(this.promptMessage),
1966
- history: lifecycleSnapshot(this.chatHistory),
1967
- maxTurns: this.maxTurnCount
1968
- });
1969
- const inputResult = await runInputGuardrails(this.guardrailPolicies, {
1970
- prompt: this.promptMessage,
1971
- history: this.chatHistory,
1972
- inputText: textFromMessage(this.promptMessage),
1973
- run: this.guardrailRunContext(runId)
1974
- });
1975
- for (const decision of inputResult.decisions) {
1976
- await this.recordGuardrailDecision(decision, runObservers);
1977
- }
1978
- this.promptMessage = inputResult.prompt;
1979
- if (inputResult.blocked) {
1980
- const output = inputResult.message ?? "The request was blocked by a guardrail.";
1981
- const result = {
1982
- status: "completed",
1983
- runId,
1984
- output,
1985
- usage,
1986
- messages: [this.promptMessage, Message.assistant(output)],
1987
- trace: runObservers.trace,
1988
- guardrails: [...this.guardrailDecisions]
1989
- };
1990
- await this.runLifecycleFinish(result);
1991
- await runObservers.end(result);
1992
- this.runState = "completed";
1993
- return result;
1994
- }
1995
- newMessages = [this.promptMessage];
1996
- await this.memoryRecorder.commitAcceptedInput(runId, newMessages);
1997
- const pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);
1998
- await this.runRunStartHook(newMessages);
1999
- while (currentTurns <= this.maxTurnCount + 1) {
2000
- const prompt = newMessages.at(-1);
2001
- if (prompt === void 0) {
2002
- throw new Error("AgentRun requires at least one message");
2003
- }
2004
- lastPrompt = prompt;
2005
- currentTurns += 1;
2006
- const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];
2007
- await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);
2008
- await this.runCompletionCallHook(prompt, historyForRequest, newMessages);
2009
- const request = await this.createTurnRequest(prompt, historyForRequest, currentTurns);
2010
- let response;
2011
- try {
2012
- response = await this.runCompletion(request, currentTurns, runObservers);
2013
- } catch (error) {
2014
- await settleFailureCleanup([
2015
- () => this.runCompletionErrorHook(prompt, error, newMessages)
2016
- ]);
2017
- throw error;
2018
- }
2019
- response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);
2020
- usage = Usage.add(usage, response.usage);
2021
- this.updateApprovalProgress(runId, usage, newMessages);
2022
- await this.runCompletionResponseHook(prompt, response, newMessages);
2023
- await this.runTurnEndHook(currentTurns, response, newMessages);
2024
- await this.activeLifecycle?.onStepFinish?.({
2025
- runId,
2026
- step: currentTurns,
2027
- response: lifecycleSnapshot(response),
2028
- usage: lifecycleSnapshot(usage)
2029
- });
2030
- const toolCalls = response.choice.filter(
2031
- (item) => item.type === "tool_call"
2032
- );
2033
- const assistantMessage = this.generatedAssistantMessage(response, request);
2034
- newMessages.push(assistantMessage);
2035
- if (toolCalls.length === 0) {
2036
- if (this.steeringMessages.length > 0) {
2037
- await this.memoryRecorder.commitMessages(
2038
- runId,
2039
- currentTurns,
2040
- [assistantMessage],
2041
- pendingTurnMessages
2042
- );
2043
- }
2044
- if (await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages)) {
2045
- await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
2046
- continue;
2047
- }
2048
- const guardedOutput = await this.runOutputGuardrailsForResponse(
2049
- runId,
2050
- usage,
2051
- response,
2052
- newMessages,
2053
- runObservers
2054
- );
2055
- response = guardedOutput.response;
2056
- const finalAssistantMessage = this.generatedAssistantMessage(response, request);
2057
- newMessages[newMessages.length - 1] = finalAssistantMessage;
2058
- await this.memoryRecorder.commitMessages(
2059
- runId,
2060
- currentTurns,
2061
- [finalAssistantMessage],
2062
- pendingTurnMessages
2063
- );
2064
- const result = {
2065
- status: "completed",
2066
- runId,
2067
- output: guardedOutput.output,
2068
- usage,
2069
- messages: [...newMessages],
2070
- trace: runObservers.trace,
2071
- guardrails: [...this.guardrailDecisions],
2072
- ...generationArtifacts(newMessages)
2073
- };
2074
- await this.runRunEndHook(result, newMessages);
2075
- await this.memoryRecorder.commitCompletedRun(
2076
- runId,
2077
- currentTurns,
2078
- newMessages,
2079
- pendingTurnMessages
2080
- );
2081
- await this.runLifecycleFinish(result);
2082
- await runObservers.end(result);
2083
- this.runState = "completed";
2084
- return result;
2085
- }
2086
- this.updateApprovalProgress(runId, usage, newMessages);
2087
- const toolResults = await this.executeToolCalls(
2088
- runId,
2089
- toolCalls,
2090
- newMessages,
2091
- void 0,
2092
- void 0,
2093
- {
2094
- turn: currentTurns,
2095
- runObservers,
2096
- toolDefinitions: request.tools
2097
- }
2098
- );
2099
- const toolMessage = Message.tool(toolResults);
2100
- newMessages.push(toolMessage);
2101
- await this.memoryRecorder.commitMessages(
2102
- runId,
2103
- currentTurns,
2104
- [assistantMessage, toolMessage],
2105
- pendingTurnMessages
2106
- );
2107
- await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages);
2108
- await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
2109
- }
2110
- throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);
2111
- } catch (error) {
2112
- if (error instanceof MemoryCompactionError && error.usage !== void 0) {
2113
- usage = Usage.add(usage, error.usage);
2114
- }
2115
- const reportedError = await this.reportRunFailure(
2116
- error,
2117
- runId,
2118
- usage,
2119
- newMessages,
2120
- runObservers
2121
- );
2122
- this.runState = reportedError instanceof AgentRunCancelledError ? "cancelled" : "errored";
2123
- throw reportedError;
2124
- }
2125
- }
2126
- async *events(includeToolCallDeltas = true) {
2127
- if (!this.agent.model.capabilities.streaming || !isStreamingCompletionModel(this.agent.model)) {
2128
- throw new Error("This completion model does not support streaming");
2129
- }
2130
- this.startRun();
2131
- const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();
2132
- this.activeRunId = runId;
2133
- let usage = Usage.empty();
2134
- let currentTurns = 0;
2135
- let lastPrompt = this.promptMessage;
2136
- let newMessages = [this.promptMessage];
2137
- const bufferOutputDeltas = hasEnforcedOutputGuardrails(this.guardrailPolicies);
2138
- let runObservers;
2139
- try {
2140
- const memoryPreparation = await this.memoryRecorder.prepareHistory(runId, newMessages.length);
2141
- this.chatHistory = memoryPreparation.history;
2142
- usage = Usage.add(usage, memoryPreparation.usage);
2143
- runObservers = await this.startRunObservers(runId);
2144
- await this.recordMemoryCompaction(memoryPreparation, runObservers);
2145
- await this.activeLifecycle?.onStart?.({
2146
- runId,
2147
- input: lifecycleSnapshot(this.promptMessage),
2148
- history: lifecycleSnapshot(this.chatHistory),
2149
- maxTurns: this.maxTurnCount
2150
- });
2151
- const inputResult = await runInputGuardrails(this.guardrailPolicies, {
2152
- prompt: this.promptMessage,
2153
- history: this.chatHistory,
2154
- inputText: textFromMessage(this.promptMessage),
2155
- run: this.guardrailRunContext(runId)
2156
- });
2157
- for (const decision of inputResult.decisions) {
2158
- await this.recordGuardrailDecision(decision, runObservers);
2159
- yield { type: "guardrail_decision", decision };
2160
- }
2161
- this.promptMessage = inputResult.prompt;
2162
- if (inputResult.blocked) {
2163
- const output = inputResult.message ?? "The request was blocked by a guardrail.";
2164
- const result = {
2165
- status: "completed",
2166
- runId,
2167
- output,
2168
- usage,
2169
- messages: [this.promptMessage, Message.assistant(output)],
2170
- trace: runObservers.trace,
2171
- guardrails: [...this.guardrailDecisions]
2172
- };
2173
- await this.runLifecycleFinish(result);
2174
- await runObservers.end(result);
2175
- this.runState = "completed";
2176
- yield {
2177
- type: "final",
2178
- runId,
2179
- output: result.output,
2180
- usage: result.usage,
2181
- messages: result.messages,
2182
- trace: result.trace,
2183
- guardrails: result.guardrails
2184
- };
2185
- return;
2186
- }
2187
- newMessages = [this.promptMessage];
2188
- await this.memoryRecorder.commitAcceptedInput(runId, newMessages);
2189
- const pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);
2190
- await this.runRunStartHook(newMessages);
2191
- while (currentTurns <= this.maxTurnCount + 1) {
2192
- const prompt = newMessages.at(-1);
2193
- if (prompt === void 0) {
2194
- throw new Error("AgentRun requires at least one message");
2195
- }
2196
- lastPrompt = prompt;
2197
- currentTurns += 1;
2198
- const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];
2199
- yield {
2200
- type: "turn_start",
2201
- turn: currentTurns,
2202
- prompt,
2203
- history: historyForRequest
2204
- };
2205
- await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);
2206
- await this.runCompletionCallHook(prompt, historyForRequest, newMessages);
2207
- const request = await this.createTurnRequest(prompt, historyForRequest, currentTurns);
2208
- assertCompletionRequestSupported(this.agent.model, request, { streaming: true });
2209
- const providerRequest = this.providerTraceRequest(request, { stream: true });
2210
- const generationStartArgs = this.generationStartArgs(
2211
- currentTurns,
2212
- request,
2213
- providerRequest
2214
- );
2215
- const generationObservers = await runObservers.startGeneration(generationStartArgs);
2216
- this.activeGeneration = { turn: currentTurns, observers: generationObservers };
2217
- const generationStartedAt = Date.now();
2218
- yield {
2219
- type: "generation_start",
2220
- turn: currentTurns,
2221
- request,
2222
- modelInfo: generationStartArgs.modelInfo
2223
- };
2224
- const bufferResponseEvents = this.shouldBufferStreamResponseEvents();
2225
- const completionState = {
2226
- response: void 0,
2227
- firstDeltaMs: void 0,
2228
- emittedToolCallIds: /* @__PURE__ */ new Set(),
2229
- providerErrorUsage: Usage.empty()
2230
- };
2231
- let response;
2232
- try {
2233
- try {
2234
- for await (const event of this.streamCompletion({
2235
- request,
2236
- turn: currentTurns,
2237
- includeToolCallDeltas,
2238
- bufferResponseEvents,
2239
- bufferOutputDeltas,
2240
- generationStartedAt,
2241
- generationObservers,
2242
- runObservers,
2243
- state: completionState
2244
- })) {
2245
- yield event;
2246
- }
2247
- } finally {
2248
- usage = Usage.add(usage, completionState.providerErrorUsage);
2249
- }
2250
- if (completionState.response === void 0) {
2251
- throw new Error("Streaming completion ended without a response.");
2252
- }
2253
- response = completionState.response;
2254
- } catch (error) {
2255
- await settleFailureCleanup([
2256
- () => this.closeActiveGeneration(error),
2257
- () => this.runCompletionErrorHook(prompt, error, newMessages)
2258
- ]);
2259
- throw error;
2260
- }
2261
- const { firstDeltaMs, emittedToolCallIds } = completionState;
2262
- const generationEndArgs = {
2263
- turn: currentTurns,
2264
- response,
2265
- ...firstDeltaMs === void 0 ? {} : { firstDeltaMs }
2266
- };
2267
- this.activeGeneration = void 0;
2268
- await generationObservers.end(generationEndArgs);
2269
- response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);
2270
- usage = Usage.add(usage, response.usage);
2271
- this.updateApprovalProgress(runId, usage, newMessages);
2272
- await this.runCompletionResponseHook(prompt, response, newMessages);
2273
- await this.runTurnEndHook(currentTurns, response, newMessages);
2274
- await this.activeLifecycle?.onStepFinish?.({
2275
- runId,
2276
- step: currentTurns,
2277
- response: lifecycleSnapshot(response),
2278
- usage: lifecycleSnapshot(usage)
2279
- });
2280
- const toolCalls = response.choice.filter(
2281
- (item) => item.type === "tool_call"
2282
- );
2283
- const assistantMessage = this.generatedAssistantMessage(response, request);
2284
- newMessages.push(assistantMessage);
2285
- if (toolCalls.length === 0) {
2286
- let emittedTurnEnd = false;
2287
- if (!bufferOutputDeltas) {
2288
- if (bufferResponseEvents) {
2289
- for (const event of responseStreamEvents(currentTurns, response)) {
2290
- yield event;
2291
- }
2292
- }
2293
- yield {
2294
- type: "turn_end",
2295
- turn: currentTurns,
2296
- response,
2297
- firstDeltaMs
2298
- };
2299
- emittedTurnEnd = true;
2300
- }
2301
- if (this.steeringMessages.length > 0) {
2302
- await this.memoryRecorder.commitMessages(
2303
- runId,
2304
- currentTurns,
2305
- [assistantMessage],
2306
- pendingTurnMessages
2307
- );
2308
- }
2309
- if (await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages)) {
2310
- await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
2311
- continue;
2312
- }
2313
- for await (const event of this.completeStreamingRun({
2314
- runId,
2315
- turn: currentTurns,
2316
- request,
2317
- response,
2318
- firstDeltaMs,
2319
- usage,
2320
- newMessages,
2321
- pendingTurnMessages,
2322
- runObservers,
2323
- bufferResponseEvents,
2324
- bufferOutputDeltas,
2325
- emittedTurnEnd
2326
- })) {
2327
- yield event;
2328
- }
2329
- return;
2330
- }
2331
- if (bufferResponseEvents) {
2332
- for (const event of responseStreamEvents(currentTurns, response)) {
2333
- yield event;
2334
- }
2335
- } else {
2336
- for (const toolCall of toolCalls) {
2337
- if (!emittedToolCallIds.has(toolCall.id)) {
2338
- yield { type: "tool_call", turn: currentTurns, toolCall };
2339
- }
2340
- }
2341
- }
2342
- this.updateApprovalProgress(runId, usage, newMessages);
2343
- yield {
2344
- type: "turn_end",
2345
- turn: currentTurns,
2346
- response,
2347
- firstDeltaMs
2348
- };
2349
- const toolExecution = this.executeStreamingToolCalls(runId, toolCalls, newMessages, {
2350
- turn: currentTurns,
2351
- runObservers,
2352
- toolDefinitions: request.tools,
2353
- includeToolCallDeltas
2354
- });
2355
- for await (const result of toolExecution.events) {
2356
- yield { turn: currentTurns, ...result };
2357
- }
2358
- const toolResults = await toolExecution.results;
2359
- const toolMessage = Message.tool(toolResults);
2360
- newMessages.push(toolMessage);
2361
- await this.memoryRecorder.commitMessages(
2362
- runId,
2363
- currentTurns,
2364
- [assistantMessage, toolMessage],
2365
- pendingTurnMessages
2366
- );
2367
- await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages);
2368
- await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
2369
- }
2370
- throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);
2371
- } catch (error) {
2372
- if (error instanceof MemoryCompactionError && error.usage !== void 0) {
2373
- usage = Usage.add(usage, error.usage);
2374
- }
2375
- const reportedError = await this.reportRunFailure(
2376
- error,
2377
- runId,
2378
- usage,
2379
- newMessages,
2380
- runObservers
2381
- );
2382
- this.runState = reportedError instanceof AgentRunCancelledError ? "cancelled" : "errored";
2383
- const finalUsage = usage;
2384
- yield { type: "error", error: reportedError, usage: finalUsage };
2385
- throw reportedError;
2386
- } finally {
2387
- if (this.runState === "running") {
2388
- const cancellation = this.cancellationError ?? new AgentRunCancelledError([...this.chatHistory, ...newMessages], "Agent stream closed.");
2389
- this.cancellationError = cancellation;
2390
- await settleFailureCleanup([() => this.closeActiveGeneration(cancellation)]);
2391
- await this.reportRunFailure(cancellation, runId, usage, newMessages, runObservers);
2392
- this.runState = "cancelled";
2393
- }
2394
- }
2395
- }
2396
- async runCompletion(request, turn, runObservers) {
2397
- assertCompletionRequestSupported(this.agent.model, request);
2398
- const providerRequest = this.providerTraceRequest(request);
2399
- const generationObservers = await runObservers.startGeneration(
2400
- this.generationStartArgs(turn, request, providerRequest)
2401
- );
2402
- try {
2403
- for (let attempt = 1; ; attempt += 1) {
2404
- let response;
2405
- try {
2406
- response = await this.agent.model.completion(request);
2407
- } catch (error) {
2408
- const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
2409
- if (retryOptions === void 0) {
2410
- throw error;
2411
- }
2412
- await this.scheduleCompletionRetry(
2413
- error,
2414
- attempt,
2415
- turn,
2416
- false,
2417
- retryOptions,
2418
- runObservers
2419
- );
2420
- continue;
2421
- }
2422
- await generationObservers.end({ turn, response });
2423
- return response;
2424
- }
2425
- } catch (error) {
2426
- await settleFailureCleanup([() => generationObservers.error({ turn, error })]);
2427
- throw error;
2428
- }
2429
- }
2430
- async createTurnRequest(prompt, history, turn) {
2431
- const ragText = extractRagText(prompt);
2432
- const documents = await fetchContextDocuments(this.agent, ragText);
2433
- const toolDefinitions = await fetchToolDefinitions(this.agent, ragText);
2434
- const request = createCompletionRequest([...history, prompt], {
2435
- model: this.agent.model,
2436
- instructions: this.agent.instructions,
2437
- documents,
2438
- tools: [...toolDefinitions, ...getAgentToolState(this.agent).providerTools],
2439
- temperature: this.agent.temperature,
2440
- maxTokens: this.agent.maxTokens,
2441
- additionalParams: this.agent.additionalParams,
2442
- toolChoice: this.agent.toolChoice,
2443
- outputSchema: this.agent.outputSchema
2444
- });
2445
- return await this.runCompletionRequestMiddlewares(request, turn);
2446
- }
2447
- async *streamCompletion(args) {
2448
- const model = this.agent.model;
2449
- if (!isStreamingCompletionModel(model)) {
2450
- throw new TypeError("Streaming completion requires a streaming-capable model.");
2451
- }
2452
- const accumulator = new CompletionStreamAccumulator();
2453
- for (let attempt = 1; ; attempt += 1) {
2454
- let hasProviderProgress = false;
2455
- try {
2456
- for await (const event of model.streamCompletion(args.request)) {
2457
- if (event.type === "error") {
2458
- if (event.usage !== void 0) {
2459
- args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, event.usage);
2460
- }
2461
- throw event.error;
2462
- }
2463
- hasProviderProgress = true;
2464
- if (args.state.firstDeltaMs === void 0 && isGenerationDeltaEvent(event.type)) {
2465
- args.state.firstDeltaMs = Date.now() - args.generationStartedAt;
2466
- }
2467
- const mapped = accumulator.accept(event);
2468
- if (args.includeToolCallDeltas && event.type === "tool_call_delta") {
2469
- yield addTurnToToolCallDelta(args.turn, event);
2470
- }
2471
- if (mapped !== void 0) {
2472
- await args.generationObservers.update?.({ turn: args.turn, delta: mapped });
2473
- if (mapped.type === "tool_call") {
2474
- args.state.emittedToolCallIds.add(mapped.toolCall.id);
2475
- }
2476
- const shouldBuffer = args.bufferResponseEvents || args.bufferOutputDeltas && (mapped.type === "text_delta" || mapped.type === "reasoning_delta");
2477
- if (!shouldBuffer) {
2478
- yield addTurn(args.turn, mapped);
2479
- }
2480
- }
2481
- }
2482
- args.state.response = accumulator.response();
2483
- return;
2484
- } catch (error) {
2485
- const retryOptions = hasProviderProgress ? void 0 : this.retryOptionsForFailure(error, attempt, args.turn, true);
2486
- if (retryOptions === void 0) {
2487
- throw error;
2488
- }
2489
- await this.scheduleCompletionRetry(
2490
- error,
2491
- attempt,
2492
- args.turn,
2493
- true,
2494
- retryOptions,
2495
- args.runObservers
2496
- );
2497
- }
2498
- }
2499
- }
2500
- async *completeStreamingRun(args) {
2501
- const guardedOutput = await this.runOutputGuardrailsForResponse(
2502
- args.runId,
2503
- args.usage,
2504
- args.response,
2505
- args.newMessages,
2506
- args.runObservers
2507
- );
2508
- for (const decision of guardedOutput.decisions) {
2509
- yield { type: "guardrail_decision", decision };
2510
- }
2511
- const response = guardedOutput.response;
2512
- const assistantMessage = this.generatedAssistantMessage(response, args.request);
2513
- args.newMessages[args.newMessages.length - 1] = assistantMessage;
2514
- await this.memoryRecorder.commitMessages(
2515
- args.runId,
2516
- args.turn,
2517
- [assistantMessage],
2518
- args.pendingTurnMessages
2519
- );
2520
- if (!args.emittedTurnEnd && (args.bufferResponseEvents || args.bufferOutputDeltas)) {
2521
- for (const event of responseStreamEvents(args.turn, response, args.bufferResponseEvents)) {
2522
- yield event;
2523
- }
2524
- }
2525
- if (!args.emittedTurnEnd) {
2526
- yield {
2527
- type: "turn_end",
2528
- turn: args.turn,
2529
- response,
2530
- firstDeltaMs: args.firstDeltaMs
2531
- };
2532
- }
2533
- const result = {
2534
- status: "completed",
2535
- runId: args.runId,
2536
- output: guardedOutput.output,
2537
- usage: args.usage,
2538
- messages: [...args.newMessages],
2539
- trace: args.runObservers.trace,
2540
- guardrails: [...this.guardrailDecisions],
2541
- ...generationArtifacts(args.newMessages)
2542
- };
2543
- await this.runRunEndHook(result, args.newMessages);
2544
- await this.memoryRecorder.commitCompletedRun(
2545
- args.runId,
2546
- args.turn,
2547
- args.newMessages,
2548
- args.pendingTurnMessages
2549
- );
2550
- await this.runLifecycleFinish(result);
2551
- await args.runObservers.end(result);
2552
- this.runState = "completed";
2553
- yield {
2554
- type: "final",
2555
- runId: args.runId,
2556
- output: result.output,
2557
- usage: result.usage,
2558
- contextUsage: result.contextUsage,
2559
- messages: result.messages,
2560
- trace: result.trace,
2561
- guardrails: result.guardrails,
2562
- sources: result.sources,
2563
- providerToolCalls: result.providerToolCalls
2564
- };
2565
- }
2566
- generatedAssistantMessage(response, request) {
2567
- const metadata = {
2568
- anvia: {
2569
- generation: {
2570
- provider: this.agent.model.provider,
2571
- model: request.model ?? this.agent.model.defaultModel,
2572
- usage: { ...response.usage },
2573
- ...response.contextUsage === void 0 ? {} : { contextUsage: response.contextUsage },
2574
- ...response.sources === void 0 ? {} : { sources: response.sources },
2575
- ...response.providerToolCalls === void 0 ? {} : { providerToolCalls: response.providerToolCalls }
2576
- }
2577
- }
2578
- };
2579
- return Message.assistant(response.choice, {
2580
- ...response.messageId === void 0 ? {} : { id: response.messageId },
2581
- metadata
2582
- });
2583
- }
2584
- providerTraceRequest(request, options = {}) {
2585
- try {
2586
- return this.agent.model.traceRequest?.(request, options);
2587
- } catch (error) {
2588
- return {
2589
- error: error instanceof Error ? error.message : String(error)
2590
- };
2591
- }
2592
- }
2593
- generationStartArgs(turn, request, providerRequest) {
2594
- return {
2595
- turn,
2596
- request,
2597
- modelInfo: {
2598
- provider: this.agent.model.provider,
2599
- defaultModel: this.agent.model.defaultModel,
2600
- capabilities: this.agent.model.capabilities
2601
- },
2602
- ...providerRequest === void 0 ? {} : { providerRequest }
2603
- };
2604
- }
2605
- retryOptionsForFailure(error, attempt, turn, streaming) {
2606
- const options = this.completionRetryOptions;
2607
- if (options === void 0 || attempt >= options.maxAttempts) {
2608
- return void 0;
2609
- }
2610
- const shouldRetry = options.shouldRetry({
2611
- error,
2612
- attempt,
2613
- maxAttempts: options.maxAttempts,
2614
- turn,
2615
- streaming
2616
- });
2617
- return shouldRetry ? options : void 0;
2618
- }
2619
- async scheduleCompletionRetry(error, attempt, turn, streaming, options, runObservers) {
2620
- const delayMs = retryDelayMs(options, attempt);
2621
- await runObservers.event({
2622
- name: "completion.retry",
2623
- level: "WARNING",
2624
- attributes: {
2625
- turn,
2626
- attempt,
2627
- nextAttempt: attempt + 1,
2628
- maxAttempts: options.maxAttempts,
2629
- delayMs,
2630
- streaming,
2631
- ...retryErrorAttributes(error)
2632
- }
2633
- });
2634
- await waitForRetry(delayMs);
2635
- }
2636
- async executeToolCalls(runId, toolCalls, newMessages, onResult, onStreamEvent, observation) {
2637
- const executor = new ToolCallExecutor(
2638
- this.agent,
2639
- this.activeHook,
2640
- (request) => this.suspendForApproval(request),
2641
- this.activeLifecycle,
2642
- {
2643
- runId,
2644
- sessionId: this.memoryContext?.sessionId,
2645
- metadata: this.memoryContext?.metadata
2646
- },
2647
- this.concurrency,
2648
- this.requestMiddlewares,
2649
- observation?.includeToolCallDeltas ?? false,
2650
- (reason) => this.cancelled(newMessages, reason)
2651
- );
2652
- return executor.execute(toolCalls, onResult, onStreamEvent, observation);
2653
- }
2654
- executeStreamingToolCalls(runId, toolCalls, newMessages, observation) {
2655
- const events = createAsyncQueue();
2656
- const results = this.executeToolCalls(
2657
- runId,
2658
- toolCalls,
2659
- newMessages,
2660
- (result) => events.enqueue(result),
2661
- (event) => events.enqueue(event),
2662
- observation
2663
- );
2664
- results.then(
2665
- () => events.close(),
2666
- (error) => events.throw(error)
2667
- );
2668
- return { events, results };
2669
- }
2670
- suspendForApproval(request) {
2671
- if (this.cancellationError !== void 0) {
2672
- return Promise.reject(this.cancellationError);
2673
- }
2674
- if (this.pendingApproval !== void 0) {
2675
- throw new Error("Agent run already has a pending tool approval.");
2676
- }
2677
- return new Promise((resolve, reject) => {
2678
- this.pendingApproval = { request, resolve, reject };
2679
- this.approvalSignal.resolve();
2680
- });
2681
- }
2682
- async closeActiveGeneration(error) {
2683
- const active = this.activeGeneration;
2684
- if (active === void 0) {
2685
- return;
2686
- }
2687
- this.activeGeneration = void 0;
2688
- await active.observers.error({ turn: active.turn, error });
2689
- }
2690
- approvalSnapshot() {
2691
- const pending = this.pendingApproval;
2692
- const runId = this.activeRunId;
2693
- if (pending === void 0 || runId === void 0) {
2694
- throw new TypeError("Agent run has no pending tool approval.");
2695
- }
2696
- const approval = {
2697
- id: pending.request.id,
2698
- toolName: pending.request.toolName,
2699
- input: lifecycleSnapshot(pending.request.args),
2700
- ...pending.request.toolCallId === void 0 ? {} : { toolCallId: pending.request.toolCallId },
2701
- ...pending.request.reason === void 0 ? {} : { reason: pending.request.reason }
2702
- };
2703
- registerAgentApprovalRequestDetails(approval, pending.request);
2704
- return {
2705
- runId,
2706
- approval,
2707
- usage: lifecycleSnapshot(this.currentUsage),
2708
- messages: lifecycleSnapshot(this.currentMessages)
2709
- };
2710
- }
2711
- updateApprovalProgress(runId, usage, messages) {
2712
- this.activeRunId = runId;
2713
- this.currentUsage = usage;
2714
- this.currentMessages = [...messages];
2715
- }
2716
- async runLifecycleFinish(result) {
2717
- await this.activeLifecycle?.onFinish?.({
2718
- runId: result.runId,
2719
- output: result.output,
2720
- usage: lifecycleSnapshot(result.usage),
2721
- messages: lifecycleSnapshot(result.messages)
2722
- });
2723
- }
2724
- async runLifecycleError(error, runId, usage, messages) {
2725
- try {
2726
- await this.activeLifecycle?.onError?.({
2727
- runId,
2728
- error: lifecycleSnapshot(error),
2729
- usage: lifecycleSnapshot(usage),
2730
- messages: lifecycleSnapshot([...this.chatHistory, ...messages])
2731
- });
2732
- return void 0;
2733
- } catch (lifecycleError) {
2734
- return lifecycleError;
2735
- }
2736
- }
2737
- async reportRunFailure(error, runId, usage, messages, runObservers) {
2738
- const reportedError = await this.resolveReportedRunError(error, runId, usage, messages);
2739
- await settleFailureCleanup([
2740
- () => runObservers?.error({
2741
- error: reportedError,
2742
- usage,
2743
- messages: [...messages]
2744
- }),
2745
- () => this.memoryRecorder.recordError(runId, reportedError, messages)
2746
- ]);
2747
- return reportedError;
2748
- }
2749
- async resolveReportedRunError(error, runId, usage, messages) {
2750
- try {
2751
- await this.runRunErrorHook(error, usage, messages);
2752
- } catch {
2753
- }
2754
- await this.runLifecycleError(error, runId, usage, messages);
2755
- return error;
2756
- }
2757
- async runOutputGuardrailsForResponse(runId, usage, response, messages, runObservers) {
2758
- const originalOutput = textFromAssistantContent(response.choice);
2759
- const result = await runOutputGuardrails(this.guardrailPolicies, {
2760
- outputText: originalOutput,
2761
- messages: [...this.chatHistory, ...messages],
2762
- usage,
2763
- run: this.guardrailRunContext(runId)
2764
- });
2765
- for (const decision of result.decisions) {
2766
- await this.recordGuardrailDecision(decision, runObservers);
2767
- }
2768
- const output = result.blocked ? result.message ?? "The response was blocked by a guardrail." : result.outputText;
2769
- if (output === originalOutput) {
2770
- return { output, response, decisions: result.decisions };
2771
- }
2772
- return {
2773
- output,
2774
- response: {
2775
- ...response,
2776
- choice: [AssistantContent.text(output)]
2777
- },
2778
- decisions: result.decisions
2779
- };
2780
- }
2781
- async recordGuardrailDecision(decision, runObservers) {
2782
- this.guardrailDecisions.push(decision);
2783
- await runObservers.event({
2784
- name: "guardrail.decision",
2785
- level: decision.action === "block" ? "WARNING" : "DEFAULT",
2786
- attributes: guardrailDecisionAttributes(decision)
2787
- });
2788
- }
2789
- async recordMemoryCompaction(preparation, runObservers) {
2790
- const compaction = preparation.compaction;
2791
- if (compaction === void 0) {
2792
- return;
2793
- }
2794
- await runObservers.event({
2795
- name: "memory.compaction",
2796
- attributes: {
2797
- originalMessageCount: compaction.originalMessageCount,
2798
- compactedMessageCount: compaction.compactedMessageCount,
2799
- retainedMessageCount: compaction.retainedMessageCount,
2800
- conflictRetries: compaction.conflictRetries,
2801
- inputTokens: preparation.usage.inputTokens,
2802
- outputTokens: preparation.usage.outputTokens,
2803
- totalTokens: preparation.usage.totalTokens
2804
- }
2805
- });
2806
- }
2807
- guardrailRunContext(runId) {
2808
- const context = {
2809
- agentId: this.agent.id,
2810
- runId
2811
- };
2812
- if (this.memoryContext !== void 0) {
2813
- context.sessionId = this.memoryContext.sessionId;
2814
- if (this.memoryContext.metadata !== void 0) {
2815
- context.metadata = this.memoryContext.metadata;
2816
- }
2817
- }
2818
- return context;
2819
- }
2820
- async startRunObservers(runId) {
2821
- const failOnObserverError = this.traceOptions?.failOnObserverError === true || this.agent.observers.some((registration) => registration.failOnObserverError === true);
2822
- return startAgentRunObservers(
2823
- this.agent.observers,
2824
- {
2825
- runId,
2826
- agentName: this.agent.name,
2827
- agentDescription: this.agent.description,
2828
- instructions: this.agent.instructions,
2829
- trace: this.traceOptions,
2830
- promptRef: this.traceOptions?.promptRef,
2831
- prompt: this.promptMessage,
2832
- history: this.chatHistory,
2833
- maxTurns: this.maxTurnCount
2834
- },
2835
- failOnObserverError
2836
- );
2837
- }
2838
- async runCompletionCallHook(prompt, history, newMessages) {
2839
- const action = await this.activeHook?.onCompletionCall?.({
2840
- prompt,
2841
- history,
2842
- run: runControl
2843
- });
2844
- if (action?.type === "terminate") {
2845
- throw this.cancelled(newMessages, action.reason);
2846
- }
2847
- }
2848
- async runRunStartHook(newMessages) {
2849
- const action = await this.activeHook?.onRunStart?.({
2850
- prompt: this.promptMessage,
2851
- history: this.chatHistory,
2852
- maxTurns: this.maxTurnCount,
2853
- run: runControl
2854
- });
2855
- if (action?.type === "terminate") {
2856
- throw this.cancelled(newMessages, action.reason);
2857
- }
2858
- }
2859
- async runRunEndHook(result, newMessages) {
2860
- const action = await this.activeHook?.onRunEnd?.({
2861
- output: result.output,
2862
- usage: result.usage,
2863
- messages: result.messages,
2864
- run: runControl
2865
- });
2866
- if (action?.type === "terminate") {
2867
- throw this.cancelled(newMessages, action.reason);
2868
- }
2869
- }
2870
- async runRunErrorHook(error, usage, newMessages) {
2871
- const action = await this.activeHook?.onRunError?.({
2872
- error,
2873
- usage,
2874
- messages: [...this.chatHistory, ...newMessages],
2875
- run: runControl
2876
- });
2877
- if (action?.type === "terminate") {
2878
- this.cancelled(newMessages, action.reason);
2879
- }
2880
- }
2881
- async runTurnStartHook(turn, prompt, history, newMessages) {
2882
- const action = await this.activeHook?.onTurnStart?.({
2883
- turn,
2884
- prompt,
2885
- history,
2886
- run: runControl
2887
- });
2888
- if (action?.type === "terminate") {
2889
- throw this.cancelled(newMessages, action.reason);
2890
- }
2891
- }
2892
- async runTurnEndHook(turn, response, newMessages) {
2893
- const action = await this.activeHook?.onTurnEnd?.({
2894
- turn,
2895
- response,
2896
- run: runControl
2897
- });
2898
- if (action?.type === "terminate") {
2899
- throw this.cancelled(newMessages, action.reason);
2900
- }
2901
- }
2902
- async runCompletionRequestMiddlewares(request, turn) {
2903
- let current = request;
2904
- for (const middleware of this.activeMiddlewares()) {
2905
- const replacement = await middleware.onCompletionRequest?.({
2906
- turn,
2907
- request: current,
2908
- originalRequest: request
2909
- });
2910
- if (replacement?.request !== void 0) {
2911
- current = replacement.request;
2912
- }
2913
- }
2914
- return current;
2915
- }
2916
- async runCompletionResponseMiddlewares(request, response, turn) {
2917
- let current = response;
2918
- for (const middleware of this.activeMiddlewares()) {
2919
- const replacement = await middleware.onCompletionResponse?.({
2920
- turn,
2921
- request,
2922
- response: current,
2923
- originalResponse: response
2924
- });
2925
- if (replacement?.response !== void 0) {
2926
- current = replacement.response;
2927
- }
2928
- }
2929
- return current;
2930
- }
2931
- async runCompletionResponseHook(prompt, response, newMessages) {
2932
- const action = await this.activeHook?.onCompletionResponse?.({
2933
- prompt,
2934
- response,
2935
- run: runControl
2936
- });
2937
- if (action?.type === "terminate") {
2938
- throw this.cancelled(newMessages, action.reason);
2939
- }
2940
- }
2941
- async runCompletionErrorHook(prompt, error, newMessages) {
2942
- const action = await this.activeHook?.onCompletionError?.({
2943
- prompt,
2944
- error,
2945
- run: runControl
2946
- });
2947
- if (action?.type === "terminate") {
2948
- throw this.cancelled(newMessages, action.reason);
2949
- }
2950
- }
2951
- activeMiddlewares() {
2952
- return [...this.agent.middlewares, ...this.requestMiddlewares];
2953
- }
2954
- shouldBufferStreamResponseEvents() {
2955
- return this.activeHook?.onCompletionResponse !== void 0 || this.activeMiddlewares().some((middleware) => middleware.onCompletionResponse !== void 0);
2956
- }
2957
- async drainSteeringMessages(runId, turn, newMessages, pendingTurnMessages) {
2958
- const messages = this.steeringMessages.splice(0);
2959
- if (messages.length === 0) {
2960
- return false;
2961
- }
2962
- newMessages.push(...messages);
2963
- await this.memoryRecorder.commitMessages(runId, turn, messages, pendingTurnMessages);
2964
- return true;
2965
- }
2966
- startRun() {
2967
- if (this.runState === "idle") {
2968
- this.runState = "running";
2969
- return;
2970
- }
2971
- if (this.runState === "running") {
2972
- throw new Error("Agent stream is already running.");
2973
- }
2974
- throw new Error("Agent stream has already been consumed.");
2975
- }
2976
- isTerminal() {
2977
- return this.runState === "completed" || this.runState === "errored" || this.runState === "cancelled";
2978
- }
2979
- cancelled(newMessages, reason) {
2980
- return new AgentRunCancelledError([...this.chatHistory, ...newMessages], reason);
2981
- }
2982
- };
2983
- function normalizeAgentInput(prompt) {
2984
- if (typeof prompt === "string") {
2985
- return { prompt: Message.user(prompt), history: [] };
2986
- }
2987
- if (!Array.isArray(prompt)) {
2988
- return { prompt, history: [] };
2989
- }
2990
- if (prompt.length === 0) {
2991
- throw new TypeError("Agent input transcript must contain at least one message.");
2992
- }
2993
- const activePrompt = prompt.at(-1);
2994
- if (activePrompt === void 0) {
2995
- throw new TypeError("Agent input transcript must contain at least one message.");
2996
- }
2997
- return {
2998
- prompt: activePrompt,
2999
- history: prompt.slice(0, -1)
3000
- };
3001
- }
3002
- function normalizeSteeringInput(input) {
3003
- if (typeof input === "string") {
3004
- return [Message.user(input)];
3005
- }
3006
- return Array.isArray(input) ? [...input] : [input];
3007
- }
3008
- function normalizeRequestedRunId(runId) {
3009
- if (runId === void 0) {
3010
- return void 0;
3011
- }
3012
- if (typeof runId !== "string" || runId.trim().length === 0) {
3013
- throw new TypeError("runId must be a non-empty string.");
3014
- }
3015
- return runId;
3016
- }
3017
- function responseStreamEvents(turn, response, includeProviderArtifacts = true) {
3018
- const events = [];
3019
- for (const item of response.choice) {
3020
- if (item.type === "text") {
3021
- if (item.text.length > 0) {
3022
- events.push({ type: "text_delta", turn, delta: item.text });
3023
- }
3024
- continue;
3025
- }
3026
- if (item.type === "reasoning") {
3027
- if (item.content === void 0) {
3028
- if (item.text.length > 0) {
3029
- events.push(reasoningDeltaEvent2(turn, item.text, { id: item.id }));
3030
- }
3031
- continue;
3032
- }
3033
- for (const content of item.content) {
3034
- const delta = content.type === "encrypted" || content.type === "redacted" ? content.data : content.text;
3035
- events.push(
3036
- reasoningDeltaEvent2(turn, delta, {
3037
- id: item.id,
3038
- contentType: content.type,
3039
- signature: content.type === "text" ? content.signature : void 0
3040
- })
3041
- );
3042
- }
3043
- continue;
3044
- }
3045
- if (item.type === "tool_call") {
3046
- events.push({ type: "tool_call", turn, toolCall: item });
3047
- }
3048
- }
3049
- if (includeProviderArtifacts) {
3050
- for (const source of response.sources ?? []) {
3051
- events.push({ type: "source", turn, source });
3052
- }
3053
- for (const toolCall of response.providerToolCalls ?? []) {
3054
- events.push({ type: "provider_tool_call", turn, toolCall });
3055
- }
3056
- }
3057
- return events;
3058
- }
3059
- function generationArtifacts(messages) {
3060
- const sources = /* @__PURE__ */ new Map();
3061
- const providerToolCalls = /* @__PURE__ */ new Map();
3062
- let contextUsage;
3063
- for (const message of messages) {
3064
- const metadata = getAssistantGenerationMetadata(message);
3065
- if (metadata !== void 0) {
3066
- contextUsage = metadata.contextUsage;
3067
- }
3068
- for (const source of metadata?.sources ?? []) {
3069
- const key = `${source.url}\0${source.startIndex ?? ""}\0${source.endIndex ?? ""}`;
3070
- sources.set(key, source);
3071
- }
3072
- for (const toolCall of metadata?.providerToolCalls ?? []) {
3073
- providerToolCalls.set(toolCall.id, toolCall);
3074
- }
3075
- }
3076
- return {
3077
- ...sources.size === 0 ? {} : { sources: [...sources.values()] },
3078
- ...providerToolCalls.size === 0 ? {} : { providerToolCalls: [...providerToolCalls.values()] },
3079
- ...contextUsage === void 0 ? {} : { contextUsage }
3080
- };
3081
- }
3082
- function reasoningDeltaEvent2(turn, delta, details = {}) {
3083
- const event = {
3084
- type: "reasoning_delta",
3085
- turn,
3086
- delta
3087
- };
3088
- if (details.id !== void 0) {
3089
- event.id = details.id;
3090
- }
3091
- if (details.contentType !== void 0) {
3092
- event.contentType = details.contentType;
3093
- }
3094
- if (details.signature !== void 0) {
3095
- event.signature = details.signature;
3096
- }
3097
- return event;
3098
- }
3099
- function textFromMessage(message) {
3100
- if (message.role === "system") {
3101
- return message.content;
3102
- }
3103
- return message.content.flatMap((content) => {
3104
- if (content.type === "text") {
3105
- return [content.text];
3106
- }
3107
- if (content.type === "document" && content.source.type === "text") {
3108
- return [content.source.text];
3109
- }
3110
- return [];
3111
- }).join("\n");
3112
- }
3113
- function guardrailDecisionAttributes(decision) {
3114
- const attributes = {
3115
- policyId: decision.policyId,
3116
- guardrailId: decision.guardrailId,
3117
- boundary: decision.boundary,
3118
- mode: decision.mode,
3119
- action: decision.action,
3120
- applied: decision.applied,
3121
- latencyMs: decision.latencyMs
3122
- };
3123
- if (decision.reason !== void 0) {
3124
- attributes.reason = decision.reason;
3125
- }
3126
- if (decision.message !== void 0) {
3127
- attributes.message = decision.message;
3128
- }
3129
- return attributes;
3130
- }
3131
-
3132
- // src/agent/ids.ts
3133
- function normalizeAgentId(id) {
3134
- if (typeof id !== "string") {
3135
- throw new TypeError("Agent id must be a string.");
3136
- }
3137
- const normalized = id.trim();
3138
- if (normalized.length === 0) {
3139
- throw new TypeError("Agent id must be a non-empty string.");
3140
- }
3141
- return normalized;
3142
- }
3143
-
3144
- // src/agent/agent.ts
3145
- var DEFAULT_MAX_TURNS = 20;
3146
- var Agent = class {
3147
- id;
3148
- name;
3149
- description;
3150
- model;
3151
- instructions;
3152
- context;
3153
- temperature;
3154
- maxTokens;
3155
- additionalParams;
3156
- tools;
3157
- toolChoice;
3158
- defaultMaxTurns;
3159
- lifecycle;
3160
- outputSchema;
3161
- observers;
3162
- guardrails;
3163
- middlewares;
3164
- memory;
3165
- constructor(options) {
3166
- const resolved = resolveAgentOptions(options);
3167
- this.id = normalizeAgentId(resolved.id);
3168
- this.name = resolved.name;
3169
- this.description = resolved.description;
3170
- this.model = resolved.model;
3171
- this.instructions = resolved.instructions;
3172
- const context = (resolved.context ?? []).map(snapshotContextInput);
3173
- assertValidContextIndexes(context);
3174
- this.context = Object.freeze(context);
3175
- this.temperature = resolved.temperature;
3176
- this.maxTokens = resolved.maxTokens;
3177
- this.additionalParams = cloneFrozenPlainData(resolved.additionalParams);
3178
- const staticTools = dedupeTools(resolved.tools ?? []);
3179
- const toolIndexes = (resolved.toolIndexes ?? []).map(snapshotToolIndex);
3180
- assertUniqueIndexedToolNames(toolIndexes);
3181
- const toolsByName = new Map(staticTools.map((tool) => [tool.name, tool]));
3182
- for (const index of toolIndexes) {
3183
- for (const tool of index.tools) {
3184
- if (!toolsByName.has(tool.name)) {
3185
- toolsByName.set(tool.name, tool);
3186
- }
3187
- }
3188
- }
3189
- this.tools = Object.freeze([...toolsByName.values()]);
3190
- const publicToolState = Object.freeze({
3191
- staticTools: Object.freeze(staticTools),
3192
- providerTools: Object.freeze((resolved.providerTools ?? []).map(snapshotProviderTool)),
3193
- toolIndexes: Object.freeze(toolIndexes)
3194
- });
3195
- registerAgentToolState(this, publicToolState, toolsByName);
3196
- this.toolChoice = cloneFrozenPlainData(resolved.toolChoice);
3197
- this.defaultMaxTurns = assertNonnegativeSafeInteger(
3198
- resolved.defaultMaxTurns ?? DEFAULT_MAX_TURNS,
3199
- "maxTurns"
3200
- );
3201
- this.lifecycle = resolved.lifecycle;
3202
- this.outputSchema = cloneFrozenPlainData(resolved.outputSchema);
3203
- this.observers = Object.freeze(
3204
- (resolved.observers ?? []).map((registration) => Object.freeze({ ...registration }))
3205
- );
3206
- this.guardrails = Object.freeze((resolved.guardrails ?? []).map(snapshotGuardrailPolicy));
3207
- this.middlewares = Object.freeze([...resolved.middlewares ?? []]);
3208
- this.memory = snapshotMemoryRegistration(resolved.memory);
3209
- }
3210
- generate(input, options = {}) {
3211
- return createGenerateExecution(this, AgentRun.fromAgent(this, input, options)).next();
3212
- }
3213
- stream(input, options = {}) {
3214
- return createStreamExecution(
3215
- this,
3216
- AgentRun.fromAgent(this, input, options),
3217
- options.includeToolCallDeltas !== false
3218
- );
3219
- }
3220
- resume(pending, decision) {
3221
- assertAgentApprovalDecision(decision);
3222
- const continuation = approvalContinuations.get(pending);
3223
- if (continuation === void 0 || continuation.agent !== this) {
3224
- throw new TypeError("Approval continuation does not belong to this agent.");
3225
- }
3226
- approvalContinuations.delete(pending);
3227
- continuation.run.resolveApproval(decision);
3228
- return continuation.mode === "generate" ? continuation.execution.next() : continuation.execution.segment();
3229
- }
3230
- session(sessionId, options = {}) {
3231
- if (this.memory === void 0) {
3232
- throw new Error(`Agent "${this.id}" has no memory store configured.`);
3233
- }
3234
- const normalized = sessionId.trim();
3235
- if (normalized.length === 0) {
3236
- throw new TypeError("Session id must be a non-empty string.");
3237
- }
3238
- const context = {
3239
- sessionId: normalized
3240
- };
3241
- if (options.userId !== void 0) {
3242
- context.userId = options.userId;
3243
- }
3244
- if (options.metadata !== void 0) {
3245
- context.metadata = cloneFrozenPlainData(options.metadata);
3246
- }
3247
- return new AgentSession(this, context);
3248
- }
3249
- asTool(options) {
3250
- const description = options.description ?? this.description ?? `Prompt the ${options.name} agent.`;
3251
- return createTool({
3252
- name: options.name,
3253
- description,
3254
- inputSchema: z.object({
3255
- prompt: z.string().describe("The prompt to send to the agent.")
3256
- }),
3257
- outputSchema: z.string(),
3258
- execute: async ({ prompt }, context) => {
3259
- if (options.stream === true && context.emitStreamEvent !== void 0 && this.model.capabilities.streaming && isStreamingCompletionModel(this.model)) {
3260
- let output = "";
3261
- const childStream = this.stream(prompt, {
3262
- maxTurns: options.maxTurns,
3263
- includeToolCallDeltas: context.includeToolCallDeltas !== false
3264
- });
3265
- for await (const event of childStream) {
3266
- if (event.type === "approval_required") {
3267
- await cancelAgentApproval(
3268
- event,
3269
- `Agent tool "${options.name}" cannot suspend for tool approval.`
3270
- );
3271
- throw new Error(
3272
- `Agent tool "${options.name}" cannot suspend for tool approval. Run the agent directly to handle approvals.`
3273
- );
3274
- }
3275
- const streamEvent = {
3276
- agentId: this.id,
3277
- event
3278
- };
3279
- if (this.name !== void 0) {
3280
- streamEvent.agentName = this.name;
3281
- }
3282
- await context.emitStreamEvent(streamEvent);
3283
- if (event.type === "final") {
3284
- output = event.output;
3285
- }
3286
- }
3287
- return output;
3288
- }
3289
- const response = await this.generate(prompt, { maxTurns: options.maxTurns });
3290
- if (response.status === "approval_required") {
3291
- await cancelAgentApproval(
3292
- response,
3293
- `Agent tool "${options.name}" cannot suspend for tool approval.`
3294
- );
3295
- throw new Error(
3296
- `Agent tool "${options.name}" cannot suspend for tool approval. Run the agent directly to handle approvals.`
3297
- );
3298
- }
3299
- return response.output;
3300
- }
3301
- });
3302
- }
3303
- getTool(toolName) {
3304
- return getRegisteredAgentTool(this, toolName);
3305
- }
3306
- async callTool(toolName, args, context) {
3307
- const tool = this.getTool(toolName);
3308
- if (tool === void 0) {
3309
- throw new ToolNotFoundError(toolName);
3310
- }
3311
- return prepareToolCall(tool, args).call(context ?? {});
3312
- }
3313
- };
3314
- var resolvedAgentOptions = /* @__PURE__ */ Symbol("resolvedAgentOptions");
3315
- function createResolvedAgent(options) {
3316
- return new Agent({
3317
- ...options,
3318
- [resolvedAgentOptions]: true
3319
- });
3320
- }
3321
- function getResolvedAgentOptions(agent) {
3322
- const toolState = getAgentToolState(agent);
3323
- return {
3324
- id: agent.id,
3325
- name: agent.name,
3326
- description: agent.description,
3327
- model: agent.model,
3328
- instructions: agent.instructions,
3329
- context: [...agent.context],
3330
- temperature: agent.temperature,
3331
- maxTokens: agent.maxTokens,
3332
- additionalParams: agent.additionalParams,
3333
- tools: [...toolState.staticTools],
3334
- providerTools: [...toolState.providerTools],
3335
- toolIndexes: [...toolState.toolIndexes],
3336
- toolChoice: agent.toolChoice,
3337
- defaultMaxTurns: agent.defaultMaxTurns,
3338
- lifecycle: agent.lifecycle,
3339
- outputSchema: agent.outputSchema,
3340
- observers: [...agent.observers],
3341
- guardrails: [...agent.guardrails],
3342
- middlewares: [...agent.middlewares],
3343
- memory: agent.memory
3344
- };
3345
- }
3346
- function resolveAgentOptions(options) {
3347
- if (isInternalAgentOptions(options)) {
3348
- return options;
3349
- }
3350
- const toolsByName = /* @__PURE__ */ new Map();
3351
- const providerTools = [];
3352
- const toolIndexes = [];
3353
- for (const tool of options.tools ?? []) {
3354
- if (isProviderTool(tool)) {
3355
- providerTools.push(tool);
3356
- } else if (isToolIndex(tool)) {
3357
- toolIndexes.push(tool);
3358
- } else if (tool.kind === "tool-index") {
3359
- throw new TypeError(
3360
- "Invalid tool index: search, searchIds, asTool, tools, and a numeric topK are required."
3361
- );
3362
- } else {
3363
- toolsByName.set(tool.name, tool);
3364
- }
3365
- }
3366
- for (const server of options.mcpServers ?? []) {
3367
- for (const tool of server.tools) {
3368
- toolsByName.set(tool.name, tool);
3369
- }
3370
- }
3371
- if (options.skills !== void 0) {
3372
- for (const tool of options.skills.tools) {
3373
- toolsByName.set(tool.name, tool);
3374
- }
3375
- }
3376
- const memory = resolveAgentMemory(options);
3377
- const instructions = [options.instructions, options.skills?.instructions].filter((part) => part !== void 0 && part.length > 0).join("\n\n");
3378
- return {
3379
- id: options.id,
3380
- name: options.name,
3381
- description: options.description,
3382
- model: options.model,
3383
- instructions: instructions.length === 0 ? void 0 : instructions,
3384
- context: [...options.context ?? []],
3385
- temperature: options.temperature,
3386
- maxTokens: options.maxTokens,
3387
- additionalParams: options.additionalParams,
3388
- tools: [...toolsByName.values()],
3389
- providerTools,
3390
- toolIndexes,
3391
- toolChoice: options.toolChoice,
3392
- defaultMaxTurns: options.maxTurns,
3393
- lifecycle: options.lifecycle,
3394
- outputSchema: options.outputSchema === void 0 ? void 0 : toProviderJsonSchema(options.outputSchema),
3395
- observers: (options.observers ?? []).map(
3396
- (input) => "observer" in input ? { observer: input.observer, failOnObserverError: input.failOnObserverError } : { observer: input }
3397
- ),
3398
- guardrails: options.guardrails === void 0 ? [] : appendGuardrailPolicies([], options.guardrails),
3399
- middlewares: [...options.middlewares ?? []],
3400
- memory
3401
- };
3402
- }
3403
- function assertUniqueIndexedToolNames(indexes) {
3404
- const owners = /* @__PURE__ */ new Map();
3405
- for (const [indexPosition, index] of indexes.entries()) {
3406
- if (!isToolIndex(index)) {
3407
- throw new TypeError(
3408
- "Invalid tool index: search, searchIds, asTool, tools, and a numeric topK are required."
3409
- );
3410
- }
3411
- assertPositiveSearchLimit(index.topK);
3412
- assertFiniteSearchThreshold(index.threshold);
3413
- for (const tool of index.tools) {
3414
- const existingPosition = owners.get(tool.name);
3415
- if (existingPosition !== void 0) {
3416
- if (existingPosition === indexPosition) {
3417
- throw new TypeError(
3418
- `Tool "${tool.name}" is registered more than once by tool index ${indexPosition + 1}. Tool names must be unique within each index.`
3419
- );
3420
- }
3421
- throw new TypeError(
3422
- `Tool "${tool.name}" is registered by multiple tool indexes (${existingPosition + 1} and ${indexPosition + 1}). Tool names must be unique across indexes.`
3423
- );
3424
- }
3425
- owners.set(tool.name, indexPosition);
3426
- }
3427
- }
3428
- }
3429
- function assertValidContextIndexes(inputs) {
3430
- for (const input of inputs) {
3431
- if (!isContextIndex(input)) continue;
3432
- assertPositiveSearchLimit(input.topK);
3433
- assertFiniteSearchThreshold(input.threshold);
3434
- }
3435
- }
3436
- function isInternalAgentOptions(options) {
3437
- return options[resolvedAgentOptions] === true;
3438
- }
3439
- function resolveAgentMemory(options) {
3440
- if (options.memory === void 0) {
3441
- return void 0;
3442
- }
3443
- const { store, ...memoryOptions } = options.memory;
3444
- const resolvedOptions = resolveMemoryOptions(memoryOptions);
3445
- if (resolvedOptions.compaction !== void 0 && store.compaction === void 0) {
3446
- throw new TypeError(
3447
- "Memory compaction requires a store with the optional compaction capability."
3448
- );
3449
- }
3450
- return { store, options: resolvedOptions };
3451
- }
3452
- var approvalContinuations = /* @__PURE__ */ new WeakMap();
3453
- function assertAgentApprovalDecision(decision) {
3454
- if (typeof decision !== "object" || decision === null || typeof decision.approved !== "boolean") {
3455
- throw new TypeError("Approval decision must include an approved boolean.");
3456
- }
3457
- if (decision.reason !== void 0 && typeof decision.reason !== "string") {
3458
- throw new TypeError("Approval decision reason must be a string.");
3459
- }
3460
- }
3461
- function createGenerateExecution(agent, run) {
3462
- const completion = run.generate();
3463
- const execution = {
3464
- async next() {
3465
- const outcome = await Promise.race([
3466
- completion.then((result) => ({ type: "completed", result })),
3467
- run.waitForApproval().then(() => ({ type: "approval" }))
3468
- ]);
3469
- if (outcome.type === "completed") {
3470
- return outcome.result;
3471
- }
3472
- const pending = run.approvalResult();
3473
- approvalContinuations.set(pending, { agent, run, mode: "generate", execution });
3474
- return pending;
3475
- },
3476
- async cancel(reason) {
3477
- run.cancel(reason);
3478
- await completion.catch(() => void 0);
3479
- }
3480
- };
3481
- return execution;
3482
- }
3483
- var StreamExecution = class {
3484
- constructor(agent, run, includeToolCallDeltas) {
3485
- this.agent = agent;
3486
- this.run = run;
3487
- this.iterator = run.events(includeToolCallDeltas)[Symbol.asyncIterator]();
3488
- }
3489
- agent;
3490
- run;
3491
- iterator;
3492
- nextEvent;
3493
- phase = "active";
3494
- segment() {
3495
- if (this.phase === "approval") {
3496
- this.phase = "active";
3497
- }
3498
- return new DefaultAgentStream(this);
3499
- }
3500
- steer(input) {
3501
- return this.run.steer(input);
3502
- }
3503
- async *events() {
3504
- while (true) {
3505
- this.nextEvent ??= this.iterator.next();
3506
- let outcome;
3507
- try {
3508
- outcome = await Promise.race([
3509
- this.nextEvent.then((event) => ({ type: "event", event })),
3510
- this.run.waitForApproval().then(() => ({ type: "approval" }))
3511
- ]);
3512
- } catch (error) {
3513
- this.phase = "terminal";
3514
- throw error;
3515
- }
3516
- if (outcome.type === "approval") {
3517
- this.phase = "approval";
3518
- const pending = this.run.approvalEvent();
3519
- approvalContinuations.set(pending, {
3520
- agent: this.agent,
3521
- run: this.run,
3522
- mode: "stream",
3523
- execution: this
3524
- });
3525
- yield pending;
3526
- return;
3527
- }
3528
- this.nextEvent = void 0;
3529
- if (outcome.event.done) {
3530
- this.phase = "terminal";
3531
- return;
3532
- }
3533
- yield outcome.event.value;
3534
- }
3535
- }
3536
- shouldCancelActiveSegment() {
3537
- return this.phase === "active";
3538
- }
3539
- async cancel(reason) {
3540
- if (this.phase === "terminal" || this.phase === "cancelled") {
3541
- return;
3542
- }
3543
- this.phase = "cancelled";
3544
- this.run.cancel(reason);
3545
- try {
3546
- await this.iterator.return?.();
3547
- } catch {
3548
- }
3549
- }
3550
- };
3551
- function createStreamExecution(agent, run, includeToolCallDeltas) {
3552
- return new StreamExecution(agent, run, includeToolCallDeltas).segment();
3553
- }
3554
- var DefaultAgentStream = class {
3555
- constructor(execution) {
3556
- this.execution = execution;
3557
- }
3558
- execution;
3559
- consuming = false;
3560
- completed = false;
3561
- steer(input) {
3562
- return this.execution.steer(input);
3563
- }
3564
- [Symbol.asyncIterator]() {
3565
- return this.consume()[Symbol.asyncIterator]();
3566
- }
3567
- async *consume() {
3568
- if (this.completed) {
3569
- throw new Error("Agent stream has already been consumed.");
3570
- }
3571
- if (this.consuming) {
3572
- throw new Error("Agent stream is already running.");
3573
- }
3574
- this.consuming = true;
3575
- try {
3576
- for await (const event of this.execution.events()) {
3577
- yield event;
3578
- }
3579
- } finally {
3580
- if (this.execution.shouldCancelActiveSegment()) {
3581
- await this.execution.cancel("Agent stream consumer closed the stream.");
3582
- }
3583
- this.consuming = false;
3584
- this.completed = true;
3585
- }
3586
- }
3587
- };
3588
- async function cancelAgentApproval(pending, reason) {
3589
- const continuation = approvalContinuations.get(pending);
3590
- if (continuation === void 0) {
3591
- return;
3592
- }
3593
- approvalContinuations.delete(pending);
3594
- await continuation.execution.cancel(reason);
3595
- }
3596
- var AgentSession = class {
3597
- constructor(agent, context) {
3598
- this.agent = agent;
3599
- this.context = context;
3600
- }
3601
- agent;
3602
- context;
3603
- generate(input, options = {}) {
3604
- if (Array.isArray(input)) {
3605
- throw new TypeError("AgentSession.generate does not accept Message[] transcripts.");
3606
- }
3607
- const run = AgentRun.fromAgent(this.agent, input, {
3608
- ...options,
3609
- memoryContext: this.context
3610
- });
3611
- return createGenerateExecution(this.agent, run).next();
3612
- }
3613
- stream(input, options = {}) {
3614
- if (Array.isArray(input)) {
3615
- throw new TypeError("AgentSession.stream does not accept Message[] transcripts.");
3616
- }
3617
- return createStreamExecution(
3618
- this.agent,
3619
- AgentRun.fromAgent(this.agent, input, { ...options, memoryContext: this.context }),
3620
- options.includeToolCallDeltas !== false
3621
- );
3622
- }
3623
- async messages() {
3624
- const memory = this.agent.memory;
3625
- if (memory === void 0) {
3626
- throw new Error(`Agent "${this.agent.id}" has no memory store configured.`);
3627
- }
3628
- return memory.store.load(this.context);
3629
- }
3630
- async contextUsage() {
3631
- const messages = await this.messages();
3632
- for (let index = messages.length - 1; index >= 0; index -= 1) {
3633
- const message = messages[index];
3634
- if (message === void 0) {
3635
- continue;
3636
- }
3637
- const generation = getAssistantGenerationMetadata(message);
3638
- if (generation !== void 0) {
3639
- return generation.contextUsage;
3640
- }
3641
- }
3642
- return void 0;
3643
- }
3644
- async clear() {
3645
- const memory = this.agent.memory;
3646
- if (memory === void 0) {
3647
- throw new Error(`Agent "${this.agent.id}" has no memory store configured.`);
3648
- }
3649
- await memory.store.clear(this.context);
3650
- }
3651
- };
3652
- function snapshotContextInput(input) {
3653
- if (!isContextIndex(input)) {
3654
- return Object.freeze({
3655
- id: input.id,
3656
- text: input.text,
3657
- ...input.additionalProps === void 0 ? {} : { additionalProps: cloneFrozenPlainData(input.additionalProps) }
3658
- });
3659
- }
3660
- const format = input.format;
3661
- return Object.freeze({
3662
- kind: "context-index",
3663
- index: input.index,
3664
- topK: input.topK,
3665
- ...input.threshold === void 0 ? {} : { threshold: input.threshold },
3666
- ...input.filter === void 0 ? {} : { filter: cloneFrozenPlainData(input.filter) },
3667
- ...format === void 0 ? {} : { format: (result) => format.call(input, result) }
3668
- });
3669
- }
3670
- function snapshotProviderTool(tool) {
3671
- return Object.freeze({
3672
- ...tool,
3673
- ...tool.configuration === void 0 ? {} : { configuration: cloneFrozenPlainData(tool.configuration) }
3674
- });
3675
- }
3676
- function snapshotToolIndex(index) {
3677
- const inspect = index.inspect;
3678
- return Object.freeze({
3679
- kind: "tool-index",
3680
- tools: Object.freeze([...index.tools]),
3681
- topK: index.topK,
3682
- ...index.threshold === void 0 ? {} : { threshold: index.threshold },
3683
- ...index.filter === void 0 ? {} : { filter: cloneFrozenPlainData(index.filter) },
3684
- search: (request) => index.search(request),
3685
- searchIds: (request) => index.searchIds(request),
3686
- asTool: (options) => index.asTool(options),
3687
- ...inspect === void 0 ? {} : { inspect: (request) => inspect.call(index, request) }
3688
- });
3689
- }
3690
- function snapshotGuardrailPolicy(policy) {
3691
- return Object.freeze({
3692
- ...policy,
3693
- input: Object.freeze([...policy.input]),
3694
- output: Object.freeze([...policy.output])
3695
- });
3696
- }
3697
- function snapshotMemoryRegistration(memory) {
3698
- if (memory === void 0) {
3699
- return void 0;
3700
- }
3701
- const compaction = memory.options.compaction === void 0 ? void 0 : Object.freeze({ ...memory.options.compaction });
3702
- return Object.freeze({
3703
- store: memory.store,
3704
- options: Object.freeze({
3705
- ...memory.options,
3706
- ...compaction === void 0 ? {} : { compaction }
3707
- })
3708
- });
3709
- }
3710
- function cloneFrozenPlainData(value) {
3711
- if (Array.isArray(value)) {
3712
- return Object.freeze(value.map(cloneFrozenPlainData));
3713
- }
3714
- if (typeof value !== "object" || value === null) {
3715
- return value;
3716
- }
3717
- const prototype = Object.getPrototypeOf(value);
3718
- if (prototype !== Object.prototype && prototype !== null) {
3719
- return value;
3720
- }
3721
- const clone = Object.fromEntries(
3722
- Object.entries(value).map(([key, item]) => [key, cloneFrozenPlainData(item)])
3723
- );
3724
- return Object.freeze(clone);
3725
- }
3726
- function dedupeTools(tools) {
3727
- const byName = /* @__PURE__ */ new Map();
3728
- for (const tool of tools) {
3729
- byName.set(tool.name, tool);
3730
- }
3731
- return [...byName.values()];
3732
- }
3733
-
3734
- export {
3735
- MaxTurnsError,
3736
- AgentRunCancelledError,
3737
- getAgentToolState,
3738
- createHook,
3739
- getAgentApprovalRequestDetails,
3740
- createContextIndex,
3741
- isContextIndex,
3742
- withInternalAgentRunOptions,
3743
- Agent,
3744
- createResolvedAgent,
3745
- getResolvedAgentOptions,
3746
- cancelAgentApproval
3747
- };
3748
- //# sourceMappingURL=chunk-IL3ZSNJI.js.map