@anvia/core 1.0.0-rc.1 → 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 (136) hide show
  1. package/README.md +283 -84
  2. package/dist/agent/index.d.ts +26 -18
  3. package/dist/agent/index.js +19 -15
  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-R2LJSQUW.js → chunk-77AIYARB.js} +251 -104
  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-6WGGTJE6.js → chunk-D37WMSP6.js} +52 -60
  16. package/dist/chunk-D37WMSP6.js.map +1 -0
  17. package/dist/{chunk-IL3ZSNJI.js → chunk-DBSCKTUL.js} +845 -800
  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-A3UBYTJT.js → chunk-FN7HLLAZ.js} +60 -6
  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-FNQB2JEH.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-I6G7BC42.js → chunk-MGNTXGTX.js} +2 -6
  32. package/dist/chunk-MGNTXGTX.js.map +1 -0
  33. package/dist/{chunk-5XKDW36Z.js → chunk-OJH6HWHX.js} +64 -75
  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-DMPUP4R3.js → chunk-XKYYBABH.js} +5 -5
  40. package/dist/client-B8DT1vUG.d.ts +83 -0
  41. package/dist/completion/index.d.ts +5 -4
  42. package/dist/completion/index.js +25 -28
  43. package/dist/{dynamic-tools-i9woysFa.d.ts → dynamic-tools-KwEGRbHp.d.ts} +21 -9
  44. package/dist/embeddings/index.d.ts +11 -9
  45. package/dist/embeddings/index.js +2 -3
  46. package/dist/evals/index.d.ts +44 -24
  47. package/dist/evals/index.js +86 -69
  48. package/dist/evals/index.js.map +1 -1
  49. package/dist/extractor/index.d.ts +23 -26
  50. package/dist/extractor/index.js +7 -8
  51. package/dist/guardrails/index.d.ts +2 -1
  52. package/dist/guardrails/index.js +1 -1
  53. package/dist/image-generation/index.d.ts +18 -16
  54. package/dist/image-generation/index.js +2 -2
  55. package/dist/index.d.ts +24 -22
  56. package/dist/index.js +50 -48
  57. package/dist/internal/agent.d.ts +30 -19
  58. package/dist/internal/agent.js +13 -11
  59. package/dist/loaders/index.d.ts +2 -1
  60. package/dist/mcp/index.d.ts +19 -13
  61. package/dist/mcp/index.js +13 -348
  62. package/dist/mcp/index.js.map +1 -1
  63. package/dist/memory/index.d.ts +20 -6
  64. package/dist/memory/index.js +10 -10
  65. package/dist/message-schema-Cn7ezRfJ.d.ts +52 -0
  66. package/dist/{middleware-KynLg_RW.d.ts → middleware-C7PdmKF7.d.ts} +4 -4
  67. package/dist/model-call-options-CZkSw_xN.d.ts +6 -0
  68. package/dist/model-listing/index.d.ts +3 -1
  69. package/dist/observability/index.d.ts +19 -5
  70. package/dist/observability/index.js +8 -5
  71. package/dist/observability/index.js.map +1 -1
  72. package/dist/pipeline/index.d.ts +105 -56
  73. package/dist/pipeline/index.js +422 -230
  74. package/dist/pipeline/index.js.map +1 -1
  75. package/dist/{retry-D3Ruy-ba.d.ts → retry-CjvSlKGW.d.ts} +2 -1
  76. package/dist/skills/index.d.ts +5 -4
  77. package/dist/skills/index.js +7 -7
  78. package/dist/speech-generation/index.d.ts +37 -0
  79. package/dist/speech-generation/index.js +8 -0
  80. package/dist/{think-tool-DZqZj2LV.d.ts → think-tool-6H2QNQzQ.d.ts} +1 -1
  81. package/dist/tool/index.d.ts +9 -7
  82. package/dist/tool/index.js +7 -10
  83. package/dist/{tool-C_8GudXn.d.ts → tool--Mz4v1eL.d.ts} +15 -7
  84. package/dist/transcription/index.d.ts +23 -14
  85. package/dist/transcription/index.js +2 -2
  86. package/dist/{index-DxB74ybJ.d.ts → types-3x3mOLHU.d.ts} +94 -64
  87. package/dist/types-BVzM4RsC.d.ts +155 -0
  88. package/dist/types-CQ_ioXWK.d.ts +319 -0
  89. package/dist/types-Cr4uiYo5.d.ts +99 -0
  90. package/dist/{types-DhQfwiZn.d.ts → types-DiJqJejp.d.ts} +1 -1
  91. package/dist/types-Dld1TpWj.d.ts +130 -0
  92. package/dist/vector-store/index.d.ts +33 -34
  93. package/dist/vector-store/index.js +6 -6
  94. package/package.json +6 -10
  95. package/dist/agent-DGYY_onS.d.ts +0 -145
  96. package/dist/audio-generation/index.d.ts +0 -31
  97. package/dist/audio-generation/index.js +0 -8
  98. package/dist/chunk-5XKDW36Z.js.map +0 -1
  99. package/dist/chunk-6WGGTJE6.js.map +0 -1
  100. package/dist/chunk-A3UBYTJT.js.map +0 -1
  101. package/dist/chunk-ADH7NNCS.js +0 -512
  102. package/dist/chunk-ADH7NNCS.js.map +0 -1
  103. package/dist/chunk-DZ3CKYTH.js +0 -267
  104. package/dist/chunk-DZ3CKYTH.js.map +0 -1
  105. package/dist/chunk-FNQB2JEH.js.map +0 -1
  106. package/dist/chunk-I6G7BC42.js.map +0 -1
  107. package/dist/chunk-IL3ZSNJI.js.map +0 -1
  108. package/dist/chunk-J6GNQART.js +0 -122
  109. package/dist/chunk-J6GNQART.js.map +0 -1
  110. package/dist/chunk-M3IOWB4Y.js +0 -280
  111. package/dist/chunk-M3IOWB4Y.js.map +0 -1
  112. package/dist/chunk-QY5GZ7HR.js +0 -39
  113. package/dist/chunk-QY5GZ7HR.js.map +0 -1
  114. package/dist/chunk-R2LJSQUW.js.map +0 -1
  115. package/dist/chunk-RFDVKCIE.js +0 -12
  116. package/dist/chunk-RFDVKCIE.js.map +0 -1
  117. package/dist/chunk-RMUBRRSK.js +0 -34
  118. package/dist/chunk-RMUBRRSK.js.map +0 -1
  119. package/dist/chunk-RXKHOYEH.js +0 -466
  120. package/dist/chunk-RXKHOYEH.js.map +0 -1
  121. package/dist/chunk-XDRSPSR7.js +0 -38
  122. package/dist/chunk-XDRSPSR7.js.map +0 -1
  123. package/dist/chunk-XWUC7CIT.js +0 -1
  124. package/dist/chunk-XWUC7CIT.js.map +0 -1
  125. package/dist/errors-CYKUcU89.d.ts +0 -17
  126. package/dist/json-Zo7K3xmt.d.ts +0 -40
  127. package/dist/types-B3A4YxaA.d.ts +0 -354
  128. package/dist/types-BBEGKB9m.d.ts +0 -119
  129. package/dist/types-DT3nEemY.d.ts +0 -79
  130. package/dist/types-DulRCYdB.d.ts +0 -70
  131. package/dist/types-p55Jc-sr.d.ts +0 -47
  132. package/dist/ui/index.d.ts +0 -107
  133. package/dist/ui/index.js +0 -10
  134. package/dist/ui/index.js.map +0 -1
  135. /package/dist/{chunk-DMPUP4R3.js.map → chunk-XKYYBABH.js.map} +0 -0
  136. /package/dist/{audio-generation → speech-generation}/index.js.map +0 -0
@@ -2,58 +2,65 @@ import {
2
2
  isSkillTool
3
3
  } from "./chunk-YK4WAAS4.js";
4
4
  import {
5
- assertFiniteSearchThreshold,
6
- assertPositiveSearchLimit,
5
+ isMcpTool
6
+ } from "./chunk-EINTGEGY.js";
7
+ import {
7
8
  isToolIndex
8
- } from "./chunk-6WGGTJE6.js";
9
+ } from "./chunk-D37WMSP6.js";
9
10
  import {
10
11
  ToolNotFoundError,
12
+ assertFiniteMinScore,
13
+ assertPositiveSearchLimit,
11
14
  assertToolApprovalRequirement,
12
15
  createTool,
13
16
  parseToolArgs,
14
17
  prepareToolCall,
18
+ retrieveDocuments,
15
19
  toolMayRequireApproval,
16
20
  toolResultContentToText
17
- } from "./chunk-R2LJSQUW.js";
21
+ } from "./chunk-77AIYARB.js";
18
22
  import {
19
23
  MemoryCompactionConflictError,
20
24
  MemoryCompactionError,
25
+ assertPositiveInteger,
21
26
  createMemoryCompactionSummary,
22
- cumulativeCompactedMessageCount,
23
- resolveMemoryOptions
24
- } from "./chunk-5XKDW36Z.js";
27
+ cumulativeCompactedMessageCount
28
+ } from "./chunk-OJH6HWHX.js";
25
29
  import {
26
- mapWithConcurrency
27
- } from "./chunk-DZ3CKYTH.js";
30
+ startAgentRunObservers
31
+ } from "./chunk-CWM7B2OO.js";
28
32
  import {
29
- createCompletionRequest,
30
- isStreamingCompletionModel
31
- } from "./chunk-M3IOWB4Y.js";
32
- import {
33
- toProviderJsonSchema
34
- } from "./chunk-RFDVKCIE.js";
33
+ mapWithConcurrency
34
+ } from "./chunk-FMHLROPQ.js";
35
35
  import {
36
- AssistantContent,
37
- Message,
38
- ToolContent,
39
36
  Usage,
40
37
  assertCompletionRequestSupported,
38
+ createCompletionRequest,
41
39
  getAssistantGenerationMetadata,
42
40
  isProviderTool,
41
+ isStreamingCompletionModel,
43
42
  textFromAssistantContent
44
- } from "./chunk-ADH7NNCS.js";
43
+ } from "./chunk-KR3RCCHJ.js";
45
44
  import {
46
- resolveRetryOptions,
47
- retryDelayMs,
48
- retryErrorAttributes,
49
- waitForRetry
50
- } from "./chunk-A3UBYTJT.js";
45
+ parseMessage,
46
+ parseMessages,
47
+ toProviderJsonSchema
48
+ } from "./chunk-TIZYTPJO.js";
51
49
  import {
52
50
  appendGuardrailPolicies,
53
51
  hasEnforcedOutputGuardrails,
54
52
  runInputGuardrails,
55
53
  runOutputGuardrails
56
- } from "./chunk-FNQB2JEH.js";
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";
57
64
 
58
65
  // src/agent/errors.ts
59
66
  var MaxTurnsError = class extends Error {
@@ -69,8 +76,8 @@ var MaxTurnsError = class extends Error {
69
76
  prompt;
70
77
  };
71
78
  var AgentRunCancelledError = class extends Error {
72
- constructor(chatHistory, reason) {
73
- super(`Agent run cancelled: ${reason}`);
79
+ constructor(chatHistory, reason, options) {
80
+ super(`Agent run cancelled: ${reason}`, options);
74
81
  this.chatHistory = chatHistory;
75
82
  this.reason = reason;
76
83
  this.name = "AgentRunCancelledError";
@@ -78,6 +85,14 @@ var AgentRunCancelledError = class extends Error {
78
85
  chatHistory;
79
86
  reason;
80
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
+ };
81
96
 
82
97
  // src/agent/tool-state.ts
83
98
  var agentToolStates = /* @__PURE__ */ new WeakMap();
@@ -152,27 +167,24 @@ function getAgentApprovalRequestDetails(approval) {
152
167
  return approvalDetails.get(approval);
153
168
  }
154
169
 
155
- // src/agent/context-index.ts
156
- function createContextIndex(index, options) {
170
+ // src/agent/vector-context.ts
171
+ function createVectorContext(options) {
157
172
  const topK = assertPositiveSearchLimit(options.topK);
158
- const threshold = assertFiniteSearchThreshold(options.threshold);
173
+ const minScore = assertFiniteMinScore(options.minScore);
159
174
  return Object.freeze({
160
175
  ...options,
161
176
  topK,
162
- ...threshold === void 0 ? {} : { threshold },
163
- kind: "context-index",
164
- index
177
+ ...minScore === void 0 ? {} : { minScore },
178
+ kind: "vector-context"
165
179
  });
166
180
  }
167
- function isContextIndex(value) {
168
- if (typeof value !== "object" || value === null) {
169
- return false;
170
- }
181
+ function isVectorContext(value) {
182
+ if (typeof value !== "object" || value === null) return false;
171
183
  const candidate = value;
172
- if (candidate.kind !== "context-index" || typeof candidate.index !== "object") {
184
+ if (candidate.kind !== "vector-context" || typeof candidate.store?.search !== "function") {
173
185
  return false;
174
186
  }
175
- return candidate.index !== null && typeof candidate.index.search === "function";
187
+ return candidate.model !== void 0 || candidate.models?.dense !== void 0 && candidate.models.sparse !== void 0;
176
188
  }
177
189
 
178
190
  // src/internal/agent-runtime/run-options.ts
@@ -253,280 +265,6 @@ function cloneLifecycleFallback(value, seen) {
253
265
  return clone;
254
266
  }
255
267
 
256
- // src/observability/snapshot.ts
257
- function observerSnapshot(value) {
258
- if (containsError(value, /* @__PURE__ */ new WeakSet())) {
259
- return cloneObserverFallback(value, /* @__PURE__ */ new WeakMap());
260
- }
261
- try {
262
- return globalThis.structuredClone(value);
263
- } catch {
264
- return cloneObserverFallback(value, /* @__PURE__ */ new WeakMap());
265
- }
266
- }
267
- function cloneObserverFallback(value, seen) {
268
- if (typeof value !== "object" || value === null) {
269
- return value;
270
- }
271
- const existing = seen.get(value);
272
- if (existing !== void 0) {
273
- return existing;
274
- }
275
- if (Array.isArray(value)) {
276
- const clone2 = [];
277
- seen.set(value, clone2);
278
- clone2.push(...value.map((item) => cloneObserverFallback(item, seen)));
279
- return clone2;
280
- }
281
- if (value instanceof Date) {
282
- return new Date(value.getTime());
283
- }
284
- if (value instanceof Error) {
285
- const clone2 = Object.create(Object.getPrototypeOf(value));
286
- seen.set(value, clone2);
287
- Object.defineProperties(clone2, {
288
- name: { configurable: true, writable: true, value: value.name },
289
- message: { configurable: true, writable: true, value: value.message }
290
- });
291
- if (value.stack !== void 0) {
292
- Object.defineProperty(clone2, "stack", {
293
- configurable: true,
294
- writable: true,
295
- value: value.stack
296
- });
297
- }
298
- if (value.cause !== void 0) {
299
- Object.defineProperty(clone2, "cause", {
300
- configurable: true,
301
- writable: true,
302
- value: cloneObserverFallback(value.cause, seen)
303
- });
304
- }
305
- for (const key of Object.getOwnPropertyNames(value)) {
306
- if (key === "name" || key === "message" || key === "stack" || key === "cause") continue;
307
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
308
- if (descriptor === void 0) continue;
309
- if ("value" in descriptor) {
310
- descriptor.value = cloneObserverFallback(descriptor.value, seen);
311
- }
312
- Object.defineProperty(clone2, key, descriptor);
313
- }
314
- return clone2;
315
- }
316
- if (Object.getPrototypeOf(value) !== Object.prototype) {
317
- return value;
318
- }
319
- const clone = {};
320
- seen.set(value, clone);
321
- for (const [key, item] of Object.entries(value)) {
322
- clone[key] = cloneObserverFallback(item, seen);
323
- }
324
- return clone;
325
- }
326
- function containsError(value, seen) {
327
- if (typeof value !== "object" || value === null) return false;
328
- if (value instanceof Error) return true;
329
- if (seen.has(value)) return false;
330
- seen.add(value);
331
- if (Array.isArray(value)) {
332
- return value.some((item) => containsError(item, seen));
333
- }
334
- if (Object.getPrototypeOf(value) !== Object.prototype) return false;
335
- return Object.values(value).some((item) => containsError(item, seen));
336
- }
337
-
338
- // src/observability/group.ts
339
- async function startAgentRunObservers(registrations, args, failOnObserverError) {
340
- const runObservers = [];
341
- for (const registration of registrations) {
342
- try {
343
- const runObserver = await registration.observer.startRun(observerSnapshot(args));
344
- if (runObserver !== void 0) {
345
- runObservers.push(runObserver);
346
- }
347
- } catch (error) {
348
- if (failOnObserverError || registration.failOnObserverError === true) {
349
- throw error;
350
- }
351
- }
352
- }
353
- return new ActiveAgentRunObservers(runObservers, failOnObserverError);
354
- }
355
- var ActiveAgentRunObservers = class {
356
- constructor(runObservers, failOnObserverError) {
357
- this.runObservers = runObservers;
358
- this.failOnObserverError = failOnObserverError;
359
- this.trace = runObservers.find((observer) => observer.trace !== void 0)?.trace;
360
- }
361
- runObservers;
362
- failOnObserverError;
363
- trace;
364
- async startGeneration(args) {
365
- const generationObservers = [];
366
- for (const runObserver of this.runObservers) {
367
- if (runObserver.startGeneration === void 0) {
368
- continue;
369
- }
370
- try {
371
- const generationObserver = await runObserver.startGeneration(observerSnapshot(args));
372
- if (generationObserver !== void 0) {
373
- generationObservers.push(generationObserver);
374
- }
375
- } catch (error) {
376
- this.handleError(error);
377
- }
378
- }
379
- return new ActiveGenerationObservers(generationObservers, this.failOnObserverError);
380
- }
381
- async startTool(args) {
382
- const toolObservers = [];
383
- for (const runObserver of this.runObservers) {
384
- if (runObserver.startTool === void 0) {
385
- continue;
386
- }
387
- try {
388
- const toolObserver = await runObserver.startTool(observerSnapshot(args));
389
- if (toolObserver !== void 0) {
390
- toolObservers.push(toolObserver);
391
- }
392
- } catch (error) {
393
- this.handleError(error);
394
- }
395
- }
396
- return new ActiveToolObservers(toolObservers, this.failOnObserverError);
397
- }
398
- async end(args) {
399
- for (const runObserver of this.runObservers) {
400
- try {
401
- await runObserver.end(observerSnapshot(args));
402
- } catch (error) {
403
- this.handleError(error);
404
- }
405
- }
406
- }
407
- async error(args) {
408
- for (const runObserver of this.runObservers) {
409
- if (runObserver.error === void 0) {
410
- continue;
411
- }
412
- try {
413
- await runObserver.error(observerSnapshot(args));
414
- } catch (error) {
415
- this.handleError(error);
416
- }
417
- }
418
- }
419
- async event(args) {
420
- for (const runObserver of this.runObservers) {
421
- if (runObserver.event === void 0) {
422
- continue;
423
- }
424
- try {
425
- await runObserver.event(observerSnapshot(args));
426
- } catch (error) {
427
- this.handleError(error);
428
- }
429
- }
430
- }
431
- handleError(error) {
432
- if (this.failOnObserverError) {
433
- throw error;
434
- }
435
- }
436
- };
437
- var ActiveGenerationObservers = class {
438
- constructor(generationObservers, failOnObserverError) {
439
- this.generationObservers = generationObservers;
440
- this.failOnObserverError = failOnObserverError;
441
- }
442
- generationObservers;
443
- failOnObserverError;
444
- async end(args) {
445
- for (const observer of this.generationObservers) {
446
- try {
447
- await observer.end(observerSnapshot(args));
448
- } catch (error) {
449
- this.handleError(error);
450
- }
451
- }
452
- }
453
- async error(args) {
454
- for (const observer of this.generationObservers) {
455
- if (observer.error === void 0) {
456
- continue;
457
- }
458
- try {
459
- await observer.error(observerSnapshot(args));
460
- } catch (error) {
461
- this.handleError(error);
462
- }
463
- }
464
- }
465
- async update(args) {
466
- for (const observer of this.generationObservers) {
467
- if (observer.update === void 0) {
468
- continue;
469
- }
470
- try {
471
- await observer.update(observerSnapshot(args));
472
- } catch (error) {
473
- this.handleError(error);
474
- }
475
- }
476
- }
477
- handleError(error) {
478
- if (this.failOnObserverError) {
479
- throw error;
480
- }
481
- }
482
- };
483
- var ActiveToolObservers = class {
484
- constructor(toolObservers, failOnObserverError) {
485
- this.toolObservers = toolObservers;
486
- this.failOnObserverError = failOnObserverError;
487
- }
488
- toolObservers;
489
- failOnObserverError;
490
- async streamEvent(args) {
491
- for (const observer of this.toolObservers) {
492
- if (observer.streamEvent === void 0) {
493
- continue;
494
- }
495
- try {
496
- await observer.streamEvent(observerSnapshot(args));
497
- } catch (error) {
498
- this.handleError(error);
499
- }
500
- }
501
- }
502
- async end(args) {
503
- for (const observer of this.toolObservers) {
504
- try {
505
- await observer.end(observerSnapshot(args));
506
- } catch (error) {
507
- this.handleError(error);
508
- }
509
- }
510
- }
511
- async error(args) {
512
- for (const observer of this.toolObservers) {
513
- if (observer.error === void 0) {
514
- continue;
515
- }
516
- try {
517
- await observer.error(observerSnapshot(args));
518
- } catch (error) {
519
- this.handleError(error);
520
- }
521
- }
522
- }
523
- handleError(error) {
524
- if (this.failOnObserverError) {
525
- throw error;
526
- }
527
- }
528
- };
529
-
530
268
  // src/internal/async-queue.ts
531
269
  function createAsyncQueue() {
532
270
  const values = [];
@@ -598,39 +336,56 @@ function createAsyncQueue() {
598
336
  // src/internal/rag-text.ts
599
337
  function extractRagText(message) {
600
338
  if (message.role === "user") {
339
+ if (typeof message.content === "string") {
340
+ return message.content;
341
+ }
601
342
  return message.content.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n");
602
343
  }
603
344
  if (message.role === "tool") {
604
- return message.content.flatMap((item) => item.content.flatMap((part) => part.type === "text" ? [part.text] : [])).join("\n");
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");
605
355
  }
606
356
  return void 0;
607
357
  }
608
358
 
609
359
  // src/internal/agent-runtime/memory.ts
610
360
  var AgentRunMemory = class {
611
- constructor(agent, memoryContext, initialHistory) {
361
+ constructor(agent, memoryScope, initialHistory) {
612
362
  this.agent = agent;
613
- this.memoryContext = memoryContext;
363
+ this.memoryScope = memoryScope;
614
364
  this.initialHistory = initialHistory;
615
365
  }
616
366
  agent;
617
- memoryContext;
367
+ memoryScope;
618
368
  initialHistory;
619
369
  memoryPolicy() {
620
- return this.memory()?.options.savePolicy;
370
+ return this.memory()?.savePolicy;
621
371
  }
622
372
  pendingTurnMessages(newMessages) {
623
373
  return this.memoryPolicy() === "turn" ? [...newMessages] : [];
624
374
  }
625
- async prepareHistory(runId, incomingMessageCount) {
375
+ async prepareHistory(runId, incomingMessageCount, abortSignal) {
626
376
  const memory = this.memory();
627
- if (memory === void 0 || this.memoryContext === void 0) {
377
+ if (memory === void 0 || this.memoryScope === void 0) {
628
378
  return {
629
379
  history: this.initialHistory,
630
380
  usage: Usage.empty()
631
381
  };
632
382
  }
633
- const preparation = await this.prepareStoredHistory(memory, runId, incomingMessageCount);
383
+ const preparation = await this.prepareStoredHistory(
384
+ memory,
385
+ runId,
386
+ incomingMessageCount,
387
+ abortSignal
388
+ );
634
389
  const memoryHistory = preparation.history;
635
390
  const chatHistory = [...memoryHistory, ...this.initialHistory];
636
391
  return {
@@ -640,11 +395,11 @@ var AgentRunMemory = class {
640
395
  }
641
396
  async commitAcceptedInput(runId, messages) {
642
397
  const memory = this.memory();
643
- if (memory === void 0 || this.memoryContext === void 0 || memory.options.savePolicy !== "message" || messages.length === 0) {
398
+ if (memory === void 0 || this.memoryScope === void 0 || memory.savePolicy !== "message" || messages.length === 0) {
644
399
  return;
645
400
  }
646
401
  await memory.store.append({
647
- context: this.memoryContext,
402
+ scope: this.memoryScope,
648
403
  runId,
649
404
  turn: 1,
650
405
  messages
@@ -652,27 +407,27 @@ var AgentRunMemory = class {
652
407
  }
653
408
  async commitMessages(runId, turn, messages, pendingTurnMessages) {
654
409
  const memory = this.memory();
655
- if (memory === void 0 || this.memoryContext === void 0 || messages.length === 0) {
410
+ if (memory === void 0 || this.memoryScope === void 0 || messages.length === 0) {
656
411
  return;
657
412
  }
658
- if (memory.options.savePolicy === "message") {
413
+ if (memory.savePolicy === "message") {
659
414
  await memory.store.append({
660
- context: this.memoryContext,
415
+ scope: this.memoryScope,
661
416
  runId,
662
417
  turn,
663
418
  messages
664
419
  });
665
- } else if (memory.options.savePolicy === "turn") {
420
+ } else if (memory.savePolicy === "turn") {
666
421
  pendingTurnMessages.push(...messages);
667
422
  }
668
423
  }
669
424
  async commitCompletedTurn(runId, turn, pendingTurnMessages) {
670
425
  const memory = this.memory();
671
- if (memory === void 0 || this.memoryContext === void 0 || memory.options.savePolicy !== "turn" || pendingTurnMessages.length === 0) {
426
+ if (memory === void 0 || this.memoryScope === void 0 || memory.savePolicy !== "turn" || pendingTurnMessages.length === 0) {
672
427
  return;
673
428
  }
674
429
  await memory.store.append({
675
- context: this.memoryContext,
430
+ scope: this.memoryScope,
676
431
  runId,
677
432
  turn,
678
433
  messages: [...pendingTurnMessages]
@@ -682,11 +437,11 @@ var AgentRunMemory = class {
682
437
  async commitCompletedRun(runId, turn, newMessages, pendingTurnMessages) {
683
438
  await this.commitCompletedTurn(runId, turn, pendingTurnMessages);
684
439
  const memory = this.memory();
685
- if (memory === void 0 || this.memoryContext === void 0 || memory.options.savePolicy !== "run") {
440
+ if (memory === void 0 || this.memoryScope === void 0 || memory.savePolicy !== "run") {
686
441
  return;
687
442
  }
688
443
  await memory.store.append({
689
- context: this.memoryContext,
444
+ scope: this.memoryScope,
690
445
  runId,
691
446
  turn,
692
447
  messages: [...newMessages]
@@ -694,41 +449,43 @@ var AgentRunMemory = class {
694
449
  }
695
450
  async recordError(runId, error, newMessages) {
696
451
  const memory = this.memory();
697
- if (memory === void 0 || this.memoryContext === void 0) {
452
+ if (memory === void 0 || this.memoryScope === void 0) {
698
453
  return;
699
454
  }
700
455
  await memory.store.recordError?.({
701
- context: this.memoryContext,
456
+ scope: this.memoryScope,
702
457
  runId,
703
458
  error,
704
459
  messages: [...newMessages]
705
460
  });
706
461
  }
707
462
  memory() {
708
- return this.memoryContext === void 0 ? void 0 : this.agent.memory;
463
+ return this.memoryScope === void 0 ? void 0 : this.agent.memory;
709
464
  }
710
- async prepareStoredHistory(memory, runId, incomingMessageCount) {
711
- const context = this.memoryContext;
712
- if (context === void 0) {
465
+ async prepareStoredHistory(memory, runId, incomingMessageCount, abortSignal) {
466
+ const scope = this.memoryScope;
467
+ if (scope === void 0) {
713
468
  return { history: [], usage: Usage.empty() };
714
469
  }
715
- const options = memory.options.compaction;
470
+ const options = memory.compaction;
716
471
  const capability = memory.store.compaction;
717
472
  if (options === void 0 || capability === void 0) {
718
473
  return {
719
- history: await memory.store.load(context),
474
+ history: await memory.store.load({ scope }),
720
475
  usage: Usage.empty()
721
476
  };
722
477
  }
723
478
  let usage = Usage.empty();
724
- let conflictRetries = 0;
725
- for (let attempt = 0; attempt <= options.conflictRetries; attempt += 1) {
726
- const snapshot = await capability.load(context);
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);
727
484
  const compactedMessageCount = compactedPrefixLength(
728
485
  snapshot.messages,
729
486
  incomingMessageCount,
730
- options.maxMessages,
731
- options.keepRecentUserTurns
487
+ options.trigger.afterMessages,
488
+ options.retention.recentUserTurns
732
489
  );
733
490
  if (compactedMessageCount === 0) {
734
491
  return { history: snapshot.messages, usage };
@@ -737,8 +494,9 @@ var AgentRunMemory = class {
737
494
  let result;
738
495
  try {
739
496
  result = await options.compactor({
740
- context,
741
- messages: prefix
497
+ scope,
498
+ messages: prefix,
499
+ abortSignal
742
500
  });
743
501
  } catch (error) {
744
502
  throw remappedCompactorError(error, usage);
@@ -756,22 +514,23 @@ var AgentRunMemory = class {
756
514
  summaryText,
757
515
  cumulativeCompactedMessageCount(prefix)
758
516
  );
759
- let commit;
517
+ throwIfAborted(abortSignal);
518
+ let replacement;
760
519
  try {
761
- commit = await capability.commit({
762
- context,
520
+ replacement = await capability.replacePrefix({
521
+ scope,
763
522
  revision: snapshot.revision,
764
- compactedMessageCount,
765
- summary,
766
- runId: `memory-compaction:${runId}:${attempt + 1}`
523
+ messageCount: compactedMessageCount,
524
+ replacement: summary,
525
+ runId: `memory-compaction:${runId}:${attempt}`
767
526
  });
768
527
  } catch (error) {
769
- throw new MemoryCompactionError("Memory compaction store commit failed.", {
528
+ throw new MemoryCompactionError("Memory compaction prefix replacement failed.", {
770
529
  cause: error,
771
530
  usage
772
531
  });
773
532
  }
774
- if (commit === "committed") {
533
+ if (replacement.status === "committed") {
775
534
  const retained = snapshot.messages.slice(compactedMessageCount);
776
535
  return {
777
536
  history: [summary, ...retained],
@@ -780,26 +539,27 @@ var AgentRunMemory = class {
780
539
  originalMessageCount: snapshot.messages.length,
781
540
  compactedMessageCount,
782
541
  retainedMessageCount: retained.length,
783
- conflictRetries
542
+ attempts: attempt,
543
+ usage
784
544
  }
785
545
  };
786
546
  }
787
- conflictRetries += 1;
547
+ throwIfAborted(abortSignal);
788
548
  }
789
- throw new MemoryCompactionConflictError(options.conflictRetries + 1, usage);
549
+ throw new MemoryCompactionConflictError(maxAttempts, usage);
790
550
  }
791
551
  };
792
- function compactedPrefixLength(messages, incomingMessageCount, maxMessages, keepRecentUserTurns) {
793
- if (messages.length + incomingMessageCount <= maxMessages) {
552
+ function compactedPrefixLength(messages, incomingMessageCount, afterMessages, recentUserTurns) {
553
+ if (messages.length + incomingMessageCount <= afterMessages) {
794
554
  return 0;
795
555
  }
796
556
  const userMessageIndexes = messages.flatMap(
797
557
  (message, index) => message.role === "user" ? [index] : []
798
558
  );
799
- if (userMessageIndexes.length <= keepRecentUserTurns) {
559
+ if (userMessageIndexes.length <= recentUserTurns) {
800
560
  return 0;
801
561
  }
802
- return userMessageIndexes[userMessageIndexes.length - keepRecentUserTurns] ?? 0;
562
+ return userMessageIndexes[userMessageIndexes.length - recentUserTurns] ?? 0;
803
563
  }
804
564
  function remappedCompactorError(error, usage) {
805
565
  if (error instanceof MemoryCompactionError) {
@@ -822,42 +582,46 @@ function isEmptyUsage(usage) {
822
582
  }
823
583
 
824
584
  // src/internal/agent-runtime/retrieval.ts
825
- async function fetchContextDocuments(agent, ragText) {
585
+ async function fetchContextDocuments(agent, ragText, abortSignal) {
826
586
  const documents = [];
827
587
  for (const input of agent.context) {
828
- if (!isContextIndex(input)) {
588
+ if (!isVectorContext(input)) {
829
589
  documents.push(input);
830
590
  continue;
831
591
  }
832
- if (ragText === void 0 || ragText.length === 0) {
833
- continue;
834
- }
835
- const results = await input.index.search({
592
+ if (ragText === void 0 || ragText.length === 0) continue;
593
+ const request = {
836
594
  query: ragText,
837
595
  topK: input.topK,
838
- threshold: input.threshold,
839
- filter: input.filter
840
- });
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 });
841
607
  for (const result of results) {
842
608
  const formatted = input.format?.(result);
843
609
  if (formatted !== void 0) {
844
610
  documents.push(formatted);
845
- } else {
846
- const metadata = formatMetadata(result.metadata);
847
- const document = {
848
- id: result.id,
849
- text: typeof result.document === "string" ? result.document : JSON.stringify(result.document, null, 2)
850
- };
851
- if (metadata !== void 0) {
852
- document.additionalProps = metadata;
853
- }
854
- documents.push(document);
611
+ continue;
855
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);
856
620
  }
857
621
  }
858
622
  return documents;
859
623
  }
860
- async function fetchToolDefinitions(agent, ragText) {
624
+ async function fetchToolDefinitions(agent, ragText, abortSignal) {
861
625
  const state = getAgentToolState(agent);
862
626
  const staticDefinitions = await Promise.all(
863
627
  state.staticTools.map((tool) => tool.definition(ragText ?? ""))
@@ -868,21 +632,12 @@ async function fetchToolDefinitions(agent, ragText) {
868
632
  const definitions = [...staticDefinitions];
869
633
  const names = new Set(staticDefinitions.map((definition) => definition.name));
870
634
  for (const index of state.toolIndexes) {
871
- const results = await index.search({
872
- query: ragText,
873
- topK: index.topK,
874
- threshold: index.threshold,
875
- filter: index.filter
876
- });
635
+ const results = await index.search({ query: ragText, abortSignal });
877
636
  for (const result of results) {
878
637
  const toolName = result.document.toolName;
879
- if (names.has(toolName)) {
880
- continue;
881
- }
638
+ if (names.has(toolName)) continue;
882
639
  const tool = index.tools.find((candidate) => candidate.name === toolName);
883
- if (tool === void 0) {
884
- continue;
885
- }
640
+ if (tool === void 0) continue;
886
641
  names.add(toolName);
887
642
  definitions.push(await tool.definition(ragText));
888
643
  }
@@ -890,9 +645,7 @@ async function fetchToolDefinitions(agent, ragText) {
890
645
  return definitions;
891
646
  }
892
647
  function formatMetadata(metadata) {
893
- if (metadata === void 0) {
894
- return void 0;
895
- }
648
+ if (metadata === void 0) return void 0;
896
649
  return Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, String(value)]));
897
650
  }
898
651
 
@@ -1022,13 +775,13 @@ var CompletionStreamAccumulator = class {
1022
775
  return response;
1023
776
  }
1024
777
  upsertToolCall(toolCall) {
1025
- if (!this.toolCalls.has(toolCall.id)) {
1026
- this.orderedParts.push({ type: "tool_call", key: toolCall.id });
778
+ if (!this.toolCalls.has(toolCall.toolCallId)) {
779
+ this.orderedParts.push({ type: "tool_call", key: toolCall.toolCallId });
1027
780
  }
1028
781
  const partial = {
1029
- id: toolCall.id,
1030
- name: toolCall.function.name,
1031
- argumentsText: JSON.stringify(toolCall.function.arguments ?? {})
782
+ id: toolCall.toolCallId,
783
+ name: toolCall.toolName,
784
+ argumentsText: JSON.stringify(toolCall.input ?? {})
1032
785
  };
1033
786
  if (toolCall.callId !== void 0) {
1034
787
  partial.callId = toolCall.callId;
@@ -1036,10 +789,7 @@ var CompletionStreamAccumulator = class {
1036
789
  if (toolCall.signature !== void 0) {
1037
790
  partial.signature = toolCall.signature;
1038
791
  }
1039
- if (toolCall.additionalParams !== void 0) {
1040
- partial.additionalParams = toolCall.additionalParams;
1041
- }
1042
- this.toolCalls.set(toolCall.id, partial);
792
+ this.toolCalls.set(toolCall.toolCallId, partial);
1043
793
  }
1044
794
  mergeFinalResponse(accumulatedResponse, finalResponse) {
1045
795
  if (finalResponse.choice.length === 0) {
@@ -1056,20 +806,20 @@ var CompletionStreamAccumulator = class {
1056
806
  const finalById = /* @__PURE__ */ new Map();
1057
807
  const finalByCallId = /* @__PURE__ */ new Map();
1058
808
  for (const content of finalResponse.choice) {
1059
- if (content.type !== "tool_call") {
809
+ if (content.type !== "tool-call") {
1060
810
  continue;
1061
811
  }
1062
- finalById.set(content.id, content);
812
+ finalById.set(content.toolCallId, content);
1063
813
  if (content.callId !== void 0) {
1064
814
  finalByCallId.set(content.callId, content);
1065
815
  }
1066
816
  }
1067
817
  const matchedFinalToolCalls = /* @__PURE__ */ new Set();
1068
818
  const choice = accumulatedResponse.choice.map((content) => {
1069
- if (content.type !== "tool_call") {
819
+ if (content.type !== "tool-call") {
1070
820
  return content;
1071
821
  }
1072
- const finalToolCall = finalById.get(content.id) ?? (content.callId === void 0 ? void 0 : finalByCallId.get(content.callId));
822
+ const finalToolCall = finalById.get(content.toolCallId) ?? (content.callId === void 0 ? void 0 : finalByCallId.get(content.callId));
1073
823
  if (finalToolCall === void 0) {
1074
824
  return content;
1075
825
  }
@@ -1077,7 +827,7 @@ var CompletionStreamAccumulator = class {
1077
827
  return mergeFinalToolCall(content, finalToolCall);
1078
828
  });
1079
829
  for (const content of finalResponse.choice) {
1080
- if (content.type !== "tool_call") {
830
+ if (content.type !== "tool-call") {
1081
831
  continue;
1082
832
  }
1083
833
  if (!matchedFinalToolCalls.has(content)) {
@@ -1172,16 +922,17 @@ var CompletionStreamAccumulator = class {
1172
922
  if (event.contentType === void 0 && event.signature === void 0) {
1173
923
  return;
1174
924
  }
1175
- reasoning.content ??= [];
1176
- const last = reasoning.content.at(-1);
925
+ reasoning.details ??= [];
926
+ const last = reasoning.details.at(-1);
1177
927
  if (contentType === "text") {
1178
928
  if (last?.type === "text") {
1179
- last.text += event.delta;
1180
- if (event.signature !== void 0) {
1181
- last.signature = event.signature;
1182
- }
929
+ reasoning.details[reasoning.details.length - 1] = {
930
+ ...last,
931
+ text: `${last.text}${event.delta}`,
932
+ ...event.signature === void 0 ? {} : { signature: event.signature }
933
+ };
1183
934
  } else {
1184
- reasoning.content.push(
935
+ reasoning.details.push(
1185
936
  event.signature === void 0 ? { type: "text", text: event.delta } : { type: "text", text: event.delta, signature: event.signature }
1186
937
  );
1187
938
  }
@@ -1189,17 +940,20 @@ var CompletionStreamAccumulator = class {
1189
940
  }
1190
941
  if (contentType === "summary") {
1191
942
  if (last?.type === "summary") {
1192
- last.text += event.delta;
943
+ reasoning.details[reasoning.details.length - 1] = {
944
+ ...last,
945
+ text: `${last.text}${event.delta}`
946
+ };
1193
947
  } else {
1194
- reasoning.content.push({ type: "summary", text: event.delta });
948
+ reasoning.details.push({ type: "summary", text: event.delta });
1195
949
  }
1196
950
  return;
1197
951
  }
1198
952
  if (contentType === "encrypted") {
1199
- reasoning.content.push({ type: "encrypted", data: event.delta });
953
+ reasoning.details.push({ type: "encrypted", data: event.delta });
1200
954
  return;
1201
955
  }
1202
- reasoning.content.push({ type: "redacted", data: event.delta });
956
+ reasoning.details.push({ type: "redacted", data: event.delta });
1203
957
  }
1204
958
  };
1205
959
  function sourceKey(source) {
@@ -1220,51 +974,37 @@ function mergeProviderToolCalls(accumulated, final) {
1220
974
  return [...toolCalls.values()];
1221
975
  }
1222
976
  function reasoningContent(reasoning) {
1223
- const content = reasoning.content === void 0 ? { type: "reasoning", text: reasoning.text } : { type: "reasoning", text: reasoning.text, content: reasoning.content };
977
+ const content = reasoning.details === void 0 ? { type: "reasoning", text: reasoning.text } : { type: "reasoning", text: reasoning.text, details: reasoning.details };
1224
978
  return reasoning.id === void 0 ? content : { ...content, id: reasoning.id };
1225
979
  }
1226
980
  function toolCallContent(toolCall, finalToolCall) {
1227
- const argumentsValue = finalToolCall !== void 0 && !isEmptyToolArguments(finalToolCall.function.arguments) ? finalToolCall.function.arguments : parseToolArguments(toolCall.id, toolCall.argumentsText);
1228
- const content = {
1229
- type: "tool_call",
1230
- id: toolCall.id,
1231
- function: {
1232
- name: toolCall.name,
1233
- arguments: argumentsValue
1234
- }
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 }
1235
989
  };
1236
- if (toolCall.callId !== void 0) {
1237
- content.callId = toolCall.callId;
1238
- }
1239
- if (toolCall.signature !== void 0) {
1240
- content.signature = toolCall.signature;
1241
- }
1242
- if (toolCall.additionalParams !== void 0) {
1243
- content.additionalParams = toolCall.additionalParams;
1244
- }
1245
- return content;
1246
990
  }
1247
991
  function matchingFinalToolCall(accumulated, finalChoice) {
1248
992
  const byId = finalChoice?.find(
1249
- (content) => content.type === "tool_call" && content.id === accumulated.id
993
+ (content) => content.type === "tool-call" && content.toolCallId === accumulated.id
1250
994
  );
1251
995
  if (byId !== void 0 || accumulated.callId === void 0) {
1252
996
  return byId;
1253
997
  }
1254
998
  return finalChoice?.find(
1255
- (content) => content.type === "tool_call" && content.callId === accumulated.callId
999
+ (content) => content.type === "tool-call" && content.callId === accumulated.callId
1256
1000
  );
1257
1001
  }
1258
1002
  function mergeFinalToolCall(accumulated, finalToolCall) {
1259
- const argumentsValue = isEmptyToolArguments(finalToolCall.function.arguments) ? accumulated.function.arguments : finalToolCall.function.arguments;
1003
+ const input = isEmptyToolArguments(finalToolCall.input) ? accumulated.input : finalToolCall.input;
1260
1004
  return {
1261
1005
  ...accumulated,
1262
1006
  ...finalToolCall,
1263
- function: {
1264
- ...accumulated.function,
1265
- ...finalToolCall.function,
1266
- arguments: argumentsValue
1267
- }
1007
+ input
1268
1008
  };
1269
1009
  }
1270
1010
  function reasoningDeltaEvent(event) {
@@ -1340,9 +1080,8 @@ function isGenerationDeltaEvent(type) {
1340
1080
  }
1341
1081
 
1342
1082
  // src/internal/agent-runtime/tool-execution.ts
1343
- var MCP_TOOL_METADATA_KEY = /* @__PURE__ */ Symbol.for("anvia.mcp.tool.metadata");
1344
1083
  var ToolCallExecutor = class {
1345
- constructor(agent, activeHook, approvalHandler, lifecycle, runContext, concurrency, requestMiddlewares, includeToolCallDeltas, cancel) {
1084
+ constructor(agent, activeHook, approvalHandler, lifecycle, runContext, concurrency, requestMiddlewares, abortSignal, cancel) {
1346
1085
  this.agent = agent;
1347
1086
  this.activeHook = activeHook;
1348
1087
  this.approvalHandler = approvalHandler;
@@ -1350,7 +1089,7 @@ var ToolCallExecutor = class {
1350
1089
  this.runContext = runContext;
1351
1090
  this.concurrency = concurrency;
1352
1091
  this.requestMiddlewares = requestMiddlewares;
1353
- this.includeToolCallDeltas = includeToolCallDeltas;
1092
+ this.abortSignal = abortSignal;
1354
1093
  this.cancel = cancel;
1355
1094
  }
1356
1095
  agent;
@@ -1360,36 +1099,37 @@ var ToolCallExecutor = class {
1360
1099
  runContext;
1361
1100
  concurrency;
1362
1101
  requestMiddlewares;
1363
- includeToolCallDeltas;
1102
+ abortSignal;
1364
1103
  cancel;
1365
1104
  async execute(toolCalls, onResult, onStreamEvent, observation) {
1366
1105
  for (const toolCall of toolCalls) {
1367
- if (toolCall.function.name.length === 0) {
1106
+ if (toolCall.toolName.length === 0) {
1368
1107
  throw new Error(
1369
- `Completion returned tool call "${toolCall.id}" with an empty function name; this indicates invalid provider output or provider mapping.`
1108
+ `Completion returned tool call "${toolCall.toolCallId}" with an empty tool name; this indicates invalid provider output or provider mapping.`
1370
1109
  );
1371
1110
  }
1372
1111
  }
1373
1112
  return mapWithConcurrency(toolCalls, this.concurrency, async (toolCall) => {
1374
- const args = JSON.stringify(toolCall.function.arguments ?? {});
1113
+ throwIfAborted(this.abortSignal);
1114
+ const args = JSON.stringify(toolCall.input);
1375
1115
  const internalCallId = globalThis.crypto.randomUUID();
1376
1116
  const hookArgs = {
1377
- toolName: toolCall.function.name,
1117
+ toolName: toolCall.toolName,
1378
1118
  internalCallId,
1379
1119
  args
1380
1120
  };
1381
1121
  if (toolCall.callId !== void 0) {
1382
1122
  hookArgs.toolCallId = toolCall.callId;
1383
1123
  }
1384
- const tool = this.agent.getTool(toolCall.function.name);
1124
+ const tool = this.agent.getTool(toolCall.toolName);
1385
1125
  const toolDefinition = observation?.toolDefinitions?.find(
1386
- (definition) => definition.name === toolCall.function.name
1126
+ (definition) => definition.name === toolCall.toolName
1387
1127
  );
1388
1128
  const toolMetadata = toolTraceMetadata(tool);
1389
1129
  const toolStartArgs = {
1390
1130
  turn: observation?.turn ?? 0,
1391
1131
  toolCall,
1392
- toolName: toolCall.function.name,
1132
+ toolName: toolCall.toolName,
1393
1133
  internalCallId,
1394
1134
  args,
1395
1135
  ...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId },
@@ -1411,7 +1151,7 @@ var ToolCallExecutor = class {
1411
1151
  throw this.cancel(callAction.reason);
1412
1152
  }
1413
1153
  if (callAction?.type === "skip") {
1414
- output = callAction.reason;
1154
+ output = { type: "text", value: callAction.reason };
1415
1155
  skipped = true;
1416
1156
  } else {
1417
1157
  try {
@@ -1423,7 +1163,7 @@ var ToolCallExecutor = class {
1423
1163
  hookArgs.args = effectiveArgs;
1424
1164
  let prepared;
1425
1165
  try {
1426
- prepared = this.prepareToolCall(tool, toolCall.function.name, effectiveArgs);
1166
+ prepared = this.prepareToolCall(tool, toolCall.toolName, effectiveArgs);
1427
1167
  } catch (error) {
1428
1168
  const outcome = await this.handleToolError(
1429
1169
  toolCall,
@@ -1447,14 +1187,14 @@ var ToolCallExecutor = class {
1447
1187
  approved: true
1448
1188
  };
1449
1189
  if (!approvalDecision.approved) {
1450
- output = approvalDecision.result;
1190
+ output = { type: "execution-denied", reason: approvalDecision.result };
1451
1191
  skipped = true;
1452
1192
  } else {
1453
1193
  const step = observation?.turn ?? 0;
1454
1194
  const lifecycleEvent = {
1455
1195
  runId: this.runContext.runId,
1456
1196
  step,
1457
- toolName: toolCall.function.name,
1197
+ toolName: toolCall.toolName,
1458
1198
  input: lifecycleSnapshot(prepared.input),
1459
1199
  ...toolCall.callId === void 0 ? {} : { toolCallId: toolCall.callId }
1460
1200
  };
@@ -1495,7 +1235,7 @@ var ToolCallExecutor = class {
1495
1235
  }
1496
1236
  }
1497
1237
  if (output === void 0) {
1498
- throw new Error(`Tool "${toolCall.function.name}" did not produce an execution result.`);
1238
+ throw new Error(`Tool "${toolCall.toolName}" did not produce an execution result.`);
1499
1239
  }
1500
1240
  let result = toolOutputToText(output);
1501
1241
  let structuredResult = toolOutputToStructuredResult(output);
@@ -1526,7 +1266,7 @@ var ToolCallExecutor = class {
1526
1266
  await toolObservation.end({
1527
1267
  turn: observation?.turn ?? 0,
1528
1268
  toolCall,
1529
- toolName: toolCall.function.name,
1269
+ toolName: toolCall.toolName,
1530
1270
  internalCallId,
1531
1271
  args: effectiveArgs,
1532
1272
  result,
@@ -1540,20 +1280,23 @@ var ToolCallExecutor = class {
1540
1280
  }
1541
1281
  const resultPayload = {
1542
1282
  type: "tool_result",
1543
- toolName: toolCall.function.name,
1283
+ toolName: toolCall.toolName,
1284
+ toolCallId: toolCall.toolCallId,
1544
1285
  internalCallId,
1545
1286
  args: effectiveArgs,
1287
+ output,
1546
1288
  result,
1547
- structuredResult
1289
+ structuredResult,
1290
+ ...toolCall.callId === void 0 ? {} : { callId: toolCall.callId }
1548
1291
  };
1549
- if (toolCall.callId !== void 0) {
1550
- resultPayload.toolCallId = toolCall.callId;
1551
- }
1552
1292
  onResult?.(resultPayload);
1553
- return ToolContent.toolResult(toolCall.id, output, {
1554
- callId: toolCall.callId,
1555
- toolName: toolCall.function.name
1556
- });
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
+ };
1557
1300
  } catch (error) {
1558
1301
  await toolObservation.error(
1559
1302
  toolErrorArgs(observation?.turn ?? 0, toolCall, internalCallId, effectiveArgs, error)
@@ -1565,11 +1308,12 @@ var ToolCallExecutor = class {
1565
1308
  async runApprovedToolCall(prepared, toolCall, hookArgs, effectiveArgs, toolObservation, observation, onStreamEvent) {
1566
1309
  try {
1567
1310
  const toolContext = {
1311
+ abortSignal: this.abortSignal,
1568
1312
  emitStreamEvent: async (event) => {
1569
1313
  const streamEventArgs = {
1570
1314
  turn: observation?.turn ?? 0,
1571
1315
  toolCall,
1572
- toolName: toolCall.function.name,
1316
+ toolName: toolCall.toolName,
1573
1317
  internalCallId: hookArgs.internalCallId,
1574
1318
  args: effectiveArgs,
1575
1319
  event,
@@ -1582,7 +1326,6 @@ var ToolCallExecutor = class {
1582
1326
  }
1583
1327
  }
1584
1328
  };
1585
- toolContext.includeToolCallDeltas = this.includeToolCallDeltas;
1586
1329
  return {
1587
1330
  output: await prepared.call(toolContext),
1588
1331
  failed: false
@@ -1622,7 +1365,10 @@ var ToolCallExecutor = class {
1622
1365
  throw this.cancel(errorAction.reason);
1623
1366
  }
1624
1367
  return {
1625
- output: error instanceof Error ? error.toString() : String(error),
1368
+ output: {
1369
+ type: "error-text",
1370
+ value: error instanceof Error ? error.toString() : String(error)
1371
+ },
1626
1372
  failed: true,
1627
1373
  error
1628
1374
  };
@@ -1650,7 +1396,7 @@ var ToolCallExecutor = class {
1650
1396
  replaced = true;
1651
1397
  }
1652
1398
  }
1653
- return replaced ? structuredResult ?? result : void 0;
1399
+ return replaced ? structuredResult === void 0 ? { type: "text", value: result } : { type: "content", value: structuredResult } : void 0;
1654
1400
  }
1655
1401
  async runToolInputMiddlewares(args) {
1656
1402
  let current = args.args;
@@ -1766,13 +1512,12 @@ function toolTraceMetadata(tool) {
1766
1512
  if (tool === void 0) {
1767
1513
  return void 0;
1768
1514
  }
1769
- const metadata = tool[MCP_TOOL_METADATA_KEY];
1770
- const mcpMetadata = typeof metadata === "object" && metadata !== null ? metadata : void 0;
1771
1515
  const result = {
1772
1516
  approvalRequired: toolMayRequireApproval(tool.requiresApproval)
1773
1517
  };
1774
- if (typeof mcpMetadata?.serverName === "string" && mcpMetadata.serverName.length > 0) {
1775
- result.mcpServerName = mcpMetadata.serverName;
1518
+ if (isMcpTool(tool)) {
1519
+ result.mcpServerName = tool.mcp.serverName;
1520
+ result.mcpRemoteName = tool.mcp.remoteName;
1776
1521
  }
1777
1522
  return result;
1778
1523
  }
@@ -1780,7 +1525,7 @@ function toolErrorArgs(turn, toolCall, internalCallId, args, error) {
1780
1525
  const observerArgs = {
1781
1526
  turn,
1782
1527
  toolCall,
1783
- toolName: toolCall.function.name,
1528
+ toolName: toolCall.toolName,
1784
1529
  internalCallId,
1785
1530
  args,
1786
1531
  error,
@@ -1809,10 +1554,21 @@ var ToolObserverScope = class {
1809
1554
  }
1810
1555
  };
1811
1556
  function toolOutputToText(output) {
1812
- return typeof output === "string" ? output : toolResultContentToText(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
+ }
1813
1569
  }
1814
1570
  function toolOutputToStructuredResult(output) {
1815
- return typeof output === "string" ? void 0 : output;
1571
+ return output.type === "content" ? output.value : void 0;
1816
1572
  }
1817
1573
  function agentToolEventPayload(toolCall, internalCallId, event) {
1818
1574
  if (typeof event.agentId !== "string" || event.agentId.length === 0) {
@@ -1820,7 +1576,7 @@ function agentToolEventPayload(toolCall, internalCallId, event) {
1820
1576
  }
1821
1577
  const payload = {
1822
1578
  type: "agent_tool_event",
1823
- toolName: toolCall.function.name,
1579
+ toolName: toolCall.toolName,
1824
1580
  internalCallId,
1825
1581
  agentId: event.agentId,
1826
1582
  event: event.event
@@ -1862,6 +1618,8 @@ var AgentRun = class _AgentRun {
1862
1618
  );
1863
1619
  const internalOptions = getInternalAgentRunOptions(options);
1864
1620
  this.activeHook = internalOptions?.hook;
1621
+ this.onInternalFailure = internalOptions?.onFailure;
1622
+ this.onInternalMemoryCompaction = internalOptions?.onMemoryCompaction;
1865
1623
  this.requestedRunId = normalizeRequestedRunId(internalOptions?.runId);
1866
1624
  this.activeLifecycle = composeAgentLifecycle(agent.lifecycle, options.lifecycle);
1867
1625
  this.guardrailPolicies = options.guardrails === void 0 ? [...agent.guardrails] : appendGuardrailPolicies([...agent.guardrails], options.guardrails);
@@ -1871,10 +1629,12 @@ var AgentRun = class _AgentRun {
1871
1629
  );
1872
1630
  this.concurrency = this.activeHook !== void 0 || agent.tools.some((tool) => toolMayRequireApproval(tool.requiresApproval)) ? 1 : configuredConcurrency;
1873
1631
  this.traceOptions = options.trace;
1874
- this.completionRetryOptions = options.retries === void 0 ? void 0 : resolveRetryOptions(options.retries);
1632
+ const retrySetting = options.retries === void 0 ? agent.retries : options.retries;
1633
+ this.completionRetryOptions = retrySetting === void 0 || retrySetting === false ? void 0 : resolveRetryOptions(retrySetting);
1875
1634
  this.requestMiddlewares = [...options.middlewares ?? []];
1876
- this.memoryContext = options.memoryContext;
1877
- this.memoryRecorder = new AgentRunMemory(agent, options.memoryContext, initialHistory);
1635
+ this.memoryScope = options.memoryScope;
1636
+ this.memoryRecorder = new AgentRunMemory(agent, options.memoryScope, initialHistory);
1637
+ this.linkExternalAbortSignal(options.abortSignal);
1878
1638
  }
1879
1639
  agent;
1880
1640
  promptMessage;
@@ -1891,7 +1651,10 @@ var AgentRun = class _AgentRun {
1891
1651
  steeringMessages = [];
1892
1652
  runState = "idle";
1893
1653
  memoryRecorder;
1894
- memoryContext;
1654
+ memoryScope;
1655
+ onInternalFailure;
1656
+ onInternalMemoryCompaction;
1657
+ memoryCompaction;
1895
1658
  pendingApproval;
1896
1659
  approvalSignal = deferredSignal();
1897
1660
  activeRunId;
@@ -1900,9 +1663,17 @@ var AgentRun = class _AgentRun {
1900
1663
  currentMessages = [];
1901
1664
  cancellationError;
1902
1665
  activeGeneration;
1903
- static fromAgent(agent, input, options = {}) {
1904
- const normalized = normalizeAgentInput(input);
1905
- return new _AgentRun(agent, normalized.prompt, normalized.history, options);
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
+ });
1906
1677
  }
1907
1678
  steer(input) {
1908
1679
  if (this.isTerminal() || this.cancellationError !== void 0) {
@@ -1937,7 +1708,11 @@ var AgentRun = class _AgentRun {
1937
1708
  }
1938
1709
  const messages = this.currentMessages.length === 0 ? [this.promptMessage] : [...this.currentMessages];
1939
1710
  const error = new AgentRunCancelledError([...this.chatHistory, ...messages], reason);
1711
+ this.setCancellationError(error);
1712
+ }
1713
+ setCancellationError(error) {
1940
1714
  this.cancellationError = error;
1715
+ if (!this.abortController.signal.aborted) this.abortController.abort(error);
1941
1716
  const pending = this.pendingApproval;
1942
1717
  if (pending !== void 0) {
1943
1718
  this.pendingApproval = void 0;
@@ -1955,11 +1730,19 @@ var AgentRun = class _AgentRun {
1955
1730
  let newMessages = [this.promptMessage];
1956
1731
  let runObservers;
1957
1732
  try {
1958
- const memoryPreparation = await this.memoryRecorder.prepareHistory(runId, newMessages.length);
1733
+ this.throwIfCancelled();
1734
+ const memoryPreparation = await this.memoryRecorder.prepareHistory(
1735
+ runId,
1736
+ newMessages.length,
1737
+ this.abortController.signal
1738
+ );
1959
1739
  this.chatHistory = memoryPreparation.history;
1960
1740
  usage = Usage.add(usage, memoryPreparation.usage);
1741
+ this.memoryCompaction = memoryPreparation.compaction;
1742
+ await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);
1961
1743
  runObservers = await this.startRunObservers(runId);
1962
1744
  await this.recordMemoryCompaction(memoryPreparation, runObservers);
1745
+ this.throwIfCancelled();
1963
1746
  await this.activeLifecycle?.onStart?.({
1964
1747
  runId,
1965
1748
  input: lifecycleSnapshot(this.promptMessage),
@@ -1977,19 +1760,22 @@ var AgentRun = class _AgentRun {
1977
1760
  }
1978
1761
  this.promptMessage = inputResult.prompt;
1979
1762
  if (inputResult.blocked) {
1980
- const output = inputResult.message ?? "The request was blocked by a guardrail.";
1763
+ const text = inputResult.message ?? "The request was blocked by a guardrail.";
1981
1764
  const result = {
1982
- status: "completed",
1765
+ status: "blocked",
1766
+ stage: "input",
1983
1767
  runId,
1984
- output,
1768
+ text,
1985
1769
  usage,
1986
- messages: [this.promptMessage, Message.assistant(output)],
1770
+ messages: [this.promptMessage, { role: "assistant", content: text }],
1987
1771
  trace: runObservers.trace,
1988
- guardrails: [...this.guardrailDecisions]
1772
+ guardrails: [...this.guardrailDecisions],
1773
+ ...this.memoryCompactionResult()
1989
1774
  };
1990
1775
  await this.runLifecycleFinish(result);
1991
1776
  await runObservers.end(result);
1992
1777
  this.runState = "completed";
1778
+ this.disposeAbortLink();
1993
1779
  return result;
1994
1780
  }
1995
1781
  newMessages = [this.promptMessage];
@@ -2028,7 +1814,7 @@ var AgentRun = class _AgentRun {
2028
1814
  usage: lifecycleSnapshot(usage)
2029
1815
  });
2030
1816
  const toolCalls = response.choice.filter(
2031
- (item) => item.type === "tool_call"
1817
+ (item) => item.type === "tool-call"
2032
1818
  );
2033
1819
  const assistantMessage = this.generatedAssistantMessage(response, request);
2034
1820
  newMessages.push(assistantMessage);
@@ -2061,17 +1847,17 @@ var AgentRun = class _AgentRun {
2061
1847
  [finalAssistantMessage],
2062
1848
  pendingTurnMessages
2063
1849
  );
2064
- const result = {
2065
- status: "completed",
1850
+ const result = this.createTerminalResult(
2066
1851
  runId,
2067
- output: guardedOutput.output,
1852
+ guardedOutput.text,
1853
+ guardedOutput.blocked,
2068
1854
  usage,
2069
- messages: [...newMessages],
2070
- trace: runObservers.trace,
2071
- guardrails: [...this.guardrailDecisions],
2072
- ...generationArtifacts(newMessages)
2073
- };
2074
- await this.runRunEndHook(result, newMessages);
1855
+ newMessages,
1856
+ runObservers
1857
+ );
1858
+ if (result.status === "completed") {
1859
+ await this.runRunEndHook(result, newMessages);
1860
+ }
2075
1861
  await this.memoryRecorder.commitCompletedRun(
2076
1862
  runId,
2077
1863
  currentTurns,
@@ -2081,6 +1867,7 @@ var AgentRun = class _AgentRun {
2081
1867
  await this.runLifecycleFinish(result);
2082
1868
  await runObservers.end(result);
2083
1869
  this.runState = "completed";
1870
+ this.disposeAbortLink();
2084
1871
  return result;
2085
1872
  }
2086
1873
  this.updateApprovalProgress(runId, usage, newMessages);
@@ -2096,7 +1883,7 @@ var AgentRun = class _AgentRun {
2096
1883
  toolDefinitions: request.tools
2097
1884
  }
2098
1885
  );
2099
- const toolMessage = Message.tool(toolResults);
1886
+ const toolMessage = { role: "tool", content: toolResults };
2100
1887
  newMessages.push(toolMessage);
2101
1888
  await this.memoryRecorder.commitMessages(
2102
1889
  runId,
@@ -2112,21 +1899,20 @@ var AgentRun = class _AgentRun {
2112
1899
  if (error instanceof MemoryCompactionError && error.usage !== void 0) {
2113
1900
  usage = Usage.add(usage, error.usage);
2114
1901
  }
1902
+ const runError = this.normalizeRunError(error);
2115
1903
  const reportedError = await this.reportRunFailure(
2116
- error,
1904
+ runError,
2117
1905
  runId,
2118
1906
  usage,
2119
1907
  newMessages,
2120
1908
  runObservers
2121
1909
  );
2122
1910
  this.runState = reportedError instanceof AgentRunCancelledError ? "cancelled" : "errored";
1911
+ this.disposeAbortLink();
2123
1912
  throw reportedError;
2124
1913
  }
2125
1914
  }
2126
- async *events(includeToolCallDeltas = true) {
2127
- if (!this.agent.model.capabilities.streaming || !isStreamingCompletionModel(this.agent.model)) {
2128
- throw new Error("This completion model does not support streaming");
2129
- }
1915
+ async *events() {
2130
1916
  this.startRun();
2131
1917
  const runId = this.requestedRunId ?? globalThis.crypto.randomUUID();
2132
1918
  this.activeRunId = runId;
@@ -2137,11 +1923,22 @@ var AgentRun = class _AgentRun {
2137
1923
  const bufferOutputDeltas = hasEnforcedOutputGuardrails(this.guardrailPolicies);
2138
1924
  let runObservers;
2139
1925
  try {
2140
- const memoryPreparation = await this.memoryRecorder.prepareHistory(runId, newMessages.length);
1926
+ this.throwIfCancelled();
1927
+ const memoryPreparation = await this.memoryRecorder.prepareHistory(
1928
+ runId,
1929
+ newMessages.length,
1930
+ this.abortController.signal
1931
+ );
2141
1932
  this.chatHistory = memoryPreparation.history;
2142
1933
  usage = Usage.add(usage, memoryPreparation.usage);
1934
+ this.memoryCompaction = memoryPreparation.compaction;
1935
+ await this.notifyInternalMemoryCompaction(memoryPreparation.compaction);
2143
1936
  runObservers = await this.startRunObservers(runId);
2144
1937
  await this.recordMemoryCompaction(memoryPreparation, runObservers);
1938
+ if (memoryPreparation.compaction !== void 0) {
1939
+ yield { type: "memory_compaction", ...memoryPreparation.compaction };
1940
+ }
1941
+ this.throwIfCancelled();
2145
1942
  await this.activeLifecycle?.onStart?.({
2146
1943
  runId,
2147
1944
  input: lifecycleSnapshot(this.promptMessage),
@@ -2160,28 +1957,23 @@ var AgentRun = class _AgentRun {
2160
1957
  }
2161
1958
  this.promptMessage = inputResult.prompt;
2162
1959
  if (inputResult.blocked) {
2163
- const output = inputResult.message ?? "The request was blocked by a guardrail.";
1960
+ const text = inputResult.message ?? "The request was blocked by a guardrail.";
2164
1961
  const result = {
2165
- status: "completed",
1962
+ status: "blocked",
1963
+ stage: "input",
2166
1964
  runId,
2167
- output,
1965
+ text,
2168
1966
  usage,
2169
- messages: [this.promptMessage, Message.assistant(output)],
1967
+ messages: [this.promptMessage, { role: "assistant", content: text }],
2170
1968
  trace: runObservers.trace,
2171
- guardrails: [...this.guardrailDecisions]
1969
+ guardrails: [...this.guardrailDecisions],
1970
+ ...this.memoryCompactionResult()
2172
1971
  };
2173
1972
  await this.runLifecycleFinish(result);
2174
1973
  await runObservers.end(result);
2175
1974
  this.runState = "completed";
2176
- yield {
2177
- type: "final",
2178
- runId,
2179
- output: result.output,
2180
- usage: result.usage,
2181
- messages: result.messages,
2182
- trace: result.trace,
2183
- guardrails: result.guardrails
2184
- };
1975
+ this.disposeAbortLink();
1976
+ yield { type: "final", result };
2185
1977
  return;
2186
1978
  }
2187
1979
  newMessages = [this.promptMessage];
@@ -2234,7 +2026,6 @@ var AgentRun = class _AgentRun {
2234
2026
  for await (const event of this.streamCompletion({
2235
2027
  request,
2236
2028
  turn: currentTurns,
2237
- includeToolCallDeltas,
2238
2029
  bufferResponseEvents,
2239
2030
  bufferOutputDeltas,
2240
2031
  generationStartedAt,
@@ -2278,7 +2069,7 @@ var AgentRun = class _AgentRun {
2278
2069
  usage: lifecycleSnapshot(usage)
2279
2070
  });
2280
2071
  const toolCalls = response.choice.filter(
2281
- (item) => item.type === "tool_call"
2072
+ (item) => item.type === "tool-call"
2282
2073
  );
2283
2074
  const assistantMessage = this.generatedAssistantMessage(response, request);
2284
2075
  newMessages.push(assistantMessage);
@@ -2334,7 +2125,7 @@ var AgentRun = class _AgentRun {
2334
2125
  }
2335
2126
  } else {
2336
2127
  for (const toolCall of toolCalls) {
2337
- if (!emittedToolCallIds.has(toolCall.id)) {
2128
+ if (!emittedToolCallIds.has(toolCall.toolCallId)) {
2338
2129
  yield { type: "tool_call", turn: currentTurns, toolCall };
2339
2130
  }
2340
2131
  }
@@ -2349,14 +2140,13 @@ var AgentRun = class _AgentRun {
2349
2140
  const toolExecution = this.executeStreamingToolCalls(runId, toolCalls, newMessages, {
2350
2141
  turn: currentTurns,
2351
2142
  runObservers,
2352
- toolDefinitions: request.tools,
2353
- includeToolCallDeltas
2143
+ toolDefinitions: request.tools
2354
2144
  });
2355
2145
  for await (const result of toolExecution.events) {
2356
2146
  yield { turn: currentTurns, ...result };
2357
2147
  }
2358
2148
  const toolResults = await toolExecution.results;
2359
- const toolMessage = Message.tool(toolResults);
2149
+ const toolMessage = { role: "tool", content: toolResults };
2360
2150
  newMessages.push(toolMessage);
2361
2151
  await this.memoryRecorder.commitMessages(
2362
2152
  runId,
@@ -2372,8 +2162,9 @@ var AgentRun = class _AgentRun {
2372
2162
  if (error instanceof MemoryCompactionError && error.usage !== void 0) {
2373
2163
  usage = Usage.add(usage, error.usage);
2374
2164
  }
2165
+ const runError = this.normalizeRunError(error);
2375
2166
  const reportedError = await this.reportRunFailure(
2376
- error,
2167
+ runError,
2377
2168
  runId,
2378
2169
  usage,
2379
2170
  newMessages,
@@ -2382,7 +2173,8 @@ var AgentRun = class _AgentRun {
2382
2173
  this.runState = reportedError instanceof AgentRunCancelledError ? "cancelled" : "errored";
2383
2174
  const finalUsage = usage;
2384
2175
  yield { type: "error", error: reportedError, usage: finalUsage };
2385
- throw reportedError;
2176
+ this.disposeAbortLink();
2177
+ return;
2386
2178
  } finally {
2387
2179
  if (this.runState === "running") {
2388
2180
  const cancellation = this.cancellationError ?? new AgentRunCancelledError([...this.chatHistory, ...newMessages], "Agent stream closed.");
@@ -2390,6 +2182,7 @@ var AgentRun = class _AgentRun {
2390
2182
  await settleFailureCleanup([() => this.closeActiveGeneration(cancellation)]);
2391
2183
  await this.reportRunFailure(cancellation, runId, usage, newMessages, runObservers);
2392
2184
  this.runState = "cancelled";
2185
+ this.disposeAbortLink();
2393
2186
  }
2394
2187
  }
2395
2188
  }
@@ -2403,7 +2196,8 @@ var AgentRun = class _AgentRun {
2403
2196
  for (let attempt = 1; ; attempt += 1) {
2404
2197
  let response;
2405
2198
  try {
2406
- response = await this.agent.model.completion(request);
2199
+ this.throwIfCancelled();
2200
+ response = await this.agent.model.completion(request, this.modelCallOptions());
2407
2201
  } catch (error) {
2408
2202
  const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
2409
2203
  if (retryOptions === void 0) {
@@ -2429,20 +2223,20 @@ var AgentRun = class _AgentRun {
2429
2223
  }
2430
2224
  async createTurnRequest(prompt, history, turn) {
2431
2225
  const ragText = extractRagText(prompt);
2432
- const documents = await fetchContextDocuments(this.agent, ragText);
2433
- const toolDefinitions = await fetchToolDefinitions(this.agent, ragText);
2226
+ const abortSignal = this.abortController.signal;
2227
+ const documents = await fetchContextDocuments(this.agent, ragText, abortSignal);
2228
+ const toolDefinitions = await fetchToolDefinitions(this.agent, ragText, abortSignal);
2434
2229
  const request = createCompletionRequest([...history, prompt], {
2435
- model: this.agent.model,
2436
2230
  instructions: this.agent.instructions,
2437
2231
  documents,
2438
2232
  tools: [...toolDefinitions, ...getAgentToolState(this.agent).providerTools],
2439
2233
  temperature: this.agent.temperature,
2440
2234
  maxTokens: this.agent.maxTokens,
2441
- additionalParams: this.agent.additionalParams,
2235
+ providerOptions: this.agent.providerOptions,
2442
2236
  toolChoice: this.agent.toolChoice,
2443
- outputSchema: this.agent.outputSchema
2237
+ outputSchema: getAgentProviderOutputSchema(this.agent)
2444
2238
  });
2445
- return await this.runCompletionRequestMiddlewares(request, turn);
2239
+ return this.runCompletionRequestMiddlewares(request, turn);
2446
2240
  }
2447
2241
  async *streamCompletion(args) {
2448
2242
  const model = this.agent.model;
@@ -2453,7 +2247,8 @@ var AgentRun = class _AgentRun {
2453
2247
  for (let attempt = 1; ; attempt += 1) {
2454
2248
  let hasProviderProgress = false;
2455
2249
  try {
2456
- for await (const event of model.streamCompletion(args.request)) {
2250
+ this.throwIfCancelled();
2251
+ for await (const event of model.streamCompletion(args.request, this.modelCallOptions())) {
2457
2252
  if (event.type === "error") {
2458
2253
  if (event.usage !== void 0) {
2459
2254
  args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, event.usage);
@@ -2465,13 +2260,13 @@ var AgentRun = class _AgentRun {
2465
2260
  args.state.firstDeltaMs = Date.now() - args.generationStartedAt;
2466
2261
  }
2467
2262
  const mapped = accumulator.accept(event);
2468
- if (args.includeToolCallDeltas && event.type === "tool_call_delta") {
2263
+ if (event.type === "tool_call_delta") {
2469
2264
  yield addTurnToToolCallDelta(args.turn, event);
2470
2265
  }
2471
2266
  if (mapped !== void 0) {
2472
2267
  await args.generationObservers.update?.({ turn: args.turn, delta: mapped });
2473
2268
  if (mapped.type === "tool_call") {
2474
- args.state.emittedToolCallIds.add(mapped.toolCall.id);
2269
+ args.state.emittedToolCallIds.add(mapped.toolCall.toolCallId);
2475
2270
  }
2476
2271
  const shouldBuffer = args.bufferResponseEvents || args.bufferOutputDeltas && (mapped.type === "text_delta" || mapped.type === "reasoning_delta");
2477
2272
  if (!shouldBuffer) {
@@ -2530,17 +2325,17 @@ var AgentRun = class _AgentRun {
2530
2325
  firstDeltaMs: args.firstDeltaMs
2531
2326
  };
2532
2327
  }
2533
- const result = {
2534
- status: "completed",
2535
- runId: args.runId,
2536
- output: guardedOutput.output,
2537
- usage: args.usage,
2538
- messages: [...args.newMessages],
2539
- trace: args.runObservers.trace,
2540
- guardrails: [...this.guardrailDecisions],
2541
- ...generationArtifacts(args.newMessages)
2542
- };
2543
- await this.runRunEndHook(result, args.newMessages);
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
+ }
2544
2339
  await this.memoryRecorder.commitCompletedRun(
2545
2340
  args.runId,
2546
2341
  args.turn,
@@ -2550,25 +2345,15 @@ var AgentRun = class _AgentRun {
2550
2345
  await this.runLifecycleFinish(result);
2551
2346
  await args.runObservers.end(result);
2552
2347
  this.runState = "completed";
2553
- yield {
2554
- type: "final",
2555
- runId: args.runId,
2556
- output: result.output,
2557
- usage: result.usage,
2558
- contextUsage: result.contextUsage,
2559
- messages: result.messages,
2560
- trace: result.trace,
2561
- guardrails: result.guardrails,
2562
- sources: result.sources,
2563
- providerToolCalls: result.providerToolCalls
2564
- };
2348
+ this.disposeAbortLink();
2349
+ yield { type: "final", result };
2565
2350
  }
2566
- generatedAssistantMessage(response, request) {
2351
+ generatedAssistantMessage(response, _request) {
2567
2352
  const metadata = {
2568
2353
  anvia: {
2569
2354
  generation: {
2570
2355
  provider: this.agent.model.provider,
2571
- model: request.model ?? this.agent.model.defaultModel,
2356
+ modelId: this.agent.model.modelId,
2572
2357
  usage: { ...response.usage },
2573
2358
  ...response.contextUsage === void 0 ? {} : { contextUsage: response.contextUsage },
2574
2359
  ...response.sources === void 0 ? {} : { sources: response.sources },
@@ -2576,10 +2361,12 @@ var AgentRun = class _AgentRun {
2576
2361
  }
2577
2362
  }
2578
2363
  };
2579
- return Message.assistant(response.choice, {
2364
+ return {
2365
+ role: "assistant",
2366
+ content: response.choice,
2580
2367
  ...response.messageId === void 0 ? {} : { id: response.messageId },
2581
2368
  metadata
2582
- });
2369
+ };
2583
2370
  }
2584
2371
  providerTraceRequest(request, options = {}) {
2585
2372
  try {
@@ -2596,25 +2383,20 @@ var AgentRun = class _AgentRun {
2596
2383
  request,
2597
2384
  modelInfo: {
2598
2385
  provider: this.agent.model.provider,
2599
- defaultModel: this.agent.model.defaultModel,
2386
+ modelId: this.agent.model.modelId,
2600
2387
  capabilities: this.agent.model.capabilities
2601
2388
  },
2602
2389
  ...providerRequest === void 0 ? {} : { providerRequest }
2603
2390
  };
2604
2391
  }
2605
2392
  retryOptionsForFailure(error, attempt, turn, streaming) {
2606
- const options = this.completionRetryOptions;
2607
- if (options === void 0 || attempt >= options.maxAttempts) {
2608
- return void 0;
2609
- }
2610
- const shouldRetry = options.shouldRetry({
2393
+ if (this.abortController.signal.aborted) return void 0;
2394
+ return retryOptionsForFailure(this.completionRetryOptions, {
2611
2395
  error,
2612
2396
  attempt,
2613
- maxAttempts: options.maxAttempts,
2614
2397
  turn,
2615
2398
  streaming
2616
2399
  });
2617
- return shouldRetry ? options : void 0;
2618
2400
  }
2619
2401
  async scheduleCompletionRetry(error, attempt, turn, streaming, options, runObservers) {
2620
2402
  const delayMs = retryDelayMs(options, attempt);
@@ -2631,7 +2413,7 @@ var AgentRun = class _AgentRun {
2631
2413
  ...retryErrorAttributes(error)
2632
2414
  }
2633
2415
  });
2634
- await waitForRetry(delayMs);
2416
+ await waitForRetry(delayMs, this.abortController.signal);
2635
2417
  }
2636
2418
  async executeToolCalls(runId, toolCalls, newMessages, onResult, onStreamEvent, observation) {
2637
2419
  const executor = new ToolCallExecutor(
@@ -2641,12 +2423,12 @@ var AgentRun = class _AgentRun {
2641
2423
  this.activeLifecycle,
2642
2424
  {
2643
2425
  runId,
2644
- sessionId: this.memoryContext?.sessionId,
2645
- metadata: this.memoryContext?.metadata
2426
+ sessionId: this.memoryScope?.sessionId,
2427
+ metadata: this.memoryScope?.metadata
2646
2428
  },
2647
2429
  this.concurrency,
2648
2430
  this.requestMiddlewares,
2649
- observation?.includeToolCallDeltas ?? false,
2431
+ this.abortController.signal,
2650
2432
  (reason) => this.cancelled(newMessages, reason)
2651
2433
  );
2652
2434
  return executor.execute(toolCalls, onResult, onStreamEvent, observation);
@@ -2705,7 +2487,8 @@ var AgentRun = class _AgentRun {
2705
2487
  runId,
2706
2488
  approval,
2707
2489
  usage: lifecycleSnapshot(this.currentUsage),
2708
- messages: lifecycleSnapshot(this.currentMessages)
2490
+ messages: lifecycleSnapshot(this.currentMessages),
2491
+ ...this.memoryCompactionResult()
2709
2492
  };
2710
2493
  }
2711
2494
  updateApprovalProgress(runId, usage, messages) {
@@ -2714,12 +2497,23 @@ var AgentRun = class _AgentRun {
2714
2497
  this.currentMessages = [...messages];
2715
2498
  }
2716
2499
  async runLifecycleFinish(result) {
2717
- await this.activeLifecycle?.onFinish?.({
2500
+ const common = {
2718
2501
  runId: result.runId,
2719
- output: result.output,
2502
+ text: result.text,
2720
2503
  usage: lifecycleSnapshot(result.usage),
2721
- messages: lifecycleSnapshot(result.messages)
2722
- });
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);
2723
2517
  }
2724
2518
  async runLifecycleError(error, runId, usage, messages) {
2725
2519
  try {
@@ -2737,6 +2531,10 @@ var AgentRun = class _AgentRun {
2737
2531
  async reportRunFailure(error, runId, usage, messages, runObservers) {
2738
2532
  const reportedError = await this.resolveReportedRunError(error, runId, usage, messages);
2739
2533
  await settleFailureCleanup([
2534
+ () => this.onInternalFailure?.({
2535
+ error: reportedError,
2536
+ messages: lifecycleSnapshot(messages)
2537
+ }),
2740
2538
  () => runObservers?.error({
2741
2539
  error: reportedError,
2742
2540
  usage,
@@ -2765,19 +2563,54 @@ var AgentRun = class _AgentRun {
2765
2563
  for (const decision of result.decisions) {
2766
2564
  await this.recordGuardrailDecision(decision, runObservers);
2767
2565
  }
2768
- const output = result.blocked ? result.message ?? "The response was blocked by a guardrail." : result.outputText;
2769
- if (output === originalOutput) {
2770
- return { output, response, decisions: result.decisions };
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 };
2771
2569
  }
2772
2570
  return {
2773
- output,
2571
+ text,
2572
+ blocked: result.blocked,
2774
2573
  response: {
2775
2574
  ...response,
2776
- choice: [AssistantContent.text(output)]
2575
+ choice: [{ type: "text", text }]
2777
2576
  },
2778
2577
  decisions: result.decisions
2779
2578
  };
2780
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
+ }
2781
2614
  async recordGuardrailDecision(decision, runObservers) {
2782
2615
  this.guardrailDecisions.push(decision);
2783
2616
  await runObservers.event({
@@ -2797,30 +2630,36 @@ var AgentRun = class _AgentRun {
2797
2630
  originalMessageCount: compaction.originalMessageCount,
2798
2631
  compactedMessageCount: compaction.compactedMessageCount,
2799
2632
  retainedMessageCount: compaction.retainedMessageCount,
2800
- conflictRetries: compaction.conflictRetries,
2801
- inputTokens: preparation.usage.inputTokens,
2802
- outputTokens: preparation.usage.outputTokens,
2803
- totalTokens: preparation.usage.totalTokens
2633
+ attempts: compaction.attempts,
2634
+ inputTokens: compaction.usage.inputTokens,
2635
+ outputTokens: compaction.usage.outputTokens,
2636
+ totalTokens: compaction.usage.totalTokens
2804
2637
  }
2805
2638
  });
2806
2639
  }
2640
+ async notifyInternalMemoryCompaction(compaction) {
2641
+ if (compaction === void 0) {
2642
+ return;
2643
+ }
2644
+ await this.onInternalMemoryCompaction?.(lifecycleSnapshot(compaction));
2645
+ }
2807
2646
  guardrailRunContext(runId) {
2808
2647
  const context = {
2809
2648
  agentId: this.agent.id,
2810
2649
  runId
2811
2650
  };
2812
- if (this.memoryContext !== void 0) {
2813
- context.sessionId = this.memoryContext.sessionId;
2814
- if (this.memoryContext.metadata !== void 0) {
2815
- context.metadata = this.memoryContext.metadata;
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;
2816
2655
  }
2817
2656
  }
2818
2657
  return context;
2819
2658
  }
2820
2659
  async startRunObservers(runId) {
2821
- const failOnObserverError = this.traceOptions?.failOnObserverError === true || this.agent.observers.some((registration) => registration.failOnObserverError === true);
2660
+ const observability = this.agent.observability;
2822
2661
  return startAgentRunObservers(
2823
- this.agent.observers,
2662
+ observability?.observers ?? {},
2824
2663
  {
2825
2664
  runId,
2826
2665
  agentName: this.agent.name,
@@ -2832,7 +2671,10 @@ var AgentRun = class _AgentRun {
2832
2671
  history: this.chatHistory,
2833
2672
  maxTurns: this.maxTurnCount
2834
2673
  },
2835
- failOnObserverError
2674
+ {
2675
+ primaryTrace: observability?.primaryTrace,
2676
+ errorPolicy: observability?.errorPolicy ?? "ignore"
2677
+ }
2836
2678
  );
2837
2679
  }
2838
2680
  async runCompletionCallHook(prompt, history, newMessages) {
@@ -2858,7 +2700,9 @@ var AgentRun = class _AgentRun {
2858
2700
  }
2859
2701
  async runRunEndHook(result, newMessages) {
2860
2702
  const action = await this.activeHook?.onRunEnd?.({
2703
+ status: "completed",
2861
2704
  output: result.output,
2705
+ text: result.text,
2862
2706
  usage: result.usage,
2863
2707
  messages: result.messages,
2864
2708
  run: runControl
@@ -2977,33 +2821,139 @@ var AgentRun = class _AgentRun {
2977
2821
  return this.runState === "completed" || this.runState === "errored" || this.runState === "cancelled";
2978
2822
  }
2979
2823
  cancelled(newMessages, reason) {
2980
- return new AgentRunCancelledError([...this.chatHistory, ...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;
2981
2860
  }
2982
2861
  };
2983
- function normalizeAgentInput(prompt) {
2984
- if (typeof prompt === "string") {
2985
- return { prompt: Message.user(prompt), history: [] };
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
+ };
2986
2892
  }
2987
- if (!Array.isArray(prompt)) {
2988
- return { prompt, history: [] };
2893
+ if (input.session !== void 0) {
2894
+ throw new TypeError("Agent messages cannot be combined with a persisted session.");
2989
2895
  }
2990
- if (prompt.length === 0) {
2896
+ const messages = input.messages;
2897
+ if (!Array.isArray(messages) || messages.length === 0) {
2991
2898
  throw new TypeError("Agent input transcript must contain at least one message.");
2992
2899
  }
2993
- const activePrompt = prompt.at(-1);
2900
+ const parsedMessages = parseMessages(messages);
2901
+ const activePrompt = parsedMessages.at(-1);
2994
2902
  if (activePrompt === void 0) {
2995
2903
  throw new TypeError("Agent input transcript must contain at least one message.");
2996
2904
  }
2905
+ if (activePrompt.role !== "user") {
2906
+ throw new TypeError("Agent input transcript must end with a user message.");
2907
+ }
2997
2908
  return {
2998
2909
  prompt: activePrompt,
2999
- history: prompt.slice(0, -1)
2910
+ history: parsedMessages.slice(0, -1)
3000
2911
  };
3001
2912
  }
3002
2913
  function normalizeSteeringInput(input) {
3003
- if (typeof input === "string") {
3004
- return [Message.user(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.");
3005
2921
  }
3006
- return Array.isArray(input) ? [...input] : [input];
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
+ });
3007
2957
  }
3008
2958
  function normalizeRequestedRunId(runId) {
3009
2959
  if (runId === void 0) {
@@ -3024,13 +2974,13 @@ function responseStreamEvents(turn, response, includeProviderArtifacts = true) {
3024
2974
  continue;
3025
2975
  }
3026
2976
  if (item.type === "reasoning") {
3027
- if (item.content === void 0) {
2977
+ if (item.details === void 0) {
3028
2978
  if (item.text.length > 0) {
3029
2979
  events.push(reasoningDeltaEvent2(turn, item.text, { id: item.id }));
3030
2980
  }
3031
2981
  continue;
3032
2982
  }
3033
- for (const content of item.content) {
2983
+ for (const content of item.details) {
3034
2984
  const delta = content.type === "encrypted" || content.type === "redacted" ? content.data : content.text;
3035
2985
  events.push(
3036
2986
  reasoningDeltaEvent2(turn, delta, {
@@ -3042,7 +2992,7 @@ function responseStreamEvents(turn, response, includeProviderArtifacts = true) {
3042
2992
  }
3043
2993
  continue;
3044
2994
  }
3045
- if (item.type === "tool_call") {
2995
+ if (item.type === "tool-call") {
3046
2996
  events.push({ type: "tool_call", turn, toolCall: item });
3047
2997
  }
3048
2998
  }
@@ -3100,12 +3050,15 @@ function textFromMessage(message) {
3100
3050
  if (message.role === "system") {
3101
3051
  return message.content;
3102
3052
  }
3053
+ if (typeof message.content === "string") {
3054
+ return message.content;
3055
+ }
3103
3056
  return message.content.flatMap((content) => {
3104
3057
  if (content.type === "text") {
3105
3058
  return [content.text];
3106
3059
  }
3107
- if (content.type === "document" && content.source.type === "text") {
3108
- return [content.source.text];
3060
+ if (content.type === "file" && content.data.type === "text") {
3061
+ return [content.data.text];
3109
3062
  }
3110
3063
  return [];
3111
3064
  }).join("\n");
@@ -3129,6 +3082,39 @@ function guardrailDecisionAttributes(decision) {
3129
3082
  return attributes;
3130
3083
  }
3131
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
+
3132
3118
  // src/agent/ids.ts
3133
3119
  function normalizeAgentId(id) {
3134
3120
  if (typeof id !== "string") {
@@ -3143,6 +3129,7 @@ function normalizeAgentId(id) {
3143
3129
 
3144
3130
  // src/agent/agent.ts
3145
3131
  var DEFAULT_MAX_TURNS = 20;
3132
+ var providerOutputSchemas = /* @__PURE__ */ new WeakMap();
3146
3133
  var Agent = class {
3147
3134
  id;
3148
3135
  name;
@@ -3152,13 +3139,15 @@ var Agent = class {
3152
3139
  context;
3153
3140
  temperature;
3154
3141
  maxTokens;
3155
- additionalParams;
3142
+ providerOptions;
3143
+ retries;
3144
+ mcpServers;
3156
3145
  tools;
3157
3146
  toolChoice;
3158
3147
  defaultMaxTurns;
3159
3148
  lifecycle;
3160
3149
  outputSchema;
3161
- observers;
3150
+ observability;
3162
3151
  guardrails;
3163
3152
  middlewares;
3164
3153
  memory;
@@ -3170,26 +3159,34 @@ var Agent = class {
3170
3159
  this.model = resolved.model;
3171
3160
  this.instructions = resolved.instructions;
3172
3161
  const context = (resolved.context ?? []).map(snapshotContextInput);
3173
- assertValidContextIndexes(context);
3162
+ assertValidVectorContexts(context);
3174
3163
  this.context = Object.freeze(context);
3175
3164
  this.temperature = resolved.temperature;
3176
3165
  this.maxTokens = resolved.maxTokens;
3177
- this.additionalParams = cloneFrozenPlainData(resolved.additionalParams);
3178
- const staticTools = dedupeTools(resolved.tools ?? []);
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)];
3179
3172
  const toolIndexes = (resolved.toolIndexes ?? []).map(snapshotToolIndex);
3180
- assertUniqueIndexedToolNames(toolIndexes);
3173
+ const providerTools = (resolved.providerTools ?? []).map(snapshotProviderTool);
3174
+ assertUniqueAgentToolNames({
3175
+ staticTools,
3176
+ providerTools,
3177
+ toolIndexes
3178
+ });
3181
3179
  const toolsByName = new Map(staticTools.map((tool) => [tool.name, tool]));
3182
3180
  for (const index of toolIndexes) {
3183
3181
  for (const tool of index.tools) {
3184
- if (!toolsByName.has(tool.name)) {
3185
- toolsByName.set(tool.name, tool);
3186
- }
3182
+ toolsByName.set(tool.name, tool);
3187
3183
  }
3188
3184
  }
3189
3185
  this.tools = Object.freeze([...toolsByName.values()]);
3190
3186
  const publicToolState = Object.freeze({
3187
+ configuredTools: Object.freeze(configuredTools),
3191
3188
  staticTools: Object.freeze(staticTools),
3192
- providerTools: Object.freeze((resolved.providerTools ?? []).map(snapshotProviderTool)),
3189
+ providerTools: Object.freeze(providerTools),
3193
3190
  toolIndexes: Object.freeze(toolIndexes)
3194
3191
  });
3195
3192
  registerAgentToolState(this, publicToolState, toolsByName);
@@ -3199,23 +3196,24 @@ var Agent = class {
3199
3196
  "maxTurns"
3200
3197
  );
3201
3198
  this.lifecycle = resolved.lifecycle;
3202
- this.outputSchema = cloneFrozenPlainData(resolved.outputSchema);
3203
- this.observers = Object.freeze(
3204
- (resolved.observers ?? []).map((registration) => Object.freeze({ ...registration }))
3205
- );
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);
3206
3204
  this.guardrails = Object.freeze((resolved.guardrails ?? []).map(snapshotGuardrailPolicy));
3207
3205
  this.middlewares = Object.freeze([...resolved.middlewares ?? []]);
3208
- this.memory = snapshotMemoryRegistration(resolved.memory);
3206
+ this.memory = snapshotAgentMemory(resolved.memory);
3209
3207
  }
3210
- generate(input, options = {}) {
3211
- return createGenerateExecution(this, AgentRun.fromAgent(this, input, options)).next();
3208
+ generate(options) {
3209
+ return createGenerateExecution(this, AgentRun.fromAgent(this, options)).next();
3212
3210
  }
3213
- stream(input, options = {}) {
3214
- return createStreamExecution(
3215
- this,
3216
- AgentRun.fromAgent(this, input, options),
3217
- options.includeToolCallDeltas !== false
3218
- );
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);
3219
3217
  }
3220
3218
  resume(pending, decision) {
3221
3219
  assertAgentApprovalDecision(decision);
@@ -3224,27 +3222,8 @@ var Agent = class {
3224
3222
  throw new TypeError("Approval continuation does not belong to this agent.");
3225
3223
  }
3226
3224
  approvalContinuations.delete(pending);
3227
- continuation.run.resolveApproval(decision);
3228
- return continuation.mode === "generate" ? continuation.execution.next() : continuation.execution.segment();
3229
- }
3230
- session(sessionId, options = {}) {
3231
- if (this.memory === void 0) {
3232
- throw new Error(`Agent "${this.id}" has no memory store configured.`);
3233
- }
3234
- const normalized = sessionId.trim();
3235
- if (normalized.length === 0) {
3236
- throw new TypeError("Session id must be a non-empty string.");
3237
- }
3238
- const context = {
3239
- sessionId: normalized
3240
- };
3241
- if (options.userId !== void 0) {
3242
- context.userId = options.userId;
3243
- }
3244
- if (options.metadata !== void 0) {
3245
- context.metadata = cloneFrozenPlainData(options.metadata);
3246
- }
3247
- return new AgentSession(this, context);
3225
+ continuation.resolve(decision);
3226
+ return continuation.mode === "generate" ? continuation.resume() : continuation.resume();
3248
3227
  }
3249
3228
  asTool(options) {
3250
3229
  const description = options.description ?? this.description ?? `Prompt the ${options.name} agent.`;
@@ -3254,13 +3233,14 @@ var Agent = class {
3254
3233
  inputSchema: z.object({
3255
3234
  prompt: z.string().describe("The prompt to send to the agent.")
3256
3235
  }),
3257
- outputSchema: z.string(),
3258
3236
  execute: async ({ prompt }, context) => {
3259
3237
  if (options.stream === true && context.emitStreamEvent !== void 0 && this.model.capabilities.streaming && isStreamingCompletionModel(this.model)) {
3260
- let output = "";
3261
- const childStream = this.stream(prompt, {
3238
+ let completed = false;
3239
+ let output;
3240
+ const childStream = this.stream({
3241
+ prompt,
3262
3242
  maxTurns: options.maxTurns,
3263
- includeToolCallDeltas: context.includeToolCallDeltas !== false
3243
+ abortSignal: context.abortSignal
3264
3244
  });
3265
3245
  for await (const event of childStream) {
3266
3246
  if (event.type === "approval_required") {
@@ -3280,13 +3260,27 @@ var Agent = class {
3280
3260
  streamEvent.agentName = this.name;
3281
3261
  }
3282
3262
  await context.emitStreamEvent(streamEvent);
3263
+ if (event.type === "error") {
3264
+ throw event.error;
3265
+ }
3283
3266
  if (event.type === "final") {
3284
- output = event.output;
3267
+ if (event.result.status === "blocked") {
3268
+ throw new AgentRunBlockedError(event.result);
3269
+ }
3270
+ output = event.result.output;
3271
+ completed = true;
3285
3272
  }
3286
3273
  }
3274
+ if (!completed) {
3275
+ throw new Error(`Agent tool "${options.name}" ended without a final result.`);
3276
+ }
3287
3277
  return output;
3288
3278
  }
3289
- const response = await this.generate(prompt, { maxTurns: options.maxTurns });
3279
+ const response = await this.generate({
3280
+ prompt,
3281
+ maxTurns: options.maxTurns,
3282
+ abortSignal: context.abortSignal
3283
+ });
3290
3284
  if (response.status === "approval_required") {
3291
3285
  await cancelAgentApproval(
3292
3286
  response,
@@ -3296,6 +3290,9 @@ var Agent = class {
3296
3290
  `Agent tool "${options.name}" cannot suspend for tool approval. Run the agent directly to handle approvals.`
3297
3291
  );
3298
3292
  }
3293
+ if (response.status === "blocked") {
3294
+ throw new AgentRunBlockedError(response);
3295
+ }
3299
3296
  return response.output;
3300
3297
  }
3301
3298
  });
@@ -3329,20 +3326,25 @@ function getResolvedAgentOptions(agent) {
3329
3326
  context: [...agent.context],
3330
3327
  temperature: agent.temperature,
3331
3328
  maxTokens: agent.maxTokens,
3332
- additionalParams: agent.additionalParams,
3333
- tools: [...toolState.staticTools],
3329
+ providerOptions: agent.providerOptions,
3330
+ retries: agent.retries,
3331
+ tools: [...toolState.configuredTools],
3332
+ mcpServers: [...agent.mcpServers],
3334
3333
  providerTools: [...toolState.providerTools],
3335
3334
  toolIndexes: [...toolState.toolIndexes],
3336
3335
  toolChoice: agent.toolChoice,
3337
3336
  defaultMaxTurns: agent.defaultMaxTurns,
3338
3337
  lifecycle: agent.lifecycle,
3339
3338
  outputSchema: agent.outputSchema,
3340
- observers: [...agent.observers],
3339
+ observability: agent.observability,
3341
3340
  guardrails: [...agent.guardrails],
3342
3341
  middlewares: [...agent.middlewares],
3343
3342
  memory: agent.memory
3344
3343
  };
3345
3344
  }
3345
+ function getAgentProviderOutputSchema(agent) {
3346
+ return providerOutputSchemas.get(agent);
3347
+ }
3346
3348
  function resolveAgentOptions(options) {
3347
3349
  if (isInternalAgentOptions(options)) {
3348
3350
  return options;
@@ -3356,21 +3358,23 @@ function resolveAgentOptions(options) {
3356
3358
  } else if (isToolIndex(tool)) {
3357
3359
  toolIndexes.push(tool);
3358
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)) {
3359
3363
  throw new TypeError(
3360
- "Invalid tool index: search, searchIds, asTool, tools, and a numeric topK are required."
3364
+ `MCP tool "${tool.name}" must be registered through Agent.mcpServers, not Agent.tools.`
3361
3365
  );
3362
3366
  } else {
3363
- toolsByName.set(tool.name, tool);
3364
- }
3365
- }
3366
- for (const server of options.mcpServers ?? []) {
3367
- for (const tool of server.tools) {
3368
- toolsByName.set(tool.name, tool);
3367
+ addUniqueTool(toolsByName, tool, "local tool");
3369
3368
  }
3370
3369
  }
3371
3370
  if (options.skills !== void 0) {
3372
3371
  for (const tool of options.skills.tools) {
3373
- toolsByName.set(tool.name, tool);
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");
3374
3378
  }
3375
3379
  }
3376
3380
  const memory = resolveAgentMemory(options);
@@ -3384,54 +3388,94 @@ function resolveAgentOptions(options) {
3384
3388
  context: [...options.context ?? []],
3385
3389
  temperature: options.temperature,
3386
3390
  maxTokens: options.maxTokens,
3387
- additionalParams: options.additionalParams,
3391
+ providerOptions: options.providerOptions,
3392
+ retries: options.retries,
3388
3393
  tools: [...toolsByName.values()],
3394
+ mcpServers: [...options.mcpServers ?? []],
3389
3395
  providerTools,
3390
3396
  toolIndexes,
3391
3397
  toolChoice: options.toolChoice,
3392
3398
  defaultMaxTurns: options.maxTurns,
3393
3399
  lifecycle: options.lifecycle,
3394
- outputSchema: options.outputSchema === void 0 ? void 0 : toProviderJsonSchema(options.outputSchema),
3395
- observers: (options.observers ?? []).map(
3396
- (input) => "observer" in input ? { observer: input.observer, failOnObserverError: input.failOnObserverError } : { observer: input }
3397
- ),
3400
+ outputSchema: options.outputSchema,
3401
+ observability: options.observability,
3398
3402
  guardrails: options.guardrails === void 0 ? [] : appendGuardrailPolicies([], options.guardrails),
3399
3403
  middlewares: [...options.middlewares ?? []],
3400
3404
  memory
3401
3405
  };
3402
3406
  }
3403
- function assertUniqueIndexedToolNames(indexes) {
3407
+ function assertUniqueAgentToolNames(options) {
3404
3408
  const owners = /* @__PURE__ */ new Map();
3405
- for (const [indexPosition, index] of indexes.entries()) {
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()) {
3406
3416
  if (!isToolIndex(index)) {
3407
- throw new TypeError(
3408
- "Invalid tool index: search, searchIds, asTool, tools, and a numeric topK are required."
3409
- );
3417
+ throw new TypeError("Invalid tool index: search, tools, and a numeric topK are required.");
3410
3418
  }
3411
3419
  assertPositiveSearchLimit(index.topK);
3412
- assertFiniteSearchThreshold(index.threshold);
3420
+ assertFiniteMinScore(index.minScore);
3413
3421
  for (const tool of index.tools) {
3414
- const existingPosition = owners.get(tool.name);
3415
- if (existingPosition !== void 0) {
3416
- if (existingPosition === indexPosition) {
3417
- throw new TypeError(
3418
- `Tool "${tool.name}" is registered more than once by tool index ${indexPosition + 1}. Tool names must be unique within each index.`
3419
- );
3420
- }
3422
+ if (isMcpTool(tool)) {
3421
3423
  throw new TypeError(
3422
- `Tool "${tool.name}" is registered by multiple tool indexes (${existingPosition + 1} and ${indexPosition + 1}). Tool names must be unique across indexes.`
3424
+ `MCP tool "${tool.name}" must be registered through Agent.mcpServers, not a tool index.`
3423
3425
  );
3424
3426
  }
3425
- owners.set(tool.name, indexPosition);
3427
+ registerToolOwner(owners, tool.name, `tool index ${indexPosition + 1}`);
3426
3428
  }
3427
3429
  }
3428
3430
  }
3429
- function assertValidContextIndexes(inputs) {
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) {
3430
3447
  for (const input of inputs) {
3431
- if (!isContextIndex(input)) continue;
3448
+ if (!isVectorContext(input)) continue;
3432
3449
  assertPositiveSearchLimit(input.topK);
3433
- assertFiniteSearchThreshold(input.threshold);
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
+ );
3434
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
+ });
3435
3479
  }
3436
3480
  function isInternalAgentOptions(options) {
3437
3481
  return options[resolvedAgentOptions] === true;
@@ -3447,7 +3491,7 @@ function resolveAgentMemory(options) {
3447
3491
  "Memory compaction requires a store with the optional compaction capability."
3448
3492
  );
3449
3493
  }
3450
- return { store, options: resolvedOptions };
3494
+ return { store, ...resolvedOptions };
3451
3495
  }
3452
3496
  var approvalContinuations = /* @__PURE__ */ new WeakMap();
3453
3497
  function assertAgentApprovalDecision(decision) {
@@ -3470,7 +3514,13 @@ function createGenerateExecution(agent, run) {
3470
3514
  return outcome.result;
3471
3515
  }
3472
3516
  const pending = run.approvalResult();
3473
- approvalContinuations.set(pending, { agent, run, mode: "generate", execution });
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
+ });
3474
3524
  return pending;
3475
3525
  },
3476
3526
  async cancel(reason) {
@@ -3481,10 +3531,10 @@ function createGenerateExecution(agent, run) {
3481
3531
  return execution;
3482
3532
  }
3483
3533
  var StreamExecution = class {
3484
- constructor(agent, run, includeToolCallDeltas) {
3534
+ constructor(agent, run) {
3485
3535
  this.agent = agent;
3486
3536
  this.run = run;
3487
- this.iterator = run.events(includeToolCallDeltas)[Symbol.asyncIterator]();
3537
+ this.iterator = run.events()[Symbol.asyncIterator]();
3488
3538
  }
3489
3539
  agent;
3490
3540
  run;
@@ -3518,9 +3568,10 @@ var StreamExecution = class {
3518
3568
  const pending = this.run.approvalEvent();
3519
3569
  approvalContinuations.set(pending, {
3520
3570
  agent: this.agent,
3521
- run: this.run,
3522
3571
  mode: "stream",
3523
- execution: this
3572
+ resolve: (decision) => this.run.resolveApproval(decision),
3573
+ resume: () => this.segment(),
3574
+ cancel: (reason) => this.cancel(reason)
3524
3575
  });
3525
3576
  yield pending;
3526
3577
  return;
@@ -3548,8 +3599,8 @@ var StreamExecution = class {
3548
3599
  }
3549
3600
  }
3550
3601
  };
3551
- function createStreamExecution(agent, run, includeToolCallDeltas) {
3552
- return new StreamExecution(agent, run, includeToolCallDeltas).segment();
3602
+ function createStreamExecution(agent, run) {
3603
+ return new StreamExecution(agent, run).segment();
3553
3604
  }
3554
3605
  var DefaultAgentStream = class {
3555
3606
  constructor(execution) {
@@ -3591,66 +3642,10 @@ async function cancelAgentApproval(pending, reason) {
3591
3642
  return;
3592
3643
  }
3593
3644
  approvalContinuations.delete(pending);
3594
- await continuation.execution.cancel(reason);
3645
+ await continuation.cancel(reason);
3595
3646
  }
3596
- var AgentSession = class {
3597
- constructor(agent, context) {
3598
- this.agent = agent;
3599
- this.context = context;
3600
- }
3601
- agent;
3602
- context;
3603
- generate(input, options = {}) {
3604
- if (Array.isArray(input)) {
3605
- throw new TypeError("AgentSession.generate does not accept Message[] transcripts.");
3606
- }
3607
- const run = AgentRun.fromAgent(this.agent, input, {
3608
- ...options,
3609
- memoryContext: this.context
3610
- });
3611
- return createGenerateExecution(this.agent, run).next();
3612
- }
3613
- stream(input, options = {}) {
3614
- if (Array.isArray(input)) {
3615
- throw new TypeError("AgentSession.stream does not accept Message[] transcripts.");
3616
- }
3617
- return createStreamExecution(
3618
- this.agent,
3619
- AgentRun.fromAgent(this.agent, input, { ...options, memoryContext: this.context }),
3620
- options.includeToolCallDeltas !== false
3621
- );
3622
- }
3623
- async messages() {
3624
- const memory = this.agent.memory;
3625
- if (memory === void 0) {
3626
- throw new Error(`Agent "${this.agent.id}" has no memory store configured.`);
3627
- }
3628
- return memory.store.load(this.context);
3629
- }
3630
- async contextUsage() {
3631
- const messages = await this.messages();
3632
- for (let index = messages.length - 1; index >= 0; index -= 1) {
3633
- const message = messages[index];
3634
- if (message === void 0) {
3635
- continue;
3636
- }
3637
- const generation = getAssistantGenerationMetadata(message);
3638
- if (generation !== void 0) {
3639
- return generation.contextUsage;
3640
- }
3641
- }
3642
- return void 0;
3643
- }
3644
- async clear() {
3645
- const memory = this.agent.memory;
3646
- if (memory === void 0) {
3647
- throw new Error(`Agent "${this.agent.id}" has no memory store configured.`);
3648
- }
3649
- await memory.store.clear(this.context);
3650
- }
3651
- };
3652
3647
  function snapshotContextInput(input) {
3653
- if (!isContextIndex(input)) {
3648
+ if (!isVectorContext(input)) {
3654
3649
  return Object.freeze({
3655
3650
  id: input.id,
3656
3651
  text: input.text,
@@ -3658,14 +3653,23 @@ function snapshotContextInput(input) {
3658
3653
  });
3659
3654
  }
3660
3655
  const format = input.format;
3661
- return Object.freeze({
3662
- kind: "context-index",
3663
- index: input.index,
3656
+ const shared = {
3657
+ kind: "vector-context",
3658
+ store: input.store,
3664
3659
  topK: input.topK,
3665
- ...input.threshold === void 0 ? {} : { threshold: input.threshold },
3660
+ ...input.minScore === void 0 ? {} : { minScore: input.minScore },
3666
3661
  ...input.filter === void 0 ? {} : { filter: cloneFrozenPlainData(input.filter) },
3662
+ ...input.retries === void 0 ? {} : { retries: cloneFrozenPlainData(input.retries) },
3667
3663
  ...format === void 0 ? {} : { format: (result) => format.call(input, result) }
3668
- });
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
+ );
3669
3673
  }
3670
3674
  function snapshotProviderTool(tool) {
3671
3675
  return Object.freeze({
@@ -3673,17 +3677,61 @@ function snapshotProviderTool(tool) {
3673
3677
  ...tool.configuration === void 0 ? {} : { configuration: cloneFrozenPlainData(tool.configuration) }
3674
3678
  });
3675
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
+ }
3676
3726
  function snapshotToolIndex(index) {
3677
3727
  const inspect = index.inspect;
3678
3728
  return Object.freeze({
3679
3729
  kind: "tool-index",
3680
3730
  tools: Object.freeze([...index.tools]),
3681
3731
  topK: index.topK,
3682
- ...index.threshold === void 0 ? {} : { threshold: index.threshold },
3732
+ ...index.minScore === void 0 ? {} : { minScore: index.minScore },
3683
3733
  ...index.filter === void 0 ? {} : { filter: cloneFrozenPlainData(index.filter) },
3684
- search: (request) => index.search(request),
3685
- searchIds: (request) => index.searchIds(request),
3686
- asTool: (options) => index.asTool(options),
3734
+ search: (options) => index.search(options),
3687
3735
  ...inspect === void 0 ? {} : { inspect: (request) => inspect.call(index, request) }
3688
3736
  });
3689
3737
  }
@@ -3694,17 +3742,20 @@ function snapshotGuardrailPolicy(policy) {
3694
3742
  output: Object.freeze([...policy.output])
3695
3743
  });
3696
3744
  }
3697
- function snapshotMemoryRegistration(memory) {
3745
+ function snapshotAgentMemory(memory) {
3698
3746
  if (memory === void 0) {
3699
3747
  return void 0;
3700
3748
  }
3701
- const compaction = memory.options.compaction === void 0 ? void 0 : Object.freeze({ ...memory.options.compaction });
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
+ });
3702
3755
  return Object.freeze({
3703
3756
  store: memory.store,
3704
- options: Object.freeze({
3705
- ...memory.options,
3706
- ...compaction === void 0 ? {} : { compaction }
3707
- })
3757
+ savePolicy: memory.savePolicy,
3758
+ ...compaction === void 0 ? {} : { compaction }
3708
3759
  });
3709
3760
  }
3710
3761
  function cloneFrozenPlainData(value) {
@@ -3723,26 +3774,20 @@ function cloneFrozenPlainData(value) {
3723
3774
  );
3724
3775
  return Object.freeze(clone);
3725
3776
  }
3726
- function dedupeTools(tools) {
3727
- const byName = /* @__PURE__ */ new Map();
3728
- for (const tool of tools) {
3729
- byName.set(tool.name, tool);
3730
- }
3731
- return [...byName.values()];
3732
- }
3733
3777
 
3734
3778
  export {
3735
3779
  MaxTurnsError,
3736
3780
  AgentRunCancelledError,
3781
+ AgentRunBlockedError,
3737
3782
  getAgentToolState,
3738
3783
  createHook,
3739
3784
  getAgentApprovalRequestDetails,
3740
- createContextIndex,
3741
- isContextIndex,
3785
+ createVectorContext,
3786
+ isVectorContext,
3742
3787
  withInternalAgentRunOptions,
3743
3788
  Agent,
3744
3789
  createResolvedAgent,
3745
3790
  getResolvedAgentOptions,
3746
3791
  cancelAgentApproval
3747
3792
  };
3748
- //# sourceMappingURL=chunk-IL3ZSNJI.js.map
3793
+ //# sourceMappingURL=chunk-DBSCKTUL.js.map