@anvia/core 0.26.0 → 1.0.0-rc.2

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