@anvia/core 0.26.0 → 1.0.0-rc.10

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 (184) hide show
  1. package/README.md +400 -94
  2. package/dist/agent/index.d.ts +67 -71
  3. package/dist/agent/index.js +36 -18
  4. package/dist/agent/interactions/index.d.ts +122 -0
  5. package/dist/agent/interactions/index.js +20 -0
  6. package/dist/agent-DWzW9SoH.d.ts +150 -0
  7. package/dist/chunk-3RM57ZT2.js +31 -0
  8. package/dist/chunk-3RM57ZT2.js.map +1 -0
  9. package/dist/chunk-3RWESPUG.js +331 -0
  10. package/dist/chunk-3RWESPUG.js.map +1 -0
  11. package/dist/{chunk-NCPN4SJR.js → chunk-3SKZ2BKP.js} +15 -13
  12. package/dist/chunk-3SKZ2BKP.js.map +1 -0
  13. package/dist/chunk-3XQGVDU5.js +69 -0
  14. package/dist/chunk-3XQGVDU5.js.map +1 -0
  15. package/dist/{chunk-MRQLEK2B.js → chunk-5C6B6ZRH.js} +69 -51
  16. package/dist/chunk-5C6B6ZRH.js.map +1 -0
  17. package/dist/chunk-6BBOCFHV.js +323 -0
  18. package/dist/chunk-6BBOCFHV.js.map +1 -0
  19. package/dist/chunk-7JLAIN6E.js +15 -0
  20. package/dist/chunk-7JLAIN6E.js.map +1 -0
  21. package/dist/chunk-7PHMK7W4.js +1516 -0
  22. package/dist/chunk-7PHMK7W4.js.map +1 -0
  23. package/dist/{chunk-CWUJUSOS.js → chunk-AZB6N7P4.js} +94 -65
  24. package/dist/chunk-AZB6N7P4.js.map +1 -0
  25. package/dist/chunk-D4PACGPA.js +37 -0
  26. package/dist/chunk-D4PACGPA.js.map +1 -0
  27. package/dist/chunk-EFLT7XZD.js +51 -0
  28. package/dist/chunk-EFLT7XZD.js.map +1 -0
  29. package/dist/chunk-EMZKPRE6.js +667 -0
  30. package/dist/chunk-EMZKPRE6.js.map +1 -0
  31. package/dist/chunk-I3Q7XSBB.js +59 -0
  32. package/dist/chunk-I3Q7XSBB.js.map +1 -0
  33. package/dist/chunk-J6LVLV6P.js +13 -0
  34. package/dist/chunk-J6LVLV6P.js.map +1 -0
  35. package/dist/chunk-LTXABCOO.js +127 -0
  36. package/dist/chunk-LTXABCOO.js.map +1 -0
  37. package/dist/chunk-OJBFDBLG.js +164 -0
  38. package/dist/chunk-OJBFDBLG.js.map +1 -0
  39. package/dist/chunk-QGX73TSQ.js +177 -0
  40. package/dist/chunk-QGX73TSQ.js.map +1 -0
  41. package/dist/chunk-QOUPWOGW.js +29 -0
  42. package/dist/chunk-QOUPWOGW.js.map +1 -0
  43. package/dist/chunk-SJMSS5SI.js +171 -0
  44. package/dist/chunk-SJMSS5SI.js.map +1 -0
  45. package/dist/chunk-T2C3CGDQ.js +56 -0
  46. package/dist/chunk-T2C3CGDQ.js.map +1 -0
  47. package/dist/chunk-VX3HS6PE.js +4569 -0
  48. package/dist/chunk-VX3HS6PE.js.map +1 -0
  49. package/dist/chunk-X4LK4ODN.js +86 -0
  50. package/dist/chunk-X4LK4ODN.js.map +1 -0
  51. package/dist/chunk-ZA564323.js +331 -0
  52. package/dist/chunk-ZA564323.js.map +1 -0
  53. package/dist/completion/index.d.ts +6 -36
  54. package/dist/completion/index.js +34 -29
  55. package/dist/documents/index.d.ts +34 -0
  56. package/dist/documents/index.js +340 -0
  57. package/dist/documents/index.js.map +1 -0
  58. package/dist/dynamic-tools-aIZlg5x1.d.ts +45 -0
  59. package/dist/embeddings/index.d.ts +11 -9
  60. package/dist/embeddings/index.js +3 -4
  61. package/dist/evals/index.d.ts +57 -21
  62. package/dist/evals/index.js +209 -104
  63. package/dist/evals/index.js.map +1 -1
  64. package/dist/extractor/index.d.ts +27 -42
  65. package/dist/extractor/index.js +9 -22
  66. package/dist/guardrails/index.d.ts +7 -129
  67. package/dist/guardrails/index.js +1 -1
  68. package/dist/image-generation/index.d.ts +23 -23
  69. package/dist/image-generation/index.js +7 -39
  70. package/dist/image-generation/index.js.map +1 -1
  71. package/dist/index.d.ts +24 -22
  72. package/dist/index.js +85 -68
  73. package/dist/internal/agent.d.ts +156 -10
  74. package/dist/internal/agent.js +58 -18
  75. package/dist/internal/agent.js.map +1 -1
  76. package/dist/mcp/index.d.ts +7 -15
  77. package/dist/mcp/index.js +3 -348
  78. package/dist/mcp/index.js.map +1 -1
  79. package/dist/memory/index.d.ts +20 -6
  80. package/dist/memory/index.js +11 -10
  81. package/dist/middleware-kcF8AusP.d.ts +59 -0
  82. package/dist/model-call-options-CZkSw_xN.d.ts +6 -0
  83. package/dist/model-listing/index.d.ts +3 -1
  84. package/dist/observability/index.d.ts +23 -4
  85. package/dist/observability/index.js +10 -5
  86. package/dist/observability/index.js.map +1 -1
  87. package/dist/pipeline/index.d.ts +111 -73
  88. package/dist/pipeline/index.js +471 -286
  89. package/dist/pipeline/index.js.map +1 -1
  90. package/dist/provider-output-error-BEwDgVv3.d.ts +99 -0
  91. package/dist/retry-CjvSlKGW.d.ts +16 -0
  92. package/dist/skills/index.d.ts +5 -4
  93. package/dist/skills/index.js +8 -8
  94. package/dist/speech-generation/index.d.ts +37 -0
  95. package/dist/speech-generation/index.js +10 -0
  96. package/dist/streaming/index.js +37 -3
  97. package/dist/streaming/index.js.map +1 -1
  98. package/dist/text-ZLECpQE7.d.ts +32 -0
  99. package/dist/think-tool-BwCsJ365.d.ts +40 -0
  100. package/dist/tool/index.d.ts +11 -6
  101. package/dist/tool/index.js +21 -21
  102. package/dist/tool-BpqpoRSE.d.ts +58 -0
  103. package/dist/transcription/index.d.ts +29 -22
  104. package/dist/transcription/index.js +7 -57
  105. package/dist/transcription/index.js.map +1 -1
  106. package/dist/type-utils-CtHVDRn_.d.ts +6 -0
  107. package/dist/types-CXNE592e.d.ts +130 -0
  108. package/dist/types-Cr4uiYo5.d.ts +99 -0
  109. package/dist/{types-04LqWrmy.d.ts → types-DC1U1XwW.d.ts} +1 -1
  110. package/dist/types-DKOXVTcq.d.ts +155 -0
  111. package/dist/types-DgvozfPc.d.ts +349 -0
  112. package/dist/types-DhkodEft.d.ts +105 -0
  113. package/dist/types-DjqRHeAi.d.ts +31 -0
  114. package/dist/types-Sue2hb_L.d.ts +403 -0
  115. package/dist/vector-store/index.d.ts +34 -34
  116. package/dist/vector-store/index.js +10 -6
  117. package/package.json +22 -24
  118. package/dist/agent-x3YTyv5i.d.ts +0 -222
  119. package/dist/audio-generation/index.d.ts +0 -33
  120. package/dist/audio-generation/index.js +0 -42
  121. package/dist/audio-generation/index.js.map +0 -1
  122. package/dist/chunk-2ODTMRHP.js +0 -54
  123. package/dist/chunk-2ODTMRHP.js.map +0 -1
  124. package/dist/chunk-ADH7NNCS.js +0 -512
  125. package/dist/chunk-ADH7NNCS.js.map +0 -1
  126. package/dist/chunk-BALBBVI3.js +0 -2732
  127. package/dist/chunk-BALBBVI3.js.map +0 -1
  128. package/dist/chunk-CQNNSZPG.js +0 -9
  129. package/dist/chunk-CQNNSZPG.js.map +0 -1
  130. package/dist/chunk-CWUJUSOS.js.map +0 -1
  131. package/dist/chunk-DALYP4PX.js +0 -225
  132. package/dist/chunk-DALYP4PX.js.map +0 -1
  133. package/dist/chunk-HYUYZEAJ.js +0 -223
  134. package/dist/chunk-HYUYZEAJ.js.map +0 -1
  135. package/dist/chunk-I6XOQ4LK.js +0 -466
  136. package/dist/chunk-I6XOQ4LK.js.map +0 -1
  137. package/dist/chunk-JI5YZWNT.js +0 -220
  138. package/dist/chunk-JI5YZWNT.js.map +0 -1
  139. package/dist/chunk-MC3CCKEB.js +0 -221
  140. package/dist/chunk-MC3CCKEB.js.map +0 -1
  141. package/dist/chunk-MELYDKWQ.js +0 -337
  142. package/dist/chunk-MELYDKWQ.js.map +0 -1
  143. package/dist/chunk-MNWK2USR.js +0 -243
  144. package/dist/chunk-MNWK2USR.js.map +0 -1
  145. package/dist/chunk-MRQLEK2B.js.map +0 -1
  146. package/dist/chunk-NCPN4SJR.js.map +0 -1
  147. package/dist/chunk-OIMLU4SF.js +0 -20
  148. package/dist/chunk-OIMLU4SF.js.map +0 -1
  149. package/dist/chunk-Q25IWLBT.js +0 -138
  150. package/dist/chunk-Q25IWLBT.js.map +0 -1
  151. package/dist/chunk-UQX6EXWG.js +0 -33
  152. package/dist/chunk-UQX6EXWG.js.map +0 -1
  153. package/dist/chunk-WQKHFADH.js +0 -12
  154. package/dist/chunk-WQKHFADH.js.map +0 -1
  155. package/dist/chunk-XUUY2L2D.js +0 -42
  156. package/dist/chunk-XUUY2L2D.js.map +0 -1
  157. package/dist/chunk-XWUC7CIT.js +0 -1
  158. package/dist/chunk-XWUC7CIT.js.map +0 -1
  159. package/dist/chunk-YLMDBQO4.js +0 -141
  160. package/dist/chunk-YLMDBQO4.js.map +0 -1
  161. package/dist/errors-2moLDuuN.d.ts +0 -17
  162. package/dist/hooks/index.d.ts +0 -12
  163. package/dist/hooks/index.js +0 -17
  164. package/dist/index-BxSbmOMr.d.ts +0 -257
  165. package/dist/json-BVPssigK.d.ts +0 -39
  166. package/dist/loaders/index.d.ts +0 -91
  167. package/dist/loaders/index.js +0 -299
  168. package/dist/loaders/index.js.map +0 -1
  169. package/dist/middleware-Dp3d_pxi.d.ts +0 -90
  170. package/dist/request/index.d.ts +0 -28
  171. package/dist/request/index.js +0 -25
  172. package/dist/think-tool-DfCMuO8e.d.ts +0 -26
  173. package/dist/tool-Cohdv5GC.d.ts +0 -65
  174. package/dist/types-BCTRUGex.d.ts +0 -47
  175. package/dist/types-BrLbKnEz.d.ts +0 -119
  176. package/dist/types-D9JpeAPF.d.ts +0 -114
  177. package/dist/types-G12i56s2.d.ts +0 -354
  178. package/dist/types-JJCxRnaZ.d.ts +0 -70
  179. package/dist/types-O-abTIin.d.ts +0 -79
  180. package/dist/ui/index.d.ts +0 -107
  181. package/dist/ui/index.js +0 -10
  182. package/dist/ui/index.js.map +0 -1
  183. /package/dist/{hooks → agent/interactions}/index.js.map +0 -0
  184. /package/dist/{request → speech-generation}/index.js.map +0 -0
@@ -0,0 +1,4569 @@
1
+ import {
2
+ assertAgentInteractionResponse,
3
+ parseAgentContinuation,
4
+ parseAgentInteractionResponse,
5
+ parseAgentQuestionPrompts
6
+ } from "./chunk-OJBFDBLG.js";
7
+ import {
8
+ isMcpTool
9
+ } from "./chunk-J6LVLV6P.js";
10
+ import {
11
+ MemoryCompactionConflictError,
12
+ MemoryCompactionError,
13
+ assertPositiveInteger,
14
+ createMemoryCompactionSummary,
15
+ cumulativeCompactedMessageCount
16
+ } from "./chunk-5C6B6ZRH.js";
17
+ import {
18
+ startAgentRunObservers
19
+ } from "./chunk-6BBOCFHV.js";
20
+ import {
21
+ isSkillTool
22
+ } from "./chunk-YK4WAAS4.js";
23
+ import {
24
+ isQuestionTool,
25
+ isToolIndex
26
+ } from "./chunk-SJMSS5SI.js";
27
+ import {
28
+ ToolNotFoundError,
29
+ ToolOutput,
30
+ assertFiniteMinScore,
31
+ assertPositiveSearchLimit,
32
+ assertToolApprovalRequirement,
33
+ createTool,
34
+ normalizeToolResultOutput,
35
+ parseToolArgs,
36
+ prepareToolCall,
37
+ prepareToolCallFromInput,
38
+ retrieveDocuments,
39
+ toolMayRequireApproval,
40
+ toolResultContentToText
41
+ } from "./chunk-EMZKPRE6.js";
42
+ import {
43
+ AgentRunBlockedError,
44
+ AgentRunCancelledError,
45
+ AgentStreamClosedError,
46
+ AgentStructuredOutputError,
47
+ AgentToolSuspensionError,
48
+ MaxTurnsError
49
+ } from "./chunk-X4LK4ODN.js";
50
+ import {
51
+ mapWithConcurrency
52
+ } from "./chunk-3RM57ZT2.js";
53
+ import {
54
+ CompletionStreamAccumulator,
55
+ Usage,
56
+ assertCompletionRequestSupported,
57
+ assertCompletionResponseIntegrity,
58
+ createCompletionRequest,
59
+ getAssistantGenerationMetadata,
60
+ isProviderTool,
61
+ isStreamingCompletionModel,
62
+ textFromAssistantContent
63
+ } from "./chunk-7PHMK7W4.js";
64
+ import {
65
+ assertJsonObject
66
+ } from "./chunk-7JLAIN6E.js";
67
+ import {
68
+ parseMessage,
69
+ parseMessages,
70
+ toProviderJsonSchema
71
+ } from "./chunk-QGX73TSQ.js";
72
+ import {
73
+ isJsonValue
74
+ } from "./chunk-3XQGVDU5.js";
75
+ import {
76
+ abortError,
77
+ completionProviderOutputErrorUsage,
78
+ resolveRetryOptions,
79
+ retryDelayMs,
80
+ retryErrorAttributes,
81
+ retryOptionsForFailure,
82
+ throwIfAborted,
83
+ waitForRetry
84
+ } from "./chunk-3RWESPUG.js";
85
+ import {
86
+ appendGuardrailPolicies,
87
+ hasEnforcedOutputGuardrails,
88
+ runInputGuardrails,
89
+ runOutputGuardrails
90
+ } from "./chunk-AZB6N7P4.js";
91
+
92
+ // src/agent/tool-state.ts
93
+ var agentToolStates = /* @__PURE__ */ new WeakMap();
94
+ function registerAgentToolState(agent, publicState, toolsByName) {
95
+ agentToolStates.set(agent, { publicState, toolsByName });
96
+ }
97
+ function getAgentToolState(agent) {
98
+ return getStoredAgentToolState(agent).publicState;
99
+ }
100
+ function getRegisteredAgentTool(agent, toolName) {
101
+ return getStoredAgentToolState(agent).toolsByName.get(toolName);
102
+ }
103
+ function getStoredAgentToolState(agent) {
104
+ const state = agentToolStates.get(agent);
105
+ if (state === void 0) {
106
+ throw new TypeError("Agent tool state is unavailable.");
107
+ }
108
+ return state;
109
+ }
110
+
111
+ // src/hooks/control.ts
112
+ function createHook(hook) {
113
+ return hook;
114
+ }
115
+ function cancelRun(reason) {
116
+ return { type: "terminate", reason };
117
+ }
118
+ function skipTool(reason) {
119
+ return { type: "skip", reason };
120
+ }
121
+ function requestToolApproval(options = {}) {
122
+ const action = {
123
+ type: "approval_request"
124
+ };
125
+ if (options.reason !== void 0) {
126
+ action.reason = options.reason;
127
+ }
128
+ if (options.rejectMessage !== void 0) {
129
+ action.rejectMessage = options.rejectMessage;
130
+ }
131
+ return action;
132
+ }
133
+ var runControl = {
134
+ continue() {
135
+ return { type: "continue" };
136
+ },
137
+ cancel(reason) {
138
+ return cancelRun(reason);
139
+ }
140
+ };
141
+ var toolCallControl = {
142
+ run() {
143
+ return { type: "continue" };
144
+ },
145
+ skip(reason) {
146
+ return skipTool(reason);
147
+ },
148
+ cancel(reason) {
149
+ return { type: "terminate", reason };
150
+ },
151
+ requestApproval(options) {
152
+ return requestToolApproval(options);
153
+ }
154
+ };
155
+
156
+ // src/agent/vector-context.ts
157
+ function createVectorContext(options) {
158
+ const topK = assertPositiveSearchLimit(options.topK);
159
+ const minScore = assertFiniteMinScore(options.minScore);
160
+ let context = {
161
+ ...options,
162
+ topK,
163
+ kind: "vector-context"
164
+ };
165
+ if (minScore !== void 0) {
166
+ context = { ...context, minScore };
167
+ }
168
+ return Object.freeze(context);
169
+ }
170
+ function isVectorContext(value) {
171
+ if (typeof value !== "object" || value === null) return false;
172
+ const candidate = value;
173
+ if (candidate.kind !== "vector-context" || typeof candidate.store?.search !== "function") {
174
+ return false;
175
+ }
176
+ return candidate.model !== void 0 || candidate.models?.dense !== void 0 && candidate.models.sparse !== void 0;
177
+ }
178
+
179
+ // src/internal/agent-runtime/run-options.ts
180
+ var internalAgentRunOptions = /* @__PURE__ */ Symbol("internalAgentRunOptions");
181
+ function withInternalAgentRunOptions(options, internal) {
182
+ return {
183
+ ...options,
184
+ [internalAgentRunOptions]: internal
185
+ };
186
+ }
187
+ function getInternalAgentRunOptions(options) {
188
+ return options[internalAgentRunOptions];
189
+ }
190
+
191
+ // src/agent/lifecycle.ts
192
+ function composeAgentLifecycle(first, second) {
193
+ if (first === void 0) return second;
194
+ if (second === void 0) return first;
195
+ return {
196
+ async onStart(event) {
197
+ await first.onStart?.(lifecycleSnapshot(event));
198
+ await second.onStart?.(lifecycleSnapshot(event));
199
+ },
200
+ async onStepFinish(event) {
201
+ await first.onStepFinish?.(lifecycleSnapshot(event));
202
+ await second.onStepFinish?.(lifecycleSnapshot(event));
203
+ },
204
+ async onToolStart(event) {
205
+ await first.onToolStart?.(lifecycleSnapshot(event));
206
+ await second.onToolStart?.(lifecycleSnapshot(event));
207
+ },
208
+ async onToolFinish(event) {
209
+ await first.onToolFinish?.(lifecycleSnapshot(event));
210
+ await second.onToolFinish?.(lifecycleSnapshot(event));
211
+ },
212
+ async onFinish(event) {
213
+ await first.onFinish?.(lifecycleSnapshot(event));
214
+ await second.onFinish?.(lifecycleSnapshot(event));
215
+ },
216
+ async onError(event) {
217
+ await first.onError?.(lifecycleSnapshot(event));
218
+ await second.onError?.(lifecycleSnapshot(event));
219
+ }
220
+ };
221
+ }
222
+ function lifecycleSnapshot(value) {
223
+ try {
224
+ return globalThis.structuredClone(value);
225
+ } catch {
226
+ return cloneLifecycleFallback(value, /* @__PURE__ */ new WeakMap());
227
+ }
228
+ }
229
+ function cloneLifecycleFallback(value, seen) {
230
+ if (typeof value !== "object" || value === null) {
231
+ return value;
232
+ }
233
+ const existing = seen.get(value);
234
+ if (existing !== void 0) {
235
+ return existing;
236
+ }
237
+ if (Array.isArray(value)) {
238
+ const clone2 = [];
239
+ seen.set(value, clone2);
240
+ clone2.push(...value.map((item) => cloneLifecycleFallback(item, seen)));
241
+ return clone2;
242
+ }
243
+ if (Object.getPrototypeOf(value) !== Object.prototype) {
244
+ return value;
245
+ }
246
+ const clone = {};
247
+ seen.set(value, clone);
248
+ for (const [key, item] of Object.entries(value)) {
249
+ clone[key] = cloneLifecycleFallback(item, seen);
250
+ }
251
+ return clone;
252
+ }
253
+
254
+ // src/agent/output-schema.ts
255
+ var providerOutputSchemas = /* @__PURE__ */ new WeakMap();
256
+ function registerAgentProviderOutputSchema(agent, schema) {
257
+ if (schema !== void 0) {
258
+ providerOutputSchemas.set(agent, toProviderJsonSchema(schema));
259
+ }
260
+ }
261
+ function getAgentProviderOutputSchema(agent) {
262
+ return providerOutputSchemas.get(agent);
263
+ }
264
+
265
+ // src/internal/async-queue.ts
266
+ function createAsyncQueue() {
267
+ const values = [];
268
+ const waiters = [];
269
+ let closed = false;
270
+ let error;
271
+ function flush() {
272
+ while (waiters.length > 0 && values.length > 0) {
273
+ const waiter = waiters.shift();
274
+ const value = values.shift();
275
+ if (waiter !== void 0) {
276
+ waiter.resolve({ value, done: false });
277
+ }
278
+ }
279
+ if (values.length > 0 || waiters.length === 0 || !closed) {
280
+ return;
281
+ }
282
+ while (waiters.length > 0) {
283
+ const waiter = waiters.shift();
284
+ if (waiter === void 0) {
285
+ continue;
286
+ }
287
+ if (error !== void 0) {
288
+ waiter.reject(error);
289
+ } else {
290
+ waiter.resolve({ value: void 0, done: true });
291
+ }
292
+ }
293
+ }
294
+ return {
295
+ enqueue(value) {
296
+ if (closed) {
297
+ return;
298
+ }
299
+ values.push(value);
300
+ flush();
301
+ },
302
+ close() {
303
+ closed = true;
304
+ flush();
305
+ },
306
+ throw(thrown) {
307
+ closed = true;
308
+ error = thrown;
309
+ flush();
310
+ },
311
+ [Symbol.asyncIterator]() {
312
+ return {
313
+ next() {
314
+ if (values.length > 0) {
315
+ const value = values.shift();
316
+ return Promise.resolve({ value, done: false });
317
+ }
318
+ if (error !== void 0) {
319
+ return Promise.reject(error);
320
+ }
321
+ if (closed) {
322
+ return Promise.resolve({ value: void 0, done: true });
323
+ }
324
+ return new Promise((resolve, reject) => {
325
+ waiters.push({ resolve, reject });
326
+ });
327
+ }
328
+ };
329
+ }
330
+ };
331
+ }
332
+
333
+ // src/internal/rag-text.ts
334
+ function extractRagText(message) {
335
+ if (message.role === "user") {
336
+ if (typeof message.content === "string") {
337
+ return message.content;
338
+ }
339
+ return message.content.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n");
340
+ }
341
+ if (message.role === "tool") {
342
+ return message.content.flatMap((item) => {
343
+ if (item.type !== "tool-result") {
344
+ return [];
345
+ }
346
+ const output = item.output;
347
+ if (output.type === "text" || output.type === "error-text") {
348
+ return [output.value];
349
+ }
350
+ if (output.type === "content") {
351
+ return output.value.flatMap((part) => part.type === "text" ? [part.text] : []);
352
+ }
353
+ return [];
354
+ }).join("\n");
355
+ }
356
+ return void 0;
357
+ }
358
+
359
+ // src/internal/agent-runtime/continuation-state.ts
360
+ function serializeContinuationState(state) {
361
+ const value = structuredClone(state);
362
+ if (!isJsonValue(value) || Array.isArray(value) || value === null) {
363
+ throw new TypeError("Agent continuation state must be strict JSON.");
364
+ }
365
+ return value;
366
+ }
367
+ function parseContinuationState(value, interaction) {
368
+ requireOnlyKeys(value, [
369
+ "kind",
370
+ "history",
371
+ "messages",
372
+ "pending",
373
+ "remainingToolCalls",
374
+ "steering",
375
+ "memoryScope"
376
+ ]);
377
+ if (value.kind !== "anvia.agent-continuation") {
378
+ throw new TypeError("Agent continuation has an unsupported internal state.");
379
+ }
380
+ const history = parseMessages(value.history);
381
+ const messages = parseMessages(value.messages);
382
+ const pending = parsePending(value.pending);
383
+ const remainingToolCalls = parseToolCalls(value.remainingToolCalls);
384
+ const steering = parseSteering(value.steering);
385
+ if (pending.toolCall.toolCallId !== interaction.toolCallId || pending.toolCall.toolName !== interaction.toolName || pending.toolCall.callId !== interaction.callId || pending.internalCallId !== interaction.internalCallId) {
386
+ throw new TypeError("Agent continuation interaction does not match its pending tool call.");
387
+ }
388
+ if (interaction.type === "tool-approval" && !jsonEqual(interaction.input, pending.input)) {
389
+ throw new TypeError("Agent continuation approval input does not match its pending tool input.");
390
+ }
391
+ if (interaction.type === "tool-question") {
392
+ const questions = object(pending.input) && "questions" in pending.input ? parseAgentQuestionPrompts(pending.input.questions) : void 0;
393
+ if (questions === void 0 || !jsonEqual(interaction.questions, questions)) {
394
+ throw new TypeError(
395
+ "Agent continuation questions do not match its pending question tool input."
396
+ );
397
+ }
398
+ }
399
+ const state = {
400
+ kind: "anvia.agent-continuation",
401
+ history,
402
+ messages,
403
+ pending,
404
+ remainingToolCalls,
405
+ steering
406
+ };
407
+ if (value.memoryScope !== void 0) {
408
+ state.memoryScope = parseOptionalJsonObject(value.memoryScope, "memoryScope");
409
+ }
410
+ return state;
411
+ }
412
+ function questionResult(answers) {
413
+ return { type: "json", value: { answers: structuredClone([...answers]) } };
414
+ }
415
+ function parsePending(value) {
416
+ if (!object(value)) throw new TypeError("Agent continuation pending state is invalid.");
417
+ const [toolCall] = parseToolCalls([value.toolCall]);
418
+ if (toolCall === void 0) throw new TypeError("Agent continuation pending tool is missing.");
419
+ if (typeof value.effectiveArgs !== "string" || typeof value.internalCallId !== "string") {
420
+ throw new TypeError("Agent continuation pending execution metadata is invalid.");
421
+ }
422
+ const pending = {
423
+ toolCall,
424
+ effectiveArgs: value.effectiveArgs,
425
+ input: parseJsonValue(value.input, "pending input"),
426
+ internalCallId: value.internalCallId
427
+ };
428
+ if (typeof value.rejectMessage === "string") {
429
+ pending.rejectMessage = value.rejectMessage;
430
+ }
431
+ return pending;
432
+ }
433
+ function parseJsonValue(value, name) {
434
+ if (!isJsonValue(value)) {
435
+ throw new TypeError(`Agent continuation ${name} is invalid.`);
436
+ }
437
+ return structuredClone(value);
438
+ }
439
+ function parseToolCalls(value) {
440
+ if (!Array.isArray(value)) throw new TypeError("Agent continuation tool calls must be an array.");
441
+ const message = parseMessages([{ role: "assistant", content: value }])[0];
442
+ if (message?.role !== "assistant" || typeof message.content === "string") {
443
+ throw new TypeError("Agent continuation tool calls are invalid.");
444
+ }
445
+ if (!message.content.every((part) => part.type === "tool-call")) {
446
+ throw new TypeError("Agent continuation contains a non-tool-call part.");
447
+ }
448
+ return message.content;
449
+ }
450
+ function parseSteering(value) {
451
+ if (!Array.isArray(value)) throw new TypeError("Agent continuation steering state is invalid.");
452
+ return value.map((item) => {
453
+ if (!object(item) || typeof item.id !== "string") {
454
+ throw new TypeError("Agent continuation steering entry is invalid.");
455
+ }
456
+ return { id: item.id, messages: parseMessages(item.messages) };
457
+ });
458
+ }
459
+ function parseOptionalJsonObject(value, name) {
460
+ if (value === void 0) return void 0;
461
+ if (!object(value) || !isJsonValue(value)) {
462
+ throw new TypeError(`Agent continuation ${name} is invalid.`);
463
+ }
464
+ return structuredClone(value);
465
+ }
466
+ function object(value) {
467
+ return typeof value === "object" && value !== null && !Array.isArray(value);
468
+ }
469
+ function requireOnlyKeys(value, allowed) {
470
+ const allowedKeys = new Set(allowed);
471
+ const unknown = Object.keys(value).find((key) => !allowedKeys.has(key));
472
+ if (unknown !== void 0) {
473
+ throw new TypeError(`Agent continuation state contains unknown key "${unknown}".`);
474
+ }
475
+ }
476
+ function jsonEqual(left, right) {
477
+ if (Object.is(left, right)) return true;
478
+ if (Array.isArray(left)) {
479
+ return Array.isArray(right) && left.length === right.length && left.every((value, index) => jsonEqual(value, right[index]));
480
+ }
481
+ if (object(left)) {
482
+ if (!object(right)) return false;
483
+ const keys = Object.keys(left);
484
+ return keys.length === Object.keys(right).length && keys.every((key) => key in right && jsonEqual(left[key], right[key]));
485
+ }
486
+ return false;
487
+ }
488
+
489
+ // src/internal/agent-runtime/interaction-suspension.ts
490
+ var AgentInteractionSignal = class extends Error {
491
+ constructor(interaction, rejectMessage) {
492
+ super("Agent execution requires a human interaction.");
493
+ this.interaction = interaction;
494
+ this.rejectMessage = rejectMessage;
495
+ this.name = "AgentInteractionSignal";
496
+ }
497
+ interaction;
498
+ rejectMessage;
499
+ };
500
+ var ToolExecutionSuspension = class extends Error {
501
+ constructor(interaction, pending) {
502
+ super("Tool execution suspended for human interaction.");
503
+ this.interaction = interaction;
504
+ this.pending = pending;
505
+ this.name = "ToolExecutionSuspension";
506
+ }
507
+ interaction;
508
+ pending;
509
+ completedResults = [];
510
+ remainingToolCalls = [];
511
+ };
512
+ function approvalInteraction(request) {
513
+ if (request.toolCallId === void 0) {
514
+ throw new TypeError("Tool approval requires a canonical toolCallId.");
515
+ }
516
+ if (!isJsonValue(request.args)) {
517
+ throw new TypeError("Tool approval input must be strict JSON.");
518
+ }
519
+ let interaction = {
520
+ type: "tool-approval",
521
+ id: request.id,
522
+ toolName: request.toolName,
523
+ toolCallId: request.toolCallId,
524
+ internalCallId: request.internalCallId,
525
+ input: request.args
526
+ };
527
+ if (request.callId !== void 0) interaction = { ...interaction, callId: request.callId };
528
+ if (request.reason !== void 0) interaction = { ...interaction, reason: request.reason };
529
+ return interaction;
530
+ }
531
+
532
+ // src/internal/agent-runtime/memory.ts
533
+ var AgentRunMemory = class {
534
+ constructor(agent, memoryScope, initialHistory) {
535
+ this.agent = agent;
536
+ this.memoryScope = memoryScope;
537
+ this.initialHistory = initialHistory;
538
+ }
539
+ agent;
540
+ memoryScope;
541
+ initialHistory;
542
+ memoryPolicy() {
543
+ return this.memory()?.savePolicy;
544
+ }
545
+ pendingTurnMessages(newMessages) {
546
+ return this.memoryPolicy() === "turn" ? [...newMessages] : [];
547
+ }
548
+ async prepareHistory(runId, incomingMessageCount, abortSignal) {
549
+ const memory = this.memory();
550
+ if (memory === void 0 || this.memoryScope === void 0) {
551
+ return {
552
+ history: this.initialHistory,
553
+ usage: Usage.empty()
554
+ };
555
+ }
556
+ const preparation = await this.prepareStoredHistory(
557
+ memory,
558
+ runId,
559
+ incomingMessageCount,
560
+ abortSignal
561
+ );
562
+ const memoryHistory = preparation.history;
563
+ const chatHistory = [...memoryHistory, ...this.initialHistory];
564
+ return {
565
+ ...preparation,
566
+ history: chatHistory
567
+ };
568
+ }
569
+ async commitAcceptedInput(runId, messages) {
570
+ const memory = this.memory();
571
+ if (memory === void 0 || this.memoryScope === void 0 || memory.savePolicy !== "message" || messages.length === 0) {
572
+ return;
573
+ }
574
+ await memory.store.append({
575
+ scope: this.memoryScope,
576
+ runId,
577
+ turn: 1,
578
+ messages
579
+ });
580
+ }
581
+ async commitMessages(runId, turn, messages, pendingTurnMessages) {
582
+ const memory = this.memory();
583
+ if (memory === void 0 || this.memoryScope === void 0 || messages.length === 0) {
584
+ return;
585
+ }
586
+ if (memory.savePolicy === "message") {
587
+ await memory.store.append({
588
+ scope: this.memoryScope,
589
+ runId,
590
+ turn,
591
+ messages
592
+ });
593
+ } else if (memory.savePolicy === "turn") {
594
+ pendingTurnMessages.push(...messages);
595
+ }
596
+ }
597
+ async commitCompletedTurn(runId, turn, pendingTurnMessages) {
598
+ const memory = this.memory();
599
+ if (memory === void 0 || this.memoryScope === void 0 || memory.savePolicy !== "turn" || pendingTurnMessages.length === 0) {
600
+ return;
601
+ }
602
+ await memory.store.append({
603
+ scope: this.memoryScope,
604
+ runId,
605
+ turn,
606
+ messages: [...pendingTurnMessages]
607
+ });
608
+ pendingTurnMessages.length = 0;
609
+ }
610
+ async commitCompletedRun(runId, turn, newMessages, pendingTurnMessages) {
611
+ await this.commitCompletedTurn(runId, turn, pendingTurnMessages);
612
+ const memory = this.memory();
613
+ if (memory === void 0 || this.memoryScope === void 0 || memory.savePolicy !== "run") {
614
+ return;
615
+ }
616
+ await memory.store.append({
617
+ scope: this.memoryScope,
618
+ runId,
619
+ turn,
620
+ messages: [...newMessages]
621
+ });
622
+ }
623
+ async recordError(runId, error, newMessages) {
624
+ const memory = this.memory();
625
+ if (memory === void 0 || this.memoryScope === void 0) {
626
+ return;
627
+ }
628
+ await memory.store.recordError?.({
629
+ scope: this.memoryScope,
630
+ runId,
631
+ error,
632
+ messages: [...newMessages]
633
+ });
634
+ }
635
+ memory() {
636
+ return this.memoryScope === void 0 ? void 0 : this.agent.memory;
637
+ }
638
+ async prepareStoredHistory(memory, runId, incomingMessageCount, abortSignal) {
639
+ const scope = this.memoryScope;
640
+ if (scope === void 0) {
641
+ return { history: [], usage: Usage.empty() };
642
+ }
643
+ const options = memory.compaction;
644
+ const capability = memory.store.compaction;
645
+ if (options === void 0 || capability === void 0) {
646
+ return {
647
+ history: await memory.store.load({ scope }),
648
+ usage: Usage.empty()
649
+ };
650
+ }
651
+ let usage = Usage.empty();
652
+ const maxAttempts = options.conflictRetries === false ? 1 : options.conflictRetries.maxAttempts;
653
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
654
+ throwIfAborted(abortSignal);
655
+ const snapshot = await capability.snapshot({ scope });
656
+ throwIfAborted(abortSignal);
657
+ const compactedMessageCount = compactedPrefixLength(
658
+ snapshot.messages,
659
+ incomingMessageCount,
660
+ options.trigger.afterMessages,
661
+ options.retention.recentUserTurns
662
+ );
663
+ if (compactedMessageCount === 0) {
664
+ return { history: snapshot.messages, usage };
665
+ }
666
+ const prefix = snapshot.messages.slice(0, compactedMessageCount);
667
+ let result;
668
+ try {
669
+ result = await options.compactor({
670
+ scope,
671
+ messages: prefix,
672
+ abortSignal
673
+ });
674
+ } catch (error) {
675
+ throw remappedCompactorError(error, usage);
676
+ }
677
+ if (result.usage !== void 0) {
678
+ usage = Usage.add(usage, result.usage);
679
+ }
680
+ const summaryText = result.summary.trim();
681
+ if (summaryText.length === 0) {
682
+ throw new MemoryCompactionError("Memory compactor returned an empty summary.", {
683
+ usage
684
+ });
685
+ }
686
+ const summary = createMemoryCompactionSummary(
687
+ summaryText,
688
+ cumulativeCompactedMessageCount(prefix)
689
+ );
690
+ throwIfAborted(abortSignal);
691
+ let replacement;
692
+ try {
693
+ replacement = await capability.replacePrefix({
694
+ scope,
695
+ revision: snapshot.revision,
696
+ messageCount: compactedMessageCount,
697
+ replacement: summary,
698
+ runId: `memory-compaction:${runId}:${attempt}`
699
+ });
700
+ } catch (error) {
701
+ throw new MemoryCompactionError("Memory compaction prefix replacement failed.", {
702
+ cause: error,
703
+ usage
704
+ });
705
+ }
706
+ if (replacement.status === "committed") {
707
+ const retained = snapshot.messages.slice(compactedMessageCount);
708
+ return {
709
+ history: [summary, ...retained],
710
+ usage,
711
+ compaction: {
712
+ originalMessageCount: snapshot.messages.length,
713
+ compactedMessageCount,
714
+ retainedMessageCount: retained.length,
715
+ attempts: attempt,
716
+ usage
717
+ }
718
+ };
719
+ }
720
+ throwIfAborted(abortSignal);
721
+ }
722
+ throw new MemoryCompactionConflictError(maxAttempts, usage);
723
+ }
724
+ };
725
+ function compactedPrefixLength(messages, incomingMessageCount, afterMessages, recentUserTurns) {
726
+ if (messages.length + incomingMessageCount <= afterMessages) {
727
+ return 0;
728
+ }
729
+ const userMessageIndexes = messages.flatMap(
730
+ (message, index) => message.role === "user" ? [index] : []
731
+ );
732
+ if (userMessageIndexes.length <= recentUserTurns) {
733
+ return 0;
734
+ }
735
+ return userMessageIndexes[userMessageIndexes.length - recentUserTurns] ?? 0;
736
+ }
737
+ function remappedCompactorError(error, usage) {
738
+ if (error instanceof MemoryCompactionError) {
739
+ const mergedUsage = error.usage === void 0 ? usage : isEmptyUsage(usage) ? error.usage : Usage.add(usage, error.usage);
740
+ if (mergedUsage === error.usage || error.usage === void 0 && isEmptyUsage(usage)) {
741
+ return error;
742
+ }
743
+ return new MemoryCompactionError(error.message, {
744
+ cause: error,
745
+ usage: mergedUsage
746
+ });
747
+ }
748
+ return new MemoryCompactionError("Memory compactor failed.", {
749
+ cause: error,
750
+ usage
751
+ });
752
+ }
753
+ function isEmptyUsage(usage) {
754
+ return usage.inputTokens === 0 && usage.outputTokens === 0 && usage.totalTokens === 0 && usage.cachedInputTokens === 0 && usage.cacheCreationInputTokens === 0;
755
+ }
756
+
757
+ // src/internal/agent-runtime/retrieval.ts
758
+ async function fetchContextDocuments(agent, ragText, abortSignal) {
759
+ const documents = [];
760
+ for (const input of agent.context) {
761
+ if (!isVectorContext(input)) {
762
+ documents.push(input);
763
+ continue;
764
+ }
765
+ if (ragText === void 0 || ragText.length === 0) continue;
766
+ const request = {
767
+ query: ragText,
768
+ topK: input.topK,
769
+ minScore: input.minScore,
770
+ filter: input.filter,
771
+ retries: input.retries,
772
+ abortSignal
773
+ };
774
+ const results = "models" in input && input.models !== void 0 ? await retrieveDocuments({
775
+ ...request,
776
+ store: input.store,
777
+ models: input.models,
778
+ fusion: input.fusion
779
+ }) : await retrieveDocuments({ ...request, store: input.store, model: input.model });
780
+ for (const result of results) {
781
+ const formatted = input.format?.(result);
782
+ if (formatted !== void 0) {
783
+ documents.push(formatted);
784
+ continue;
785
+ }
786
+ const metadata = formatMetadata(result.metadata);
787
+ const document = {
788
+ id: result.id,
789
+ text: typeof result.document === "string" ? result.document : JSON.stringify(result.document, null, 2)
790
+ };
791
+ if (metadata !== void 0) document.additionalProps = metadata;
792
+ documents.push(document);
793
+ }
794
+ }
795
+ return documents;
796
+ }
797
+ async function fetchToolDefinitions(agent, ragText, abortSignal) {
798
+ const state = getAgentToolState(agent);
799
+ const staticDefinitions = await Promise.all(
800
+ state.staticTools.map((tool) => tool.definition(ragText ?? ""))
801
+ );
802
+ if (ragText === void 0 || ragText.length === 0 || state.toolIndexes.length === 0) {
803
+ return staticDefinitions;
804
+ }
805
+ const definitions = [...staticDefinitions];
806
+ const names = new Set(staticDefinitions.map((definition) => definition.name));
807
+ for (const index of state.toolIndexes) {
808
+ const results = await index.search({ query: ragText, abortSignal });
809
+ for (const result of results) {
810
+ const toolName = result.document.toolName;
811
+ if (names.has(toolName)) continue;
812
+ const tool = index.tools.find((candidate) => candidate.name === toolName);
813
+ if (tool === void 0) continue;
814
+ names.add(toolName);
815
+ definitions.push(await tool.definition(ragText));
816
+ }
817
+ }
818
+ return definitions;
819
+ }
820
+ function formatMetadata(metadata) {
821
+ if (metadata === void 0) return void 0;
822
+ return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, String(value)]));
823
+ }
824
+
825
+ // src/internal/agent-runtime/run-validation.ts
826
+ function assertNonnegativeSafeInteger(value, name) {
827
+ if (!Number.isSafeInteger(value) || value < 0) {
828
+ throw new TypeError(`${name} must be a nonnegative safe integer.`);
829
+ }
830
+ return value;
831
+ }
832
+ function assertPositiveSafeInteger(value, name) {
833
+ if (!Number.isSafeInteger(value) || value <= 0) {
834
+ throw new TypeError(`${name} must be a positive safe integer.`);
835
+ }
836
+ return value;
837
+ }
838
+
839
+ // src/internal/agent-runtime/stream-events.ts
840
+ function addTurn(turn, event) {
841
+ if (event.type === "text_delta") {
842
+ return { type: "text_delta", turn, delta: event.delta };
843
+ }
844
+ if (event.type === "reasoning_delta") {
845
+ const mapped = { type: "reasoning_delta", turn, delta: event.delta };
846
+ if (event.id !== void 0) mapped.id = event.id;
847
+ if (event.contentType !== void 0) mapped.contentType = event.contentType;
848
+ if (event.signature !== void 0) mapped.signature = event.signature;
849
+ return mapped;
850
+ }
851
+ if (event.type === "source") {
852
+ return { type: "source", turn, source: event.source };
853
+ }
854
+ if (event.type === "provider_tool_call") {
855
+ return { type: "provider_tool_call", turn, toolCall: event.toolCall };
856
+ }
857
+ return { type: "tool_call", turn, toolCall: event.toolCall };
858
+ }
859
+ function addTurnToToolCallDelta(turn, event) {
860
+ const mapped = {
861
+ type: "tool_call_delta",
862
+ turn,
863
+ id: event.id
864
+ };
865
+ if (event.callId !== void 0) mapped.callId = event.callId;
866
+ if (event.name !== void 0) mapped.name = event.name;
867
+ if (event.argumentsDelta !== void 0) mapped.argumentsDelta = event.argumentsDelta;
868
+ if (event.argumentsMode !== void 0) mapped.argumentsMode = event.argumentsMode;
869
+ if (event.signature !== void 0) mapped.signature = event.signature;
870
+ return mapped;
871
+ }
872
+ function isGenerationDeltaEvent(type) {
873
+ return type === "text_delta" || type === "reasoning_delta" || type === "tool_call_delta" || type === "tool_call" || type === "source" || type === "provider_tool_call";
874
+ }
875
+
876
+ // src/internal/agent-runtime/structured-output.ts
877
+ var JSON_FENCE_START = "```json\n";
878
+ var JSON_FENCE_CRLF_START = "```json\r\n";
879
+ var UNLABELED_FENCE_START = "```\n";
880
+ var UNLABELED_FENCE_CRLF_START = "```\r\n";
881
+ var FENCE_END = "\n```";
882
+ var STRUCTURED_OUTPUT_RETRY_PROMPT = "Your previous response was invalid structured output. Return only raw JSON that matches the supplied JSON schema. Do not use Markdown fences or include commentary.";
883
+ var STRUCTURED_OUTPUT_TRUNCATED_RETRY_PROMPT = "Your previous response exceeded the provider output limit. Return substantially shorter raw JSON that matches the supplied JSON schema. Do not use Markdown fences or include commentary.";
884
+ var STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH = 8192;
885
+ var STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER = "\n...[output omitted]...\n";
886
+ function structuredOutputRepairPreview(text) {
887
+ if (text.length <= STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH) {
888
+ return { text, includedOutputLength: text.length };
889
+ }
890
+ const availableLength = STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH - STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER.length;
891
+ const headLength = Math.ceil(availableLength / 2);
892
+ const tailLength = availableLength - headLength;
893
+ return {
894
+ text: `${text.slice(0, headLength)}${STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER}${text.slice(-tailLength)}`,
895
+ includedOutputLength: headLength + tailLength
896
+ };
897
+ }
898
+ function normalizeStructuredOutput(text) {
899
+ const trimmed = text.trim();
900
+ const opening = fenceOpening(trimmed);
901
+ if (opening === void 0 || !trimmed.endsWith(FENCE_END)) {
902
+ return { text: trimmed, format: "raw" };
903
+ }
904
+ const closingStart = trimmed.length - 3;
905
+ const precedingNewline = closingStart - 1;
906
+ const contentEnd = trimmed[precedingNewline - 1] === "\r" ? precedingNewline - 1 : precedingNewline;
907
+ return {
908
+ text: trimmed.slice(opening.length, contentEnd).trim(),
909
+ format: opening.format
910
+ };
911
+ }
912
+ function fenceOpening(text) {
913
+ if (text.startsWith(JSON_FENCE_START)) {
914
+ return { length: JSON_FENCE_START.length, format: "json-fence" };
915
+ }
916
+ if (text.startsWith(JSON_FENCE_CRLF_START)) {
917
+ return { length: JSON_FENCE_CRLF_START.length, format: "json-fence" };
918
+ }
919
+ if (text.startsWith(UNLABELED_FENCE_START)) {
920
+ return { length: UNLABELED_FENCE_START.length, format: "unlabeled-fence" };
921
+ }
922
+ if (text.startsWith(UNLABELED_FENCE_CRLF_START)) {
923
+ return { length: UNLABELED_FENCE_CRLF_START.length, format: "unlabeled-fence" };
924
+ }
925
+ return void 0;
926
+ }
927
+
928
+ // src/internal/agent-runtime/tool-execution.ts
929
+ var ToolCallExecutor = class {
930
+ constructor(agent, activeHook, approvalHandler, lifecycle, runContext, concurrency, requestMiddlewares, abortSignal, cancel) {
931
+ this.agent = agent;
932
+ this.activeHook = activeHook;
933
+ this.approvalHandler = approvalHandler;
934
+ this.lifecycle = lifecycle;
935
+ this.runContext = runContext;
936
+ this.concurrency = concurrency;
937
+ this.requestMiddlewares = requestMiddlewares;
938
+ this.abortSignal = abortSignal;
939
+ this.cancel = cancel;
940
+ }
941
+ agent;
942
+ activeHook;
943
+ approvalHandler;
944
+ lifecycle;
945
+ runContext;
946
+ concurrency;
947
+ requestMiddlewares;
948
+ abortSignal;
949
+ cancel;
950
+ async execute(toolCalls, onResult, onStreamEvent, observation) {
951
+ assertCompletionResponseIntegrity({
952
+ response: {
953
+ choice: [...toolCalls],
954
+ usage: Usage.empty(),
955
+ rawResponse: void 0
956
+ }
957
+ });
958
+ const executeOne = async (toolCall) => {
959
+ throwIfAborted(this.abortSignal);
960
+ const args = JSON.stringify(toolCall.input);
961
+ const internalCallId = globalThis.crypto.randomUUID();
962
+ const hookArgs = {
963
+ toolName: toolCall.toolName,
964
+ toolCallId: toolCall.toolCallId,
965
+ internalCallId,
966
+ args
967
+ };
968
+ if (toolCall.callId !== void 0) {
969
+ hookArgs.callId = toolCall.callId;
970
+ }
971
+ const tool = this.agent.getTool(toolCall.toolName);
972
+ const toolDefinition = observation?.toolDefinitions?.find(
973
+ (definition) => definition.name === toolCall.toolName
974
+ );
975
+ const toolMetadata = toolTraceMetadata(tool);
976
+ let toolStartArgs = {
977
+ turn: observation?.turn ?? 0,
978
+ toolCall,
979
+ toolName: toolCall.toolName,
980
+ internalCallId,
981
+ args
982
+ };
983
+ if (toolCall.callId !== void 0) {
984
+ toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };
985
+ }
986
+ if (toolDefinition !== void 0) toolStartArgs = { ...toolStartArgs, toolDefinition };
987
+ if (toolMetadata !== void 0) toolStartArgs = { ...toolStartArgs, toolMetadata };
988
+ const toolObservers = await observation?.runObservers.startTool(toolStartArgs);
989
+ const toolObservation = new ToolObserverScope(toolObservers);
990
+ let output;
991
+ let skipped = false;
992
+ let toolExecutionFailed = false;
993
+ let effectiveArgs = args;
994
+ try {
995
+ const callAction = await this.activeHook?.onToolCall?.({
996
+ ...hookArgs,
997
+ tool: toolCallControl
998
+ });
999
+ if (callAction?.type === "terminate") {
1000
+ throw this.cancel(callAction.reason);
1001
+ }
1002
+ if (callAction?.type === "skip") {
1003
+ output = { type: "text", value: callAction.reason };
1004
+ skipped = true;
1005
+ } else {
1006
+ try {
1007
+ effectiveArgs = await this.runToolInputMiddlewares({
1008
+ ...hookArgs,
1009
+ turn: observation?.turn ?? 0,
1010
+ originalArgs: args
1011
+ });
1012
+ hookArgs.args = effectiveArgs;
1013
+ let prepared;
1014
+ try {
1015
+ prepared = this.prepareToolCall(tool, toolCall.toolName, effectiveArgs);
1016
+ } catch (error) {
1017
+ const outcome = await this.handleToolError(
1018
+ toolCall,
1019
+ hookArgs,
1020
+ effectiveArgs,
1021
+ error,
1022
+ toolObservation,
1023
+ observation
1024
+ );
1025
+ output = outcome.output;
1026
+ toolExecutionFailed = outcome.failed;
1027
+ }
1028
+ if (prepared !== void 0 && isQuestionTool(tool)) {
1029
+ try {
1030
+ const questions = parseAgentQuestionPrompts(
1031
+ prepared.input.questions
1032
+ );
1033
+ const interaction = {
1034
+ type: "tool-question",
1035
+ id: globalThis.crypto.randomUUID(),
1036
+ toolName: toolCall.toolName,
1037
+ toolCallId: toolCall.toolCallId,
1038
+ internalCallId,
1039
+ questions
1040
+ };
1041
+ if (toolCall.callId !== void 0) {
1042
+ Object.assign(interaction, { callId: toolCall.callId });
1043
+ }
1044
+ throw new AgentInteractionSignal(interaction);
1045
+ } catch (error) {
1046
+ if (error instanceof AgentInteractionSignal) throw error;
1047
+ const outcome = await this.handleToolError(
1048
+ toolCall,
1049
+ hookArgs,
1050
+ effectiveArgs,
1051
+ error,
1052
+ toolObservation,
1053
+ observation
1054
+ );
1055
+ output = outcome.output;
1056
+ toolExecutionFailed = outcome.failed;
1057
+ prepared = void 0;
1058
+ }
1059
+ }
1060
+ if (prepared !== void 0) {
1061
+ const approvalContext = createApprovalContext(
1062
+ prepared.input,
1063
+ hookArgs,
1064
+ this.agent,
1065
+ this.runContext
1066
+ );
1067
+ const approvalDecision = callAction?.type === "approval_request" ? await this.requestApproval(approvalContext, callAction, observation) : await this.evaluateToolApproval(tool, approvalContext, observation) ?? {
1068
+ approved: true
1069
+ };
1070
+ if (!approvalDecision.approved) {
1071
+ output = { type: "execution-denied", reason: approvalDecision.result };
1072
+ skipped = true;
1073
+ } else {
1074
+ const step = observation?.turn ?? 0;
1075
+ const lifecycleEvent = {
1076
+ runId: this.runContext.runId,
1077
+ step,
1078
+ toolName: toolCall.toolName,
1079
+ input: lifecycleSnapshot(prepared.input)
1080
+ };
1081
+ if (toolCall.callId !== void 0) {
1082
+ Object.assign(lifecycleEvent, { toolCallId: toolCall.callId });
1083
+ }
1084
+ await this.lifecycle?.onToolStart?.(lifecycleEvent);
1085
+ const startedAt = Date.now();
1086
+ const outcome = await this.runApprovedToolCall(
1087
+ prepared,
1088
+ toolCall,
1089
+ hookArgs,
1090
+ effectiveArgs,
1091
+ toolObservation,
1092
+ observation,
1093
+ onStreamEvent
1094
+ );
1095
+ output = outcome.output;
1096
+ toolExecutionFailed = outcome.failed;
1097
+ const durationMs = Date.now() - startedAt;
1098
+ await this.lifecycle?.onToolFinish?.(
1099
+ outcome.failed ? {
1100
+ ...lifecycleEvent,
1101
+ durationMs,
1102
+ success: false,
1103
+ error: lifecycleSnapshot(outcome.error)
1104
+ } : {
1105
+ ...lifecycleEvent,
1106
+ durationMs,
1107
+ success: true,
1108
+ output: lifecycleSnapshot(output)
1109
+ }
1110
+ );
1111
+ }
1112
+ }
1113
+ } catch (error) {
1114
+ if (error instanceof AgentInteractionSignal) {
1115
+ await toolObservation.suspend({
1116
+ ...toolStartArgs,
1117
+ interaction: error.interaction
1118
+ });
1119
+ throw error;
1120
+ }
1121
+ await toolObservation.error(
1122
+ toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
1123
+ );
1124
+ throw error;
1125
+ }
1126
+ }
1127
+ if (output === void 0) {
1128
+ throw new Error(`Tool "${toolCall.toolName}" did not produce an execution result.`);
1129
+ }
1130
+ let result = toolOutputToText(output);
1131
+ let structuredResult = toolOutputToStructuredResult(output);
1132
+ if (!isSkillTool(tool)) {
1133
+ const middlewareReplacement = await this.runToolResultMiddlewares({
1134
+ ...hookArgs,
1135
+ args: effectiveArgs,
1136
+ result,
1137
+ originalResult: result,
1138
+ structuredResult,
1139
+ originalStructuredResult: structuredResult,
1140
+ turn: observation?.turn ?? 0
1141
+ });
1142
+ if (middlewareReplacement !== void 0) {
1143
+ output = middlewareReplacement;
1144
+ result = toolOutputToText(middlewareReplacement);
1145
+ structuredResult = toolOutputToStructuredResult(middlewareReplacement);
1146
+ }
1147
+ }
1148
+ const resultAction = await this.activeHook?.onToolResult?.({
1149
+ ...hookArgs,
1150
+ args: effectiveArgs,
1151
+ result,
1152
+ structuredResult,
1153
+ run: runControl
1154
+ });
1155
+ if (!toolExecutionFailed) {
1156
+ await toolObservation.end({
1157
+ turn: observation?.turn ?? 0,
1158
+ toolCall,
1159
+ toolName: toolCall.toolName,
1160
+ internalCallId,
1161
+ args: effectiveArgs,
1162
+ result,
1163
+ structuredResult,
1164
+ skipped,
1165
+ toolCallId: toolCall.callId
1166
+ });
1167
+ }
1168
+ if (resultAction?.type === "terminate") {
1169
+ throw this.cancel(resultAction.reason);
1170
+ }
1171
+ const resultPayload = {
1172
+ type: "tool_result",
1173
+ toolName: toolCall.toolName,
1174
+ toolCallId: toolCall.toolCallId,
1175
+ internalCallId,
1176
+ args: effectiveArgs,
1177
+ output,
1178
+ result,
1179
+ structuredResult
1180
+ };
1181
+ if (toolCall.callId !== void 0) resultPayload.callId = toolCall.callId;
1182
+ onResult?.(resultPayload);
1183
+ let resultPart = {
1184
+ type: "tool-result",
1185
+ toolCallId: toolCall.toolCallId,
1186
+ toolName: toolCall.toolName,
1187
+ output
1188
+ };
1189
+ if (toolCall.callId !== void 0) {
1190
+ resultPart = { ...resultPart, callId: toolCall.callId };
1191
+ }
1192
+ return resultPart;
1193
+ } catch (error) {
1194
+ if (error instanceof AgentInteractionSignal) {
1195
+ const pending = {
1196
+ toolCall,
1197
+ effectiveArgs,
1198
+ input: error.interaction.type === "tool-approval" ? error.interaction.input : parseToolArgs(effectiveArgs),
1199
+ internalCallId
1200
+ };
1201
+ if (error.rejectMessage !== void 0) pending.rejectMessage = error.rejectMessage;
1202
+ throw new ToolExecutionSuspension(error.interaction, pending);
1203
+ }
1204
+ await toolObservation.error(
1205
+ toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
1206
+ );
1207
+ throw error;
1208
+ }
1209
+ };
1210
+ if (this.concurrency === 1) {
1211
+ const results = [];
1212
+ for (const toolCall of toolCalls) {
1213
+ try {
1214
+ results.push(await executeOne(toolCall));
1215
+ } catch (error) {
1216
+ if (error instanceof ToolExecutionSuspension) {
1217
+ error.completedResults = [...results];
1218
+ error.remainingToolCalls = toolCalls.slice(results.length + 1);
1219
+ }
1220
+ throw error;
1221
+ }
1222
+ }
1223
+ return results;
1224
+ }
1225
+ return mapWithConcurrency(toolCalls, this.concurrency, executeOne);
1226
+ }
1227
+ async executeResumed(pending, onResult, onStreamEvent, observation) {
1228
+ throwIfAborted(this.abortSignal);
1229
+ const { toolCall, internalCallId, effectiveArgs } = pending;
1230
+ const tool = this.agent.getTool(toolCall.toolName);
1231
+ if (tool === void 0) {
1232
+ throw new Error(
1233
+ `Cannot resume tool interaction because tool "${toolCall.toolName}" is no longer registered.`
1234
+ );
1235
+ }
1236
+ if (isQuestionTool(tool)) {
1237
+ throw new TypeError("Question interactions are resolved from their submitted answers.");
1238
+ }
1239
+ const hookArgs = {
1240
+ toolName: toolCall.toolName,
1241
+ toolCallId: toolCall.toolCallId,
1242
+ internalCallId,
1243
+ args: effectiveArgs
1244
+ };
1245
+ if (toolCall.callId !== void 0) hookArgs.callId = toolCall.callId;
1246
+ const toolDefinition = observation?.toolDefinitions?.find(
1247
+ (definition) => definition.name === toolCall.toolName
1248
+ );
1249
+ const toolMetadata = toolTraceMetadata(tool);
1250
+ let toolStartArgs = {
1251
+ turn: observation?.turn ?? 0,
1252
+ toolCall,
1253
+ toolName: toolCall.toolName,
1254
+ internalCallId,
1255
+ args: effectiveArgs
1256
+ };
1257
+ if (toolCall.callId !== void 0) {
1258
+ toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };
1259
+ }
1260
+ if (toolDefinition !== void 0) toolStartArgs = { ...toolStartArgs, toolDefinition };
1261
+ if (toolMetadata !== void 0) toolStartArgs = { ...toolStartArgs, toolMetadata };
1262
+ const observers = await observation?.runObservers.startTool(toolStartArgs);
1263
+ const toolObservation = new ToolObserverScope(observers);
1264
+ let output;
1265
+ let failed = false;
1266
+ try {
1267
+ const prepared = prepareToolCallFromInput(tool, pending.input);
1268
+ const step = observation?.turn ?? 0;
1269
+ const lifecycleEvent = {
1270
+ runId: this.runContext.runId,
1271
+ step,
1272
+ toolName: toolCall.toolName,
1273
+ input: lifecycleSnapshot(prepared.input)
1274
+ };
1275
+ if (toolCall.callId !== void 0) {
1276
+ Object.assign(lifecycleEvent, { toolCallId: toolCall.callId });
1277
+ }
1278
+ await this.lifecycle?.onToolStart?.(lifecycleEvent);
1279
+ const startedAt = Date.now();
1280
+ const outcome = await this.runApprovedToolCall(
1281
+ prepared,
1282
+ toolCall,
1283
+ hookArgs,
1284
+ effectiveArgs,
1285
+ toolObservation,
1286
+ observation,
1287
+ onStreamEvent
1288
+ );
1289
+ output = outcome.output;
1290
+ failed = outcome.failed;
1291
+ const durationMs = Date.now() - startedAt;
1292
+ await this.lifecycle?.onToolFinish?.(
1293
+ outcome.failed ? {
1294
+ ...lifecycleEvent,
1295
+ durationMs,
1296
+ success: false,
1297
+ error: lifecycleSnapshot(outcome.error)
1298
+ } : {
1299
+ ...lifecycleEvent,
1300
+ durationMs,
1301
+ success: true,
1302
+ output: lifecycleSnapshot(output)
1303
+ }
1304
+ );
1305
+ let result = toolOutputToText(output);
1306
+ let structuredResult = toolOutputToStructuredResult(output);
1307
+ if (!isSkillTool(tool)) {
1308
+ const replacement = await this.runToolResultMiddlewares({
1309
+ ...hookArgs,
1310
+ args: effectiveArgs,
1311
+ result,
1312
+ originalResult: result,
1313
+ structuredResult,
1314
+ originalStructuredResult: structuredResult,
1315
+ turn: step
1316
+ });
1317
+ if (replacement !== void 0) {
1318
+ output = replacement;
1319
+ result = toolOutputToText(replacement);
1320
+ structuredResult = toolOutputToStructuredResult(replacement);
1321
+ }
1322
+ }
1323
+ const resultAction = await this.activeHook?.onToolResult?.({
1324
+ ...hookArgs,
1325
+ result,
1326
+ structuredResult,
1327
+ run: runControl
1328
+ });
1329
+ if (!failed) {
1330
+ await toolObservation.end({
1331
+ turn: step,
1332
+ toolCall,
1333
+ toolName: toolCall.toolName,
1334
+ internalCallId,
1335
+ args: effectiveArgs,
1336
+ result,
1337
+ structuredResult,
1338
+ skipped: false,
1339
+ toolCallId: toolCall.callId
1340
+ });
1341
+ }
1342
+ if (resultAction?.type === "terminate") {
1343
+ throw this.cancel(resultAction.reason);
1344
+ }
1345
+ const resultPayload = {
1346
+ type: "tool_result",
1347
+ toolName: toolCall.toolName,
1348
+ toolCallId: toolCall.toolCallId,
1349
+ internalCallId,
1350
+ args: effectiveArgs,
1351
+ output,
1352
+ result,
1353
+ structuredResult
1354
+ };
1355
+ if (toolCall.callId !== void 0) resultPayload.callId = toolCall.callId;
1356
+ onResult?.(resultPayload);
1357
+ let resultPart = {
1358
+ type: "tool-result",
1359
+ toolName: toolCall.toolName,
1360
+ toolCallId: toolCall.toolCallId,
1361
+ output
1362
+ };
1363
+ if (toolCall.callId !== void 0) resultPart = { ...resultPart, callId: toolCall.callId };
1364
+ return resultPart;
1365
+ } catch (error) {
1366
+ await toolObservation.error(
1367
+ toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
1368
+ );
1369
+ throw error;
1370
+ }
1371
+ }
1372
+ async resolveResumed(pending, initialOutput, onResult, observation) {
1373
+ throwIfAborted(this.abortSignal);
1374
+ const { toolCall, internalCallId, effectiveArgs } = pending;
1375
+ const tool = this.agent.getTool(toolCall.toolName);
1376
+ if (tool === void 0) {
1377
+ throw new Error(
1378
+ `Cannot resume tool interaction because tool "${toolCall.toolName}" is no longer registered.`
1379
+ );
1380
+ }
1381
+ const hookArgs = {
1382
+ toolName: toolCall.toolName,
1383
+ toolCallId: toolCall.toolCallId,
1384
+ internalCallId,
1385
+ args: effectiveArgs
1386
+ };
1387
+ if (toolCall.callId !== void 0) hookArgs.callId = toolCall.callId;
1388
+ const toolDefinition = observation?.toolDefinitions?.find(
1389
+ (definition) => definition.name === toolCall.toolName
1390
+ );
1391
+ const toolMetadata = toolTraceMetadata(tool);
1392
+ let toolStartArgs = {
1393
+ turn: observation?.turn ?? 0,
1394
+ toolCall,
1395
+ toolName: toolCall.toolName,
1396
+ internalCallId,
1397
+ args: effectiveArgs
1398
+ };
1399
+ if (toolCall.callId !== void 0) {
1400
+ toolStartArgs = { ...toolStartArgs, toolCallId: toolCall.callId };
1401
+ }
1402
+ if (toolDefinition !== void 0) toolStartArgs = { ...toolStartArgs, toolDefinition };
1403
+ if (toolMetadata !== void 0) toolStartArgs = { ...toolStartArgs, toolMetadata };
1404
+ const observers = await observation?.runObservers.startTool(toolStartArgs);
1405
+ const toolObservation = new ToolObserverScope(observers);
1406
+ try {
1407
+ let output = initialOutput;
1408
+ let result = toolOutputToText(output);
1409
+ let structuredResult = toolOutputToStructuredResult(output);
1410
+ if (!isSkillTool(tool)) {
1411
+ const replacement = await this.runToolResultMiddlewares({
1412
+ ...hookArgs,
1413
+ args: effectiveArgs,
1414
+ result,
1415
+ originalResult: result,
1416
+ structuredResult,
1417
+ originalStructuredResult: structuredResult,
1418
+ turn: observation?.turn ?? 0
1419
+ });
1420
+ if (replacement !== void 0) {
1421
+ output = replacement;
1422
+ result = toolOutputToText(replacement);
1423
+ structuredResult = toolOutputToStructuredResult(replacement);
1424
+ }
1425
+ }
1426
+ const resultAction = await this.activeHook?.onToolResult?.({
1427
+ ...hookArgs,
1428
+ result,
1429
+ structuredResult,
1430
+ run: runControl
1431
+ });
1432
+ await toolObservation.end({
1433
+ turn: observation?.turn ?? 0,
1434
+ toolCall,
1435
+ toolName: toolCall.toolName,
1436
+ internalCallId,
1437
+ args: effectiveArgs,
1438
+ result,
1439
+ structuredResult,
1440
+ skipped: true,
1441
+ toolCallId: toolCall.callId
1442
+ });
1443
+ if (resultAction?.type === "terminate") {
1444
+ throw this.cancel(resultAction.reason);
1445
+ }
1446
+ const resultPayload = {
1447
+ type: "tool_result",
1448
+ toolName: toolCall.toolName,
1449
+ toolCallId: toolCall.toolCallId,
1450
+ internalCallId,
1451
+ args: effectiveArgs,
1452
+ output,
1453
+ result,
1454
+ structuredResult
1455
+ };
1456
+ if (toolCall.callId !== void 0) resultPayload.callId = toolCall.callId;
1457
+ onResult?.(resultPayload);
1458
+ let resultPart = {
1459
+ type: "tool-result",
1460
+ toolName: toolCall.toolName,
1461
+ toolCallId: toolCall.toolCallId,
1462
+ output
1463
+ };
1464
+ if (toolCall.callId !== void 0) resultPart = { ...resultPart, callId: toolCall.callId };
1465
+ return resultPart;
1466
+ } catch (error) {
1467
+ await toolObservation.error(
1468
+ toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
1469
+ );
1470
+ throw error;
1471
+ }
1472
+ }
1473
+ async runApprovedToolCall(prepared, toolCall, hookArgs, effectiveArgs, toolObservation, observation, onStreamEvent) {
1474
+ try {
1475
+ const toolContext = {
1476
+ abortSignal: this.abortSignal,
1477
+ emitStreamEvent: async (event) => {
1478
+ let streamEventArgs = {
1479
+ turn: observation?.turn ?? 0,
1480
+ toolCall,
1481
+ toolName: toolCall.toolName,
1482
+ internalCallId: hookArgs.internalCallId,
1483
+ args: effectiveArgs,
1484
+ event
1485
+ };
1486
+ if (toolCall.callId !== void 0) {
1487
+ streamEventArgs = { ...streamEventArgs, toolCallId: toolCall.callId };
1488
+ }
1489
+ await toolObservation.streamEvent(streamEventArgs);
1490
+ const payload = agentToolEventPayload(toolCall, hookArgs.internalCallId, event);
1491
+ if (payload !== void 0) {
1492
+ onStreamEvent?.(payload);
1493
+ }
1494
+ }
1495
+ };
1496
+ return {
1497
+ output: await prepared.call(toolContext),
1498
+ failed: false
1499
+ };
1500
+ } catch (error) {
1501
+ return this.handleToolError(
1502
+ toolCall,
1503
+ hookArgs,
1504
+ effectiveArgs,
1505
+ error,
1506
+ toolObservation,
1507
+ observation
1508
+ );
1509
+ }
1510
+ }
1511
+ prepareToolCall(tool, toolName, args) {
1512
+ if (tool !== void 0) {
1513
+ return prepareToolCall(tool, args);
1514
+ }
1515
+ const input = parseToolArgs(args);
1516
+ return {
1517
+ input,
1518
+ call: (context) => this.agent.callTool(toolName, args, context)
1519
+ };
1520
+ }
1521
+ async handleToolError(toolCall, hookArgs, args, error, toolObservation, observation) {
1522
+ const errorAction = await this.activeHook?.onToolError?.({
1523
+ ...hookArgs,
1524
+ args,
1525
+ error,
1526
+ run: runControl
1527
+ });
1528
+ await toolObservation.error(
1529
+ toolErrorArgs(observation?.turn ?? 0, toolCall, hookArgs.internalCallId, args, error)
1530
+ );
1531
+ if (errorAction?.type === "terminate") {
1532
+ throw this.cancel(errorAction.reason);
1533
+ }
1534
+ return {
1535
+ output: {
1536
+ type: "error-text",
1537
+ value: error instanceof Error ? error.toString() : String(error)
1538
+ },
1539
+ failed: true,
1540
+ error
1541
+ };
1542
+ }
1543
+ async runToolResultMiddlewares(args) {
1544
+ let result = args.result;
1545
+ let structuredResult = args.structuredResult;
1546
+ let replaced = false;
1547
+ for (const middleware of this.activeMiddlewares()) {
1548
+ const outputReplacement = await middleware.onToolOutput?.({
1549
+ ...args,
1550
+ result,
1551
+ structuredResult
1552
+ });
1553
+ if (outputReplacement !== void 0) {
1554
+ const normalized = normalizeToolOutputMiddlewareResult(outputReplacement);
1555
+ if (normalized.result !== void 0) {
1556
+ result = normalized.result;
1557
+ structuredResult = void 0;
1558
+ }
1559
+ if (normalized.structuredResult !== void 0) {
1560
+ structuredResult = normalized.structuredResult;
1561
+ result = toolResultContentToText(normalized.structuredResult);
1562
+ }
1563
+ replaced = true;
1564
+ }
1565
+ }
1566
+ return replaced ? structuredResult === void 0 ? { type: "text", value: result } : { type: "content", value: structuredResult } : void 0;
1567
+ }
1568
+ async runToolInputMiddlewares(args) {
1569
+ let current = args.args;
1570
+ for (const middleware of this.activeMiddlewares()) {
1571
+ const replacement = await middleware.onToolInput?.({
1572
+ ...args,
1573
+ args: current
1574
+ });
1575
+ if (replacement?.args !== void 0) {
1576
+ if (typeof replacement.args === "string") {
1577
+ current = replacement.args;
1578
+ } else {
1579
+ if (!isJsonValue(replacement.args)) {
1580
+ throw new TypeError("Tool input middleware args must be a strict JSON value.");
1581
+ }
1582
+ current = JSON.stringify(replacement.args);
1583
+ }
1584
+ }
1585
+ }
1586
+ return current;
1587
+ }
1588
+ activeMiddlewares() {
1589
+ return [...this.agent.middlewares, ...this.requestMiddlewares];
1590
+ }
1591
+ async evaluateToolApproval(tool, context, observation) {
1592
+ const requirement = tool?.requiresApproval;
1593
+ if (requirement === void 0) return void 0;
1594
+ const resolved = typeof requirement === "function" ? await requirement(context.args, context) : requirement;
1595
+ assertToolApprovalRequirement(resolved, { allowFunction: false });
1596
+ if (resolved === false) return { approved: true };
1597
+ const reason = resolved === true ? void 0 : resolved.reason;
1598
+ return this.requestApproval(context, reason === void 0 ? {} : { reason }, observation);
1599
+ }
1600
+ async requestApproval(context, options, observation) {
1601
+ const request = {
1602
+ ...context,
1603
+ id: globalThis.crypto.randomUUID()
1604
+ };
1605
+ if (options.reason !== void 0) {
1606
+ request.reason = options.reason;
1607
+ }
1608
+ if (options.rejectMessage !== void 0) {
1609
+ request.rejectMessage = options.rejectMessage;
1610
+ }
1611
+ await observation?.runObservers.event({
1612
+ name: "tool.approval_requested",
1613
+ attributes: approvalEventAttributes(request, observation.turn)
1614
+ });
1615
+ let decision;
1616
+ try {
1617
+ decision = await this.approvalHandler(request);
1618
+ } catch (error) {
1619
+ if (error instanceof AgentInteractionSignal) {
1620
+ throw error;
1621
+ }
1622
+ await observation?.runObservers.event({
1623
+ name: "tool.approval_failed",
1624
+ level: "ERROR",
1625
+ attributes: {
1626
+ ...approvalEventAttributes(request, observation.turn),
1627
+ errorName: error instanceof Error ? error.name : typeof error
1628
+ }
1629
+ });
1630
+ throw error;
1631
+ }
1632
+ const attributes = {
1633
+ ...approvalEventAttributes(request, observation?.turn ?? 0),
1634
+ approved: decision.approved
1635
+ };
1636
+ if (decision.reason !== void 0) attributes.decisionReason = decision.reason;
1637
+ await observation?.runObservers.event({
1638
+ name: "tool.approval_resolved",
1639
+ attributes
1640
+ });
1641
+ if (decision.approved) {
1642
+ return { approved: true };
1643
+ }
1644
+ return {
1645
+ approved: false,
1646
+ result: decision.reason ?? request.rejectMessage ?? "Tool approval was rejected."
1647
+ };
1648
+ }
1649
+ };
1650
+ function createApprovalContext(input, hookArgs, agent, run) {
1651
+ const approvalRun = {
1652
+ agentId: agent.id,
1653
+ runId: run.runId
1654
+ };
1655
+ if (run.sessionId !== void 0) {
1656
+ approvalRun.sessionId = run.sessionId;
1657
+ }
1658
+ if (run.metadata !== void 0) {
1659
+ approvalRun.metadata = run.metadata;
1660
+ }
1661
+ const context = {
1662
+ toolName: hookArgs.toolName,
1663
+ args: lifecycleSnapshot(input),
1664
+ rawArgs: hookArgs.args,
1665
+ toolCallId: hookArgs.toolCallId,
1666
+ internalCallId: hookArgs.internalCallId,
1667
+ run: approvalRun
1668
+ };
1669
+ if (hookArgs.callId !== void 0) {
1670
+ context.callId = hookArgs.callId;
1671
+ }
1672
+ return context;
1673
+ }
1674
+ function approvalEventAttributes(request, turn) {
1675
+ const attributes = {
1676
+ turn,
1677
+ approvalId: request.id,
1678
+ toolName: request.toolName,
1679
+ internalCallId: request.internalCallId
1680
+ };
1681
+ if (request.toolCallId !== void 0) attributes.toolCallId = request.toolCallId;
1682
+ if (request.reason !== void 0) attributes.reason = request.reason;
1683
+ return attributes;
1684
+ }
1685
+ function normalizeToolOutputMiddlewareResult(result) {
1686
+ if (typeof result === "string") {
1687
+ return { result };
1688
+ }
1689
+ if (typeof result !== "object" || result === null) {
1690
+ throw new TypeError("Tool output middleware must return text or structured content.");
1691
+ }
1692
+ const prototype = Object.getPrototypeOf(result);
1693
+ if (prototype !== Object.prototype && prototype !== null) {
1694
+ throw new TypeError("Tool output middleware must return text or structured content.");
1695
+ }
1696
+ const keys = Reflect.ownKeys(result);
1697
+ const hasResult = keys.includes("result");
1698
+ const hasStructuredResult = keys.includes("structuredResult");
1699
+ if (hasResult === hasStructuredResult || keys.some((key) => key !== "result" && key !== "structuredResult")) {
1700
+ throw new TypeError(
1701
+ "Tool output middleware must return exactly one of result or structuredResult."
1702
+ );
1703
+ }
1704
+ if (hasResult) {
1705
+ const descriptor2 = Object.getOwnPropertyDescriptor(result, "result");
1706
+ if (descriptor2 === void 0 || !("value" in descriptor2) || typeof descriptor2.value !== "string") {
1707
+ throw new TypeError("Tool output middleware result must be a string.");
1708
+ }
1709
+ return { result: descriptor2.value };
1710
+ }
1711
+ const descriptor = Object.getOwnPropertyDescriptor(result, "structuredResult");
1712
+ if (descriptor === void 0 || !("value" in descriptor)) {
1713
+ throw new TypeError("Tool output middleware structuredResult must be valid tool content.");
1714
+ }
1715
+ const normalized = normalizeToolResultOutput(ToolOutput.content(descriptor.value));
1716
+ if (normalized.type !== "content") {
1717
+ throw new TypeError("Tool output middleware structuredResult must be valid tool content.");
1718
+ }
1719
+ return { structuredResult: normalized.value };
1720
+ }
1721
+ function toolTraceMetadata(tool) {
1722
+ if (tool === void 0) {
1723
+ return void 0;
1724
+ }
1725
+ const result = {
1726
+ approvalRequired: toolMayRequireApproval(tool.requiresApproval)
1727
+ };
1728
+ if (isMcpTool(tool)) {
1729
+ result.mcpServerName = tool.mcp.serverName;
1730
+ result.mcpRemoteName = tool.mcp.remoteName;
1731
+ }
1732
+ return result;
1733
+ }
1734
+ function toolErrorArgs(turn, toolCall, internalCallId, args, error) {
1735
+ let observerArgs = {
1736
+ turn,
1737
+ toolCall,
1738
+ toolName: toolCall.toolName,
1739
+ internalCallId,
1740
+ args,
1741
+ error
1742
+ };
1743
+ if (toolCall.callId !== void 0) {
1744
+ observerArgs = { ...observerArgs, toolCallId: toolCall.callId };
1745
+ }
1746
+ return observerArgs;
1747
+ }
1748
+ var ToolObserverScope = class {
1749
+ constructor(observers) {
1750
+ this.observers = observers;
1751
+ }
1752
+ observers;
1753
+ terminal = false;
1754
+ streamEvent(args) {
1755
+ return this.observers?.streamEvent(args);
1756
+ }
1757
+ async end(args) {
1758
+ if (this.terminal) return;
1759
+ this.terminal = true;
1760
+ await this.observers?.end(args);
1761
+ }
1762
+ async suspend(args) {
1763
+ if (this.terminal) return;
1764
+ this.terminal = true;
1765
+ await this.observers?.suspend(args);
1766
+ }
1767
+ async error(args) {
1768
+ if (this.terminal) return;
1769
+ this.terminal = true;
1770
+ await this.observers?.error(args);
1771
+ }
1772
+ };
1773
+ function toolOutputToText(output) {
1774
+ switch (output.type) {
1775
+ case "text":
1776
+ case "error-text":
1777
+ return output.value;
1778
+ case "json":
1779
+ case "error-json":
1780
+ return JSON.stringify(output.value);
1781
+ case "content":
1782
+ return toolResultContentToText(output.value);
1783
+ case "execution-denied":
1784
+ return output.reason ?? "Tool execution was denied.";
1785
+ }
1786
+ }
1787
+ function toolOutputToStructuredResult(output) {
1788
+ return output.type === "content" ? output.value : void 0;
1789
+ }
1790
+ function agentToolEventPayload(toolCall, internalCallId, event) {
1791
+ if (typeof event.agentId !== "string" || event.agentId.length === 0) {
1792
+ return void 0;
1793
+ }
1794
+ const payload = {
1795
+ type: "agent_tool_event",
1796
+ toolName: toolCall.toolName,
1797
+ internalCallId,
1798
+ agentId: event.agentId,
1799
+ event: event.event
1800
+ };
1801
+ if (toolCall.callId !== void 0) {
1802
+ payload.toolCallId = toolCall.callId;
1803
+ }
1804
+ if (event.agentName !== void 0) {
1805
+ payload.agentName = event.agentName;
1806
+ }
1807
+ return payload;
1808
+ }
1809
+
1810
+ // src/internal/agent-runtime/agent-run.ts
1811
+ async function settleFailureCleanup(operations) {
1812
+ for (const operation of operations) {
1813
+ try {
1814
+ await operation();
1815
+ } catch {
1816
+ }
1817
+ }
1818
+ }
1819
+ var AgentRun = class _AgentRun {
1820
+ constructor(agent, promptMessage, initialHistory = [], options = {}) {
1821
+ this.agent = agent;
1822
+ this.promptMessage = promptMessage;
1823
+ this.chatHistory = initialHistory;
1824
+ this.maxTurnCount = assertNonnegativeSafeInteger(
1825
+ options.maxTurns ?? agent.defaultMaxTurns ?? 0,
1826
+ "maxTurns"
1827
+ );
1828
+ const internalOptions = getInternalAgentRunOptions(options);
1829
+ this.activeHook = internalOptions?.hook;
1830
+ this.onInternalFailure = internalOptions?.onFailure;
1831
+ this.onInternalMemoryCompaction = internalOptions?.onMemoryCompaction;
1832
+ this.requestedRunId = normalizeRequestedRunId(internalOptions?.runId);
1833
+ this.activeLifecycle = composeAgentLifecycle(agent.lifecycle, options.lifecycle);
1834
+ this.guardrailPolicies = options.guardrails === void 0 ? [...agent.guardrails] : appendGuardrailPolicies([...agent.guardrails], options.guardrails);
1835
+ const configuredConcurrency = assertPositiveSafeInteger(
1836
+ options.toolConcurrency ?? 1,
1837
+ "toolConcurrency"
1838
+ );
1839
+ this.concurrency = this.activeHook !== void 0 || agent.tools.some(
1840
+ (tool) => toolMayRequireApproval(tool.requiresApproval) || isQuestionTool(tool)
1841
+ ) ? 1 : configuredConcurrency;
1842
+ this.traceOptions = options.trace;
1843
+ const retrySetting = options.retries === void 0 ? agent.retries : options.retries;
1844
+ this.completionRetryOptions = retrySetting === void 0 || retrySetting === false ? void 0 : resolveRetryOptions(retrySetting);
1845
+ this.requestMiddlewares = [...options.middlewares ?? []];
1846
+ this.memoryScope = options.memoryScope;
1847
+ this.memoryRecorder = new AgentRunMemory(agent, options.memoryScope, initialHistory);
1848
+ this.continuationState = options.continuationState;
1849
+ this.interactionResponse = options.interactionResponse;
1850
+ if (options.continuationState !== void 0) {
1851
+ this.steeringMessages.push(
1852
+ ...options.continuationState.steering.map((entry) => ({
1853
+ id: entry.id,
1854
+ messages: [...entry.messages]
1855
+ }))
1856
+ );
1857
+ }
1858
+ this.resumedFrom = options.sourceRunId === void 0 || options.interactionId === void 0 ? void 0 : { runId: options.sourceRunId, interactionId: options.interactionId };
1859
+ this.linkExternalAbortSignal(options.abortSignal);
1860
+ }
1861
+ agent;
1862
+ promptMessage;
1863
+ chatHistory;
1864
+ maxTurnCount;
1865
+ activeHook;
1866
+ activeLifecycle;
1867
+ guardrailPolicies;
1868
+ guardrailDecisions = [];
1869
+ concurrency;
1870
+ traceOptions;
1871
+ completionRetryOptions;
1872
+ requestMiddlewares;
1873
+ steeringMessages = [];
1874
+ runState = "idle";
1875
+ memoryRecorder;
1876
+ memoryScope;
1877
+ onInternalFailure;
1878
+ onInternalMemoryCompaction;
1879
+ memoryCompaction;
1880
+ requestedRunId;
1881
+ continuationState;
1882
+ interactionResponse;
1883
+ resumedFrom;
1884
+ currentMessages = [];
1885
+ cancellationError;
1886
+ activeGeneration;
1887
+ validatedStructuredOutput;
1888
+ failedCompletionUsage = Usage.empty();
1889
+ abortController = new AbortController();
1890
+ removeExternalAbortListener;
1891
+ static fromAgent(agent, options) {
1892
+ const normalized = normalizeAgentInput(agent.id, options);
1893
+ if (normalized.scope !== void 0 && agent.memory === void 0) {
1894
+ throw new TypeError(`Agent "${agent.id}" cannot use a session without a memory store.`);
1895
+ }
1896
+ return new _AgentRun(agent, normalized.prompt, normalized.history, {
1897
+ ...options,
1898
+ memoryScope: normalized.scope,
1899
+ continuationState: normalized.continuationState,
1900
+ interactionResponse: normalized.interactionResponse,
1901
+ sourceRunId: normalized.sourceRunId,
1902
+ interactionId: normalized.interactionId
1903
+ });
1904
+ }
1905
+ steer(input) {
1906
+ if (this.isTerminal() || this.cancellationError !== void 0) {
1907
+ throw new AgentStreamClosedError();
1908
+ }
1909
+ const receipt = Object.freeze({
1910
+ id: globalThis.crypto.randomUUID(),
1911
+ status: "queued"
1912
+ });
1913
+ this.steeringMessages.push({ id: receipt.id, messages: normalizeSteeringInput(input) });
1914
+ return receipt;
1915
+ }
1916
+ cancel(reason) {
1917
+ if (this.isTerminal() || this.cancellationError !== void 0) {
1918
+ return;
1919
+ }
1920
+ const messages = this.currentMessages.length === 0 ? [this.promptMessage] : [...this.currentMessages];
1921
+ const error = new AgentRunCancelledError([...this.chatHistory, ...messages], reason);
1922
+ this.setCancellationError(error);
1923
+ }
1924
+ setCancellationError(error) {
1925
+ this.cancellationError = error;
1926
+ if (!this.abortController.signal.aborted) this.abortController.abort(error);
1927
+ }
1928
+ async generate() {
1929
+ this.startRun();
1930
+ const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();
1931
+ let usage = Usage.empty();
1932
+ let currentTurns = 0;
1933
+ let lastPrompt = this.promptMessage;
1934
+ let newMessages = [this.promptMessage];
1935
+ let runObservers;
1936
+ let pendingTurnMessages = [];
1937
+ try {
1938
+ this.throwIfCancelled();
1939
+ const memoryPreparation = this.continuationState === void 0 ? await this.memoryRecorder.prepareHistory(
1940
+ runId,
1941
+ newMessages.length,
1942
+ this.abortController.signal
1943
+ ) : void 0;
1944
+ if (memoryPreparation !== void 0) {
1945
+ this.chatHistory = memoryPreparation.history;
1946
+ usage = Usage.add(usage, memoryPreparation.usage);
1947
+ this.memoryCompaction = memoryPreparation.compaction;
1948
+ await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);
1949
+ }
1950
+ runObservers = await this.startRunObservers(runId);
1951
+ if (memoryPreparation !== void 0) {
1952
+ await this.recordMemoryCompaction(memoryPreparation, runObservers);
1953
+ }
1954
+ this.throwIfCancelled();
1955
+ await this.activeLifecycle?.onStart?.({
1956
+ runId,
1957
+ input: lifecycleSnapshot(this.promptMessage),
1958
+ history: lifecycleSnapshot(this.chatHistory),
1959
+ maxTurns: this.maxTurnCount
1960
+ });
1961
+ if (this.continuationState === void 0) {
1962
+ const inputResult = await runInputGuardrails(this.guardrailPolicies, {
1963
+ prompt: this.promptMessage,
1964
+ history: this.chatHistory,
1965
+ inputText: textFromMessage(this.promptMessage),
1966
+ run: this.guardrailRunContext(runId)
1967
+ });
1968
+ for (const decision of inputResult.decisions) {
1969
+ await this.recordGuardrailDecision(decision, runObservers);
1970
+ }
1971
+ this.promptMessage = inputResult.prompt;
1972
+ if (inputResult.blocked) {
1973
+ const text = inputResult.message ?? "The request was blocked by a guardrail.";
1974
+ const result = {
1975
+ status: "blocked",
1976
+ stage: "input",
1977
+ runId,
1978
+ text,
1979
+ usage,
1980
+ messages: [this.promptMessage, { role: "assistant", content: text }],
1981
+ trace: runObservers.trace,
1982
+ guardrails: [...this.guardrailDecisions],
1983
+ ...this.memoryCompactionResult()
1984
+ };
1985
+ if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
1986
+ this.runState = "closing";
1987
+ await this.runLifecycleFinish(result);
1988
+ await runObservers.end(result);
1989
+ this.runState = "completed";
1990
+ this.disposeAbortLink();
1991
+ return result;
1992
+ }
1993
+ }
1994
+ newMessages = [this.promptMessage];
1995
+ await this.memoryRecorder.commitAcceptedInput(runId, newMessages);
1996
+ pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);
1997
+ await this.runRunStartHook(newMessages);
1998
+ if (this.continuationState !== void 0) {
1999
+ const interactionAttributes = {};
2000
+ if (this.resumedFrom?.runId !== void 0) {
2001
+ interactionAttributes.sourceRunId = this.resumedFrom.runId;
2002
+ }
2003
+ if (this.resumedFrom?.interactionId !== void 0) {
2004
+ interactionAttributes.interactionId = this.resumedFrom.interactionId;
2005
+ }
2006
+ if (this.interactionResponse?.type !== void 0) {
2007
+ interactionAttributes.interactionType = this.interactionResponse.type;
2008
+ }
2009
+ await runObservers.event({
2010
+ name: "agent.interaction_response",
2011
+ attributes: interactionAttributes
2012
+ });
2013
+ try {
2014
+ const toolResults = await this.resolveContinuationTools(
2015
+ runId,
2016
+ newMessages,
2017
+ void 0,
2018
+ void 0,
2019
+ {
2020
+ turn: 1,
2021
+ runObservers
2022
+ }
2023
+ );
2024
+ const toolMessage = { role: "tool", content: toolResults };
2025
+ newMessages.push(toolMessage);
2026
+ await this.memoryRecorder.commitMessages(runId, 1, [toolMessage], pendingTurnMessages);
2027
+ await this.drainSteeringMessages(runId, 1, newMessages, pendingTurnMessages);
2028
+ await this.memoryRecorder.commitCompletedTurn(runId, 1, pendingTurnMessages);
2029
+ } catch (error) {
2030
+ if (error instanceof ToolExecutionSuspension) {
2031
+ return this.finishSuspension({
2032
+ runId,
2033
+ turn: 1,
2034
+ usage,
2035
+ newMessages,
2036
+ pendingTurnMessages,
2037
+ runObservers,
2038
+ suspension: error,
2039
+ uncommittedMessages: []
2040
+ });
2041
+ }
2042
+ throw error;
2043
+ }
2044
+ }
2045
+ while (currentTurns <= this.maxTurnCount + 1) {
2046
+ const prompt = newMessages.at(-1);
2047
+ if (prompt === void 0) {
2048
+ throw new Error("AgentRun requires at least one message");
2049
+ }
2050
+ lastPrompt = prompt;
2051
+ currentTurns += 1;
2052
+ const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];
2053
+ await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);
2054
+ await this.runCompletionCallHook(prompt, historyForRequest, newMessages);
2055
+ const request = await this.createTurnRequest(prompt, historyForRequest, currentTurns);
2056
+ let response;
2057
+ try {
2058
+ response = await this.runCompletion(request, currentTurns, runObservers);
2059
+ } catch (error) {
2060
+ await settleFailureCleanup([
2061
+ () => this.runCompletionErrorHook(prompt, error, newMessages)
2062
+ ]);
2063
+ throw error;
2064
+ }
2065
+ response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);
2066
+ try {
2067
+ assertCompletionResponseIntegrity({ response });
2068
+ } catch (error) {
2069
+ const providerOutputUsage = completionProviderOutputErrorUsage(error);
2070
+ if (providerOutputUsage !== void 0) usage = Usage.add(usage, providerOutputUsage);
2071
+ throw error;
2072
+ }
2073
+ usage = Usage.add(usage, response.usage);
2074
+ this.updateRunProgress(newMessages);
2075
+ await this.runCompletionResponseHook(prompt, response, newMessages);
2076
+ await this.runTurnEndHook(currentTurns, response, newMessages);
2077
+ await this.activeLifecycle?.onStepFinish?.({
2078
+ runId,
2079
+ step: currentTurns,
2080
+ response: lifecycleSnapshot(response),
2081
+ usage: lifecycleSnapshot(usage)
2082
+ });
2083
+ const toolCalls = response.choice.filter(
2084
+ (item) => item.type === "tool-call"
2085
+ );
2086
+ const assistantMessage = this.generatedAssistantMessage(response, request);
2087
+ newMessages.push(assistantMessage);
2088
+ if (toolCalls.length === 0) {
2089
+ if (this.steeringMessages.length > 0) {
2090
+ await this.memoryRecorder.commitMessages(
2091
+ runId,
2092
+ currentTurns,
2093
+ [assistantMessage],
2094
+ pendingTurnMessages
2095
+ );
2096
+ }
2097
+ const appliedSteering = await this.drainSteeringMessages(
2098
+ runId,
2099
+ currentTurns,
2100
+ newMessages,
2101
+ pendingTurnMessages,
2102
+ { closeWhenEmpty: true }
2103
+ );
2104
+ if (appliedSteering.length > 0) {
2105
+ for (const receipt of appliedSteering) {
2106
+ await runObservers.event({
2107
+ name: "agent.steering_applied",
2108
+ attributes: { id: receipt.id, turn: currentTurns }
2109
+ });
2110
+ }
2111
+ await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
2112
+ continue;
2113
+ }
2114
+ const guardedOutput = await this.runOutputGuardrailsForResponse(
2115
+ runId,
2116
+ usage,
2117
+ response,
2118
+ newMessages,
2119
+ runObservers
2120
+ );
2121
+ response = guardedOutput.response;
2122
+ const finalAssistantMessage = this.generatedAssistantMessage(response, request);
2123
+ newMessages[newMessages.length - 1] = finalAssistantMessage;
2124
+ await this.memoryRecorder.commitMessages(
2125
+ runId,
2126
+ currentTurns,
2127
+ [finalAssistantMessage],
2128
+ pendingTurnMessages
2129
+ );
2130
+ const result = this.createTerminalResult(
2131
+ runId,
2132
+ guardedOutput.text,
2133
+ guardedOutput.blocked,
2134
+ usage,
2135
+ newMessages,
2136
+ runObservers
2137
+ );
2138
+ if (result.status === "completed") {
2139
+ await this.runRunEndHook(result, newMessages);
2140
+ }
2141
+ await this.memoryRecorder.commitCompletedRun(
2142
+ runId,
2143
+ currentTurns,
2144
+ newMessages,
2145
+ pendingTurnMessages
2146
+ );
2147
+ await this.runLifecycleFinish(result);
2148
+ await runObservers.end(result);
2149
+ this.runState = "completed";
2150
+ this.disposeAbortLink();
2151
+ return result;
2152
+ }
2153
+ this.updateRunProgress(newMessages);
2154
+ let toolResults;
2155
+ try {
2156
+ toolResults = await this.executeToolCalls(
2157
+ runId,
2158
+ toolCalls,
2159
+ newMessages,
2160
+ void 0,
2161
+ void 0,
2162
+ {
2163
+ turn: currentTurns,
2164
+ runObservers,
2165
+ toolDefinitions: request.tools
2166
+ }
2167
+ );
2168
+ } catch (error) {
2169
+ if (error instanceof ToolExecutionSuspension) {
2170
+ return this.finishSuspension({
2171
+ runId,
2172
+ turn: currentTurns,
2173
+ usage,
2174
+ newMessages,
2175
+ pendingTurnMessages,
2176
+ runObservers,
2177
+ suspension: error,
2178
+ uncommittedMessages: [assistantMessage]
2179
+ });
2180
+ }
2181
+ throw error;
2182
+ }
2183
+ const toolMessage = { role: "tool", content: toolResults };
2184
+ newMessages.push(toolMessage);
2185
+ await this.memoryRecorder.commitMessages(
2186
+ runId,
2187
+ currentTurns,
2188
+ [assistantMessage, toolMessage],
2189
+ pendingTurnMessages
2190
+ );
2191
+ await this.drainSteeringMessages(runId, currentTurns, newMessages, pendingTurnMessages);
2192
+ await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
2193
+ }
2194
+ throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);
2195
+ } catch (error) {
2196
+ if (error instanceof MemoryCompactionError && error.usage !== void 0) {
2197
+ usage = Usage.add(usage, error.usage);
2198
+ }
2199
+ const failedCompletionUsage = this.takeFailedCompletionUsage();
2200
+ if (error instanceof AgentStructuredOutputError) {
2201
+ usage = Usage.add(usage, error.usage);
2202
+ } else {
2203
+ usage = Usage.add(usage, failedCompletionUsage);
2204
+ }
2205
+ this.runState = "closing";
2206
+ const runError = this.normalizeRunError(error);
2207
+ const reportedError = await this.reportRunFailure(
2208
+ runError,
2209
+ runId,
2210
+ usage,
2211
+ newMessages,
2212
+ runObservers
2213
+ );
2214
+ this.runState = reportedError instanceof AgentRunCancelledError ? "cancelled" : "errored";
2215
+ this.disposeAbortLink();
2216
+ throw reportedError;
2217
+ }
2218
+ }
2219
+ async *events() {
2220
+ this.startRun();
2221
+ const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();
2222
+ let usage = Usage.empty();
2223
+ let currentTurns = 0;
2224
+ let lastPrompt = this.promptMessage;
2225
+ let newMessages = [this.promptMessage];
2226
+ const bufferOutputDeltas = hasEnforcedOutputGuardrails(this.guardrailPolicies);
2227
+ let runObservers;
2228
+ let pendingTurnMessages = [];
2229
+ try {
2230
+ this.throwIfCancelled();
2231
+ const memoryPreparation = this.continuationState === void 0 ? await this.memoryRecorder.prepareHistory(
2232
+ runId,
2233
+ newMessages.length,
2234
+ this.abortController.signal
2235
+ ) : void 0;
2236
+ if (memoryPreparation !== void 0) {
2237
+ this.chatHistory = memoryPreparation.history;
2238
+ usage = Usage.add(usage, memoryPreparation.usage);
2239
+ this.memoryCompaction = memoryPreparation.compaction;
2240
+ await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);
2241
+ }
2242
+ runObservers = await this.startRunObservers(runId);
2243
+ if (memoryPreparation !== void 0) {
2244
+ await this.recordMemoryCompaction(memoryPreparation, runObservers);
2245
+ }
2246
+ if (memoryPreparation?.compaction !== void 0) {
2247
+ yield { type: "memory_compaction", ...memoryPreparation.compaction };
2248
+ }
2249
+ this.throwIfCancelled();
2250
+ await this.activeLifecycle?.onStart?.({
2251
+ runId,
2252
+ input: lifecycleSnapshot(this.promptMessage),
2253
+ history: lifecycleSnapshot(this.chatHistory),
2254
+ maxTurns: this.maxTurnCount
2255
+ });
2256
+ if (this.continuationState === void 0) {
2257
+ const inputResult = await runInputGuardrails(this.guardrailPolicies, {
2258
+ prompt: this.promptMessage,
2259
+ history: this.chatHistory,
2260
+ inputText: textFromMessage(this.promptMessage),
2261
+ run: this.guardrailRunContext(runId)
2262
+ });
2263
+ for (const decision of inputResult.decisions) {
2264
+ await this.recordGuardrailDecision(decision, runObservers);
2265
+ yield { type: "guardrail_decision", decision };
2266
+ }
2267
+ this.promptMessage = inputResult.prompt;
2268
+ if (inputResult.blocked) {
2269
+ const text = inputResult.message ?? "The request was blocked by a guardrail.";
2270
+ const result = {
2271
+ status: "blocked",
2272
+ stage: "input",
2273
+ runId,
2274
+ text,
2275
+ usage,
2276
+ messages: [this.promptMessage, { role: "assistant", content: text }],
2277
+ trace: runObservers.trace,
2278
+ guardrails: [...this.guardrailDecisions],
2279
+ ...this.memoryCompactionResult()
2280
+ };
2281
+ if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
2282
+ this.runState = "closing";
2283
+ await this.runLifecycleFinish(result);
2284
+ await runObservers.end(result);
2285
+ this.runState = "completed";
2286
+ this.disposeAbortLink();
2287
+ yield { type: "final", result };
2288
+ return;
2289
+ }
2290
+ }
2291
+ newMessages = [this.promptMessage];
2292
+ await this.memoryRecorder.commitAcceptedInput(runId, newMessages);
2293
+ pendingTurnMessages = this.memoryRecorder.pendingTurnMessages(newMessages);
2294
+ await this.runRunStartHook(newMessages);
2295
+ if (this.continuationState !== void 0) {
2296
+ const responsePart = this.promptMessage.role === "tool" ? this.promptMessage.content[0] : void 0;
2297
+ if (responsePart === void 0 || responsePart.type === "tool-result") {
2298
+ throw new TypeError("Agent continuation response message is invalid.");
2299
+ }
2300
+ yield {
2301
+ type: "interaction_response",
2302
+ response: responsePart,
2303
+ sourceRunId: this.resumedFrom?.runId ?? this.continuationState.kind
2304
+ };
2305
+ try {
2306
+ const execution = this.executeContinuationToolStream(runId, newMessages, {
2307
+ turn: 1,
2308
+ runObservers
2309
+ });
2310
+ for await (const event of execution.events) {
2311
+ yield { turn: 1, ...event };
2312
+ }
2313
+ const toolResults = await execution.results;
2314
+ const toolMessage = { role: "tool", content: toolResults };
2315
+ newMessages.push(toolMessage);
2316
+ await this.memoryRecorder.commitMessages(runId, 1, [toolMessage], pendingTurnMessages);
2317
+ for (const receipt of await this.drainSteeringMessages(
2318
+ runId,
2319
+ 1,
2320
+ newMessages,
2321
+ pendingTurnMessages
2322
+ )) {
2323
+ yield { type: "steering_applied", id: receipt.id, turn: 1 };
2324
+ }
2325
+ await this.memoryRecorder.commitCompletedTurn(runId, 1, pendingTurnMessages);
2326
+ } catch (error) {
2327
+ if (error instanceof ToolExecutionSuspension) {
2328
+ const result = await this.finishSuspension({
2329
+ runId,
2330
+ turn: 1,
2331
+ usage,
2332
+ newMessages,
2333
+ pendingTurnMessages,
2334
+ runObservers,
2335
+ suspension: error,
2336
+ uncommittedMessages: []
2337
+ });
2338
+ yield { type: "final", result };
2339
+ return;
2340
+ }
2341
+ throw error;
2342
+ }
2343
+ }
2344
+ while (currentTurns <= this.maxTurnCount + 1) {
2345
+ const prompt = newMessages.at(-1);
2346
+ if (prompt === void 0) {
2347
+ throw new Error("AgentRun requires at least one message");
2348
+ }
2349
+ lastPrompt = prompt;
2350
+ currentTurns += 1;
2351
+ const historyForRequest = [...this.chatHistory, ...newMessages.slice(0, -1)];
2352
+ yield {
2353
+ type: "turn_start",
2354
+ turn: currentTurns,
2355
+ prompt,
2356
+ history: historyForRequest
2357
+ };
2358
+ await this.runTurnStartHook(currentTurns, prompt, historyForRequest, newMessages);
2359
+ await this.runCompletionCallHook(prompt, historyForRequest, newMessages);
2360
+ const request = await this.createTurnRequest(prompt, historyForRequest, currentTurns);
2361
+ assertCompletionRequestSupported(this.agent.model, request, { streaming: true });
2362
+ const providerRequest = this.providerTraceRequest(request, { stream: true });
2363
+ const generationStartArgs = this.generationStartArgs(
2364
+ currentTurns,
2365
+ request,
2366
+ providerRequest
2367
+ );
2368
+ const generationObservers = await runObservers.startGeneration(generationStartArgs);
2369
+ this.activeGeneration = { turn: currentTurns, observers: generationObservers };
2370
+ const generationStartedAt = Date.now();
2371
+ yield {
2372
+ type: "generation_start",
2373
+ turn: currentTurns,
2374
+ request,
2375
+ modelInfo: generationStartArgs.modelInfo
2376
+ };
2377
+ const bufferResponseEvents = this.shouldBufferStreamResponseEvents() || this.agent.outputSchema !== void 0;
2378
+ const completionState = {
2379
+ response: void 0,
2380
+ firstDeltaMs: void 0,
2381
+ emittedToolCallIds: /* @__PURE__ */ new Set(),
2382
+ providerErrorUsage: Usage.empty()
2383
+ };
2384
+ let response;
2385
+ try {
2386
+ try {
2387
+ for await (const event of this.streamCompletion({
2388
+ request,
2389
+ turn: currentTurns,
2390
+ bufferResponseEvents,
2391
+ bufferOutputDeltas,
2392
+ generationStartedAt,
2393
+ generationObservers,
2394
+ runObservers,
2395
+ state: completionState
2396
+ })) {
2397
+ yield event;
2398
+ }
2399
+ } finally {
2400
+ usage = Usage.add(usage, completionState.providerErrorUsage);
2401
+ }
2402
+ if (completionState.response === void 0) {
2403
+ throw new Error("Streaming completion ended without a response.");
2404
+ }
2405
+ response = completionState.response;
2406
+ } catch (error) {
2407
+ await settleFailureCleanup([
2408
+ () => this.closeActiveGeneration(error),
2409
+ () => this.runCompletionErrorHook(prompt, error, newMessages)
2410
+ ]);
2411
+ throw error;
2412
+ }
2413
+ const { firstDeltaMs, emittedToolCallIds } = completionState;
2414
+ let generationEndArgs = {
2415
+ turn: currentTurns,
2416
+ response
2417
+ };
2418
+ if (firstDeltaMs !== void 0) {
2419
+ generationEndArgs = { ...generationEndArgs, firstDeltaMs };
2420
+ }
2421
+ this.activeGeneration = void 0;
2422
+ await generationObservers.end(generationEndArgs);
2423
+ response = await this.runCompletionResponseMiddlewares(request, response, currentTurns);
2424
+ try {
2425
+ assertCompletionResponseIntegrity({ response });
2426
+ } catch (error) {
2427
+ const providerOutputUsage = completionProviderOutputErrorUsage(error);
2428
+ if (providerOutputUsage !== void 0) usage = Usage.add(usage, providerOutputUsage);
2429
+ throw error;
2430
+ }
2431
+ usage = Usage.add(usage, response.usage);
2432
+ this.updateRunProgress(newMessages);
2433
+ await this.runCompletionResponseHook(prompt, response, newMessages);
2434
+ await this.runTurnEndHook(currentTurns, response, newMessages);
2435
+ await this.activeLifecycle?.onStepFinish?.({
2436
+ runId,
2437
+ step: currentTurns,
2438
+ response: lifecycleSnapshot(response),
2439
+ usage: lifecycleSnapshot(usage)
2440
+ });
2441
+ const toolCalls = response.choice.filter(
2442
+ (item) => item.type === "tool-call"
2443
+ );
2444
+ const assistantMessage = this.generatedAssistantMessage(response, request);
2445
+ newMessages.push(assistantMessage);
2446
+ if (toolCalls.length === 0) {
2447
+ let emittedTurnEnd = false;
2448
+ if (!bufferOutputDeltas) {
2449
+ if (bufferResponseEvents) {
2450
+ for (const event of responseStreamEvents(currentTurns, response)) {
2451
+ yield event;
2452
+ }
2453
+ }
2454
+ yield {
2455
+ type: "turn_end",
2456
+ turn: currentTurns,
2457
+ response,
2458
+ firstDeltaMs
2459
+ };
2460
+ emittedTurnEnd = true;
2461
+ }
2462
+ if (this.steeringMessages.length > 0) {
2463
+ await this.memoryRecorder.commitMessages(
2464
+ runId,
2465
+ currentTurns,
2466
+ [assistantMessage],
2467
+ pendingTurnMessages
2468
+ );
2469
+ }
2470
+ const appliedSteering = await this.drainSteeringMessages(
2471
+ runId,
2472
+ currentTurns,
2473
+ newMessages,
2474
+ pendingTurnMessages,
2475
+ { closeWhenEmpty: true }
2476
+ );
2477
+ for (const receipt of appliedSteering) {
2478
+ yield { type: "steering_applied", id: receipt.id, turn: currentTurns };
2479
+ }
2480
+ if (appliedSteering.length > 0) {
2481
+ await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
2482
+ continue;
2483
+ }
2484
+ for await (const event of this.completeStreamingRun({
2485
+ runId,
2486
+ turn: currentTurns,
2487
+ request,
2488
+ response,
2489
+ firstDeltaMs,
2490
+ usage,
2491
+ newMessages,
2492
+ pendingTurnMessages,
2493
+ runObservers,
2494
+ bufferResponseEvents,
2495
+ bufferOutputDeltas,
2496
+ emittedTurnEnd
2497
+ })) {
2498
+ yield event;
2499
+ }
2500
+ return;
2501
+ }
2502
+ if (bufferResponseEvents) {
2503
+ for (const event of responseStreamEvents(currentTurns, response)) {
2504
+ yield event;
2505
+ }
2506
+ } else {
2507
+ for (const toolCall of toolCalls) {
2508
+ if (!emittedToolCallIds.has(toolCall.toolCallId)) {
2509
+ yield { type: "tool_call", turn: currentTurns, toolCall };
2510
+ }
2511
+ }
2512
+ }
2513
+ this.updateRunProgress(newMessages);
2514
+ yield {
2515
+ type: "turn_end",
2516
+ turn: currentTurns,
2517
+ response,
2518
+ firstDeltaMs
2519
+ };
2520
+ let toolResults;
2521
+ try {
2522
+ const toolExecution = this.executeStreamingToolCalls(runId, toolCalls, newMessages, {
2523
+ turn: currentTurns,
2524
+ runObservers,
2525
+ toolDefinitions: request.tools
2526
+ });
2527
+ for await (const result of toolExecution.events) {
2528
+ yield { turn: currentTurns, ...result };
2529
+ }
2530
+ toolResults = await toolExecution.results;
2531
+ } catch (error) {
2532
+ if (error instanceof ToolExecutionSuspension) {
2533
+ const result = await this.finishSuspension({
2534
+ runId,
2535
+ turn: currentTurns,
2536
+ usage,
2537
+ newMessages,
2538
+ pendingTurnMessages,
2539
+ runObservers,
2540
+ suspension: error,
2541
+ uncommittedMessages: [assistantMessage]
2542
+ });
2543
+ yield { type: "final", result };
2544
+ return;
2545
+ }
2546
+ throw error;
2547
+ }
2548
+ const toolMessage = { role: "tool", content: toolResults };
2549
+ newMessages.push(toolMessage);
2550
+ await this.memoryRecorder.commitMessages(
2551
+ runId,
2552
+ currentTurns,
2553
+ [assistantMessage, toolMessage],
2554
+ pendingTurnMessages
2555
+ );
2556
+ for (const receipt of await this.drainSteeringMessages(
2557
+ runId,
2558
+ currentTurns,
2559
+ newMessages,
2560
+ pendingTurnMessages
2561
+ )) {
2562
+ yield { type: "steering_applied", id: receipt.id, turn: currentTurns };
2563
+ }
2564
+ await this.memoryRecorder.commitCompletedTurn(runId, currentTurns, pendingTurnMessages);
2565
+ }
2566
+ throw new MaxTurnsError(this.maxTurnCount, [...this.chatHistory, ...newMessages], lastPrompt);
2567
+ } catch (error) {
2568
+ if (error instanceof MemoryCompactionError && error.usage !== void 0) {
2569
+ usage = Usage.add(usage, error.usage);
2570
+ }
2571
+ if (error instanceof AgentStructuredOutputError) {
2572
+ usage = Usage.add(usage, error.usage);
2573
+ }
2574
+ this.runState = "closing";
2575
+ const runError = this.normalizeRunError(error);
2576
+ const reportedError = await this.reportRunFailure(
2577
+ runError,
2578
+ runId,
2579
+ usage,
2580
+ newMessages,
2581
+ runObservers
2582
+ );
2583
+ this.runState = reportedError instanceof AgentRunCancelledError ? "cancelled" : "errored";
2584
+ const finalUsage = usage;
2585
+ yield { type: "error", error: reportedError, usage: finalUsage };
2586
+ this.disposeAbortLink();
2587
+ return;
2588
+ } finally {
2589
+ if (this.runState === "running" || this.runState === "closing") {
2590
+ const cancellation = this.cancellationError ?? new AgentRunCancelledError([...this.chatHistory, ...newMessages], "Agent stream closed.");
2591
+ this.cancellationError = cancellation;
2592
+ await settleFailureCleanup([() => this.closeActiveGeneration(cancellation)]);
2593
+ await this.reportRunFailure(cancellation, runId, usage, newMessages, runObservers);
2594
+ this.runState = "cancelled";
2595
+ this.disposeAbortLink();
2596
+ }
2597
+ }
2598
+ }
2599
+ async runCompletion(request, turn, runObservers) {
2600
+ assertCompletionRequestSupported(this.agent.model, request);
2601
+ this.validatedStructuredOutput = void 0;
2602
+ this.failedCompletionUsage = Usage.empty();
2603
+ const providerRequest = this.providerTraceRequest(request);
2604
+ const generationObservers = await runObservers.startGeneration(
2605
+ this.generationStartArgs(turn, request, providerRequest)
2606
+ );
2607
+ let currentRequest = request;
2608
+ let failedAttemptUsage = Usage.empty();
2609
+ try {
2610
+ for (let attempt = 1; ; attempt += 1) {
2611
+ let response;
2612
+ try {
2613
+ this.throwIfCancelled();
2614
+ response = await this.agent.model.completion(currentRequest, this.modelCallOptions());
2615
+ assertCompletionResponseIntegrity({ response });
2616
+ } catch (error) {
2617
+ const attemptUsage = completionProviderOutputErrorUsage(error);
2618
+ if (attemptUsage !== void 0) {
2619
+ failedAttemptUsage = Usage.add(failedAttemptUsage, attemptUsage);
2620
+ this.failedCompletionUsage = failedAttemptUsage;
2621
+ }
2622
+ const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
2623
+ if (retryOptions === void 0) {
2624
+ throw error;
2625
+ }
2626
+ await this.scheduleCompletionRetry(
2627
+ error,
2628
+ attempt,
2629
+ turn,
2630
+ false,
2631
+ retryOptions,
2632
+ runObservers,
2633
+ providerOutputRetryEventAttributes(error, failedAttemptUsage)
2634
+ );
2635
+ continue;
2636
+ }
2637
+ const cumulativeUsage = Usage.add(failedAttemptUsage, response.usage);
2638
+ try {
2639
+ this.validateStructuredResponse(response, attempt, cumulativeUsage);
2640
+ } catch (error) {
2641
+ const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
2642
+ if (retryOptions === void 0) {
2643
+ throw error;
2644
+ }
2645
+ failedAttemptUsage = cumulativeUsage;
2646
+ this.failedCompletionUsage = failedAttemptUsage;
2647
+ const retryRequest = structuredOutputRetryRequest(request, response, error);
2648
+ currentRequest = retryRequest.request;
2649
+ await this.scheduleCompletionRetry(
2650
+ error,
2651
+ attempt,
2652
+ turn,
2653
+ false,
2654
+ retryOptions,
2655
+ runObservers,
2656
+ structuredOutputRetryEventAttributes(error, retryRequest)
2657
+ );
2658
+ continue;
2659
+ }
2660
+ const finalResponse = Usage.isEmpty(failedAttemptUsage) ? response : { ...response, usage: cumulativeUsage };
2661
+ await generationObservers.end({ turn, response: finalResponse });
2662
+ this.failedCompletionUsage = Usage.empty();
2663
+ return finalResponse;
2664
+ }
2665
+ } catch (error) {
2666
+ await settleFailureCleanup([() => generationObservers.error({ turn, error })]);
2667
+ throw error;
2668
+ }
2669
+ }
2670
+ async createTurnRequest(prompt, history, turn) {
2671
+ const ragText = extractRagText(prompt);
2672
+ const abortSignal = this.abortController.signal;
2673
+ const documents = await fetchContextDocuments(this.agent, ragText, abortSignal);
2674
+ const toolDefinitions = await fetchToolDefinitions(this.agent, ragText, abortSignal);
2675
+ const request = createCompletionRequest(providerMessages([...history, prompt]), {
2676
+ instructions: this.agent.instructions,
2677
+ documents,
2678
+ tools: [...toolDefinitions, ...getAgentToolState(this.agent).providerTools],
2679
+ temperature: this.agent.temperature,
2680
+ maxTokens: this.agent.maxTokens,
2681
+ providerOptions: this.agent.providerOptions,
2682
+ toolChoice: this.agent.toolChoice,
2683
+ outputSchema: getAgentProviderOutputSchema(this.agent)
2684
+ });
2685
+ return this.runCompletionRequestMiddlewares(request, turn);
2686
+ }
2687
+ async *streamCompletion(args) {
2688
+ const model = this.agent.model;
2689
+ if (!isStreamingCompletionModel(model)) {
2690
+ throw new TypeError("Streaming completion requires a streaming-capable model.");
2691
+ }
2692
+ this.validatedStructuredOutput = void 0;
2693
+ let currentRequest = args.request;
2694
+ for (let attempt = 1; ; attempt += 1) {
2695
+ const accumulator = new CompletionStreamAccumulator();
2696
+ let hasProviderProgress = false;
2697
+ let recordedErrorUsage = false;
2698
+ let attemptErrorUsage;
2699
+ try {
2700
+ this.throwIfCancelled();
2701
+ for await (const event of model.streamCompletion(currentRequest, this.modelCallOptions())) {
2702
+ if (event.type === "error") {
2703
+ const eventUsage = event.usage ?? completionProviderOutputErrorUsage(event.error);
2704
+ if (eventUsage !== void 0) {
2705
+ args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, eventUsage);
2706
+ recordedErrorUsage = true;
2707
+ attemptErrorUsage = eventUsage;
2708
+ }
2709
+ throw event.error;
2710
+ }
2711
+ const mapped = accumulator.accept(event);
2712
+ if (event.type === "final") break;
2713
+ if (event.type === "tool_call_delta" || mapped !== void 0) {
2714
+ hasProviderProgress = true;
2715
+ }
2716
+ if (args.state.firstDeltaMs === void 0 && isGenerationDeltaEvent(event.type)) {
2717
+ args.state.firstDeltaMs = Date.now() - args.generationStartedAt;
2718
+ }
2719
+ if (event.type === "tool_call_delta") {
2720
+ yield addTurnToToolCallDelta(args.turn, event);
2721
+ }
2722
+ if (mapped !== void 0) {
2723
+ await args.generationObservers.update?.({ turn: args.turn, delta: mapped });
2724
+ if (mapped.type === "tool_call") {
2725
+ args.state.emittedToolCallIds.add(mapped.toolCall.toolCallId);
2726
+ }
2727
+ const shouldBuffer = args.bufferResponseEvents || args.bufferOutputDeltas && (mapped.type === "text_delta" || mapped.type === "reasoning_delta");
2728
+ if (!shouldBuffer) {
2729
+ yield addTurn(args.turn, mapped);
2730
+ }
2731
+ }
2732
+ }
2733
+ const response = accumulator.response();
2734
+ assertCompletionResponseIntegrity({ response });
2735
+ const cumulativeStructuredUsage = Usage.add(args.state.providerErrorUsage, response.usage);
2736
+ try {
2737
+ this.validateStructuredResponse(response, attempt, cumulativeStructuredUsage);
2738
+ } catch (error) {
2739
+ const retryOptions = this.retryOptionsForFailure(error, attempt, args.turn, true);
2740
+ if (retryOptions === void 0) {
2741
+ if (error instanceof AgentStructuredOutputError) {
2742
+ args.state.providerErrorUsage = Usage.empty();
2743
+ }
2744
+ throw error;
2745
+ }
2746
+ args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, response.usage);
2747
+ args.state.firstDeltaMs = void 0;
2748
+ args.state.emittedToolCallIds.clear();
2749
+ const retryRequest = structuredOutputRetryRequest(args.request, response, error);
2750
+ currentRequest = retryRequest.request;
2751
+ await this.scheduleCompletionRetry(
2752
+ error,
2753
+ attempt,
2754
+ args.turn,
2755
+ true,
2756
+ retryOptions,
2757
+ args.runObservers,
2758
+ structuredOutputRetryEventAttributes(error, retryRequest)
2759
+ );
2760
+ continue;
2761
+ }
2762
+ args.state.response = Usage.isEmpty(args.state.providerErrorUsage) ? response : { ...response, usage: cumulativeStructuredUsage };
2763
+ args.state.providerErrorUsage = Usage.empty();
2764
+ return;
2765
+ } catch (error) {
2766
+ if (!recordedErrorUsage) {
2767
+ const attemptUsage = completionProviderOutputErrorUsage(error);
2768
+ if (attemptUsage !== void 0) {
2769
+ args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, attemptUsage);
2770
+ attemptErrorUsage = attemptUsage;
2771
+ }
2772
+ }
2773
+ const retryOptions = hasProviderProgress ? void 0 : this.retryOptionsForFailure(error, attempt, args.turn, true);
2774
+ if (retryOptions === void 0) {
2775
+ throw error;
2776
+ }
2777
+ await this.scheduleCompletionRetry(
2778
+ error,
2779
+ attempt,
2780
+ args.turn,
2781
+ true,
2782
+ retryOptions,
2783
+ args.runObservers,
2784
+ providerOutputRetryEventAttributes(
2785
+ error,
2786
+ args.state.providerErrorUsage,
2787
+ attemptErrorUsage
2788
+ )
2789
+ );
2790
+ }
2791
+ }
2792
+ }
2793
+ async *completeStreamingRun(args) {
2794
+ const guardedOutput = await this.runOutputGuardrailsForResponse(
2795
+ args.runId,
2796
+ args.usage,
2797
+ args.response,
2798
+ args.newMessages,
2799
+ args.runObservers
2800
+ );
2801
+ for (const decision of guardedOutput.decisions) {
2802
+ yield { type: "guardrail_decision", decision };
2803
+ }
2804
+ const response = guardedOutput.response;
2805
+ const assistantMessage = this.generatedAssistantMessage(response, args.request);
2806
+ args.newMessages[args.newMessages.length - 1] = assistantMessage;
2807
+ await this.memoryRecorder.commitMessages(
2808
+ args.runId,
2809
+ args.turn,
2810
+ [assistantMessage],
2811
+ args.pendingTurnMessages
2812
+ );
2813
+ if (!args.emittedTurnEnd && (args.bufferResponseEvents || args.bufferOutputDeltas)) {
2814
+ for (const event of responseStreamEvents(args.turn, response, args.bufferResponseEvents)) {
2815
+ yield event;
2816
+ }
2817
+ }
2818
+ if (!args.emittedTurnEnd) {
2819
+ yield {
2820
+ type: "turn_end",
2821
+ turn: args.turn,
2822
+ response,
2823
+ firstDeltaMs: args.firstDeltaMs
2824
+ };
2825
+ }
2826
+ const result = this.createTerminalResult(
2827
+ args.runId,
2828
+ guardedOutput.text,
2829
+ guardedOutput.blocked,
2830
+ args.usage,
2831
+ args.newMessages,
2832
+ args.runObservers
2833
+ );
2834
+ if (result.status === "completed") {
2835
+ await this.runRunEndHook(result, args.newMessages);
2836
+ }
2837
+ await this.memoryRecorder.commitCompletedRun(
2838
+ args.runId,
2839
+ args.turn,
2840
+ args.newMessages,
2841
+ args.pendingTurnMessages
2842
+ );
2843
+ await this.runLifecycleFinish(result);
2844
+ await args.runObservers.end(result);
2845
+ this.runState = "completed";
2846
+ this.disposeAbortLink();
2847
+ yield { type: "final", result };
2848
+ }
2849
+ async finishSuspension(args) {
2850
+ const partialToolMessage = args.suspension.completedResults.length === 0 ? void 0 : { role: "tool", content: [...args.suspension.completedResults] };
2851
+ if (partialToolMessage !== void 0) {
2852
+ args.newMessages.push(partialToolMessage);
2853
+ args.uncommittedMessages.push(partialToolMessage);
2854
+ }
2855
+ await this.memoryRecorder.commitMessages(
2856
+ args.runId,
2857
+ args.turn,
2858
+ args.uncommittedMessages,
2859
+ args.pendingTurnMessages
2860
+ );
2861
+ await this.memoryRecorder.commitCompletedRun(
2862
+ args.runId,
2863
+ args.turn,
2864
+ args.newMessages,
2865
+ args.pendingTurnMessages
2866
+ );
2867
+ this.runState = "closing";
2868
+ const continuationState = {
2869
+ kind: "anvia.agent-continuation",
2870
+ history: [...this.chatHistory],
2871
+ messages: [...args.newMessages],
2872
+ pending: args.suspension.pending,
2873
+ remainingToolCalls: [...args.suspension.remainingToolCalls],
2874
+ steering: this.steeringMessages.map((entry) => ({
2875
+ id: entry.id,
2876
+ messages: [...entry.messages]
2877
+ }))
2878
+ };
2879
+ if (this.memoryScope !== void 0) continuationState.memoryScope = this.memoryScope;
2880
+ const continuation = parseAgentContinuation({
2881
+ version: 1,
2882
+ agentId: this.agent.id,
2883
+ sourceRunId: args.runId,
2884
+ interaction: args.suspension.interaction,
2885
+ state: serializeContinuationState(continuationState)
2886
+ });
2887
+ const result = {
2888
+ status: "suspended",
2889
+ runId: args.runId,
2890
+ text: latestAssistantText([...this.chatHistory, ...args.newMessages]),
2891
+ usage: args.usage,
2892
+ messages: [...args.newMessages],
2893
+ trace: args.runObservers.trace,
2894
+ guardrails: [...this.guardrailDecisions],
2895
+ interaction: continuation.interaction,
2896
+ continuation,
2897
+ ...generationArtifacts([...this.chatHistory, ...args.newMessages]),
2898
+ ...this.memoryCompactionResult()
2899
+ };
2900
+ if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
2901
+ await this.runLifecycleFinish(result);
2902
+ await args.runObservers.end(result);
2903
+ this.runState = "completed";
2904
+ this.currentMessages = [...args.newMessages];
2905
+ this.disposeAbortLink();
2906
+ return result;
2907
+ }
2908
+ generatedAssistantMessage(response, _request) {
2909
+ const generation = {
2910
+ provider: this.agent.model.provider,
2911
+ modelId: this.agent.model.modelId,
2912
+ usage: { ...response.usage }
2913
+ };
2914
+ if (response.finishReason !== void 0) generation.finishReason = response.finishReason;
2915
+ if (response.providerFinishReason !== void 0) {
2916
+ generation.providerFinishReason = response.providerFinishReason;
2917
+ }
2918
+ if (response.contextUsage !== void 0) generation.contextUsage = response.contextUsage;
2919
+ if (response.sources !== void 0) generation.sources = response.sources;
2920
+ if (response.providerToolCalls !== void 0) {
2921
+ generation.providerToolCalls = response.providerToolCalls;
2922
+ }
2923
+ const metadata = { anvia: { generation } };
2924
+ let message = {
2925
+ role: "assistant",
2926
+ content: response.choice,
2927
+ metadata
2928
+ };
2929
+ if (response.messageId !== void 0) message = { ...message, id: response.messageId };
2930
+ return message;
2931
+ }
2932
+ providerTraceRequest(request, options = {}) {
2933
+ try {
2934
+ return this.agent.model.traceRequest?.(request, options);
2935
+ } catch (error) {
2936
+ return {
2937
+ error: error instanceof Error ? error.message : String(error)
2938
+ };
2939
+ }
2940
+ }
2941
+ generationStartArgs(turn, request, providerRequest) {
2942
+ let args = {
2943
+ turn,
2944
+ request,
2945
+ modelInfo: {
2946
+ provider: this.agent.model.provider,
2947
+ modelId: this.agent.model.modelId,
2948
+ capabilities: this.agent.model.capabilities
2949
+ }
2950
+ };
2951
+ if (providerRequest !== void 0) args = { ...args, providerRequest };
2952
+ return args;
2953
+ }
2954
+ retryOptionsForFailure(error, attempt, turn, streaming) {
2955
+ if (this.abortController.signal.aborted) return void 0;
2956
+ return retryOptionsForFailure(this.completionRetryOptions, {
2957
+ error,
2958
+ attempt,
2959
+ turn,
2960
+ streaming
2961
+ });
2962
+ }
2963
+ async scheduleCompletionRetry(error, attempt, turn, streaming, options, runObservers, additionalAttributes) {
2964
+ const delayMs = retryDelayMs(options, attempt);
2965
+ const attributes = {
2966
+ turn,
2967
+ attempt,
2968
+ nextAttempt: attempt + 1,
2969
+ maxAttempts: options.maxAttempts,
2970
+ delayMs,
2971
+ streaming,
2972
+ ...retryErrorAttributes(error)
2973
+ };
2974
+ if (additionalAttributes !== void 0) {
2975
+ Object.assign(attributes, additionalAttributes);
2976
+ }
2977
+ await runObservers.event({
2978
+ name: "completion.retry",
2979
+ level: "WARNING",
2980
+ attributes
2981
+ });
2982
+ await waitForRetry(delayMs, this.abortController.signal);
2983
+ }
2984
+ async executeToolCalls(runId, toolCalls, newMessages, onResult, onStreamEvent, observation) {
2985
+ const executor = this.createToolExecutor(runId, newMessages);
2986
+ return executor.execute(toolCalls, onResult, onStreamEvent, observation);
2987
+ }
2988
+ createToolExecutor(runId, newMessages) {
2989
+ return new ToolCallExecutor(
2990
+ this.agent,
2991
+ this.activeHook,
2992
+ async (request) => {
2993
+ throw new AgentInteractionSignal(approvalInteraction(request), request.rejectMessage);
2994
+ },
2995
+ this.activeLifecycle,
2996
+ {
2997
+ runId,
2998
+ sessionId: this.memoryScope?.sessionId,
2999
+ metadata: this.memoryScope?.metadata
3000
+ },
3001
+ this.concurrency,
3002
+ this.requestMiddlewares,
3003
+ this.abortController.signal,
3004
+ (reason) => this.cancelled(newMessages, reason)
3005
+ );
3006
+ }
3007
+ async resolveContinuationTools(runId, newMessages, onResult, onStreamEvent, observation) {
3008
+ const state = this.continuationState;
3009
+ const response = this.interactionResponse;
3010
+ if (state === void 0 || response === void 0) {
3011
+ return [];
3012
+ }
3013
+ const pending = state.pending;
3014
+ const interaction = this.resumedFrom;
3015
+ if (interaction === void 0) {
3016
+ throw new TypeError("Agent continuation is missing its source run linkage.");
3017
+ }
3018
+ const executor = this.createToolExecutor(runId, newMessages);
3019
+ const results = [];
3020
+ if (response.type === "tool-approval") {
3021
+ const attributes = {
3022
+ approvalId: interaction.interactionId,
3023
+ toolName: pending.toolCall.toolName,
3024
+ toolCallId: pending.toolCall.toolCallId,
3025
+ internalCallId: pending.internalCallId,
3026
+ approved: response.approved
3027
+ };
3028
+ if (response.reason !== void 0) attributes.decisionReason = response.reason;
3029
+ await observation.runObservers.event({
3030
+ name: "tool.approval_resolved",
3031
+ attributes
3032
+ });
3033
+ if (response.approved) {
3034
+ results.push(await executor.executeResumed(pending, onResult, onStreamEvent, observation));
3035
+ } else {
3036
+ const output = {
3037
+ type: "execution-denied",
3038
+ reason: response.reason ?? pending.rejectMessage ?? "Tool approval was rejected."
3039
+ };
3040
+ results.push(await executor.resolveResumed(pending, output, onResult, observation));
3041
+ }
3042
+ } else {
3043
+ const currentTool = this.agent.getTool(pending.toolCall.toolName);
3044
+ if (currentTool === void 0 || !isQuestionTool(currentTool)) {
3045
+ throw new TypeError(
3046
+ `Cannot resume question interaction because tool "${pending.toolCall.toolName}" is no longer registered as a question tool.`
3047
+ );
3048
+ }
3049
+ const output = questionResult(response.answers);
3050
+ results.push(await executor.resolveResumed(pending, output, onResult, observation));
3051
+ }
3052
+ try {
3053
+ results.push(
3054
+ ...await executor.execute(state.remainingToolCalls, onResult, onStreamEvent, observation)
3055
+ );
3056
+ } catch (error) {
3057
+ if (error instanceof ToolExecutionSuspension) {
3058
+ error.completedResults = [...results, ...error.completedResults];
3059
+ }
3060
+ throw error;
3061
+ }
3062
+ return results;
3063
+ }
3064
+ executeStreamingToolCalls(runId, toolCalls, newMessages, observation) {
3065
+ const events = createAsyncQueue();
3066
+ const results = this.executeToolCalls(
3067
+ runId,
3068
+ toolCalls,
3069
+ newMessages,
3070
+ (result) => events.enqueue(result),
3071
+ (event) => events.enqueue(event),
3072
+ observation
3073
+ );
3074
+ results.then(
3075
+ () => events.close(),
3076
+ (error) => events.throw(error)
3077
+ );
3078
+ return { events, results };
3079
+ }
3080
+ executeContinuationToolStream(runId, newMessages, observation) {
3081
+ const events = createAsyncQueue();
3082
+ const results = this.resolveContinuationTools(
3083
+ runId,
3084
+ newMessages,
3085
+ (result) => events.enqueue(result),
3086
+ (event) => events.enqueue(event),
3087
+ observation
3088
+ );
3089
+ results.then(
3090
+ () => events.close(),
3091
+ (error) => events.throw(error)
3092
+ );
3093
+ return { events, results };
3094
+ }
3095
+ async closeActiveGeneration(error) {
3096
+ const active = this.activeGeneration;
3097
+ if (active === void 0) {
3098
+ return;
3099
+ }
3100
+ this.activeGeneration = void 0;
3101
+ await active.observers.error({ turn: active.turn, error });
3102
+ }
3103
+ updateRunProgress(messages) {
3104
+ this.currentMessages = [...messages];
3105
+ }
3106
+ async runLifecycleFinish(result) {
3107
+ const common = {
3108
+ runId: result.runId,
3109
+ text: result.text,
3110
+ usage: lifecycleSnapshot(result.usage),
3111
+ messages: lifecycleSnapshot(result.messages)
3112
+ };
3113
+ if (result.memoryCompaction !== void 0) {
3114
+ Object.assign(common, { memoryCompaction: lifecycleSnapshot(result.memoryCompaction) });
3115
+ }
3116
+ const event = result.status === "completed" ? {
3117
+ ...common,
3118
+ status: "completed",
3119
+ output: lifecycleSnapshot(result.output)
3120
+ } : result.status === "blocked" ? {
3121
+ ...common,
3122
+ status: "blocked",
3123
+ stage: result.stage
3124
+ } : {
3125
+ ...common,
3126
+ status: "suspended",
3127
+ interaction: lifecycleSnapshot(result.interaction)
3128
+ };
3129
+ await this.activeLifecycle?.onFinish?.(event);
3130
+ }
3131
+ async runLifecycleError(error, runId, usage, messages) {
3132
+ try {
3133
+ await this.activeLifecycle?.onError?.({
3134
+ runId,
3135
+ error: lifecycleSnapshot(error),
3136
+ usage: lifecycleSnapshot(usage),
3137
+ messages: lifecycleSnapshot([...this.chatHistory, ...messages])
3138
+ });
3139
+ return void 0;
3140
+ } catch (lifecycleError) {
3141
+ return lifecycleError;
3142
+ }
3143
+ }
3144
+ async reportRunFailure(error, runId, usage, messages, runObservers) {
3145
+ const reportedError = await this.resolveReportedRunError(error, runId, usage, messages);
3146
+ await settleFailureCleanup([
3147
+ () => this.onInternalFailure?.({
3148
+ error: reportedError,
3149
+ messages: lifecycleSnapshot(messages)
3150
+ }),
3151
+ () => runObservers?.error({
3152
+ error: reportedError,
3153
+ usage,
3154
+ messages: [...messages]
3155
+ }),
3156
+ () => this.memoryRecorder.recordError(runId, reportedError, messages)
3157
+ ]);
3158
+ return reportedError;
3159
+ }
3160
+ async resolveReportedRunError(error, runId, usage, messages) {
3161
+ try {
3162
+ await this.runRunErrorHook(error, usage, messages);
3163
+ } catch {
3164
+ }
3165
+ await this.runLifecycleError(error, runId, usage, messages);
3166
+ return error;
3167
+ }
3168
+ async runOutputGuardrailsForResponse(runId, usage, response, messages, runObservers) {
3169
+ const originalOutput = textFromAssistantContent(response.choice);
3170
+ const result = await runOutputGuardrails(this.guardrailPolicies, {
3171
+ outputText: originalOutput,
3172
+ messages: [...this.chatHistory, ...messages],
3173
+ usage,
3174
+ run: this.guardrailRunContext(runId)
3175
+ });
3176
+ for (const decision of result.decisions) {
3177
+ await this.recordGuardrailDecision(decision, runObservers);
3178
+ }
3179
+ const text = result.blocked ? result.message ?? "The response was blocked by a guardrail." : result.outputText;
3180
+ if (text === originalOutput) {
3181
+ return { text, blocked: result.blocked, response, decisions: result.decisions };
3182
+ }
3183
+ return {
3184
+ text,
3185
+ blocked: result.blocked,
3186
+ response: {
3187
+ ...response,
3188
+ choice: [{ type: "text", text }]
3189
+ },
3190
+ decisions: result.decisions
3191
+ };
3192
+ }
3193
+ createTerminalResult(runId, text, blocked, usage, messages, runObservers) {
3194
+ const common = {
3195
+ runId,
3196
+ text,
3197
+ usage,
3198
+ messages: [...messages],
3199
+ trace: runObservers.trace,
3200
+ guardrails: [...this.guardrailDecisions],
3201
+ ...generationArtifacts(messages),
3202
+ ...this.memoryCompactionResult()
3203
+ };
3204
+ if (this.resumedFrom !== void 0) Object.assign(common, { resumedFrom: this.resumedFrom });
3205
+ if (blocked) {
3206
+ return { ...common, status: "blocked", stage: "output" };
3207
+ }
3208
+ return {
3209
+ ...common,
3210
+ status: "completed",
3211
+ output: this.parseOutput(text)
3212
+ };
3213
+ }
3214
+ validateStructuredResponse(response, attempt, usage) {
3215
+ if (this.agent.outputSchema === void 0) return;
3216
+ if (response.choice.some((item) => item.type === "tool-call")) return;
3217
+ const text = textFromAssistantContent(response.choice);
3218
+ const normalized = normalizeStructuredOutput(text);
3219
+ if (response.finishReason === "content-filter") {
3220
+ throw new AgentStructuredOutputError({
3221
+ phase: "content-filter",
3222
+ attempt,
3223
+ maxAttempts: this.completionRetryOptions?.maxAttempts ?? 1,
3224
+ outputLength: text.length,
3225
+ normalizedLength: normalized.text.length,
3226
+ outputFormat: normalized.format,
3227
+ attemptUsage: response.usage,
3228
+ usage,
3229
+ finishReason: response.finishReason,
3230
+ providerFinishReason: response.providerFinishReason
3231
+ });
3232
+ }
3233
+ if (response.finishReason === "length") {
3234
+ throw new AgentStructuredOutputError({
3235
+ phase: "truncated",
3236
+ attempt,
3237
+ maxAttempts: this.completionRetryOptions?.maxAttempts ?? 1,
3238
+ outputLength: text.length,
3239
+ normalizedLength: normalized.text.length,
3240
+ outputFormat: normalized.format,
3241
+ attemptUsage: response.usage,
3242
+ usage,
3243
+ finishReason: response.finishReason,
3244
+ providerFinishReason: response.providerFinishReason
3245
+ });
3246
+ }
3247
+ const output = this.parseOutput(text, attempt, usage, {
3248
+ useValidatedOutput: false,
3249
+ attemptUsage: response.usage,
3250
+ finishReason: response.finishReason,
3251
+ providerFinishReason: response.providerFinishReason
3252
+ });
3253
+ this.validatedStructuredOutput = { text, output };
3254
+ }
3255
+ takeFailedCompletionUsage() {
3256
+ const usage = this.failedCompletionUsage;
3257
+ this.failedCompletionUsage = Usage.empty();
3258
+ return usage;
3259
+ }
3260
+ parseOutput(text, attempt = 1, usage = Usage.empty(), options = {}) {
3261
+ const schema = this.agent.outputSchema;
3262
+ if (schema === void 0) return text;
3263
+ if (options.useValidatedOutput !== false && this.validatedStructuredOutput?.text === text) {
3264
+ return this.validatedStructuredOutput.output;
3265
+ }
3266
+ const normalized = normalizeStructuredOutput(text);
3267
+ const maxAttempts = this.completionRetryOptions?.maxAttempts ?? 1;
3268
+ let json;
3269
+ try {
3270
+ json = JSON.parse(normalized.text);
3271
+ if (!isJsonValue(json)) {
3272
+ throw new TypeError("Agent structured output is not a JSON value.");
3273
+ }
3274
+ } catch (error) {
3275
+ throw new AgentStructuredOutputError({
3276
+ phase: "parse",
3277
+ attempt,
3278
+ maxAttempts,
3279
+ outputLength: text.length,
3280
+ normalizedLength: normalized.text.length,
3281
+ outputFormat: normalized.format,
3282
+ attemptUsage: options.attemptUsage ?? usage,
3283
+ usage,
3284
+ finishReason: options.finishReason,
3285
+ providerFinishReason: options.providerFinishReason,
3286
+ cause: error
3287
+ });
3288
+ }
3289
+ try {
3290
+ return schema.parse(json);
3291
+ } catch (error) {
3292
+ throw new AgentStructuredOutputError({
3293
+ phase: "schema",
3294
+ attempt,
3295
+ maxAttempts,
3296
+ outputLength: text.length,
3297
+ normalizedLength: normalized.text.length,
3298
+ outputFormat: normalized.format,
3299
+ attemptUsage: options.attemptUsage ?? usage,
3300
+ usage,
3301
+ finishReason: options.finishReason,
3302
+ providerFinishReason: options.providerFinishReason,
3303
+ cause: error
3304
+ });
3305
+ }
3306
+ }
3307
+ memoryCompactionResult() {
3308
+ return this.memoryCompaction === void 0 ? {} : { memoryCompaction: lifecycleSnapshot(this.memoryCompaction) };
3309
+ }
3310
+ async recordGuardrailDecision(decision, runObservers) {
3311
+ this.guardrailDecisions.push(decision);
3312
+ await runObservers.event({
3313
+ name: "guardrail.decision",
3314
+ level: decision.action === "block" ? "WARNING" : "DEFAULT",
3315
+ attributes: guardrailDecisionAttributes(decision)
3316
+ });
3317
+ }
3318
+ async recordMemoryCompaction(preparation, runObservers) {
3319
+ const compaction = preparation.compaction;
3320
+ if (compaction === void 0) {
3321
+ return;
3322
+ }
3323
+ await runObservers.event({
3324
+ name: "memory.compaction",
3325
+ attributes: {
3326
+ originalMessageCount: compaction.originalMessageCount,
3327
+ compactedMessageCount: compaction.compactedMessageCount,
3328
+ retainedMessageCount: compaction.retainedMessageCount,
3329
+ attempts: compaction.attempts,
3330
+ inputTokens: compaction.usage.inputTokens,
3331
+ outputTokens: compaction.usage.outputTokens,
3332
+ totalTokens: compaction.usage.totalTokens
3333
+ }
3334
+ });
3335
+ }
3336
+ async notifyInternalMemoryCompaction(compaction) {
3337
+ if (compaction === void 0) {
3338
+ return;
3339
+ }
3340
+ await this.onInternalMemoryCompaction?.(lifecycleSnapshot(compaction));
3341
+ }
3342
+ guardrailRunContext(runId) {
3343
+ const context = {
3344
+ agentId: this.agent.id,
3345
+ runId
3346
+ };
3347
+ if (this.memoryScope !== void 0) {
3348
+ context.sessionId = this.memoryScope.sessionId;
3349
+ if (this.memoryScope.metadata !== void 0) {
3350
+ context.metadata = this.memoryScope.metadata;
3351
+ }
3352
+ }
3353
+ return context;
3354
+ }
3355
+ async startRunObservers(runId) {
3356
+ const observability = this.agent.observability;
3357
+ return startAgentRunObservers(
3358
+ observability?.observers ?? {},
3359
+ {
3360
+ runId,
3361
+ agentName: this.agent.name,
3362
+ agentDescription: this.agent.description,
3363
+ instructions: this.agent.instructions,
3364
+ trace: this.traceOptions,
3365
+ promptRef: this.traceOptions?.promptRef,
3366
+ prompt: this.promptMessage,
3367
+ history: this.chatHistory,
3368
+ maxTurns: this.maxTurnCount
3369
+ },
3370
+ {
3371
+ primaryTrace: observability?.primaryTrace,
3372
+ errorPolicy: observability?.errorPolicy ?? "ignore"
3373
+ }
3374
+ );
3375
+ }
3376
+ async runCompletionCallHook(prompt, history, newMessages) {
3377
+ const action = await this.activeHook?.onCompletionCall?.({
3378
+ prompt,
3379
+ history,
3380
+ run: runControl
3381
+ });
3382
+ if (action?.type === "terminate") {
3383
+ throw this.cancelled(newMessages, action.reason);
3384
+ }
3385
+ }
3386
+ async runRunStartHook(newMessages) {
3387
+ const action = await this.activeHook?.onRunStart?.({
3388
+ prompt: this.promptMessage,
3389
+ history: this.chatHistory,
3390
+ maxTurns: this.maxTurnCount,
3391
+ run: runControl
3392
+ });
3393
+ if (action?.type === "terminate") {
3394
+ throw this.cancelled(newMessages, action.reason);
3395
+ }
3396
+ }
3397
+ async runRunEndHook(result, newMessages) {
3398
+ const action = await this.activeHook?.onRunEnd?.({
3399
+ status: "completed",
3400
+ output: result.output,
3401
+ text: result.text,
3402
+ usage: result.usage,
3403
+ messages: result.messages,
3404
+ run: runControl
3405
+ });
3406
+ if (action?.type === "terminate") {
3407
+ throw this.cancelled(newMessages, action.reason);
3408
+ }
3409
+ }
3410
+ async runRunErrorHook(error, usage, newMessages) {
3411
+ const action = await this.activeHook?.onRunError?.({
3412
+ error,
3413
+ usage,
3414
+ messages: [...this.chatHistory, ...newMessages],
3415
+ run: runControl
3416
+ });
3417
+ if (action?.type === "terminate") {
3418
+ this.cancelled(newMessages, action.reason);
3419
+ }
3420
+ }
3421
+ async runTurnStartHook(turn, prompt, history, newMessages) {
3422
+ const action = await this.activeHook?.onTurnStart?.({
3423
+ turn,
3424
+ prompt,
3425
+ history,
3426
+ run: runControl
3427
+ });
3428
+ if (action?.type === "terminate") {
3429
+ throw this.cancelled(newMessages, action.reason);
3430
+ }
3431
+ }
3432
+ async runTurnEndHook(turn, response, newMessages) {
3433
+ const action = await this.activeHook?.onTurnEnd?.({
3434
+ turn,
3435
+ response,
3436
+ run: runControl
3437
+ });
3438
+ if (action?.type === "terminate") {
3439
+ throw this.cancelled(newMessages, action.reason);
3440
+ }
3441
+ }
3442
+ async runCompletionRequestMiddlewares(request, turn) {
3443
+ let current = request;
3444
+ for (const middleware of this.activeMiddlewares()) {
3445
+ const replacement = await middleware.onCompletionRequest?.({
3446
+ turn,
3447
+ request: current,
3448
+ originalRequest: request
3449
+ });
3450
+ if (replacement?.request !== void 0) {
3451
+ current = replacement.request;
3452
+ if (current.providerOptions !== void 0) {
3453
+ assertJsonObject(current.providerOptions, "providerOptions");
3454
+ }
3455
+ }
3456
+ }
3457
+ return current;
3458
+ }
3459
+ async runCompletionResponseMiddlewares(request, response, turn) {
3460
+ let current = response;
3461
+ for (const middleware of this.activeMiddlewares()) {
3462
+ const replacement = await middleware.onCompletionResponse?.({
3463
+ turn,
3464
+ request,
3465
+ response: current,
3466
+ originalResponse: response
3467
+ });
3468
+ if (replacement?.response !== void 0) {
3469
+ current = replacement.response;
3470
+ }
3471
+ }
3472
+ return current;
3473
+ }
3474
+ async runCompletionResponseHook(prompt, response, newMessages) {
3475
+ const action = await this.activeHook?.onCompletionResponse?.({
3476
+ prompt,
3477
+ response,
3478
+ run: runControl
3479
+ });
3480
+ if (action?.type === "terminate") {
3481
+ throw this.cancelled(newMessages, action.reason);
3482
+ }
3483
+ }
3484
+ async runCompletionErrorHook(prompt, error, newMessages) {
3485
+ const action = await this.activeHook?.onCompletionError?.({
3486
+ prompt,
3487
+ error,
3488
+ run: runControl
3489
+ });
3490
+ if (action?.type === "terminate") {
3491
+ throw this.cancelled(newMessages, action.reason);
3492
+ }
3493
+ }
3494
+ activeMiddlewares() {
3495
+ return [...this.agent.middlewares, ...this.requestMiddlewares];
3496
+ }
3497
+ shouldBufferStreamResponseEvents() {
3498
+ return this.activeHook?.onCompletionResponse !== void 0 || this.activeMiddlewares().some((middleware) => middleware.onCompletionResponse !== void 0);
3499
+ }
3500
+ async drainSteeringMessages(runId, turn, newMessages, pendingTurnMessages, options = {}) {
3501
+ const receipts = this.steeringMessages.splice(0);
3502
+ if (receipts.length === 0) {
3503
+ if (options.closeWhenEmpty === true) {
3504
+ this.runState = "closing";
3505
+ }
3506
+ return [];
3507
+ }
3508
+ const messages = receipts.flatMap((receipt) => receipt.messages);
3509
+ newMessages.push(...messages);
3510
+ await this.memoryRecorder.commitMessages(runId, turn, messages, pendingTurnMessages);
3511
+ return receipts;
3512
+ }
3513
+ startRun() {
3514
+ if (this.runState === "idle") {
3515
+ this.runState = "running";
3516
+ return;
3517
+ }
3518
+ if (this.runState === "running") {
3519
+ throw new Error("Agent stream is already running.");
3520
+ }
3521
+ throw new Error("Agent stream has already been consumed.");
3522
+ }
3523
+ isTerminal() {
3524
+ return this.runState !== "idle" && this.runState !== "running";
3525
+ }
3526
+ cancelled(newMessages, reason) {
3527
+ if (this.cancellationError !== void 0) return this.cancellationError;
3528
+ const error = new AgentRunCancelledError([...this.chatHistory, ...newMessages], reason);
3529
+ this.setCancellationError(error);
3530
+ return error;
3531
+ }
3532
+ linkExternalAbortSignal(signal) {
3533
+ if (signal === void 0) return;
3534
+ const cancelFromSignal = () => {
3535
+ if (this.cancellationError !== void 0 || this.isTerminal()) return;
3536
+ const cause = abortError(signal.reason);
3537
+ const reason = abortReason(signal.reason);
3538
+ const messages = this.currentMessages.length === 0 ? [this.promptMessage] : [...this.currentMessages];
3539
+ this.setCancellationError(
3540
+ new AgentRunCancelledError([...this.chatHistory, ...messages], reason, { cause })
3541
+ );
3542
+ };
3543
+ if (signal.aborted) {
3544
+ cancelFromSignal();
3545
+ return;
3546
+ }
3547
+ signal.addEventListener("abort", cancelFromSignal, { once: true });
3548
+ this.removeExternalAbortListener = () => signal.removeEventListener("abort", cancelFromSignal);
3549
+ }
3550
+ throwIfCancelled() {
3551
+ if (this.cancellationError !== void 0) throw this.cancellationError;
3552
+ throwIfAborted(this.abortController.signal);
3553
+ }
3554
+ normalizeRunError(error) {
3555
+ return this.abortController.signal.aborted && this.cancellationError !== void 0 ? this.cancellationError : error;
3556
+ }
3557
+ modelCallOptions() {
3558
+ return { abortSignal: this.abortController.signal };
3559
+ }
3560
+ disposeAbortLink() {
3561
+ this.removeExternalAbortListener?.();
3562
+ this.removeExternalAbortListener = void 0;
3563
+ }
3564
+ };
3565
+ function abortReason(reason) {
3566
+ if (typeof reason === "string" && reason.trim().length > 0) return reason;
3567
+ if (reason instanceof Error && reason.message.trim().length > 0) return reason.message;
3568
+ return "External abort signal.";
3569
+ }
3570
+ function normalizeAgentInput(agentId, input) {
3571
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
3572
+ throw new TypeError("Agent runs require one options object with prompt or messages.");
3573
+ }
3574
+ const hasContinuation = "continuation" in input && input.continuation !== void 0;
3575
+ const hasPrompt = "prompt" in input && input.prompt !== void 0;
3576
+ const hasMessages = "messages" in input && input.messages !== void 0;
3577
+ if (Number(hasContinuation) + Number(hasPrompt) + Number(hasMessages) !== 1) {
3578
+ throw new TypeError("Agent runs require exactly one of prompt, messages, or continuation.");
3579
+ }
3580
+ if (hasContinuation) {
3581
+ if (!("response" in input) || input.response === void 0) {
3582
+ throw new TypeError("Agent continuation runs require an interaction response.");
3583
+ }
3584
+ if ("session" in input && input.session !== void 0) {
3585
+ throw new TypeError("Agent continuations carry their memory scope and cannot use session.");
3586
+ }
3587
+ const continuation = parseAgentContinuation(input.continuation);
3588
+ if (continuation.agentId !== agentId) {
3589
+ throw new TypeError(
3590
+ `Agent continuation belongs to "${continuation.agentId}", not "${agentId}".`
3591
+ );
3592
+ }
3593
+ const response = parseAgentInteractionResponse(input.response);
3594
+ assertAgentInteractionResponse(continuation.interaction, response);
3595
+ const state = parseContinuationState(continuation.state, continuation.interaction);
3596
+ let responsePart;
3597
+ if (response.type === "tool-approval") {
3598
+ responsePart = {
3599
+ type: "tool-approval-response",
3600
+ interactionId: continuation.interaction.id,
3601
+ toolCallId: continuation.interaction.toolCallId,
3602
+ toolName: continuation.interaction.toolName,
3603
+ approved: response.approved
3604
+ };
3605
+ if (response.reason !== void 0)
3606
+ responsePart = { ...responsePart, reason: response.reason };
3607
+ } else {
3608
+ responsePart = {
3609
+ type: "tool-question-response",
3610
+ interactionId: continuation.interaction.id,
3611
+ toolCallId: continuation.interaction.toolCallId,
3612
+ toolName: continuation.interaction.toolName,
3613
+ answers: response.answers
3614
+ };
3615
+ }
3616
+ if (continuation.interaction.callId !== void 0) {
3617
+ responsePart = { ...responsePart, callId: continuation.interaction.callId };
3618
+ }
3619
+ const normalized = {
3620
+ prompt: parseMessage({ role: "tool", content: [responsePart] }),
3621
+ history: [...state.history, ...state.messages],
3622
+ continuationState: state,
3623
+ interactionResponse: response,
3624
+ sourceRunId: continuation.sourceRunId,
3625
+ interactionId: continuation.interaction.id
3626
+ };
3627
+ if (state.memoryScope !== void 0) {
3628
+ Object.assign(normalized, { scope: normalizeMemoryScope(state.memoryScope) });
3629
+ }
3630
+ return normalized;
3631
+ }
3632
+ if (hasPrompt) {
3633
+ const prompt = input.prompt;
3634
+ if (typeof prompt !== "string" && (typeof prompt !== "object" || prompt === null || prompt.role !== "user")) {
3635
+ throw new TypeError("Agent prompt must be text or a user message.");
3636
+ }
3637
+ const parsedPrompt = parseMessage(
3638
+ typeof prompt === "string" ? { role: "user", content: prompt } : prompt
3639
+ );
3640
+ if (parsedPrompt.role !== "user") {
3641
+ throw new TypeError("Agent prompt must be text or a user message.");
3642
+ }
3643
+ const normalized = {
3644
+ prompt: parsedPrompt,
3645
+ history: []
3646
+ };
3647
+ if (input.session !== void 0) {
3648
+ Object.assign(normalized, { scope: normalizeMemoryScope(input.session) });
3649
+ }
3650
+ return normalized;
3651
+ }
3652
+ if (input.session !== void 0) {
3653
+ throw new TypeError("Agent messages cannot be combined with a persisted session.");
3654
+ }
3655
+ const messages = input.messages;
3656
+ if (!Array.isArray(messages) || messages.length === 0) {
3657
+ throw new TypeError("Agent input transcript must contain at least one message.");
3658
+ }
3659
+ const parsedMessages = parseMessages(messages);
3660
+ const activePrompt = parsedMessages.at(-1);
3661
+ if (activePrompt === void 0) {
3662
+ throw new TypeError("Agent input transcript must contain at least one message.");
3663
+ }
3664
+ if (activePrompt.role !== "user") {
3665
+ throw new TypeError("Agent input transcript must end with a user message.");
3666
+ }
3667
+ return {
3668
+ prompt: activePrompt,
3669
+ history: parsedMessages.slice(0, -1)
3670
+ };
3671
+ }
3672
+ function normalizeSteeringInput(input) {
3673
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
3674
+ throw new TypeError("Agent steering requires one options object with prompt or messages.");
3675
+ }
3676
+ const hasPrompt = "prompt" in input && input.prompt !== void 0;
3677
+ const hasMessages = "messages" in input && input.messages !== void 0;
3678
+ if (hasPrompt === hasMessages) {
3679
+ throw new TypeError("Agent steering requires exactly one of prompt or messages.");
3680
+ }
3681
+ if (hasPrompt) {
3682
+ const prompt = input.prompt;
3683
+ if (typeof prompt !== "string" && (typeof prompt !== "object" || prompt === null || prompt.role !== "user")) {
3684
+ throw new TypeError("Agent steering prompt must be text or a user message.");
3685
+ }
3686
+ const parsedPrompt = parseMessage(
3687
+ typeof prompt === "string" ? { role: "user", content: prompt } : prompt
3688
+ );
3689
+ if (parsedPrompt.role !== "user") {
3690
+ throw new TypeError("Agent steering prompt must be text or a user message.");
3691
+ }
3692
+ return [parsedPrompt];
3693
+ }
3694
+ const messages = input.messages;
3695
+ if (!Array.isArray(messages) || messages.length === 0) {
3696
+ throw new TypeError("Agent steering messages must contain at least one user message.");
3697
+ }
3698
+ const parsedMessages = parseMessages(messages);
3699
+ if (parsedMessages.some((message) => message.role !== "user")) {
3700
+ throw new TypeError("Agent steering messages must all be user messages.");
3701
+ }
3702
+ return parsedMessages;
3703
+ }
3704
+ function normalizeMemoryScope(scope) {
3705
+ if (typeof scope !== "object" || scope === null) {
3706
+ throw new TypeError("Agent session must be an object.");
3707
+ }
3708
+ if (typeof scope.sessionId !== "string" || scope.sessionId.trim().length === 0) {
3709
+ throw new TypeError("Agent sessionId must be a non-empty string.");
3710
+ }
3711
+ const normalized = {
3712
+ sessionId: scope.sessionId.trim()
3713
+ };
3714
+ if (scope.userId !== void 0) normalized.userId = scope.userId;
3715
+ if (scope.metadata !== void 0) normalized.metadata = scope.metadata;
3716
+ return lifecycleSnapshot(normalized);
3717
+ }
3718
+ function normalizeRequestedRunId(runId) {
3719
+ if (runId === void 0) {
3720
+ return void 0;
3721
+ }
3722
+ if (typeof runId !== "string" || runId.trim().length === 0) {
3723
+ throw new TypeError("runId must be a non-empty string.");
3724
+ }
3725
+ return runId;
3726
+ }
3727
+ function responseStreamEvents(turn, response, includeProviderArtifacts = true) {
3728
+ const events = [];
3729
+ for (const item of response.choice) {
3730
+ if (item.type === "text") {
3731
+ if (item.text.length > 0) {
3732
+ events.push({ type: "text_delta", turn, delta: item.text });
3733
+ }
3734
+ continue;
3735
+ }
3736
+ if (item.type === "reasoning") {
3737
+ if (item.details === void 0) {
3738
+ if (item.text.length > 0) {
3739
+ events.push(reasoningDeltaEvent(turn, item.text, { id: item.id }));
3740
+ }
3741
+ continue;
3742
+ }
3743
+ for (const content of item.details) {
3744
+ const delta = content.type === "encrypted" || content.type === "redacted" ? content.data : content.text;
3745
+ events.push(
3746
+ reasoningDeltaEvent(turn, delta, {
3747
+ id: item.id,
3748
+ contentType: content.type,
3749
+ signature: content.type === "text" ? content.signature : void 0
3750
+ })
3751
+ );
3752
+ }
3753
+ continue;
3754
+ }
3755
+ if (item.type === "tool-call") {
3756
+ events.push({ type: "tool_call", turn, toolCall: item });
3757
+ }
3758
+ }
3759
+ if (includeProviderArtifacts) {
3760
+ for (const source of response.sources ?? []) {
3761
+ events.push({ type: "source", turn, source });
3762
+ }
3763
+ for (const toolCall of response.providerToolCalls ?? []) {
3764
+ events.push({ type: "provider_tool_call", turn, toolCall });
3765
+ }
3766
+ }
3767
+ return events;
3768
+ }
3769
+ function generationArtifacts(messages) {
3770
+ const sources = /* @__PURE__ */ new Map();
3771
+ const providerToolCalls = /* @__PURE__ */ new Map();
3772
+ let finishReason;
3773
+ let providerFinishReason;
3774
+ let contextUsage;
3775
+ for (const message of messages) {
3776
+ const metadata = getAssistantGenerationMetadata(message);
3777
+ if (metadata !== void 0) {
3778
+ finishReason = metadata.finishReason;
3779
+ providerFinishReason = metadata.providerFinishReason;
3780
+ contextUsage = metadata.contextUsage;
3781
+ }
3782
+ for (const source of metadata?.sources ?? []) {
3783
+ const key = `${source.url}\0${source.startIndex ?? ""}\0${source.endIndex ?? ""}`;
3784
+ sources.set(key, source);
3785
+ }
3786
+ for (const toolCall of metadata?.providerToolCalls ?? []) {
3787
+ providerToolCalls.set(toolCall.id, toolCall);
3788
+ }
3789
+ }
3790
+ const artifacts = {};
3791
+ if (sources.size > 0) artifacts.sources = [...sources.values()];
3792
+ if (providerToolCalls.size > 0) {
3793
+ artifacts.providerToolCalls = [...providerToolCalls.values()];
3794
+ }
3795
+ if (finishReason !== void 0) artifacts.finishReason = finishReason;
3796
+ if (providerFinishReason !== void 0) {
3797
+ artifacts.providerFinishReason = providerFinishReason;
3798
+ }
3799
+ if (contextUsage !== void 0) artifacts.contextUsage = contextUsage;
3800
+ return artifacts;
3801
+ }
3802
+ function reasoningDeltaEvent(turn, delta, details = {}) {
3803
+ const event = {
3804
+ type: "reasoning_delta",
3805
+ turn,
3806
+ delta
3807
+ };
3808
+ if (details.id !== void 0) {
3809
+ event.id = details.id;
3810
+ }
3811
+ if (details.contentType !== void 0) {
3812
+ event.contentType = details.contentType;
3813
+ }
3814
+ if (details.signature !== void 0) {
3815
+ event.signature = details.signature;
3816
+ }
3817
+ return event;
3818
+ }
3819
+ function textFromMessage(message) {
3820
+ if (message.role === "system") {
3821
+ return message.content;
3822
+ }
3823
+ if (typeof message.content === "string") {
3824
+ return message.content;
3825
+ }
3826
+ return message.content.flatMap((content) => {
3827
+ if (content.type === "text") {
3828
+ return [content.text];
3829
+ }
3830
+ if (content.type === "file" && content.data.type === "text") {
3831
+ return [content.data.text];
3832
+ }
3833
+ return [];
3834
+ }).join("\n");
3835
+ }
3836
+ function latestAssistantText(messages) {
3837
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
3838
+ const message = messages[index];
3839
+ if (message?.role === "assistant") {
3840
+ return typeof message.content === "string" ? message.content : textFromAssistantContent(message.content);
3841
+ }
3842
+ }
3843
+ return "";
3844
+ }
3845
+ function structuredOutputRetryRequest(request, response, error) {
3846
+ const truncated = error instanceof AgentStructuredOutputError && error.phase === "truncated";
3847
+ const correction = {
3848
+ role: "user",
3849
+ content: truncated ? STRUCTURED_OUTPUT_TRUNCATED_RETRY_PROMPT : STRUCTURED_OUTPUT_RETRY_PROMPT
3850
+ };
3851
+ if (truncated) {
3852
+ return {
3853
+ request: {
3854
+ ...request,
3855
+ chatHistory: [...request.chatHistory, correction]
3856
+ },
3857
+ previousResponse: "omitted",
3858
+ includedOutputLength: 0
3859
+ };
3860
+ }
3861
+ const preview = structuredOutputRepairPreview(textFromAssistantContent(response.choice));
3862
+ if (preview.includedOutputLength === 0) {
3863
+ return {
3864
+ request: {
3865
+ ...request,
3866
+ chatHistory: [...request.chatHistory, correction]
3867
+ },
3868
+ previousResponse: "omitted",
3869
+ includedOutputLength: 0
3870
+ };
3871
+ }
3872
+ const invalidResponse = {
3873
+ role: "assistant",
3874
+ content: [{ type: "text", text: preview.text }]
3875
+ };
3876
+ return {
3877
+ request: {
3878
+ ...request,
3879
+ chatHistory: [...request.chatHistory, invalidResponse, correction]
3880
+ },
3881
+ previousResponse: "preview",
3882
+ includedOutputLength: preview.includedOutputLength
3883
+ };
3884
+ }
3885
+ function structuredOutputRetryEventAttributes(error, retryRequest) {
3886
+ const attributes = {
3887
+ previousResponse: retryRequest.previousResponse,
3888
+ includedOutputLength: retryRequest.includedOutputLength
3889
+ };
3890
+ if (!(error instanceof AgentStructuredOutputError)) return attributes;
3891
+ Object.assign(attributes, {
3892
+ failurePhase: error.phase,
3893
+ outputLength: error.outputLength,
3894
+ normalizedLength: error.normalizedLength,
3895
+ attemptUsage: usageEventValue(error.attemptUsage),
3896
+ cumulativeUsage: usageEventValue(error.usage)
3897
+ });
3898
+ if (error.finishReason !== void 0) attributes.finishReason = error.finishReason;
3899
+ if (error.providerFinishReason !== void 0) {
3900
+ attributes.providerFinishReason = error.providerFinishReason;
3901
+ }
3902
+ return attributes;
3903
+ }
3904
+ function providerOutputRetryEventAttributes(error, cumulativeUsage, attemptUsage) {
3905
+ const resolvedAttemptUsage = attemptUsage ?? completionProviderOutputErrorUsage(error);
3906
+ if (resolvedAttemptUsage === void 0) return void 0;
3907
+ return {
3908
+ attemptUsage: usageEventValue(resolvedAttemptUsage),
3909
+ cumulativeUsage: usageEventValue(cumulativeUsage)
3910
+ };
3911
+ }
3912
+ function usageEventValue(usage) {
3913
+ const value = {
3914
+ inputTokens: usage.inputTokens,
3915
+ outputTokens: usage.outputTokens,
3916
+ totalTokens: usage.totalTokens,
3917
+ cachedInputTokens: usage.cachedInputTokens,
3918
+ cacheCreationInputTokens: usage.cacheCreationInputTokens
3919
+ };
3920
+ if (usage.details !== void 0) value.details = { ...usage.details };
3921
+ return value;
3922
+ }
3923
+ function providerMessages(messages) {
3924
+ const providerMessages2 = [];
3925
+ for (const message of messages) {
3926
+ if (message.role !== "tool") {
3927
+ providerMessages2.push(message);
3928
+ continue;
3929
+ }
3930
+ const results = message.content.filter((part) => part.type === "tool-result");
3931
+ if (results.length > 0) {
3932
+ providerMessages2.push({ ...message, content: results });
3933
+ }
3934
+ }
3935
+ return providerMessages2;
3936
+ }
3937
+ function guardrailDecisionAttributes(decision) {
3938
+ const attributes = {
3939
+ policyId: decision.policyId,
3940
+ guardrailId: decision.guardrailId,
3941
+ boundary: decision.boundary,
3942
+ mode: decision.mode,
3943
+ action: decision.action,
3944
+ applied: decision.applied,
3945
+ latencyMs: decision.latencyMs
3946
+ };
3947
+ if (decision.reason !== void 0) {
3948
+ attributes.reason = decision.reason;
3949
+ }
3950
+ if (decision.message !== void 0) {
3951
+ attributes.message = decision.message;
3952
+ }
3953
+ return attributes;
3954
+ }
3955
+
3956
+ // src/agent/agent-stream.ts
3957
+ function createAgentStream(run) {
3958
+ return new DefaultAgentStream(run);
3959
+ }
3960
+ var DefaultAgentStream = class {
3961
+ constructor(run) {
3962
+ this.run = run;
3963
+ }
3964
+ run;
3965
+ consuming = false;
3966
+ completed = false;
3967
+ steer(input) {
3968
+ return this.run.steer(input);
3969
+ }
3970
+ [Symbol.asyncIterator]() {
3971
+ return this.consume()[Symbol.asyncIterator]();
3972
+ }
3973
+ async *consume() {
3974
+ if (this.completed) {
3975
+ throw new Error("Agent stream has already been consumed.");
3976
+ }
3977
+ if (this.consuming) {
3978
+ throw new Error("Agent stream is already running.");
3979
+ }
3980
+ this.consuming = true;
3981
+ try {
3982
+ for await (const event of this.run.events()) {
3983
+ yield event;
3984
+ }
3985
+ } finally {
3986
+ if (!this.completed) {
3987
+ this.run.cancel("Agent stream consumer closed the stream.");
3988
+ }
3989
+ this.consuming = false;
3990
+ this.completed = true;
3991
+ }
3992
+ }
3993
+ };
3994
+
3995
+ // src/agent/agent-tool.ts
3996
+ import { z } from "zod";
3997
+ function createAgentTool(agent, options) {
3998
+ if (options.suspension !== "reject") {
3999
+ throw new TypeError('Agent.asTool() requires suspension: "reject".');
4000
+ }
4001
+ const description = options.description ?? agent.description ?? `Prompt the ${options.name} agent.`;
4002
+ return createTool({
4003
+ name: options.name,
4004
+ description,
4005
+ inputSchema: z.object({
4006
+ prompt: z.string().describe("The prompt to send to the agent.")
4007
+ }),
4008
+ execute: async ({ prompt }, context) => {
4009
+ if (options.stream === true && context.emitStreamEvent !== void 0 && agent.model.capabilities.streaming && isStreamingCompletionModel(agent.model)) {
4010
+ let completed = false;
4011
+ let output;
4012
+ const childStream = agent.stream({
4013
+ prompt,
4014
+ maxTurns: options.maxTurns,
4015
+ abortSignal: context.abortSignal
4016
+ });
4017
+ for await (const event of childStream) {
4018
+ const streamEvent = {
4019
+ agentId: agent.id,
4020
+ event
4021
+ };
4022
+ if (agent.name !== void 0) {
4023
+ streamEvent.agentName = agent.name;
4024
+ }
4025
+ await context.emitStreamEvent(streamEvent);
4026
+ if (event.type === "error") {
4027
+ throw event.error;
4028
+ }
4029
+ if (event.type === "final") {
4030
+ if (event.result.status === "suspended") {
4031
+ throw new AgentToolSuspensionError(event.result);
4032
+ }
4033
+ if (event.result.status === "blocked") {
4034
+ throw new AgentRunBlockedError(event.result);
4035
+ }
4036
+ output = event.result.output;
4037
+ completed = true;
4038
+ }
4039
+ }
4040
+ if (!completed) {
4041
+ throw new Error(`Agent tool "${options.name}" ended without a final result.`);
4042
+ }
4043
+ return output;
4044
+ }
4045
+ const response = await agent.generate({
4046
+ prompt,
4047
+ maxTurns: options.maxTurns,
4048
+ abortSignal: context.abortSignal
4049
+ });
4050
+ if (response.status === "suspended") {
4051
+ throw new AgentToolSuspensionError(response);
4052
+ }
4053
+ if (response.status === "blocked") {
4054
+ throw new AgentRunBlockedError(response);
4055
+ }
4056
+ return response.output;
4057
+ }
4058
+ });
4059
+ }
4060
+
4061
+ // src/agent/ids.ts
4062
+ function normalizeAgentId(id) {
4063
+ if (typeof id !== "string") {
4064
+ throw new TypeError("Agent id must be a string.");
4065
+ }
4066
+ const normalized = id.trim();
4067
+ if (normalized.length === 0) {
4068
+ throw new TypeError("Agent id must be a non-empty string.");
4069
+ }
4070
+ return normalized;
4071
+ }
4072
+
4073
+ // src/memory/options.ts
4074
+ function resolveMemoryOptions(options = {}) {
4075
+ const resolved = {
4076
+ savePolicy: options.savePolicy ?? "message"
4077
+ };
4078
+ if (options.compaction !== void 0) {
4079
+ assertPositiveInteger(
4080
+ options.compaction.trigger.afterMessages,
4081
+ "compaction.trigger.afterMessages"
4082
+ );
4083
+ const recentUserTurns = options.compaction.retention?.recentUserTurns ?? 4;
4084
+ assertPositiveInteger(recentUserTurns, "compaction.retention.recentUserTurns");
4085
+ if (typeof options.compaction.compactor !== "function") {
4086
+ throw new TypeError("compaction.compactor must be a function.");
4087
+ }
4088
+ const conflictRetries = options.compaction.conflictRetries ?? false;
4089
+ if (conflictRetries !== false) {
4090
+ assertPositiveInteger(conflictRetries.maxAttempts, "compaction.conflictRetries.maxAttempts");
4091
+ }
4092
+ resolved.compaction = {
4093
+ trigger: {
4094
+ afterMessages: options.compaction.trigger.afterMessages
4095
+ },
4096
+ retention: {
4097
+ recentUserTurns
4098
+ },
4099
+ compactor: options.compaction.compactor,
4100
+ conflictRetries
4101
+ };
4102
+ }
4103
+ return resolved;
4104
+ }
4105
+
4106
+ // src/agent/resolve-options.ts
4107
+ var resolvedAgentOptions = /* @__PURE__ */ Symbol("resolvedAgentOptions");
4108
+ function resolveAgentOptions(options) {
4109
+ if (isInternalAgentOptions(options)) {
4110
+ return options;
4111
+ }
4112
+ const toolsByName = /* @__PURE__ */ new Map();
4113
+ const providerTools = [];
4114
+ const toolIndexes = [];
4115
+ for (const tool of options.tools ?? []) {
4116
+ if (isProviderTool(tool)) {
4117
+ providerTools.push(tool);
4118
+ } else if (isToolIndex(tool)) {
4119
+ toolIndexes.push(tool);
4120
+ } else if (tool.kind === "tool-index") {
4121
+ throw new TypeError("Invalid tool index: search, tools, and a numeric topK are required.");
4122
+ } else if (isMcpTool(tool)) {
4123
+ throw new TypeError(
4124
+ `MCP tool "${tool.name}" must be registered through Agent.mcpServers, not Agent.tools.`
4125
+ );
4126
+ } else {
4127
+ addUniqueTool(toolsByName, tool, "local tool");
4128
+ }
4129
+ }
4130
+ if (options.skills !== void 0) {
4131
+ for (const tool of options.skills.tools) {
4132
+ if (isMcpTool(tool)) {
4133
+ throw new TypeError(
4134
+ `MCP tool "${tool.name}" must be registered through Agent.mcpServers, not Agent.skills.`
4135
+ );
4136
+ }
4137
+ addUniqueTool(toolsByName, tool, "skill tool");
4138
+ }
4139
+ }
4140
+ const memory = resolveAgentMemory(options);
4141
+ const instructions = [options.instructions, options.skills?.instructions].filter((part) => part !== void 0 && part.length > 0).join("\n\n");
4142
+ return {
4143
+ id: options.id,
4144
+ name: options.name,
4145
+ description: options.description,
4146
+ model: options.model,
4147
+ instructions: instructions.length === 0 ? void 0 : instructions,
4148
+ context: [...options.context ?? []],
4149
+ temperature: options.temperature,
4150
+ maxTokens: options.maxTokens,
4151
+ providerOptions: options.providerOptions,
4152
+ retries: options.retries,
4153
+ tools: [...toolsByName.values()],
4154
+ mcpServers: [...options.mcpServers ?? []],
4155
+ providerTools,
4156
+ toolIndexes,
4157
+ toolChoice: options.toolChoice,
4158
+ defaultMaxTurns: options.maxTurns,
4159
+ lifecycle: options.lifecycle,
4160
+ outputSchema: options.outputSchema,
4161
+ observability: options.observability,
4162
+ guardrails: options.guardrails === void 0 ? [] : appendGuardrailPolicies([], options.guardrails),
4163
+ middlewares: [...options.middlewares ?? []],
4164
+ memory
4165
+ };
4166
+ }
4167
+ function markResolvedAgentOptions(options) {
4168
+ return {
4169
+ ...options,
4170
+ [resolvedAgentOptions]: true
4171
+ };
4172
+ }
4173
+ function isInternalAgentOptions(options) {
4174
+ return options[resolvedAgentOptions] === true;
4175
+ }
4176
+ function resolveAgentMemory(options) {
4177
+ if (options.memory === void 0) {
4178
+ return void 0;
4179
+ }
4180
+ const { store, ...memoryOptions } = options.memory;
4181
+ const resolvedOptions = resolveMemoryOptions(memoryOptions);
4182
+ if (resolvedOptions.compaction !== void 0 && store.compaction === void 0) {
4183
+ throw new TypeError(
4184
+ "Memory compaction requires a store with the optional compaction capability."
4185
+ );
4186
+ }
4187
+ return { store, ...resolvedOptions };
4188
+ }
4189
+ function addUniqueTool(tools, tool, source) {
4190
+ if (tools.has(tool.name)) {
4191
+ throw new TypeError(`Duplicate ${source} name "${tool.name}".`);
4192
+ }
4193
+ tools.set(tool.name, tool);
4194
+ }
4195
+
4196
+ // src/agent/snapshot.ts
4197
+ function snapshotAgentContext(inputs) {
4198
+ const context = (inputs ?? []).map(snapshotContextInput);
4199
+ for (const input of context) {
4200
+ if (!isVectorContext(input)) continue;
4201
+ assertPositiveSearchLimit(input.topK);
4202
+ assertFiniteMinScore(input.minScore);
4203
+ }
4204
+ return Object.freeze(context);
4205
+ }
4206
+ function snapshotAgentObservability(observability) {
4207
+ if (observability === void 0) return void 0;
4208
+ const observers = {};
4209
+ for (const [name, observer] of Object.entries(observability.observers)) {
4210
+ if (name.trim().length === 0) {
4211
+ throw new TypeError("Agent observer names must not be empty.");
4212
+ }
4213
+ if (typeof observer !== "object" || observer === null || typeof observer.startRun !== "function") {
4214
+ throw new TypeError(`Agent observer "${name}" must implement startRun().`);
4215
+ }
4216
+ observers[name] = observer;
4217
+ }
4218
+ if (observability.primaryTrace !== void 0 && !(observability.primaryTrace in observers)) {
4219
+ throw new TypeError(
4220
+ `Agent primaryTrace "${observability.primaryTrace}" must name a configured observer.`
4221
+ );
4222
+ }
4223
+ const errorPolicy = observability.errorPolicy ?? "ignore";
4224
+ if (errorPolicy !== "ignore" && errorPolicy !== "throw") {
4225
+ throw new TypeError('Agent observability.errorPolicy must be "ignore" or "throw".');
4226
+ }
4227
+ let snapshot = {
4228
+ observers: Object.freeze(observers),
4229
+ errorPolicy
4230
+ };
4231
+ if (observability.primaryTrace !== void 0) {
4232
+ snapshot = { ...snapshot, primaryTrace: observability.primaryTrace };
4233
+ }
4234
+ return Object.freeze(snapshot);
4235
+ }
4236
+ function snapshotGuardrailPolicies(policies) {
4237
+ return Object.freeze((policies ?? []).map(snapshotGuardrailPolicy));
4238
+ }
4239
+ function snapshotAgentMemory(memory) {
4240
+ if (memory === void 0) {
4241
+ return void 0;
4242
+ }
4243
+ const compaction = memory.compaction === void 0 ? void 0 : Object.freeze({
4244
+ ...memory.compaction,
4245
+ trigger: Object.freeze({ ...memory.compaction.trigger }),
4246
+ retention: Object.freeze({ ...memory.compaction.retention }),
4247
+ conflictRetries: memory.compaction.conflictRetries === false ? false : Object.freeze({ ...memory.compaction.conflictRetries })
4248
+ });
4249
+ let snapshot = {
4250
+ store: memory.store,
4251
+ savePolicy: memory.savePolicy
4252
+ };
4253
+ if (compaction !== void 0) {
4254
+ snapshot = { ...snapshot, compaction };
4255
+ }
4256
+ return Object.freeze(snapshot);
4257
+ }
4258
+ function cloneFrozenPlainData(value) {
4259
+ if (Array.isArray(value)) {
4260
+ return Object.freeze(value.map(cloneFrozenPlainData));
4261
+ }
4262
+ if (typeof value !== "object" || value === null) {
4263
+ return value;
4264
+ }
4265
+ const prototype = Object.getPrototypeOf(value);
4266
+ if (prototype !== Object.prototype && prototype !== null) {
4267
+ return value;
4268
+ }
4269
+ const clone = Object.fromEntries(
4270
+ Object.entries(value).map(([key, item]) => [key, cloneFrozenPlainData(item)])
4271
+ );
4272
+ return Object.freeze(clone);
4273
+ }
4274
+ function snapshotContextInput(input) {
4275
+ if (!isVectorContext(input)) {
4276
+ let document = {
4277
+ id: input.id,
4278
+ text: input.text
4279
+ };
4280
+ if (input.additionalProps !== void 0) {
4281
+ document = {
4282
+ ...document,
4283
+ additionalProps: cloneFrozenPlainData(input.additionalProps)
4284
+ };
4285
+ }
4286
+ return Object.freeze(document);
4287
+ }
4288
+ const format = input.format;
4289
+ let shared = {
4290
+ kind: "vector-context",
4291
+ store: input.store,
4292
+ topK: input.topK
4293
+ };
4294
+ if (input.minScore !== void 0) {
4295
+ shared = { ...shared, minScore: input.minScore };
4296
+ }
4297
+ if (input.filter !== void 0) {
4298
+ shared = { ...shared, filter: cloneFrozenPlainData(input.filter) };
4299
+ }
4300
+ if (input.retries !== void 0) {
4301
+ shared = { ...shared, retries: cloneFrozenPlainData(input.retries) };
4302
+ }
4303
+ if (format !== void 0) {
4304
+ shared = {
4305
+ ...shared,
4306
+ format: (result) => format.call(input, result)
4307
+ };
4308
+ }
4309
+ if (!("models" in input) || input.models === void 0) {
4310
+ return Object.freeze({ ...shared, store: input.store, model: input.model });
4311
+ }
4312
+ let context = {
4313
+ ...shared,
4314
+ store: input.store,
4315
+ models: input.models
4316
+ };
4317
+ if (input.fusion !== void 0) {
4318
+ context = { ...context, fusion: input.fusion };
4319
+ }
4320
+ return Object.freeze(context);
4321
+ }
4322
+ function snapshotGuardrailPolicy(policy) {
4323
+ return Object.freeze({
4324
+ ...policy,
4325
+ input: Object.freeze([...policy.input]),
4326
+ output: Object.freeze([...policy.output])
4327
+ });
4328
+ }
4329
+
4330
+ // src/agent/tool-catalog.ts
4331
+ function prepareAgentTools(options) {
4332
+ assertUniqueMcpServerNames(options.mcpServers ?? []);
4333
+ const mcpServers = Object.freeze((options.mcpServers ?? []).map(snapshotMcpServer));
4334
+ const configuredTools = [...options.tools ?? []];
4335
+ const staticTools = [...configuredTools, ...mcpServers.flatMap((server) => server.tools)];
4336
+ const toolIndexes = (options.toolIndexes ?? []).map(snapshotToolIndex);
4337
+ const providerTools = (options.providerTools ?? []).map(snapshotProviderTool);
4338
+ assertUniqueAgentToolNames({ staticTools, providerTools, toolIndexes });
4339
+ const toolsByName = new Map(staticTools.map((tool) => [tool.name, tool]));
4340
+ for (const index of toolIndexes) {
4341
+ for (const tool of index.tools) {
4342
+ toolsByName.set(tool.name, tool);
4343
+ }
4344
+ }
4345
+ const tools = Object.freeze([...toolsByName.values()]);
4346
+ const publicState = Object.freeze({
4347
+ configuredTools: Object.freeze(configuredTools),
4348
+ staticTools: Object.freeze(staticTools),
4349
+ providerTools: Object.freeze(providerTools),
4350
+ toolIndexes: Object.freeze(toolIndexes)
4351
+ });
4352
+ return { mcpServers, tools, publicState, toolsByName };
4353
+ }
4354
+ function assertUniqueAgentToolNames(options) {
4355
+ const owners = /* @__PURE__ */ new Map();
4356
+ for (const tool of options.staticTools) {
4357
+ registerToolOwner(owners, tool.name, isMcpTool(tool) ? "MCP tool" : "local or skill tool");
4358
+ }
4359
+ for (const tool of options.providerTools) {
4360
+ registerToolOwner(owners, tool.name, "provider tool");
4361
+ }
4362
+ for (const [indexPosition, index] of options.toolIndexes.entries()) {
4363
+ if (!isToolIndex(index)) {
4364
+ throw new TypeError("Invalid tool index: search, tools, and a numeric topK are required.");
4365
+ }
4366
+ assertPositiveSearchLimit(index.topK);
4367
+ assertFiniteMinScore(index.minScore);
4368
+ for (const tool of index.tools) {
4369
+ if (isMcpTool(tool)) {
4370
+ throw new TypeError(
4371
+ `MCP tool "${tool.name}" must be registered through Agent.mcpServers, not a tool index.`
4372
+ );
4373
+ }
4374
+ registerToolOwner(owners, tool.name, `tool index ${indexPosition + 1}`);
4375
+ }
4376
+ }
4377
+ }
4378
+ function registerToolOwner(owners, name, owner) {
4379
+ const existing = owners.get(name);
4380
+ if (existing !== void 0) {
4381
+ throw new TypeError(
4382
+ `Tool name collision for "${name}" between ${existing} and ${owner}. Tool names must be unique across every Agent tool source.`
4383
+ );
4384
+ }
4385
+ owners.set(name, owner);
4386
+ }
4387
+ function snapshotProviderTool(tool) {
4388
+ let snapshot = {
4389
+ ...tool
4390
+ };
4391
+ if (tool.configuration !== void 0) {
4392
+ snapshot = { ...snapshot, configuration: cloneFrozenPlainData(tool.configuration) };
4393
+ }
4394
+ return Object.freeze(snapshot);
4395
+ }
4396
+ function snapshotMcpServer(server) {
4397
+ if (server.name.trim() === "") {
4398
+ throw new TypeError("MCP server name must not be empty.");
4399
+ }
4400
+ for (const tool of server.tools) {
4401
+ if (!isMcpTool(tool)) {
4402
+ throw new TypeError(`MCP server "${server.name}" contains an invalid MCP tool.`);
4403
+ }
4404
+ if (tool.mcp.serverName !== server.name) {
4405
+ throw new TypeError(
4406
+ `MCP tool "${tool.name}" belongs to server "${tool.mcp.serverName}", not "${server.name}".`
4407
+ );
4408
+ }
4409
+ }
4410
+ const tools = server.tools.map(snapshotMcpTool);
4411
+ let snapshot = {
4412
+ name: server.name,
4413
+ tools: Object.freeze(tools)
4414
+ };
4415
+ if (server.serverInfo !== void 0) {
4416
+ snapshot = { ...snapshot, serverInfo: cloneFrozenPlainData(server.serverInfo) };
4417
+ }
4418
+ if (server.capabilities !== void 0) {
4419
+ snapshot = { ...snapshot, capabilities: cloneFrozenPlainData(server.capabilities) };
4420
+ }
4421
+ if (server.instructions !== void 0) {
4422
+ snapshot = { ...snapshot, instructions: server.instructions };
4423
+ }
4424
+ return Object.freeze(snapshot);
4425
+ }
4426
+ function snapshotMcpTool(tool) {
4427
+ if (Object.isFrozen(tool) && Object.isFrozen(tool.mcp)) {
4428
+ return tool;
4429
+ }
4430
+ const parseInput = tool.parseInput;
4431
+ let snapshot = {
4432
+ name: tool.name,
4433
+ mcp: Object.freeze({ ...tool.mcp }),
4434
+ definition: (prompt) => tool.definition(prompt),
4435
+ call: (args, context) => tool.call(args, context)
4436
+ };
4437
+ if (tool.requiresApproval !== void 0) {
4438
+ snapshot = { ...snapshot, requiresApproval: tool.requiresApproval };
4439
+ }
4440
+ if (parseInput !== void 0) {
4441
+ snapshot = {
4442
+ ...snapshot,
4443
+ parseInput: (args) => parseInput.call(tool, args)
4444
+ };
4445
+ }
4446
+ return Object.freeze(snapshot);
4447
+ }
4448
+ function assertUniqueMcpServerNames(servers) {
4449
+ const names = /* @__PURE__ */ new Set();
4450
+ for (const server of servers) {
4451
+ if (names.has(server.name)) {
4452
+ throw new TypeError(`Duplicate MCP server name "${server.name}".`);
4453
+ }
4454
+ names.add(server.name);
4455
+ }
4456
+ }
4457
+ function snapshotToolIndex(index) {
4458
+ const inspect = index.inspect;
4459
+ let snapshot = {
4460
+ kind: "tool-index",
4461
+ tools: Object.freeze([...index.tools]),
4462
+ topK: index.topK,
4463
+ search: (options) => index.search(options)
4464
+ };
4465
+ if (index.minScore !== void 0) {
4466
+ snapshot = { ...snapshot, minScore: index.minScore };
4467
+ }
4468
+ if (index.filter !== void 0) {
4469
+ snapshot = { ...snapshot, filter: cloneFrozenPlainData(index.filter) };
4470
+ }
4471
+ if (inspect !== void 0) {
4472
+ snapshot = {
4473
+ ...snapshot,
4474
+ inspect: (request) => inspect.call(index, request)
4475
+ };
4476
+ }
4477
+ return Object.freeze(snapshot);
4478
+ }
4479
+
4480
+ // src/agent/agent.ts
4481
+ var DEFAULT_MAX_TURNS = 20;
4482
+ var Agent = class {
4483
+ id;
4484
+ name;
4485
+ description;
4486
+ model;
4487
+ instructions;
4488
+ context;
4489
+ temperature;
4490
+ maxTokens;
4491
+ providerOptions;
4492
+ retries;
4493
+ mcpServers;
4494
+ tools;
4495
+ toolChoice;
4496
+ defaultMaxTurns;
4497
+ lifecycle;
4498
+ outputSchema;
4499
+ observability;
4500
+ guardrails;
4501
+ middlewares;
4502
+ memory;
4503
+ constructor(options) {
4504
+ const resolved = resolveAgentOptions(options);
4505
+ this.id = normalizeAgentId(resolved.id);
4506
+ this.name = resolved.name;
4507
+ this.description = resolved.description;
4508
+ this.model = resolved.model;
4509
+ this.instructions = resolved.instructions;
4510
+ this.context = snapshotAgentContext(resolved.context);
4511
+ this.temperature = resolved.temperature;
4512
+ this.maxTokens = resolved.maxTokens;
4513
+ if (resolved.providerOptions !== void 0) {
4514
+ assertJsonObject(resolved.providerOptions, "Agent providerOptions");
4515
+ }
4516
+ this.providerOptions = cloneFrozenPlainData(resolved.providerOptions);
4517
+ this.retries = cloneFrozenPlainData(resolved.retries);
4518
+ const preparedTools = prepareAgentTools(resolved);
4519
+ this.mcpServers = preparedTools.mcpServers;
4520
+ this.tools = preparedTools.tools;
4521
+ registerAgentToolState(this, preparedTools.publicState, preparedTools.toolsByName);
4522
+ this.toolChoice = cloneFrozenPlainData(resolved.toolChoice);
4523
+ this.defaultMaxTurns = assertNonnegativeSafeInteger(
4524
+ resolved.defaultMaxTurns ?? DEFAULT_MAX_TURNS,
4525
+ "maxTurns"
4526
+ );
4527
+ this.lifecycle = resolved.lifecycle;
4528
+ this.outputSchema = resolved.outputSchema;
4529
+ registerAgentProviderOutputSchema(this, resolved.outputSchema);
4530
+ this.observability = snapshotAgentObservability(resolved.observability);
4531
+ this.guardrails = snapshotGuardrailPolicies(resolved.guardrails);
4532
+ this.middlewares = Object.freeze([...resolved.middlewares ?? []]);
4533
+ this.memory = snapshotAgentMemory(resolved.memory);
4534
+ }
4535
+ generate(options) {
4536
+ return AgentRun.fromAgent(this, options).generate();
4537
+ }
4538
+ stream(options) {
4539
+ const run = AgentRun.fromAgent(this, options);
4540
+ if (!this.model.capabilities.streaming || !isStreamingCompletionModel(this.model)) {
4541
+ throw new Error("This completion model does not support streaming");
4542
+ }
4543
+ return createAgentStream(run);
4544
+ }
4545
+ asTool(options) {
4546
+ return createAgentTool(this, options);
4547
+ }
4548
+ getTool(toolName) {
4549
+ return getRegisteredAgentTool(this, toolName);
4550
+ }
4551
+ async callTool(toolName, args, context) {
4552
+ const tool = this.getTool(toolName);
4553
+ if (tool === void 0) {
4554
+ throw new ToolNotFoundError(toolName);
4555
+ }
4556
+ return prepareToolCall(tool, args).call(context ?? {});
4557
+ }
4558
+ };
4559
+
4560
+ export {
4561
+ getAgentToolState,
4562
+ createHook,
4563
+ createVectorContext,
4564
+ isVectorContext,
4565
+ withInternalAgentRunOptions,
4566
+ markResolvedAgentOptions,
4567
+ Agent
4568
+ };
4569
+ //# sourceMappingURL=chunk-VX3HS6PE.js.map