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

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