@anvia/core 1.2.1 → 1.3.0

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 (169) hide show
  1. package/README.md +16 -0
  2. package/dist/agent/agent-tool.js +10 -8
  3. package/dist/agent/agent.js +24 -22
  4. package/dist/agent/index.d.ts +12 -12
  5. package/dist/agent/index.js +30 -28
  6. package/dist/agent/interactions/index.d.ts +1 -1
  7. package/dist/agent/resolve-options.js +8 -8
  8. package/dist/agent/resolved-agent.js +25 -23
  9. package/dist/agent/team/agent-team.js +30 -28
  10. package/dist/agent/team/index.js +30 -28
  11. package/dist/agent/tool-catalog.js +7 -7
  12. package/dist/{agent-C9VhENdj.d.ts → agent-D3iyrJQb.d.ts} +9 -9
  13. package/dist/{chunk-UTAB3XQI.js → chunk-2JZV4LUS.js} +2 -2
  14. package/dist/{chunk-G336L2IE.js → chunk-4BDSO4PQ.js} +2 -2
  15. package/dist/{chunk-KZGSXJKU.js → chunk-4VDDYI6P.js} +4 -4
  16. package/dist/{chunk-LKIABZNR.js → chunk-5SJBSCG2.js} +3 -3
  17. package/dist/{chunk-MHOJJYDK.js → chunk-647TQE3E.js} +2 -2
  18. package/dist/chunk-6OO5C5GW.js +32 -0
  19. package/dist/chunk-6OO5C5GW.js.map +1 -0
  20. package/dist/{chunk-UOGM62JL.js → chunk-7TUAAGVR.js} +3 -3
  21. package/dist/{chunk-RT5LUEO3.js → chunk-A3DGCDGF.js} +11 -11
  22. package/dist/{chunk-J4SINPUA.js → chunk-B57NNDEF.js} +23 -11
  23. package/dist/chunk-B57NNDEF.js.map +1 -0
  24. package/dist/{chunk-B47EXUHL.js → chunk-CJKGTEN4.js} +2 -2
  25. package/dist/{chunk-HP34GRQX.js → chunk-E44DRLUL.js} +2 -2
  26. package/dist/{chunk-T4KS577P.js → chunk-FSBDE6RF.js} +7 -6
  27. package/dist/chunk-FSBDE6RF.js.map +1 -0
  28. package/dist/{chunk-F3E2RLC7.js → chunk-GE46NHN4.js} +3 -3
  29. package/dist/{chunk-CKKNO4XB.js → chunk-GSVOMQEE.js} +2 -2
  30. package/dist/{chunk-IDNL6IH4.js → chunk-HJ6KTQTZ.js} +7 -1
  31. package/dist/chunk-HJ6KTQTZ.js.map +1 -0
  32. package/dist/{chunk-T4IAJJUU.js → chunk-IYDGPF3C.js} +3 -3
  33. package/dist/{chunk-PPJ7SYQL.js → chunk-JMNIWUFV.js} +3 -3
  34. package/dist/{chunk-72LBHKYP.js → chunk-JWD43K7W.js} +2 -2
  35. package/dist/{chunk-MNYMLWWA.js → chunk-KNZNSNP4.js} +2 -2
  36. package/dist/{chunk-4S4OECPW.js → chunk-KRUDSNFN.js} +11 -11
  37. package/dist/{chunk-O6DTOCBM.js → chunk-KX2TRKO2.js} +2 -2
  38. package/dist/{chunk-BDDC72GF.js → chunk-LJGQ6VQB.js} +2 -2
  39. package/dist/chunk-NMPDZTBM.js +1 -0
  40. package/dist/chunk-NMPDZTBM.js.map +1 -0
  41. package/dist/{chunk-6N4ENZO4.js → chunk-OYHU4HNC.js} +2 -2
  42. package/dist/{chunk-Y7JTHNCU.js → chunk-RFFOL6ON.js} +2 -2
  43. package/dist/{chunk-47NTHIVB.js → chunk-SCFWN3T2.js} +2 -1
  44. package/dist/chunk-SCFWN3T2.js.map +1 -0
  45. package/dist/{chunk-QUS6S2NB.js → chunk-SIXS4CCU.js} +2 -2
  46. package/dist/{chunk-IV6YQTY2.js → chunk-T3ZOZEAB.js} +2 -2
  47. package/dist/{chunk-AOG6KSV4.js → chunk-T4UW4SUK.js} +3 -3
  48. package/dist/{chunk-BUPC72Y2.js → chunk-V5DWNXVH.js} +3 -3
  49. package/dist/{chunk-SIYZDPVH.js → chunk-VKRGWGA4.js} +39 -30
  50. package/dist/chunk-VKRGWGA4.js.map +1 -0
  51. package/dist/{chunk-5FCZ64HM.js → chunk-WCWSPU74.js} +3 -3
  52. package/dist/{chunk-XV3DH5GC.js → chunk-Y365ABZY.js} +5 -5
  53. package/dist/{chunk-BDKFFFVX.js → chunk-YMTBHHLQ.js} +64 -15
  54. package/dist/chunk-YMTBHHLQ.js.map +1 -0
  55. package/dist/{chunk-XJRNBTIV.js → chunk-YNA3UR42.js} +2 -2
  56. package/dist/chunk-YOLOFTAY.js +144 -0
  57. package/dist/chunk-YOLOFTAY.js.map +1 -0
  58. package/dist/{chunk-TIZGADU4.js → chunk-ZGDUEOSH.js} +7 -7
  59. package/dist/{chunk-TIZGADU4.js.map → chunk-ZGDUEOSH.js.map} +1 -1
  60. package/dist/completion/generate-completion.js +6 -4
  61. package/dist/completion/index.d.ts +3 -4
  62. package/dist/completion/index.js +6 -4
  63. package/dist/completion/stream-accumulator.js +2 -2
  64. package/dist/completion/types.js +1 -1
  65. package/dist/{dynamic-tools-CNHSPXr1.d.ts → dynamic-tools-BXXLc34l.d.ts} +3 -3
  66. package/dist/evals/advanced-metrics.js +9 -7
  67. package/dist/evals/cli.js +8 -6
  68. package/dist/evals/index.d.ts +5 -5
  69. package/dist/evals/index.js +12 -10
  70. package/dist/evals/judge.js +8 -6
  71. package/dist/evals/metrics.js +8 -6
  72. package/dist/evals/runner.js +7 -5
  73. package/dist/extractor/extractor.js +7 -5
  74. package/dist/extractor/index.d.ts +1 -1
  75. package/dist/extractor/index.js +7 -5
  76. package/dist/guardrails/index.d.ts +4 -4
  77. package/dist/image-generation/index.d.ts +1 -1
  78. package/dist/index.d.ts +13 -13
  79. package/dist/index.js +44 -38
  80. package/dist/internal/agent-runtime/agent-run.js +20 -18
  81. package/dist/internal/agent-runtime/continuation-state.js +6 -4
  82. package/dist/internal/agent-runtime/interaction-suspension.js +6 -4
  83. package/dist/internal/agent-runtime/memory.js +8 -6
  84. package/dist/internal/agent-runtime/prepared-tool-call.js +2 -2
  85. package/dist/internal/agent-runtime/retrieval.js +5 -5
  86. package/dist/internal/agent-runtime/tool-execution.js +16 -14
  87. package/dist/internal/agent.d.ts +45 -12
  88. package/dist/internal/agent.js +25 -23
  89. package/dist/internal/completion-request.js +2 -2
  90. package/dist/internal/team-runtime/member.js +7 -5
  91. package/dist/internal/team-runtime/run.js +28 -26
  92. package/dist/internal/team-runtime/tools.js +4 -4
  93. package/dist/mcp/index.d.ts +4 -4
  94. package/dist/memory/compaction.js +7 -5
  95. package/dist/memory/index.d.ts +3 -3
  96. package/dist/memory/index.js +7 -5
  97. package/dist/{middleware-CWjnMbiH.d.ts → middleware-DORuwSy-.d.ts} +67 -4
  98. package/dist/observability/group.js +7 -5
  99. package/dist/observability/index.d.ts +5 -5
  100. package/dist/observability/index.js +7 -5
  101. package/dist/pipeline/index.d.ts +10 -10
  102. package/dist/pipeline/index.js +8 -6
  103. package/dist/pipeline/pipeline.js +8 -6
  104. package/dist/provider-output-error-CQD0MWey.d.ts +221 -0
  105. package/dist/schema/index.js +7 -0
  106. package/dist/schema/standard-json-schema.js +10 -0
  107. package/dist/schema/standard-json-schema.js.map +1 -0
  108. package/dist/schema/standard-schema.js +11 -0
  109. package/dist/schema/standard-schema.js.map +1 -0
  110. package/dist/skills/index.d.ts +4 -4
  111. package/dist/skills/index.js +12 -12
  112. package/dist/skills/load.js +11 -11
  113. package/dist/skills/tools.js +10 -10
  114. package/dist/speech-generation/index.d.ts +1 -1
  115. package/dist/speech-generation/index.js +1 -1
  116. package/dist/{text-GbW4WYMg.d.ts → text-CklbSG7K.d.ts} +1 -1
  117. package/dist/{think-tool-YWsV98I5.d.ts → think-tool-2unWbq1w.d.ts} +1 -1
  118. package/dist/tool/create-tool.js +3 -3
  119. package/dist/tool/dynamic-tools.js +6 -6
  120. package/dist/tool/index.d.ts +8 -8
  121. package/dist/tool/index.js +11 -11
  122. package/dist/tool/question-tool.js +4 -4
  123. package/dist/tool/think-tool.js +4 -4
  124. package/dist/tool/tool.js +1 -1
  125. package/dist/{tool-DQMZpZSS.d.ts → tool-D_jV3cRZ.d.ts} +38 -1
  126. package/dist/transcription/index.d.ts +1 -1
  127. package/dist/{types-DfRPfehE.d.ts → types-0t3BczrD.d.ts} +2 -2
  128. package/dist/{types-CODGMHnp.d.ts → types-ChyQISt-.d.ts} +1 -1
  129. package/dist/{types-Bqw0AuFl.d.ts → types-CqiX-4_C.d.ts} +1 -1
  130. package/dist/{types-C1xYKXF2.d.ts → types-Cu2tEf3V.d.ts} +1 -1
  131. package/dist/{types-CiHjqE6J.d.ts → types-DYqZKDA8.d.ts} +140 -0
  132. package/dist/{types-CafU6Ux5.d.ts → types-DhWxTobb.d.ts} +37 -1
  133. package/dist/vector-store/index.d.ts +4 -4
  134. package/dist/vector-store/index.js +8 -8
  135. package/package.json +9 -1
  136. package/dist/chunk-47NTHIVB.js.map +0 -1
  137. package/dist/chunk-BDKFFFVX.js.map +0 -1
  138. package/dist/chunk-IDNL6IH4.js.map +0 -1
  139. package/dist/chunk-J4SINPUA.js.map +0 -1
  140. package/dist/chunk-SIYZDPVH.js.map +0 -1
  141. package/dist/chunk-T4KS577P.js.map +0 -1
  142. package/dist/provider-output-error-OQ4fjw5W.d.ts +0 -107
  143. /package/dist/{chunk-UTAB3XQI.js.map → chunk-2JZV4LUS.js.map} +0 -0
  144. /package/dist/{chunk-G336L2IE.js.map → chunk-4BDSO4PQ.js.map} +0 -0
  145. /package/dist/{chunk-KZGSXJKU.js.map → chunk-4VDDYI6P.js.map} +0 -0
  146. /package/dist/{chunk-LKIABZNR.js.map → chunk-5SJBSCG2.js.map} +0 -0
  147. /package/dist/{chunk-MHOJJYDK.js.map → chunk-647TQE3E.js.map} +0 -0
  148. /package/dist/{chunk-UOGM62JL.js.map → chunk-7TUAAGVR.js.map} +0 -0
  149. /package/dist/{chunk-RT5LUEO3.js.map → chunk-A3DGCDGF.js.map} +0 -0
  150. /package/dist/{chunk-B47EXUHL.js.map → chunk-CJKGTEN4.js.map} +0 -0
  151. /package/dist/{chunk-HP34GRQX.js.map → chunk-E44DRLUL.js.map} +0 -0
  152. /package/dist/{chunk-F3E2RLC7.js.map → chunk-GE46NHN4.js.map} +0 -0
  153. /package/dist/{chunk-CKKNO4XB.js.map → chunk-GSVOMQEE.js.map} +0 -0
  154. /package/dist/{chunk-T4IAJJUU.js.map → chunk-IYDGPF3C.js.map} +0 -0
  155. /package/dist/{chunk-PPJ7SYQL.js.map → chunk-JMNIWUFV.js.map} +0 -0
  156. /package/dist/{chunk-72LBHKYP.js.map → chunk-JWD43K7W.js.map} +0 -0
  157. /package/dist/{chunk-MNYMLWWA.js.map → chunk-KNZNSNP4.js.map} +0 -0
  158. /package/dist/{chunk-4S4OECPW.js.map → chunk-KRUDSNFN.js.map} +0 -0
  159. /package/dist/{chunk-O6DTOCBM.js.map → chunk-KX2TRKO2.js.map} +0 -0
  160. /package/dist/{chunk-BDDC72GF.js.map → chunk-LJGQ6VQB.js.map} +0 -0
  161. /package/dist/{chunk-6N4ENZO4.js.map → chunk-OYHU4HNC.js.map} +0 -0
  162. /package/dist/{chunk-Y7JTHNCU.js.map → chunk-RFFOL6ON.js.map} +0 -0
  163. /package/dist/{chunk-QUS6S2NB.js.map → chunk-SIXS4CCU.js.map} +0 -0
  164. /package/dist/{chunk-IV6YQTY2.js.map → chunk-T3ZOZEAB.js.map} +0 -0
  165. /package/dist/{chunk-AOG6KSV4.js.map → chunk-T4UW4SUK.js.map} +0 -0
  166. /package/dist/{chunk-BUPC72Y2.js.map → chunk-V5DWNXVH.js.map} +0 -0
  167. /package/dist/{chunk-5FCZ64HM.js.map → chunk-WCWSPU74.js.map} +0 -0
  168. /package/dist/{chunk-XV3DH5GC.js.map → chunk-Y365ABZY.js.map} +0 -0
  169. /package/dist/{chunk-XJRNBTIV.js.map → chunk-YNA3UR42.js.map} +0 -0
@@ -7,7 +7,7 @@ import {
7
7
  } from "./chunk-ZPJFXRQZ.js";
8
8
  import {
9
9
  generateCompletion
10
- } from "./chunk-BDKFFFVX.js";
10
+ } from "./chunk-YMTBHHLQ.js";
11
11
 
12
12
  // src/memory/compaction.ts
13
13
  var defaultSummaryInstructions = `Summarize the conversation transcript for use as future agent memory.
@@ -209,4 +209,4 @@ export {
209
209
  createMemoryCompactionSummary,
210
210
  cumulativeCompactedMessageCount
211
211
  };
212
- //# sourceMappingURL=chunk-HP34GRQX.js.map
212
+ //# sourceMappingURL=chunk-E44DRLUL.js.map
@@ -8,17 +8,18 @@ import {
8
8
 
9
9
  // src/internal/team-runtime/member.ts
10
10
  function memberSummary(member) {
11
- return {
11
+ const summary = {
12
12
  instanceId: member.instanceId,
13
13
  agentId: member.agent.id,
14
14
  name: member.name,
15
15
  depth: member.depth,
16
16
  status: member.status,
17
- usage: lifecycleSnapshot(member.usage),
18
- ...member.parentInstanceId === void 0 ? {} : { parentInstanceId: member.parentInstanceId },
19
- ...member.outcome === void 0 ? {} : { outcome: lifecycleSnapshot(member.outcome) },
20
- ...member.error === void 0 ? {} : { error: member.error }
17
+ usage: lifecycleSnapshot(member.usage)
21
18
  };
19
+ if (member.parentInstanceId !== void 0) summary.parentInstanceId = member.parentInstanceId;
20
+ if (member.outcome !== void 0) summary.outcome = lifecycleSnapshot(member.outcome);
21
+ if (member.error !== void 0) summary.error = member.error;
22
+ return summary;
22
23
  }
23
24
  function steeringMessages(input) {
24
25
  if (typeof input !== "object" || input === null || input.prompt === void 0 === (input.messages === void 0)) {
@@ -55,4 +56,4 @@ export {
55
56
  steeringMessages,
56
57
  agentMessageInput
57
58
  };
58
- //# sourceMappingURL=chunk-T4KS577P.js.map
59
+ //# sourceMappingURL=chunk-FSBDE6RF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/team-runtime/member.ts"],"sourcesContent":["import type {\n AgentTeamMemberStatus,\n AgentTeamMemberSummary,\n AgentTeamMessage,\n} from \"../../agent/team/types\";\nimport type { AgentOutcome, AgentSteerInput } from \"../../agent/run-types\";\nimport type { Message, UserMessage } from \"../../completion\";\nimport { parseMessage, parseMessages, Usage } from \"../../completion\";\nimport type { Writable } from \"../type-utils\";\nimport type { AgentRun } from \"../agent-runtime/agent-run\";\nimport type { Agent } from \"../../agent/agent\";\nimport { lifecycleSnapshot } from \"../../agent/lifecycle\";\n\nexport type TeamInput = {\n id: string;\n messages: UserMessage[];\n message?: AgentTeamMessage;\n submitted: boolean;\n};\n\nexport type TeamMember = {\n instanceId: string;\n parentInstanceId?: string;\n depth: number;\n definition: Agent<unknown>;\n name: string;\n agent: Agent<unknown>;\n status: AgentTeamMemberStatus;\n history: Message[];\n inputs: TeamInput[];\n receipts: Map<string, TeamInput>;\n controller: AbortController;\n release?: (() => void) | undefined;\n task?: Promise<void> | undefined;\n activeRun?: AgentRun<unknown> | undefined;\n runId?: string | undefined;\n outcome?: Exclude<AgentOutcome<unknown>, { type: \"interaction\" }>;\n error?: unknown;\n usage: Usage;\n notifications: { from: string; type: \"message\" | \"outcome\"; id: string }[];\n};\n\nexport function memberSummary(member: TeamMember): AgentTeamMemberSummary {\n const summary: Writable<AgentTeamMemberSummary> = {\n instanceId: member.instanceId,\n agentId: member.agent.id,\n name: member.name,\n depth: member.depth,\n status: member.status,\n usage: lifecycleSnapshot(member.usage),\n };\n if (member.parentInstanceId !== undefined) summary.parentInstanceId = member.parentInstanceId;\n if (member.outcome !== undefined) summary.outcome = lifecycleSnapshot(member.outcome);\n if (member.error !== undefined) summary.error = member.error;\n return summary;\n}\n\nexport function steeringMessages(input: AgentSteerInput): UserMessage[] {\n if (\n typeof input !== \"object\" ||\n input === null ||\n (input.prompt === undefined) === (input.messages === undefined)\n ) {\n throw new TypeError(\"Agent team steering requires exactly one of prompt or messages.\");\n }\n const messages =\n input.prompt === undefined\n ? parseMessages(input.messages)\n : [\n parseMessage(\n typeof input.prompt === \"string\"\n ? { role: \"user\", content: input.prompt }\n : input.prompt,\n ),\n ];\n if (messages.length === 0 || messages.some((message) => message.role !== \"user\")) {\n throw new TypeError(\"Agent team steering requires user messages.\");\n }\n return messages as UserMessage[];\n}\n\nexport function agentMessageInput(message: AgentTeamMessage): TeamInput {\n return {\n id: message.id,\n submitted: false,\n message,\n messages: [\n {\n role: \"user\",\n content: `Message from another agent (not a user approval):\\n${JSON.stringify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AAAA,EACF;AACF;","names":[]}
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  createMemoryCompactionSummary,
3
3
  cumulativeCompactedMessageCount
4
- } from "./chunk-HP34GRQX.js";
4
+ } from "./chunk-E44DRLUL.js";
5
5
  import {
6
6
  MemoryCompactionConflictError,
7
7
  MemoryCompactionError
8
8
  } from "./chunk-LQJ4KHMY.js";
9
9
  import {
10
10
  Usage
11
- } from "./chunk-IDNL6IH4.js";
11
+ } from "./chunk-HJ6KTQTZ.js";
12
12
  import {
13
13
  throwIfAborted
14
14
  } from "./chunk-USRKPEQN.js";
@@ -339,4 +339,4 @@ function isEmptyUsage(usage) {
339
339
  export {
340
340
  AgentRunMemory
341
341
  };
342
- //# sourceMappingURL=chunk-F3E2RLC7.js.map
342
+ //# sourceMappingURL=chunk-GE46NHN4.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-4ONUNWGC.js";
4
4
  import {
5
5
  isProviderTool
6
- } from "./chunk-IDNL6IH4.js";
6
+ } from "./chunk-HJ6KTQTZ.js";
7
7
  import {
8
8
  parseMessage,
9
9
  parseMessages
@@ -67,4 +67,4 @@ function messagesFromInput(input) {
67
67
  export {
68
68
  createCompletionRequest
69
69
  };
70
- //# sourceMappingURL=chunk-CKKNO4XB.js.map
70
+ //# sourceMappingURL=chunk-GSVOMQEE.js.map
@@ -45,6 +45,7 @@ function resolveModelContextLimits(modelId, catalog, override) {
45
45
  return override ?? catalog[modelId];
46
46
  }
47
47
  var Usage = {
48
+ /** Returns an all-zero usage value. */
48
49
  empty() {
49
50
  return {
50
51
  inputTokens: 0,
@@ -54,6 +55,10 @@ var Usage = {
54
55
  cacheCreationInputTokens: 0
55
56
  };
56
57
  },
58
+ /**
59
+ * Sums two usage values bucket by bucket. `details` are merged only when
60
+ * both sides carry them; if either side omits them, the result omits them.
61
+ */
57
62
  add(left, right) {
58
63
  const result = {
59
64
  inputTokens: left.inputTokens + right.inputTokens,
@@ -68,6 +73,7 @@ var Usage = {
68
73
  }
69
74
  return result;
70
75
  },
76
+ /** Returns true when every bucket, including `details`, is zero. */
71
77
  isEmpty(usage) {
72
78
  return isEmptyUsage(usage) && (usage.details === void 0 || Object.values(usage.details).every((value) => value === 0));
73
79
  }
@@ -291,4 +297,4 @@ export {
291
297
  assertCompletionControlsSupported,
292
298
  textFromAssistantContent
293
299
  };
294
- //# sourceMappingURL=chunk-IDNL6IH4.js.map
300
+ //# sourceMappingURL=chunk-HJ6KTQTZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/completion/types.ts"],"sourcesContent":["import type { ModelCallOptions } from \"../model-call-options\";\nimport { isJsonValue } from \"./json\";\n\nexport type JsonPrimitive = string | number | boolean | null;\n/** Any JSON-compatible value: primitives, objects, or readonly arrays of JSON values. */\nexport type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];\nexport type JsonObject = { [key: string]: JsonValue };\n\n/** A retrievable text document passed to a completion as grounding context. */\nexport type Document = {\n id: string;\n text: string;\n /** String metadata rendered as a `<metadata ... />` header above the text when documents are serialized into prompts. */\n additionalProps?: Record<string, string>;\n};\n\n/**\n * A text segment, optionally carrying a provider reasoning signature.\n */\nexport type TextPart = Readonly<{\n type: \"text\";\n text: string;\n /** Provider signature preserved so reasoning can be replayed on later turns. */\n signature?: string;\n}>;\n\n/** Image input fidelity hint forwarded to providers that support it. */\nexport type ImageDetail = \"auto\" | \"low\" | \"high\";\n\n/**\n * File payload for image/file parts: a remote URL, base64 data, or literal text\n * interpreted as a document.\n */\nexport type FileData =\n | Readonly<{ type: \"url\"; url: string }>\n | Readonly<{ type: \"data\"; data: string }>\n | Readonly<{ type: \"text\"; text: string }>;\n\n/** Image input with an optional media type override and detail hint. */\nexport type ImagePart = Readonly<{\n type: \"image\";\n image: Exclude<FileData, Readonly<{ type: \"text\"; text: string }>>;\n mediaType?: string;\n detail?: ImageDetail;\n}>;\n\n/** Document/file input part; non-text data is rejected by models without `documentInput`. */\nexport type FilePart = Readonly<{\n type: \"file\";\n data: FileData;\n mediaType: string;\n filename?: string;\n}>;\n\n/** Model reasoning content, replayable across turns to preserve thinking state. */\nexport type ReasoningPart = Readonly<{\n type: \"reasoning\";\n text: string;\n id?: string;\n details?: readonly ReasoningDetail[];\n}>;\n\n/**\n * Reasoning detail variants:\n *\n * - `text` / `summary`: displayable reasoning text\n * - `encrypted` / `redacted`: opaque payloads that can only be echoed back to\n * the provider; their content is not readable by the application\n */\nexport type ReasoningDetail =\n | Readonly<{\n type: \"text\";\n text: string;\n signature?: string;\n }>\n | Readonly<{\n type: \"summary\";\n text: string;\n }>\n | Readonly<{\n type: \"encrypted\";\n data: string;\n }>\n | Readonly<{\n type: \"redacted\";\n data: string;\n }>;\n\nexport type ReasoningContentType = ReasoningDetail[\"type\"];\n\n/** A tool call requested by the model; `signature` preserves provider replay state. */\nexport type ToolCallPart = Readonly<{\n type: \"tool-call\";\n toolCallId: string;\n callId?: string;\n toolName: string;\n input: JsonValue;\n signature?: string;\n}>;\n\n/** The content variants allowed inside a tool result payload. */\nexport type ToolResultContentPart = TextPart | FilePart;\n\n/**\n * Outcome of one tool execution, as recorded in tool messages:\n *\n * - `text` / `json`: successful result as plain text or JSON\n * - `content`: successful result as mixed content parts\n * - `execution-denied`: the call was blocked (e.g. by a required approval)\n * - `error-text` / `error-json`: failure surfaced to the model so the run can\n * continue instead of aborting\n */\nexport type ToolResultOutput =\n | Readonly<{ type: \"text\"; value: string }>\n | Readonly<{ type: \"json\"; value: JsonValue }>\n | Readonly<{ type: \"content\"; value: readonly ToolResultContentPart[] }>\n | Readonly<{ type: \"execution-denied\"; reason?: string }>\n | Readonly<{ type: \"error-text\"; value: string }>\n | Readonly<{ type: \"error-json\"; value: JsonValue }>;\n\n/** Tool result reported back to the model, matched to its call via `toolCallId`. */\nexport type ToolResultPart = Readonly<{\n type: \"tool-result\";\n toolCallId: string;\n callId?: string;\n toolName: string;\n output: ToolResultOutput;\n}>;\n\n/** Human decision on a tool call that required approval before execution. */\nexport type ToolApprovalResponsePart = Readonly<{\n type: \"tool-approval-response\";\n interactionId: string;\n toolCallId: string;\n callId?: string;\n toolName: string;\n approved: boolean;\n reason?: string;\n}>;\n\n/** Answer to one question asked by a tool suspended on a human interaction. */\nexport type ToolQuestionAnswer = Readonly<{\n questionId: string;\n value: string;\n}>;\n\n/** Answers to tool questions, delivered back through the suspended run. */\nexport type ToolQuestionResponsePart = Readonly<{\n type: \"tool-question-response\";\n interactionId: string;\n toolCallId: string;\n callId?: string;\n toolName: string;\n answers: readonly ToolQuestionAnswer[];\n}>;\n\n/** A tool or human-interaction response delivered inside a `role: \"tool\"` message. */\nexport type ToolInteractionResponsePart = ToolApprovalResponsePart | ToolQuestionResponsePart;\n\n/** Content parts allowed in user messages. */\nexport type UserContentPart = TextPart | ImagePart | FilePart;\n/** Content parts allowed in assistant messages, including replayed reasoning and tool calls. */\nexport type AssistantContentPart = TextPart | ImagePart | FilePart | ReasoningPart | ToolCallPart;\n\nexport type SystemMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"system\";\n content: string;\n metadata?: Metadata;\n}>;\n\nexport type UserMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"user\";\n content: string | readonly UserContentPart[];\n metadata?: Metadata;\n}>;\n\nexport type AssistantMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"assistant\";\n id?: string;\n content: string | readonly AssistantContentPart[];\n metadata?: Metadata;\n}>;\n\nexport type ToolMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"tool\";\n content: readonly (ToolResultPart | ToolInteractionResponsePart)[];\n metadata?: Metadata;\n}>;\n\n/**\n * A conversation message from the system, user, assistant, or tool role.\n *\n * Framework-generated metadata (provider, model, usage of the generation that\n * produced an assistant message) is stored under the `anvia` key of `metadata`;\n * read it back with {@link getAssistantGenerationMetadata}.\n */\nexport type Message<Metadata extends JsonObject = JsonObject> =\n | SystemMessage<Metadata>\n | UserMessage<Metadata>\n | AssistantMessage<Metadata>\n | ToolMessage<Metadata>;\n\n/** Joins the human-readable text of a reasoning part or its details. */\nexport function reasoningDisplayText(\n reasoning: ReasoningPart | readonly ReasoningDetail[],\n): string {\n const details = \"type\" in reasoning ? reasoning.details : reasoning;\n if (details === undefined) {\n return \"type\" in reasoning ? reasoning.text : \"\";\n }\n return details\n .flatMap((item) => {\n if (item.type === \"text\" || item.type === \"summary\") {\n return [item.text];\n }\n return [];\n })\n .join(\"\");\n}\n\n/**\n * How the model may call tools: freely, mandatorily, never, or a named function.\n * Requires the model's `toolChoice` capability.\n */\nexport type ToolChoice =\n | \"auto\"\n | \"required\"\n | \"none\"\n | {\n type: \"function\";\n name: string;\n };\n\n/** JSON Schema-shaped tool description sent to the model (a local tool's public face). */\nexport type ToolDefinition = {\n name: string;\n description: string;\n parameters: JsonObject;\n};\n\n/**\n * A tool executed by the model provider rather than by Anvia's local tool runtime.\n *\n * Provider packages expose typed factories for these values. Application code can\n * pass them through the same high-level `tools` APIs used for local tools.\n */\nexport type ProviderTool = {\n kind: \"provider\";\n provider: string;\n name: string;\n configuration?: JsonObject;\n};\n\nexport type CompletionTool = ToolDefinition | ProviderTool;\n\n/** Narrows an unknown value to a well-formed {@link ProviderTool}. */\nexport function isProviderTool(value: unknown): value is ProviderTool {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const candidate = value as Partial<ProviderTool>;\n return (\n candidate.kind === \"provider\" &&\n typeof candidate.provider === \"string\" &&\n candidate.provider.trim().length > 0 &&\n typeof candidate.name === \"string\" &&\n candidate.name.trim().length > 0 &&\n (candidate.configuration === undefined ||\n (typeof candidate.configuration === \"object\" &&\n candidate.configuration !== null &&\n !Array.isArray(candidate.configuration) &&\n isJsonValue(candidate.configuration)))\n );\n}\n\n/** A grounding source (e.g. web result) returned by the provider, with optional text offsets. */\nexport type CompletionSource = {\n type: \"url\";\n url: string;\n title?: string;\n id?: string;\n startIndex?: number;\n endIndex?: number;\n};\n\n/** A tool call executed on the provider side, surfaced for observability. */\nexport type ProviderToolCall = {\n id: string;\n name: string;\n status?: string;\n details?: JsonObject;\n};\n\n/**\n * Provider-normalized, mutually exclusive usage buckets.\n *\n * Every token should appear in exactly one non-total bucket. `total` is the\n * only aggregate key and should equal the sum of the other buckets.\n */\nexport type UsageDetails = Record<string, number>;\n\n/**\n * Token usage for one or more generations.\n *\n * `cachedInputTokens` counts input tokens served from the provider's prompt\n * cache; `cacheCreationInputTokens` counts input tokens billed for writing to\n * that cache. Both are subsets of `inputTokens`.\n */\nexport type Usage = {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cachedInputTokens: number;\n cacheCreationInputTokens: number;\n details?: UsageDetails;\n};\n\n/** Model context window bounds; unset input/output caps fall back to the window. */\nexport type ModelContextLimits = {\n contextWindow: number;\n maxInputTokens?: number;\n maxOutputTokens?: number;\n};\n\n/** Identifies a model together with its context limits. */\nexport type CompletionModelInfo = {\n modelId: string;\n context: ModelContextLimits;\n};\n\n/** Snapshot of how much of a model's context window a request consumed. */\nexport type ContextUsage = {\n model: CompletionModelInfo;\n usedTokens: number;\n remainingTokens: number;\n usedPercent: number;\n remainingPercent: number;\n};\n\n/** Computes context usage, or undefined when the model or usage data is unusable. */\nexport function calculateContextUsage(\n usage: Usage,\n model: CompletionModelInfo | undefined,\n): ContextUsage | undefined {\n if (\n model === undefined ||\n !Number.isFinite(usage.inputTokens) ||\n usage.inputTokens <= 0 ||\n !Number.isFinite(model.context.contextWindow) ||\n model.context.contextWindow <= 0\n ) {\n return undefined;\n }\n\n const usedTokens = Math.max(0, usage.inputTokens);\n const remainingTokens = Math.max(0, model.context.contextWindow - usedTokens);\n const usedPercent = Math.min(100, (usedTokens / model.context.contextWindow) * 100);\n return {\n model,\n usedTokens,\n remainingTokens,\n usedPercent,\n remainingPercent: 100 - usedPercent,\n };\n}\n\n/** Attaches context usage to a response when model limits are known. */\nexport function withContextUsage<RawResponse>(\n response: CompletionResponse<RawResponse>,\n model: CompletionModelInfo | undefined,\n): CompletionResponse<RawResponse> {\n const contextUsage = calculateContextUsage(response.usage, model);\n return contextUsage === undefined ? response : { ...response, contextUsage };\n}\n\n/** Resolves a model's context limits: explicit override wins over catalog lookup. */\nexport function resolveModelContextLimits(\n modelId: string,\n catalog: Readonly<Record<string, ModelContextLimits>>,\n override?: ModelContextLimits,\n): ModelContextLimits | undefined {\n return override ?? catalog[modelId];\n}\n\n/** Provider/model/usage metadata embedded in assistant message metadata by the runtime. */\nexport type AssistantGenerationMetadata = {\n provider: string;\n modelId: string;\n usage: Usage;\n finishReason?: CompletionFinishReason;\n providerFinishReason?: string;\n contextUsage?: ContextUsage;\n sources?: CompletionSource[];\n providerToolCalls?: ProviderToolCall[];\n};\n\n/**\n * Helpers for constructing and combining token usage.\n */\nexport const Usage = {\n /** Returns an all-zero usage value. */\n empty(): Usage {\n return {\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n cachedInputTokens: 0,\n cacheCreationInputTokens: 0,\n };\n },\n /**\n * Sums two usage values bucket by bucket. `details` are merged only when\n * both sides carry them; if either side omits them, the result omits them.\n */\n add(left: Usage, right: Usage): Usage {\n const result: Usage = {\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n totalTokens: left.totalTokens + right.totalTokens,\n cachedInputTokens: left.cachedInputTokens + right.cachedInputTokens,\n cacheCreationInputTokens: left.cacheCreationInputTokens + right.cacheCreationInputTokens,\n };\n const details = addUsageDetails(left, right);\n if (details !== undefined) {\n result.details = details;\n }\n return result;\n },\n /** Returns true when every bucket, including `details`, is zero. */\n isEmpty(usage: Usage): boolean {\n return (\n isEmptyUsage(usage) &&\n (usage.details === undefined || Object.values(usage.details).every((value) => value === 0))\n );\n },\n};\n\nfunction addUsageDetails(left: Usage, right: Usage): UsageDetails | undefined {\n if (isEmptyUsage(left) && left.details === undefined) {\n return right.details === undefined ? undefined : { ...right.details };\n }\n if (isEmptyUsage(right) && right.details === undefined) {\n return left.details === undefined ? undefined : { ...left.details };\n }\n if (left.details === undefined || right.details === undefined) {\n return undefined;\n }\n const details: UsageDetails = { ...left.details };\n for (const [key, value] of Object.entries(right.details)) {\n details[key] = (details[key] ?? 0) + value;\n }\n return details;\n}\n\nfunction isEmptyUsage(usage: Usage): boolean {\n return (\n usage.inputTokens === 0 &&\n usage.outputTokens === 0 &&\n usage.totalTokens === 0 &&\n usage.cachedInputTokens === 0 &&\n usage.cacheCreationInputTokens === 0\n );\n}\n\n/**\n * Reads the generation metadata the runtime embeds in assistant messages, when\n * present and structurally valid.\n */\nexport function getAssistantGenerationMetadata(\n message: Message,\n): AssistantGenerationMetadata | undefined {\n if (message.role !== \"assistant\" || !isJsonObjectValue(message.metadata)) {\n return undefined;\n }\n const frameworkMetadata = message.metadata.anvia;\n if (!isJsonObjectValue(frameworkMetadata)) {\n return undefined;\n }\n const generation = frameworkMetadata.generation;\n if (\n !isJsonObjectValue(generation) ||\n typeof generation.provider !== \"string\" ||\n typeof generation.modelId !== \"string\" ||\n !isUsageValue(generation.usage)\n ) {\n return undefined;\n }\n let usage: Usage = { ...generation.usage };\n if (generation.usage.details !== undefined) {\n usage = { ...usage, details: { ...generation.usage.details } };\n }\n const metadata: AssistantGenerationMetadata = {\n provider: generation.provider,\n modelId: generation.modelId,\n usage,\n };\n if (isCompletionFinishReason(generation.finishReason)) {\n metadata.finishReason = generation.finishReason;\n }\n if (typeof generation.providerFinishReason === \"string\") {\n metadata.providerFinishReason = generation.providerFinishReason;\n }\n if (isContextUsageValue(generation.contextUsage)) {\n metadata.contextUsage = {\n ...generation.contextUsage,\n model: {\n ...generation.contextUsage.model,\n context: { ...generation.contextUsage.model.context },\n },\n };\n }\n if (isCompletionSourceArray(generation.sources)) {\n metadata.sources = generation.sources.map((source) => ({ ...source }));\n }\n if (isProviderToolCallArray(generation.providerToolCalls)) {\n metadata.providerToolCalls = generation.providerToolCalls.map((toolCall) => {\n let copy: ProviderToolCall = { ...toolCall };\n if (toolCall.details !== undefined) {\n copy = { ...copy, details: { ...toolCall.details } };\n }\n return copy;\n });\n }\n return metadata;\n}\n\nfunction isJsonObjectValue(value: JsonValue | undefined): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isContextUsageValue(value: JsonValue | undefined): value is JsonObject & ContextUsage {\n if (!isJsonObjectValue(value) || !isJsonObjectValue(value.model)) {\n return false;\n }\n const context = value.model.context;\n if (\n typeof value.model.modelId === \"string\" &&\n isJsonObjectValue(context) &&\n isPositiveFiniteNumber(context.contextWindow) &&\n isOptionalPositiveFiniteNumber(context.maxInputTokens) &&\n isOptionalPositiveFiniteNumber(context.maxOutputTokens) &&\n isNonnegativeFiniteNumber(value.usedTokens) &&\n isNonnegativeFiniteNumber(value.remainingTokens) &&\n isPercentage(value.usedPercent) &&\n isPercentage(value.remainingPercent)\n ) {\n const contextWindow = context.contextWindow;\n const remainingTokens = Math.max(0, contextWindow - value.usedTokens);\n const usedPercent = Math.min(100, (value.usedTokens / contextWindow) * 100);\n const remainingPercent = (remainingTokens / contextWindow) * 100;\n return (\n value.remainingTokens === remainingTokens &&\n approximatelyEqual(value.usedPercent, usedPercent) &&\n approximatelyEqual(value.remainingPercent, remainingPercent)\n );\n }\n return false;\n}\n\nfunction approximatelyEqual(left: number, right: number): boolean {\n const scale = Math.max(1, Math.abs(left), Math.abs(right));\n return Math.abs(left - right) <= Number.EPSILON * scale * 8;\n}\n\nfunction isPositiveFiniteNumber(value: JsonValue | undefined): value is number {\n return isNonnegativeFiniteNumber(value) && value > 0;\n}\n\nfunction isOptionalPositiveFiniteNumber(value: JsonValue | undefined): boolean {\n return value === undefined || isPositiveFiniteNumber(value);\n}\n\nfunction isPercentage(value: JsonValue | undefined): value is number {\n return isNonnegativeFiniteNumber(value) && value <= 100;\n}\n\nfunction isUsageValue(value: JsonValue | undefined): value is JsonObject & Usage {\n if (!isJsonObjectValue(value)) {\n return false;\n }\n return (\n isNonnegativeFiniteNumber(value.inputTokens) &&\n isNonnegativeFiniteNumber(value.outputTokens) &&\n isNonnegativeFiniteNumber(value.totalTokens) &&\n isNonnegativeFiniteNumber(value.cachedInputTokens) &&\n isNonnegativeFiniteNumber(value.cacheCreationInputTokens) &&\n isUsageDetailsValue(value.details)\n );\n}\n\nfunction isNonnegativeFiniteNumber(value: JsonValue | undefined): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\nfunction isUsageDetailsValue(value: JsonValue | undefined): value is JsonObject | undefined {\n if (value === undefined) {\n return true;\n }\n if (!isJsonObjectValue(value)) {\n return false;\n }\n let total: number | undefined;\n let bucketSum = 0;\n for (const [key, detail] of Object.entries(value)) {\n if (detail === undefined || !isNonnegativeFiniteNumber(detail)) {\n return false;\n }\n if (key === \"total\") {\n total = detail;\n } else {\n bucketSum += detail;\n }\n }\n return total !== undefined && total === bucketSum;\n}\n\nfunction isCompletionSourceArray(value: JsonValue | undefined): value is CompletionSource[] {\n return (\n Array.isArray(value) &&\n value.every(\n (source) =>\n isJsonObjectValue(source) &&\n source.type === \"url\" &&\n typeof source.url === \"string\" &&\n (source.title === undefined || typeof source.title === \"string\") &&\n (source.id === undefined || typeof source.id === \"string\") &&\n (source.startIndex === undefined || typeof source.startIndex === \"number\") &&\n (source.endIndex === undefined || typeof source.endIndex === \"number\"),\n )\n );\n}\n\nfunction isProviderToolCallArray(value: JsonValue | undefined): value is ProviderToolCall[] {\n return (\n Array.isArray(value) &&\n value.every(\n (toolCall) =>\n isJsonObjectValue(toolCall) &&\n typeof toolCall.id === \"string\" &&\n typeof toolCall.name === \"string\" &&\n (toolCall.status === undefined || typeof toolCall.status === \"string\") &&\n (toolCall.details === undefined || isJsonObjectValue(toolCall.details)),\n )\n );\n}\n\n/** Provider-agnostic completion request assembled by the runtime for adapters. */\nexport type CompletionRequest = {\n instructions?: string;\n chatHistory: Message[];\n documents: Document[];\n tools: ToolDefinition[];\n providerTools?: ProviderTool[];\n temperature?: number;\n maxTokens?: number;\n toolChoice?: ToolChoice;\n /** Values for the model's declared completion controls; validated before sending. */\n controls?: Readonly<Record<string, string>>;\n /** Provider-specific passthrough options; never validated by the core runtime. */\n providerOptions?: JsonObject;\n /** JSON Schema the output must conform to; requires the `outputSchema` capability. */\n outputSchema?: JsonObject;\n};\n\n/** Normalized finish reasons:\n *\n * - `stop`: the model finished naturally\n * - `length`: an output token limit was hit\n * - `content-filter`: output was blocked by a safety filter\n * - `tool-calls`: the model stopped to request tool calls\n * - `other`: any provider-specific reason\n */\nexport type CompletionFinishReason = \"stop\" | \"length\" | \"content-filter\" | \"tool-calls\" | \"other\";\n\n/** A provider's raw completion response: normalized parts plus usage and metadata. */\nexport type CompletionResponse<RawResponse = unknown> = {\n choice: AssistantContentPart[];\n usage: Usage;\n finishReason?: CompletionFinishReason;\n providerFinishReason?: string;\n contextUsage?: ContextUsage;\n /** The provider SDK's original response object, unmodified. */\n rawResponse: RawResponse;\n messageId?: string;\n sources?: CompletionSource[];\n providerToolCalls?: ProviderToolCall[];\n};\n\n/** Final result of a completion: typed output, plain text, full content, and usage. */\nexport type CompletionResult<Output = string, RawResponse = unknown> = {\n /**\n * The typed output. When an output schema was requested this is the parsed,\n * validated object; otherwise it is the plain text.\n */\n output: Output;\n /** The generated text, joined from the response's text parts. */\n text: string;\n /** Every content part the model produced, including reasoning and tool calls. */\n content: readonly AssistantContentPart[];\n usage: Usage;\n finishReason?: CompletionFinishReason;\n providerFinishReason?: string;\n contextUsage?: ContextUsage;\n rawResponse: RawResponse;\n messageId?: string;\n sources?: readonly CompletionSource[];\n providerToolCalls?: readonly ProviderToolCall[];\n};\n\nfunction isCompletionFinishReason(value: JsonValue | undefined): value is CompletionFinishReason {\n return (\n value === \"stop\" ||\n value === \"length\" ||\n value === \"content-filter\" ||\n value === \"tool-calls\" ||\n value === \"other\"\n );\n}\n\n/** Feature flags a model declares; requests are validated against these at runtime. */\nexport type CompletionModelCapabilities = {\n streaming: boolean;\n tools: boolean;\n toolChoice: boolean;\n imageInput: boolean;\n documentInput: boolean;\n outputSchema: boolean;\n reasoning: boolean;\n providerTools?: boolean;\n};\n\n/** A selectable model control exposed to applications (e.g. \"reasoning effort\"). */\nexport type CompletionModelSelectControl<Option extends string = string> = Readonly<{\n type: \"select\";\n label: string;\n options: readonly Option[];\n description?: string | undefined;\n defaultValue?: Option | undefined;\n}>;\n\n/** Named set of controls a model supports, keyed by control id. */\nexport type CompletionModelControls = Readonly<\n Record<string, CompletionModelSelectControl<string>>\n>;\n\n/** Marker type for models that accept no completion controls. */\nexport type NoCompletionModelControls = Readonly<Record<string, never>>;\n\n/** The option values a model's controls accept, keyed by control id. */\nexport type CompletionControlValues<Controls extends CompletionModelControls> = Readonly<\n Partial<{\n [Key in keyof Controls]: Controls[Key] extends CompletionModelSelectControl<infer Option>\n ? Option\n : never;\n }>\n>;\n\n/** Extracts a model's control types, defaulting to the open controls record. */\nexport type CompletionModelControlsOf<Model> =\n Model extends CompletionModel<unknown, infer Controls> ? Controls : CompletionModelControls;\n\n/**\n * The provider-agnostic model contract every adapter implements: non-streaming\n * completions plus capability, context, and control metadata.\n */\nexport interface CompletionModel<\n RawResponse = unknown,\n Controls extends CompletionModelControls = CompletionModelControls,\n> {\n readonly provider: string;\n readonly modelId: string;\n readonly contextLimits?: ModelContextLimits | undefined;\n readonly capabilities: CompletionModelCapabilities;\n readonly controls?: Controls | undefined;\n /**\n * Returns a JSON-safe representation of the outgoing request for\n * observability traces, or undefined to omit the trace payload. Errors\n * thrown here are swallowed by the runtime and recorded as a trace error.\n */\n traceRequest?(\n request: CompletionRequest,\n options?: { stream?: boolean | undefined },\n ): JsonObject | undefined;\n completion(\n request: CompletionRequest,\n options?: ModelCallOptions,\n ): Promise<CompletionResponse<RawResponse>>;\n}\n\n/** How a `tool_call_delta` updates arguments: append to, or replace, accumulated JSON. */\nexport type ToolCallArgumentsMode = \"append\" | \"replace\";\n\n/**\n * Incremental completion stream content:\n *\n * - `text_delta` / `reasoning_delta`: incremental text or reasoning content\n * - `tool_call_delta`: partial tool call input; argument fragments accumulate\n * according to `argumentsMode` (`append` continues the JSON string, `replace`\n * restarts it)\n * - `tool_call`: a complete tool call\n * - `source`: a grounding source discovered during generation\n * - `provider_tool_call`: progress on a provider-executed tool\n * - `message_id`: the id of the message being generated\n */\nexport type CompletionStreamPart =\n | {\n type: \"text_delta\";\n delta: string;\n }\n | {\n type: \"reasoning_delta\";\n delta: string;\n id?: string;\n contentType?: ReasoningContentType;\n /** Provider signature preserved for reasoning replay. */\n signature?: string;\n }\n | {\n type: \"tool_call_delta\";\n id: string;\n callId?: string;\n name?: string;\n argumentsDelta?: string;\n argumentsMode?: ToolCallArgumentsMode;\n signature?: string;\n }\n | {\n type: \"tool_call\";\n toolCall: ToolCallPart;\n }\n | {\n type: \"source\";\n source: CompletionSource;\n }\n | {\n type: \"provider_tool_call\";\n toolCall: ProviderToolCall;\n }\n | {\n type: \"message_id\";\n id: string;\n };\n\n/** Raw model stream events: stream parts, the final response, or a terminal error. */\nexport type CompletionModelStreamEvent<RawResponse = unknown> =\n | CompletionStreamPart\n | {\n type: \"final\";\n response: CompletionResponse<RawResponse>;\n }\n | {\n type: \"error\";\n error: unknown;\n usage?: Usage;\n };\n\n/** High-level stream events: stream parts, the final typed result, or a terminal error. */\nexport type CompletionStreamEvent<Output = string, RawResponse = unknown> =\n | CompletionStreamPart\n | {\n type: \"final\";\n result: CompletionResult<Output, RawResponse>;\n }\n | {\n type: \"error\";\n error: unknown;\n usage: Usage;\n };\n\n/** A completion model that can additionally stream events as they are produced. */\nexport interface StreamingCompletionModel<\n RawResponse = unknown,\n Controls extends CompletionModelControls = CompletionModelControls,\n> extends CompletionModel<RawResponse, Controls> {\n streamCompletion(\n request: CompletionRequest,\n options?: ModelCallOptions,\n ): AsyncIterable<CompletionModelStreamEvent<RawResponse>>;\n}\n\n/** Thrown when a request uses a capability the target model does not declare. */\nexport class CompletionCapabilityError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CompletionCapabilityError\";\n }\n}\n\n/** Validates a request against a model's declared capabilities; throws {@link CompletionCapabilityError}. */\nexport function assertCompletionRequestSupported(\n model: CompletionModel,\n request: CompletionRequest,\n options: { streaming?: boolean | undefined } = {},\n): void {\n const modelLabel = `${model.provider}:${model.modelId}`;\n const capabilities = model.capabilities;\n\n assertCompletionControlsSupported(model, request.controls);\n\n if (options.streaming === true && !capabilities.streaming) {\n throw new CompletionCapabilityError(`${modelLabel} does not support streaming completions.`);\n }\n\n if (request.tools.length > 0 && !capabilities.tools) {\n throw new CompletionCapabilityError(`${modelLabel} does not support tool definitions.`);\n }\n\n if ((request.providerTools?.length ?? 0) > 0 && capabilities.providerTools !== true) {\n throw new CompletionCapabilityError(`${modelLabel} does not support provider-executed tools.`);\n }\n\n if (request.toolChoice !== undefined && !capabilities.toolChoice) {\n throw new CompletionCapabilityError(`${modelLabel} does not support tool choice.`);\n }\n\n if (request.outputSchema !== undefined && !capabilities.outputSchema) {\n throw new CompletionCapabilityError(`${modelLabel} does not support output schemas.`);\n }\n\n if (!capabilities.imageInput && requestHasImageInput(request)) {\n throw new CompletionCapabilityError(`${modelLabel} does not support image input.`);\n }\n\n if (!capabilities.documentInput && requestHasFileDocumentInput(request)) {\n throw new CompletionCapabilityError(`${modelLabel} does not support document file input.`);\n }\n}\n\n/** Validates control values against a model's controls; throws {@link CompletionCapabilityError}. */\nexport function assertCompletionControlsSupported(\n model: CompletionModel,\n controls: Readonly<Record<string, string | undefined>> | undefined,\n): void {\n const modelLabel = `${model.provider}:${model.modelId}`;\n for (const [controlId, value] of Object.entries(controls ?? {})) {\n if (value === undefined) continue;\n const modelControls = model.controls;\n const control =\n modelControls !== undefined && Object.hasOwn(modelControls, controlId)\n ? modelControls[controlId]\n : undefined;\n if (control === undefined) {\n throw new CompletionCapabilityError(\n `${modelLabel} does not support completion control \"${controlId}\".`,\n );\n }\n if (!control.options.includes(value)) {\n throw new CompletionCapabilityError(\n `${modelLabel} completion control \"${controlId}\" does not support value \"${value}\".`,\n );\n }\n }\n}\n\n/** Joins the text parts of assistant content with newlines. */\nexport function textFromAssistantContent(content: readonly AssistantContentPart[]): string {\n return content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n}\n\nfunction requestHasImageInput(request: CompletionRequest): boolean {\n return request.chatHistory.some((message) =>\n message.role === \"system\" || typeof message.content === \"string\"\n ? false\n : message.content.some((content) => content.type === \"image\"),\n );\n}\n\nfunction requestHasFileDocumentInput(request: CompletionRequest): boolean {\n return request.chatHistory.some((message) =>\n message.role === \"user\" && typeof message.content !== \"string\"\n ? message.content.some((content) => content.type === \"file\" && content.data.type !== \"text\")\n : false,\n );\n}\n"],"mappings":";;;;;AA2MO,SAAS,qBACd,WACQ;AACR,QAAM,UAAU,UAAU,YAAY,UAAU,UAAU;AAC1D,MAAI,YAAY,QAAW;AACzB,WAAO,UAAU,YAAY,UAAU,OAAO;AAAA,EAChD;AACA,SAAO,QACJ,QAAQ,CAAC,SAAS;AACjB,QAAI,KAAK,SAAS,UAAU,KAAK,SAAS,WAAW;AACnD,aAAO,CAAC,KAAK,IAAI;AAAA,IACnB;AACA,WAAO,CAAC;AAAA,EACV,CAAC,EACA,KAAK,EAAE;AACZ;AAsCO,SAAS,eAAe,OAAuC;AACpE,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG;AACvE,WAAO;AAAA,EACT;AACA,QAAM,YAAY;AAClB,SACE,UAAU,SAAS,cACnB,OAAO,UAAU,aAAa,YAC9B,UAAU,SAAS,KAAK,EAAE,SAAS,KACnC,OAAO,UAAU,SAAS,YAC1B,UAAU,KAAK,KAAK,EAAE,SAAS,MAC9B,UAAU,kBAAkB,UAC1B,OAAO,UAAU,kBAAkB,YAClC,UAAU,kBAAkB,QAC5B,CAAC,MAAM,QAAQ,UAAU,aAAa,KACtC,YAAY,UAAU,aAAa;AAE3C;AAmEO,SAAS,sBACd,OACA,OAC0B;AAC1B,MACE,UAAU,UACV,CAAC,OAAO,SAAS,MAAM,WAAW,KAClC,MAAM,eAAe,KACrB,CAA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AgB,MAAM;AAC5B,UAAM,UACJ,kBAAkB,UAAa,OAAO,OAAO,eAAe,SAAS,IACjE,cAAc,SAAS,IACvB;AACN,QAAI,YAAY,QAAW;AACzB,YAAM,IAAI;AAAA,QACR,GAAG,UAAU,yCAAyC,SAAS;AAAA,MACjE;AAAA,IACF;AACA,QAAI,CAAC,QAAQ,QAAQ,SAAS,KAAK,GAAG;AACpC,YAAM,IAAI;AAAA,QACR,GAAG,UAAU,wBAAwB,SAAS,6BAA6B,KAAK;AAAA,MAClF;AAAA,IACF;AAAA,EACF;AACF;AAGO,SAAS,yBAAyB,SAAkD;AACzF,SAAO,QAAQ,QAAQ,CAAC,SAAU,KAAK,SAAS,SAAS,CAAC,KAAK,IAAI,IAAI,CAAC,CAAE,EAAE,KAAK,IAAI;AACvF;AAEA,SAAS,qBAAqB,SAAqC;AACjE,SAAO,QAAQ,YAAY;AAAA,IAAK,CAAC,YAC/B,QAAQ,SAAS,YAAY,OAAO,QAAQ,YAAY,WACpD,QACA,QAAQ,QAAQ,KAAK,CAAC,YAAY,QAAQ,SAAS,OAAO;AAAA,EAChE;AACF;AAEA,SAAS,4BAA4B,SAAqC;AACxE,SAAO,QAAQ,YAAY;AAAA,IAAK,CAAC,YAC/B,QAAQ,SAAS,UAAU,OAAO,QAAQ,YAAY,WAClD,QAAQ,QAAQ,KAAK,CAAC,YAAY,QAAQ,SAAS,UAAU,QAAQ,KAAK,SAAS,MAAM,IACzF;AAAA,EACN;AACF;","names":[]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  Agent
3
- } from "./chunk-4S4OECPW.js";
3
+ } from "./chunk-KRUDSNFN.js";
4
4
  import {
5
5
  getAgentToolState
6
6
  } from "./chunk-A7BXVZXZ.js";
7
7
  import {
8
8
  markResolvedAgentOptions
9
- } from "./chunk-5FCZ64HM.js";
9
+ } from "./chunk-WCWSPU74.js";
10
10
 
11
11
  // src/agent/resolved-agent.ts
12
12
  function createResolvedAgent(options) {
@@ -45,4 +45,4 @@ export {
45
45
  createResolvedAgent,
46
46
  getResolvedAgentOptions
47
47
  };
48
- //# sourceMappingURL=chunk-T4IAJJUU.js.map
48
+ //# sourceMappingURL=chunk-IYDGPF3C.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  isStreamingCompletionModel
3
- } from "./chunk-BDKFFFVX.js";
3
+ } from "./chunk-YMTBHHLQ.js";
4
4
  import {
5
5
  createTool
6
- } from "./chunk-XV3DH5GC.js";
6
+ } from "./chunk-Y365ABZY.js";
7
7
  import {
8
8
  AgentRunBlockedError,
9
9
  AgentToolSuspensionError
@@ -78,4 +78,4 @@ function createAgentTool(agent, options) {
78
78
  export {
79
79
  createAgentTool
80
80
  };
81
- //# sourceMappingURL=chunk-PPJ7SYQL.js.map
81
+ //# sourceMappingURL=chunk-JMNIWUFV.js.map
@@ -16,7 +16,7 @@ import {
16
16
  } from "./chunk-5V533R7F.js";
17
17
  import {
18
18
  createTool
19
- } from "./chunk-XV3DH5GC.js";
19
+ } from "./chunk-Y365ABZY.js";
20
20
 
21
21
  // src/vector-store/index.ts
22
22
  import { z } from "zod";
@@ -233,4 +233,4 @@ export {
233
233
  InMemoryVectorStore,
234
234
  createVectorSearchTool
235
235
  };
236
- //# sourceMappingURL=chunk-72LBHKYP.js.map
236
+ //# sourceMappingURL=chunk-JWD43K7W.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isToolIndex
3
- } from "./chunk-G336L2IE.js";
3
+ } from "./chunk-4BDSO4PQ.js";
4
4
  import {
5
5
  isMcpTool
6
6
  } from "./chunk-PLDJCCVL.js";
@@ -165,4 +165,4 @@ function snapshotToolIndex(index) {
165
165
  export {
166
166
  prepareAgentTools
167
167
  };
168
- //# sourceMappingURL=chunk-MNYMLWWA.js.map
168
+ //# sourceMappingURL=chunk-KNZNSNP4.js.map
@@ -1,18 +1,18 @@
1
1
  import {
2
2
  AgentRun
3
- } from "./chunk-RT5LUEO3.js";
3
+ } from "./chunk-A3DGCDGF.js";
4
+ import {
5
+ AgentRunMemory
6
+ } from "./chunk-GE46NHN4.js";
4
7
  import {
5
8
  assertNonnegativeSafeInteger
6
9
  } from "./chunk-NPJ2T3L5.js";
7
10
  import {
8
11
  normalizeMemoryScope
9
12
  } from "./chunk-LAIATEUB.js";
10
- import {
11
- AgentRunMemory
12
- } from "./chunk-F3E2RLC7.js";
13
13
  import {
14
14
  prepareAgentTools
15
- } from "./chunk-MNYMLWWA.js";
15
+ } from "./chunk-KNZNSNP4.js";
16
16
  import {
17
17
  getRegisteredAgentTool,
18
18
  registerAgentToolState
@@ -22,7 +22,7 @@ import {
22
22
  } from "./chunk-GLMYZ6OA.js";
23
23
  import {
24
24
  resolveAgentOptions
25
- } from "./chunk-5FCZ64HM.js";
25
+ } from "./chunk-WCWSPU74.js";
26
26
  import {
27
27
  cloneFrozenPlainData,
28
28
  snapshotAgentContext,
@@ -35,22 +35,22 @@ import {
35
35
  } from "./chunk-KY4VXIN2.js";
36
36
  import {
37
37
  createAgentTool
38
- } from "./chunk-PPJ7SYQL.js";
38
+ } from "./chunk-JMNIWUFV.js";
39
39
  import {
40
40
  isStreamingCompletionModel
41
- } from "./chunk-BDKFFFVX.js";
41
+ } from "./chunk-YMTBHHLQ.js";
42
42
  import {
43
43
  assertJsonObject
44
44
  } from "./chunk-4ONUNWGC.js";
45
45
  import {
46
46
  prepareToolCall
47
- } from "./chunk-MHOJJYDK.js";
47
+ } from "./chunk-647TQE3E.js";
48
48
  import {
49
49
  ToolNotFoundError
50
50
  } from "./chunk-J6S6MT7O.js";
51
51
  import {
52
52
  assertCompletionControlsSupported
53
- } from "./chunk-IDNL6IH4.js";
53
+ } from "./chunk-HJ6KTQTZ.js";
54
54
  import {
55
55
  normalizeAgentId
56
56
  } from "./chunk-KBBQSP4M.js";
@@ -155,4 +155,4 @@ var Agent = class {
155
155
  export {
156
156
  Agent
157
157
  };
158
- //# sourceMappingURL=chunk-4S4OECPW.js.map
158
+ //# sourceMappingURL=chunk-KRUDSNFN.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runEvalSuite
3
- } from "./chunk-QUS6S2NB.js";
3
+ } from "./chunk-SIXS4CCU.js";
4
4
 
5
5
  // src/evals/cli.ts
6
6
  var EvalAssertionError = class extends Error {
@@ -352,4 +352,4 @@ export {
352
352
  assertEvalOutcomes,
353
353
  runEvalCli
354
354
  };
355
- //# sourceMappingURL=chunk-O6DTOCBM.js.map
355
+ //# sourceMappingURL=chunk-KX2TRKO2.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-2NLINXRF.js";
4
4
  import {
5
5
  createTool
6
- } from "./chunk-XV3DH5GC.js";
6
+ } from "./chunk-Y365ABZY.js";
7
7
 
8
8
  // src/skills/tools.ts
9
9
  import { spawn } from "child_process";
@@ -186,4 +186,4 @@ function appendLimited(current, chunk) {
186
186
  export {
187
187
  createSkillTools
188
188
  };
189
- //# sourceMappingURL=chunk-BDDC72GF.js.map
189
+ //# sourceMappingURL=chunk-LJGQ6VQB.js.map
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=chunk-NMPDZTBM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createTool
3
- } from "./chunk-XV3DH5GC.js";
3
+ } from "./chunk-Y365ABZY.js";
4
4
 
5
5
  // src/tool/think-tool.ts
6
6
  import { z } from "zod";
@@ -21,4 +21,4 @@ function createThinkTool(options = {}) {
21
21
  export {
22
22
  createThinkTool
23
23
  };
24
- //# sourceMappingURL=chunk-6N4ENZO4.js.map
24
+ //# sourceMappingURL=chunk-OYHU4HNC.js.map
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-ZPXOBQDS.js";
7
7
  import {
8
8
  extract
9
- } from "./chunk-UOGM62JL.js";
9
+ } from "./chunk-7TUAAGVR.js";
10
10
  import {
11
11
  evalValuesEqual,
12
12
  formatValue
@@ -315,4 +315,4 @@ export {
315
315
  llmJudge,
316
316
  llmScore
317
317
  };
318
- //# sourceMappingURL=chunk-Y7JTHNCU.js.map
318
+ //# sourceMappingURL=chunk-RFFOL6ON.js.map
@@ -16,6 +16,7 @@ var ToolResultSerializationError = class extends TypeError {
16
16
  output;
17
17
  };
18
18
  var ToolOutput = {
19
+ /** Wraps content parts so a tool can return text and files together. */
19
20
  content(content) {
20
21
  return { [richToolOutput]: true, content };
21
22
  }
@@ -73,4 +74,4 @@ export {
73
74
  toolResultContentToText,
74
75
  parseToolArgs
75
76
  };
76
- //# sourceMappingURL=chunk-47NTHIVB.js.map
77
+ //# sourceMappingURL=chunk-SCFWN3T2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tool/tool.ts"],"sourcesContent":["import { isJsonValue } from \"../completion/json\";\nimport { parseMessage } from \"../completion/message-schema\";\nimport type {\n JsonObject,\n JsonValue,\n ToolDefinition,\n ToolResultContentPart,\n ToolResultOutput,\n} from \"../completion/types\";\n\n/** Identifies the agent run that requested a tool approval. */\nexport type ToolApprovalRunContext = {\n agentId: string;\n runId: string;\n sessionId?: string;\n metadata?: JsonObject;\n};\n\n/** Details of the pending tool call being evaluated for approval. */\nexport type ToolApprovalContext<Args = unknown> = {\n toolName: string;\n args: Args;\n /** The serialized argument string passed to hooks and approval checks. */\n rawArgs: string;\n toolCallId: string;\n callId?: string;\n internalCallId: string;\n run: ToolApprovalRunContext;\n};\n\n/** An approval demand, with an optional human-readable reason. */\nexport type ToolApprovalRequirement = {\n reason?: string | undefined;\n};\n\n/**\n * Whether a tool call needs human approval before execution:\n *\n * - `boolean`: a static requirement\n * - `ToolApprovalRequirement`: a requirement with a reason\n * - a function: evaluated per call, receiving the parsed args and call context\n */\nexport type ToolRequiresApproval<Args = unknown> =\n | boolean\n | ToolApprovalRequirement\n | ((\n args: Args,\n context: ToolApprovalContext<Args>,\n ) => boolean | ToolApprovalRequirement | Promise<boolean | ToolApprovalRequirement>);\n\n/** A child-agent event forwarded through a tool into the parent run's stream. */\nexport type ToolCallStreamEvent = {\n agentId: string;\n agentName?: string | undefined;\n event: unknown;\n};\n\n/** Execution context handed to a tool when the run invokes it. */\nexport type ToolCallContext = {\n /** Emits a child-agent event into the parent run's stream. */\n emitStreamEvent?(event: ToolCallStreamEvent): void | Promise<void>;\n /** Aborted when the run is cancelled or the stream consumer leaves. */\n abortSignal?: AbortSignal | undefined;\n};\n\n/**\n * A model-callable tool. `definition` builds the model-facing JSON description,\n * `call` executes it, and the optional `parseInput` converts raw model-supplied\n * JSON arguments into the typed `Args` before `call` runs.\n */\nexport interface Tool<Args = unknown, Output = unknown> {\n readonly name: string;\n readonly requiresApproval?: ToolRequiresApproval<Args>;\n definition(prompt: string): ToolDefinition | Promise<ToolDefinition>;\n call(args: Args, context?: ToolCallContext): Output | Promise<Output>;\n parseInput?(args: JsonValue): Args;\n}\n\n/** A tool with its argument and output types erased, e.g. as stored in an agent's catalog. */\nexport type AnyTool = Omit<Tool<unknown, unknown>, \"requiresApproval\"> & {\n readonly requiresApproval?: unknown;\n};\n\nconst richToolOutput: unique symbol = Symbol.for(\"anvia.tool-output.content\");\n\n/**\n * A tool result carrying mixed content parts (text, files), created with\n * {@link ToolOutput.content}. The brand symbol keeps plain objects from\n * impersonating rich outputs.\n */\nexport type RichToolOutput = Readonly<{\n [richToolOutput]: true;\n content: readonly ToolResultContentPart[];\n}>;\n\n/** Normalized tool result as stored in tool messages. */\nexport type NormalizedToolOutput = ToolResultOutput;\n\n/** Thrown when a tool returns a value that cannot be represented as a tool result. */\nexport class ToolResultSerializationError extends TypeError {\n constructor(readonly output: unknown) {\n super(\"Tool output must be a string, a strict JSON value, or ToolOutput.content(...).\");\n this.name = \"ToolResultSerializationError\";\n }\n}\n\n/** Helpers for building tool results. */\nexport const ToolOutput = {\n /** Wraps content parts so a tool can return text and files together. */\n content(content: readonly ToolResultContentPart[]): RichToolOutput {\n return { [richToolOutput]: true, content };\n },\n};\n\n/**\n * Coerces a tool's return value into a normalized result: strings become text,\n * rich outputs are validated, and strict JSON values become JSON results.\n * Anything else throws {@link ToolResultSerializationError}.\n */\nexport function normalizeToolResultOutput(output: unknown): NormalizedToolOutput {\n if (typeof output === \"string\") {\n return { type: \"text\", value: output };\n }\n if (isRichToolOutput(output)) {\n try {\n const message = parseMessage({\n role: \"tool\",\n content: [\n {\n type: \"tool-result\",\n toolCallId: \"validation\",\n toolName: \"validation\",\n output: { type: \"content\", value: output.content },\n },\n ],\n });\n if (message.role !== \"tool\") throw new TypeError(\"Unexpected message role\");\n const result = message.content[0];\n if (result?.type !== \"tool-result\") throw new TypeError(\"Unexpected tool result part\");\n if (result?.output.type !== \"content\") throw new TypeError(\"Unexpected tool output\");\n return result.output;\n } catch {\n throw new ToolResultSerializationError(output);\n }\n }\n if (isJsonValue(output)) {\n return { type: \"json\", value: output };\n }\n throw new ToolResultSerializationError(output);\n}\n\n/** Renders tool result content as text; file parts become `[file:<mediaType>]` placeholders. */\nexport function toolResultContentToText(content: readonly ToolResultContentPart[]): string {\n return content\n .map((item) => (item.type === \"text\" ? item.text : `[file:${item.mediaType}]`))\n .join(\"\\n\");\n}\n\nfunction isRichToolOutput(value: unknown): value is RichToolOutput {\n if (typeof value !== \"object\" || value === null) return false;\n return Object.getOwnPropertyDescriptor(value, richToolOutput)?.value === true;\n}\n\n/** Parses and JSON-validates the raw argument string supplied by the model. */\nexport function parseToolArgs(args: string): JsonValue {\n const value: unknown = JSON.parse(args);\n if (!isJsonValue(value)) {\n throw new TypeError(\"Tool arguments must be a JSON value.\");\n }\n return value;\n}\n"],"mappings":";;;;;;;;AAmFA,IAAM,iBAAgC,uBAAO,IAAI,2BAA2B;AAgBrE,IAAM,+BAAN,cAA2C,UAAU;AAAA,EAC1D,YAAqB,QAAiB;AACpC,UAAM,gFAAgF;AADnE;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;AAGO,IAAM,aAAa;AAAA;AAAA,EAExB,QAAQ,SAA2D;AACjE,WAAO,EAAE,CAAC,cAAc,GAAG,M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,UAAU,sCAAsC;AAAA,EAC5D;AACA,SAAO;AACT;","names":[]}
@@ -16,7 +16,7 @@ import {
16
16
  } from "./chunk-JMMZICU7.js";
17
17
  import {
18
18
  Usage
19
- } from "./chunk-IDNL6IH4.js";
19
+ } from "./chunk-HJ6KTQTZ.js";
20
20
 
21
21
  // src/evals/runner.ts
22
22
  var EvalReporterDispatchError = class extends AggregateError {
@@ -660,4 +660,4 @@ export {
660
660
  EvalFailFastError,
661
661
  runEvalSuite
662
662
  };
663
- //# sourceMappingURL=chunk-QUS6S2NB.js.map
663
+ //# sourceMappingURL=chunk-SIXS4CCU.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createTool
3
- } from "./chunk-XV3DH5GC.js";
3
+ } from "./chunk-Y365ABZY.js";
4
4
 
5
5
  // src/tool/question-tool.ts
6
6
  import { z } from "zod";
@@ -44,4 +44,4 @@ export {
44
44
  createQuestionTool,
45
45
  isQuestionTool
46
46
  };
47
- //# sourceMappingURL=chunk-IV6YQTY2.js.map
47
+ //# sourceMappingURL=chunk-T3ZOZEAB.js.map
@@ -3,13 +3,13 @@ import {
3
3
  } from "./chunk-X6WS3XWL.js";
4
4
  import {
5
5
  TeamRun
6
- } from "./chunk-SIYZDPVH.js";
6
+ } from "./chunk-VKRGWGA4.js";
7
7
  import {
8
8
  TeamStream
9
9
  } from "./chunk-3TAQXJBC.js";
10
10
  import {
11
11
  Agent
12
- } from "./chunk-4S4OECPW.js";
12
+ } from "./chunk-KRUDSNFN.js";
13
13
  import {
14
14
  assertPositiveSafeInteger
15
15
  } from "./chunk-NPJ2T3L5.js";
@@ -104,4 +104,4 @@ var AgentTeam = class {
104
104
  export {
105
105
  AgentTeam
106
106
  };
107
- //# sourceMappingURL=chunk-AOG6KSV4.js.map
107
+ //# sourceMappingURL=chunk-T4UW4SUK.js.map
@@ -2,7 +2,7 @@ import {
2
2
  addUsage,
3
3
  evaluationMetadata,
4
4
  runJudge
5
- } from "./chunk-LKIABZNR.js";
5
+ } from "./chunk-5SJBSCG2.js";
6
6
  import {
7
7
  resolveActualText,
8
8
  resolveExpected
@@ -19,7 +19,7 @@ import {
19
19
  } from "./chunk-4FIVU53H.js";
20
20
  import {
21
21
  Usage
22
- } from "./chunk-IDNL6IH4.js";
22
+ } from "./chunk-HJ6KTQTZ.js";
23
23
  import {
24
24
  isJsonValue
25
25
  } from "./chunk-4C7AXYOM.js";
@@ -1004,4 +1004,4 @@ export {
1004
1004
  turnRelevancy,
1005
1005
  knowledgeRetention
1006
1006
  };
1007
- //# sourceMappingURL=chunk-BUPC72Y2.js.map
1007
+ //# sourceMappingURL=chunk-V5DWNXVH.js.map