@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
@@ -0,0 +1,50 @@
1
+ import {
2
+ resolveRetryOptions,
3
+ runWithRetries,
4
+ throwIfAborted
5
+ } from "./chunk-FN7HLLAZ.js";
6
+
7
+ // src/transcription/transcribe.ts
8
+ async function transcribe(options) {
9
+ const data = toUint8Array(options.audio.data);
10
+ if (data.byteLength === 0) {
11
+ throw new Error("Transcription audio cannot be empty.");
12
+ }
13
+ if (typeof options.audio.filename !== "string" || options.audio.filename.trim().length === 0) {
14
+ throw new TypeError("Transcription filename must be a non-empty string.");
15
+ }
16
+ throwIfAborted(options.abortSignal);
17
+ const request = { data, filename: options.audio.filename };
18
+ if (options.audio.mediaType !== void 0) request.mediaType = options.audio.mediaType;
19
+ if (options.language !== void 0) request.language = options.language;
20
+ if (options.prompt !== void 0) request.prompt = options.prompt;
21
+ if (options.temperature !== void 0) request.temperature = options.temperature;
22
+ if (options.providerOptions !== void 0) request.providerOptions = options.providerOptions;
23
+ return await runWithRetries(
24
+ () => {
25
+ throwIfAborted(options.abortSignal);
26
+ return options.model.transcription(request, modelCallOptions(options.abortSignal));
27
+ },
28
+ resolveRetries(options.retries),
29
+ { streaming: false, abortSignal: options.abortSignal }
30
+ );
31
+ }
32
+ function resolveRetries(setting) {
33
+ return setting === void 0 || setting === false ? void 0 : resolveRetryOptions(setting);
34
+ }
35
+ function modelCallOptions(abortSignal) {
36
+ return abortSignal === void 0 ? void 0 : { abortSignal };
37
+ }
38
+ function toUint8Array(bytes) {
39
+ if (bytes instanceof Uint8Array) {
40
+ return new Uint8Array(
41
+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
42
+ );
43
+ }
44
+ return new Uint8Array(bytes.slice(0));
45
+ }
46
+
47
+ export {
48
+ transcribe
49
+ };
50
+ //# sourceMappingURL=chunk-GKDERULJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transcription/transcribe.ts"],"sourcesContent":["import type { JsonObject } from \"../completion\";\nimport { throwIfAborted } from \"../internal/abort\";\nimport type { ModelCallOptions } from \"../model-call-options\";\nimport {\n type ResolvedRetryOptions,\n type RetrySetting,\n resolveRetryOptions,\n runWithRetries,\n} from \"../retry\";\nimport type { TranscriptionModel, TranscriptionRequest, TranscriptionResult } from \"./types\";\n\nexport type TranscriptionAudio = {\n data: Uint8Array | ArrayBuffer;\n filename: string;\n mediaType?: string | undefined;\n};\n\nexport type TranscribeOptions<Model extends TranscriptionModel = TranscriptionModel> = {\n model: Model;\n audio: TranscriptionAudio;\n language?: string | undefined;\n prompt?: string | undefined;\n temperature?: number | undefined;\n providerOptions?: JsonObject | undefined;\n retries?: RetrySetting | undefined;\n abortSignal?: AbortSignal | undefined;\n};\n\ntype RawResponseOf<Model> =\n Model extends TranscriptionModel<infer RawResponse> ? RawResponse : unknown;\n\nexport async function transcribe<Model extends TranscriptionModel>(\n options: TranscribeOptions<Model>,\n): Promise<TranscriptionResult<RawResponseOf<Model>>> {\n const data = toUint8Array(options.audio.data);\n if (data.byteLength === 0) {\n throw new Error(\"Transcription audio cannot be empty.\");\n }\n if (typeof options.audio.filename !== \"string\" || options.audio.filename.trim().length === 0) {\n throw new TypeError(\"Transcription filename must be a non-empty string.\");\n }\n throwIfAborted(options.abortSignal);\n\n const request: TranscriptionRequest = { data, filename: options.audio.filename };\n if (options.audio.mediaType !== undefined) request.mediaType = options.audio.mediaType;\n if (options.language !== undefined) request.language = options.language;\n if (options.prompt !== undefined) request.prompt = options.prompt;\n if (options.temperature !== undefined) request.temperature = options.temperature;\n if (options.providerOptions !== undefined) request.providerOptions = options.providerOptions;\n\n return await runWithRetries(\n () => {\n throwIfAborted(options.abortSignal);\n return options.model.transcription(request, modelCallOptions(options.abortSignal)) as Promise<\n TranscriptionResult<RawResponseOf<Model>>\n >;\n },\n resolveRetries(options.retries),\n { streaming: false, abortSignal: options.abortSignal },\n );\n}\n\nfunction resolveRetries(setting: RetrySetting | undefined): ResolvedRetryOptions | undefined {\n return setting === undefined || setting === false ? undefined : resolveRetryOptions(setting);\n}\n\nfunction modelCallOptions(abortSignal: AbortSignal | undefined): ModelCallOptions | undefined {\n return abortSignal === undefined ? undefined : { abortSignal };\n}\n\nfunction toUint8Array(bytes: Uint8Array | ArrayBuffer): Uint8Array {\n if (bytes instanceof Uint8Array) {\n return new Uint8Array(\n bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),\n );\n }\n return new Uint8Array(bytes.slice(0));\n}\n"],"mappings":";;;;;;;AA+BA,eAAsB,WACpB,SACoD;AACpD,QAAM,OAAO,aAAa,QAAQ,MAAM,IAAI;AAC5C,MAAI,KAAK,eAAe,GAAG;AACzB,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AACA,MAAI,OAAO,QAAQ,MAAM,aAAa,YAAY,QAAQ,MAAM,SAAS,KAAK,EAAE,WAAW,GAAG;AAC5F,UAAM,IAAI,UAAU,oDAAoD;AAAA,EAC1E;AACA,iBAAe,QAAQ,WAAW;AAElC,QAAM,UAAgC,EAAE,MAAM,UAAU,QAAQ,MAAM,SAAS;AAC/E,MAAI,QAAQ,MAAM,cAAc,OAAW,SAAQ,YAAY,QAAQ,MAAM;AAC7E,MAAI,QAAQ,aAAa,OAAW,SAAQ,WAAW,QAAQ;AAC/D,MAAI,QAAQ,WAAW,OAAW,SAAQ,SAAS,QAAQ;AAC3D,MAAI,QAAQ,gBAAgB,OAAW,SAAQ,cAAc,QAAQ;AACrE,MAAI,QAAQ,oBAAoB,OAAW,SAAQ,kBAAkB,QAAQ;AAE7E,SAAO,MAAM;AAAA,IACX,MAAM;AACJ,qBAAe,QAAQ,WAAW;AAClC,aAAO,QAAQ,MAAM,cAAc,SAAS,iBAAiB,QAAQ,WAAW,CAAC;AAAA,IAGnF;AAAA,IACA,eAAe,QAAQ,OAAO;AAAA,IAC9B,EAAE,WAAW,OAAO,aAAa,QAAQ,YAAY;AAAA,EACvD;AACF;AAEA,SAAS,eAAe,SAAqE;AAC3F,SAAO,YAAY,UAAa,YAAY,QAAQ,SAAY,oBAAoB,OAAO;AAC7F;AAEA,SAAS,iBAAiB,aAAoE;AAC5F,SAAO,gBAAgB,SAAY,SAAY,EAAE,YAAY;AAC/D;AAEA,SAAS,aAAa,OAA6C;AACjE,MAAI,iBAAiB,YAAY;AAC/B,WAAO,IAAI;AAAA,MACT,MAAM,OAAO,MAAM,MAAM,YAAY,MAAM,aAAa,MAAM,UAAU;AAAA,IAC1E;AAAA,EACF;AACA,SAAO,IAAI,WAAW,MAAM,MAAM,CAAC,CAAC;AACtC;","names":[]}
@@ -244,12 +244,18 @@ function textFromMessage(message) {
244
244
  if (message.role === "system") {
245
245
  return message.content;
246
246
  }
247
+ if (typeof message.content === "string") {
248
+ return message.content;
249
+ }
247
250
  return message.content.flatMap((content) => {
248
251
  if (content.type === "text") {
249
252
  return [content.text];
250
253
  }
251
- if (content.type === "document" && content.source.type === "text") {
252
- return [content.source.text];
254
+ if (content.type === "file" && content.data.type === "text") {
255
+ return [content.data.text];
256
+ }
257
+ if (content.type === "tool-result") {
258
+ return textFromToolResult(content.output);
253
259
  }
254
260
  return [];
255
261
  }).join("\n");
@@ -259,12 +265,13 @@ function rewriteMessageText(message, text) {
259
265
  return { ...message, content: text };
260
266
  }
261
267
  if (message.role === "user") {
268
+ const content = typeof message.content === "string" ? [] : message.content;
262
269
  return {
263
270
  ...message,
264
271
  content: [
265
272
  { type: "text", text },
266
- ...message.content.filter(
267
- (item) => item.type !== "text" && !(item.type === "document" && item.source.type === "text")
273
+ ...content.filter(
274
+ (item) => item.type !== "text" && !(item.type === "file" && item.data.type === "text")
268
275
  )
269
276
  ]
270
277
  };
@@ -274,6 +281,20 @@ function rewriteMessageText(message, text) {
274
281
  }
275
282
  return message;
276
283
  }
284
+ function textFromToolResult(output) {
285
+ switch (output.type) {
286
+ case "text":
287
+ case "error-text":
288
+ return [output.value];
289
+ case "json":
290
+ case "error-json":
291
+ return [JSON.stringify(output.value)];
292
+ case "content":
293
+ return output.value.flatMap((part) => part.type === "text" ? [part.text] : []);
294
+ case "execution-denied":
295
+ return output.reason === void 0 ? [] : [output.reason];
296
+ }
297
+ }
277
298
 
278
299
  export {
279
300
  defineGuardrailPolicy,
@@ -288,4 +309,4 @@ export {
288
309
  runInputGuardrails,
289
310
  runOutputGuardrails
290
311
  };
291
- //# sourceMappingURL=chunk-FNQB2JEH.js.map
312
+ //# sourceMappingURL=chunk-KIDGIJM7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/guardrails/index.ts"],"sourcesContent":["import type { JsonObject, Message, ToolResultPart, Usage } from \"../completion\";\nimport type { MaybePromise } from \"../internal/type-utils\";\n\nexport type GuardrailMode = \"enforce\" | \"observe\";\n\nexport type GuardrailBoundary = \"input\" | \"output\";\n\nexport type GuardrailRunContext = {\n agentId: string;\n runId: string;\n sessionId?: string | undefined;\n metadata?: JsonObject | undefined;\n};\n\nexport type GuardrailDecisionRecord = {\n policyId: string;\n guardrailId: string;\n boundary: GuardrailBoundary;\n mode: GuardrailMode;\n action: GuardrailActionName;\n applied: boolean;\n reason?: string | undefined;\n message?: string | undefined;\n metadata?: JsonObject | undefined;\n latencyMs: number;\n};\n\nexport type GuardrailActionName = \"allow\" | \"block\" | \"rewrite\" | \"error\";\n\nexport type GuardrailActionBase = {\n reason?: string | undefined;\n metadata?: JsonObject | undefined;\n};\n\nexport type GuardrailAllow = GuardrailActionBase & {\n action: \"allow\";\n};\n\nexport type GuardrailBlock = GuardrailActionBase & {\n action: \"block\";\n reason: string;\n message?: string | undefined;\n};\n\nexport type InputGuardrailRewrite = GuardrailActionBase & {\n action: \"rewrite\";\n prompt?: Message | undefined;\n inputText?: string | undefined;\n};\n\nexport type OutputGuardrailRewrite = GuardrailActionBase & {\n action: \"rewrite\";\n outputText: string;\n};\n\nexport type InputGuardrailResult = GuardrailAllow | GuardrailBlock | InputGuardrailRewrite;\nexport type OutputGuardrailResult = GuardrailAllow | GuardrailBlock | OutputGuardrailRewrite;\n\nexport type GuardrailCommonActions = {\n allow(options?: GuardrailActionBase): GuardrailAllow;\n block(options: Omit<GuardrailBlock, \"action\">): GuardrailBlock;\n};\n\nexport type InputGuardrailActions = GuardrailCommonActions & {\n rewrite(options: Omit<InputGuardrailRewrite, \"action\">): InputGuardrailRewrite;\n};\n\nexport type OutputGuardrailActions = GuardrailCommonActions & {\n rewrite(options: Omit<OutputGuardrailRewrite, \"action\">): OutputGuardrailRewrite;\n};\n\nexport type InputGuardrailContext = {\n prompt: Message;\n history: Message[];\n inputText: string;\n run: GuardrailRunContext;\n};\n\nexport type OutputGuardrailContext = {\n outputText: string;\n messages: Message[];\n usage: Usage;\n run: GuardrailRunContext;\n};\n\nexport type InputGuardrail = {\n id: string;\n check(\n context: InputGuardrailContext,\n actions: InputGuardrailActions,\n ): MaybePromise<InputGuardrailResult | undefined>;\n};\n\nexport type OutputGuardrail = {\n id: string;\n check(\n context: OutputGuardrailContext,\n actions: OutputGuardrailActions,\n ): MaybePromise<OutputGuardrailResult | undefined>;\n};\n\nexport type GuardrailPolicy = {\n id: string;\n mode: GuardrailMode;\n input: InputGuardrail[];\n output: OutputGuardrail[];\n};\n\nexport type GuardrailPolicyOptions = {\n id: string;\n mode?: GuardrailMode | undefined;\n input?: InputGuardrail[] | undefined;\n output?: OutputGuardrail[] | undefined;\n};\n\nexport type GuardrailPolicyInput = GuardrailPolicy | GuardrailPolicy[];\n\nexport type InputGuardrailRunResult = {\n prompt: Message;\n inputText: string;\n blocked: boolean;\n message?: string | undefined;\n decisions: GuardrailDecisionRecord[];\n};\n\nexport type OutputGuardrailRunResult = {\n outputText: string;\n blocked: boolean;\n message?: string | undefined;\n decisions: GuardrailDecisionRecord[];\n};\n\nexport function defineGuardrailPolicy(options: GuardrailPolicyOptions): GuardrailPolicy {\n return {\n id: options.id,\n mode: options.mode ?? \"enforce\",\n input: options.input ?? [],\n output: options.output ?? [],\n };\n}\n\nexport function defineInputGuardrail(guardrail: InputGuardrail): InputGuardrail {\n return guardrail;\n}\n\nexport function defineOutputGuardrail(guardrail: OutputGuardrail): OutputGuardrail {\n return guardrail;\n}\n\nexport function allow(options: GuardrailActionBase = {}): GuardrailAllow {\n return { action: \"allow\", ...options };\n}\n\nexport function block(options: Omit<GuardrailBlock, \"action\">): GuardrailBlock {\n return { action: \"block\", ...options };\n}\n\nexport const guardrails = {\n blockText,\n redactText,\n};\n\nexport function normalizeGuardrailPolicies(\n policies: GuardrailPolicyInput | undefined,\n): GuardrailPolicy[] {\n if (policies === undefined) {\n return [];\n }\n return Array.isArray(policies) ? policies : [policies];\n}\n\nexport function appendGuardrailPolicies(\n current: GuardrailPolicy[],\n next: GuardrailPolicyInput,\n): GuardrailPolicy[] {\n return [...current, ...normalizeGuardrailPolicies(next)];\n}\n\nexport function hasEnforcedOutputGuardrails(policies: GuardrailPolicy[]): boolean {\n return policies.some((policy) => policy.mode === \"enforce\" && policy.output.length > 0);\n}\n\nexport async function runInputGuardrails(\n policies: GuardrailPolicy[],\n context: InputGuardrailContext,\n): Promise<InputGuardrailRunResult> {\n let prompt = context.prompt;\n let inputText = context.inputText;\n const decisions: GuardrailDecisionRecord[] = [];\n\n for (const policy of policies) {\n for (const guardrail of policy.input) {\n const currentContext = { ...context, prompt, inputText };\n const result = await runGuardrail(policy, guardrail.id, \"input\", () =>\n guardrail.check(currentContext, inputActions),\n );\n decisions.push(result.decision);\n\n if (policy.mode === \"observe\") {\n continue;\n }\n if (result.action.action === \"block\") {\n return {\n prompt,\n inputText,\n blocked: true,\n message: result.action.message,\n decisions,\n };\n }\n if (result.action.action === \"rewrite\") {\n if (result.action.prompt !== undefined) {\n prompt = result.action.prompt;\n inputText = textFromMessage(prompt);\n } else if (result.action.inputText !== undefined) {\n inputText = result.action.inputText;\n prompt = rewriteMessageText(prompt, inputText);\n }\n }\n }\n }\n\n return { prompt, inputText, blocked: false, decisions };\n}\n\nexport async function runOutputGuardrails(\n policies: GuardrailPolicy[],\n context: OutputGuardrailContext,\n): Promise<OutputGuardrailRunResult> {\n let outputText = context.outputText;\n const decisions: GuardrailDecisionRecord[] = [];\n\n for (const policy of policies) {\n for (const guardrail of policy.output) {\n const currentContext = { ...context, outputText };\n const result = await runGuardrail(policy, guardrail.id, \"output\", () =>\n guardrail.check(currentContext, outputActions),\n );\n decisions.push(result.decision);\n\n if (policy.mode === \"observe\") {\n continue;\n }\n if (result.action.action === \"block\") {\n return {\n outputText,\n blocked: true,\n message: result.action.message,\n decisions,\n };\n }\n if (result.action.action === \"rewrite\") {\n outputText = result.action.outputText;\n }\n }\n }\n\n return { outputText, blocked: false, decisions };\n}\n\ntype RunGuardrailResult<TAction extends { action: GuardrailActionName }> = {\n action: TAction;\n decision: GuardrailDecisionRecord;\n};\n\nasync function runGuardrail<TAction extends { action: GuardrailActionName } & GuardrailActionBase>(\n policy: GuardrailPolicy,\n guardrailId: string,\n boundary: GuardrailBoundary,\n run: () => MaybePromise<TAction | undefined>,\n): Promise<RunGuardrailResult<TAction | GuardrailAllow>> {\n const startedAt = Date.now();\n try {\n const action = (await run()) ?? allow();\n return {\n action,\n decision: decisionRecord({\n policy,\n guardrailId,\n boundary,\n action,\n latencyMs: Date.now() - startedAt,\n }),\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (policy.mode === \"observe\") {\n return {\n action: allow(),\n decision: {\n policyId: policy.id,\n guardrailId,\n boundary,\n mode: policy.mode,\n action: \"error\",\n applied: false,\n reason: message,\n latencyMs: Date.now() - startedAt,\n },\n };\n }\n throw error;\n }\n}\n\nfunction decisionRecord(args: {\n policy: GuardrailPolicy;\n guardrailId: string;\n boundary: GuardrailBoundary;\n action: GuardrailAllow | GuardrailBlock | ({ action: GuardrailActionName } & GuardrailActionBase);\n latencyMs: number;\n}): GuardrailDecisionRecord {\n const applied = args.policy.mode === \"enforce\" && args.action.action !== \"allow\";\n const record: GuardrailDecisionRecord = {\n policyId: args.policy.id,\n guardrailId: args.guardrailId,\n boundary: args.boundary,\n mode: args.policy.mode,\n action: args.action.action,\n applied,\n latencyMs: args.latencyMs,\n };\n if (args.action.reason !== undefined) record.reason = args.action.reason;\n if (\"message\" in args.action && typeof args.action.message === \"string\") {\n record.message = args.action.message;\n }\n if (args.action.metadata !== undefined) record.metadata = args.action.metadata;\n return record;\n}\n\nconst commonActions: GuardrailCommonActions = {\n allow,\n block,\n};\n\nconst inputActions: InputGuardrailActions = {\n ...commonActions,\n rewrite(options) {\n return { action: \"rewrite\", ...options };\n },\n};\n\nconst outputActions: OutputGuardrailActions = {\n ...commonActions,\n rewrite(options) {\n return { action: \"rewrite\", ...options };\n },\n};\n\ntype TextPatternBoundary = \"input\" | \"output\";\n\ntype TextPatternGuardrailFor<Boundary extends TextPatternBoundary> = Boundary extends \"input\"\n ? InputGuardrail\n : OutputGuardrail;\n\ntype TextPatternGuardrailOptions<Boundary extends TextPatternBoundary = TextPatternBoundary> = {\n id: string;\n boundary: Boundary;\n patterns: Array<string | RegExp>;\n reason: string;\n message?: string | undefined;\n};\n\ntype TextPatternRedactOptions<Boundary extends TextPatternBoundary = TextPatternBoundary> =\n TextPatternGuardrailOptions<Boundary> & { replacement?: string | undefined };\n\nfunction blockText<Boundary extends TextPatternBoundary>(\n options: TextPatternGuardrailOptions<Boundary>,\n): TextPatternGuardrailFor<Boundary> {\n return textPatternGuardrail(options, \"block\");\n}\n\nfunction redactText<Boundary extends TextPatternBoundary>(\n options: TextPatternRedactOptions<Boundary>,\n): TextPatternGuardrailFor<Boundary> {\n return textPatternGuardrail(options, \"rewrite\");\n}\n\nfunction textPatternGuardrail<Boundary extends TextPatternBoundary>(\n options: TextPatternRedactOptions<Boundary>,\n action: \"block\" | \"rewrite\",\n): TextPatternGuardrailFor<Boundary> {\n if (options.boundary === \"input\") {\n return defineInputGuardrail({\n id: options.id,\n check(ctx, actions) {\n return textPatternAction(ctx.inputText, options, action, (value) =>\n actions.rewrite({ inputText: value, reason: options.reason }),\n );\n },\n }) as TextPatternGuardrailFor<Boundary>;\n }\n return defineOutputGuardrail({\n id: options.id,\n check(ctx, actions) {\n return textPatternAction(ctx.outputText, options, action, (value) =>\n actions.rewrite({ outputText: value, reason: options.reason }),\n );\n },\n }) as TextPatternGuardrailFor<Boundary>;\n}\n\nfunction textPatternAction<TRewrite>(\n text: string,\n options: TextPatternGuardrailOptions & { replacement?: string | undefined },\n action: \"block\" | \"rewrite\",\n rewrite: (value: string) => TRewrite,\n): GuardrailAllow | GuardrailBlock | TRewrite {\n const matched = options.patterns.some((pattern) => textPatternMatches(text, pattern));\n if (!matched) {\n return allow();\n }\n if (action === \"block\") {\n return block({\n reason: options.reason,\n message: options.message,\n });\n }\n let current = text;\n for (const pattern of options.patterns) {\n current = replaceTextPattern(current, pattern, options.replacement ?? \"[redacted]\");\n }\n return rewrite(current);\n}\n\nfunction textPatternMatches(text: string, pattern: string | RegExp): boolean {\n if (typeof pattern === \"string\") {\n return text.includes(pattern);\n }\n pattern.lastIndex = 0;\n const matched = pattern.test(text);\n pattern.lastIndex = 0;\n return matched;\n}\n\nfunction replaceTextPattern(text: string, pattern: string | RegExp, replacement: string): string {\n if (typeof pattern === \"string\") {\n return text.split(pattern).join(replacement);\n }\n pattern.lastIndex = 0;\n const flags = pattern.flags.replace(\"y\", \"\");\n const globalFlags = flags.includes(\"g\") ? flags : `${flags}g`;\n return text.replace(new RegExp(pattern.source, globalFlags), replacement);\n}\n\nfunction textFromMessage(message: Message): string {\n if (message.role === \"system\") {\n return message.content;\n }\n if (typeof message.content === \"string\") {\n return message.content;\n }\n return message.content\n .flatMap((content) => {\n if (content.type === \"text\") {\n return [content.text];\n }\n if (content.type === \"file\" && content.data.type === \"text\") {\n return [content.data.text];\n }\n if (content.type === \"tool-result\") {\n return textFromToolResult(content.output);\n }\n return [];\n })\n .join(\"\\n\");\n}\n\nfunction rewriteMessageText(message: Message, text: string): Message {\n if (message.role === \"system\") {\n return { ...message, content: text };\n }\n if (message.role === \"user\") {\n const content = typeof message.content === \"string\" ? [] : message.content;\n return {\n ...message,\n content: [\n { type: \"text\", text },\n ...content.filter(\n (item) => item.type !== \"text\" && !(item.type === \"file\" && item.data.type === \"text\"),\n ),\n ],\n };\n }\n if (message.role === \"assistant\") {\n return { ...message, content: [{ type: \"text\", text }] };\n }\n return message;\n}\n\nfunction textFromToolResult(output: ToolResultPart[\"output\"]): string[] {\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n return [output.value];\n case \"json\":\n case \"error-json\":\n return [JSON.stringify(output.value)];\n case \"content\":\n return output.value.flatMap((part) => (part.type === \"text\" ? [part.text] : []));\n case \"execution-denied\":\n return output.reason === undefined ? [] : [output.reason];\n }\n}\n"],"mappings":";AAoIO,SAAS,sBAAsB,SAAkD;AACtF,SAAO;AAAA,IACL,IAAI,QAAQ;AAAA,IACZ,MAAM,QAAQ,QAAQ;AAAA,IACtB,OAAO,QAAQ,SAAS,CAAC;AAAA,IACzB,QAAQ,QAAQ,UAAU,CAAC;AAAA,EAC7B;AACF;AAEO,SAAS,qBAAqB,WAA2C;AAC9E,SAAO;AACT;AAEO,SAAS,sBAAsB,WAA6C;AACjF,SAAO;AACT;AAEO,SAAS,MAAM,UAA+B,CAAC,GAAmB;AACvE,SAAO,EAAE,QAAQ,SAAS,GAAG,QAAQ;AACvC;AAEO,SAAS,MAAM,SAAyD;AAC7E,SAAO,EAAE,QAAQ,SAAS,GAAG,QAAQ;AACvC;AAEO,IAAM,aAAa;AAAA,EACxB;AAAA,EACA;AACF;AAEO,SAAS,2BACd,UACmB;AACnB,MAAI,aAAa,QAAW;AAC1B,WAAO,CAAC;AAAA,EACV;AACA,SAAO,MAAM,QAAQ,QAAQ,IAAI,WAAW,CAAC,QAAQ;AACvD;AAEO,SAAS,wBACd,SACA,MACmB;AACnB,SAAO,CAAC,GAAG,SAAS,GAAG,2BAA2B,IAAI,CAAC;AACzD;AAEO,SAAS,4BAA4B,UAAsC;AAChF,SAAO,SAAS,KAAK,CAAC,WAAW,OAAO,SAAS,aAAa,OAAO,OAAO,SAAS,CAAC;AACxF;AAEA,eAAsB,mBACpB,UACA,SACkC;AAClC,MAAI,SAAS,QAAQ;AACrB,MAAI,YAAY,QAAQ;AACxB,QAAM,YAAuC,CAAC;AAE9C,aAAW,UA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@@
1
+ import {
2
+ isJsonValue,
3
+ parseMessage,
4
+ parseMessages,
5
+ toProviderJsonSchema
6
+ } from "./chunk-TIZYTPJO.js";
7
+ import {
8
+ abortError,
9
+ resolveRetryOptions,
10
+ retryDelayMs,
11
+ retryOptionsForFailure,
12
+ runWithRetries,
13
+ throwIfAborted,
14
+ waitForRetry
15
+ } from "./chunk-FN7HLLAZ.js";
16
+
17
+ // src/completion/types.ts
18
+ function reasoningDisplayText(reasoning) {
19
+ const details = "type" in reasoning ? reasoning.details : reasoning;
20
+ if (details === void 0) {
21
+ return "type" in reasoning ? reasoning.text : "";
22
+ }
23
+ return details.flatMap((item) => {
24
+ if (item.type === "text" || item.type === "summary") {
25
+ return [item.text];
26
+ }
27
+ return [];
28
+ }).join("");
29
+ }
30
+ function isProviderTool(value) {
31
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
32
+ return false;
33
+ }
34
+ const candidate = value;
35
+ return candidate.kind === "provider" && typeof candidate.provider === "string" && candidate.provider.trim().length > 0 && typeof candidate.name === "string" && candidate.name.trim().length > 0 && (candidate.configuration === void 0 || typeof candidate.configuration === "object" && candidate.configuration !== null && !Array.isArray(candidate.configuration) && isJsonValue(candidate.configuration));
36
+ }
37
+ function calculateContextUsage(usage, model) {
38
+ if (model === void 0 || !Number.isFinite(usage.inputTokens) || usage.inputTokens <= 0 || !Number.isFinite(model.context.contextWindow) || model.context.contextWindow <= 0) {
39
+ return void 0;
40
+ }
41
+ const usedTokens = Math.max(0, usage.inputTokens);
42
+ const remainingTokens = Math.max(0, model.context.contextWindow - usedTokens);
43
+ const usedPercent = Math.min(100, usedTokens / model.context.contextWindow * 100);
44
+ return {
45
+ model,
46
+ usedTokens,
47
+ remainingTokens,
48
+ usedPercent,
49
+ remainingPercent: 100 - usedPercent
50
+ };
51
+ }
52
+ function withContextUsage(response, model) {
53
+ const contextUsage = calculateContextUsage(response.usage, model);
54
+ return contextUsage === void 0 ? response : { ...response, contextUsage };
55
+ }
56
+ function resolveModelContextLimits(modelId, catalog, override) {
57
+ return override ?? catalog[modelId];
58
+ }
59
+ var Usage = {
60
+ empty() {
61
+ return {
62
+ inputTokens: 0,
63
+ outputTokens: 0,
64
+ totalTokens: 0,
65
+ cachedInputTokens: 0,
66
+ cacheCreationInputTokens: 0
67
+ };
68
+ },
69
+ add(left, right) {
70
+ const result = {
71
+ inputTokens: left.inputTokens + right.inputTokens,
72
+ outputTokens: left.outputTokens + right.outputTokens,
73
+ totalTokens: left.totalTokens + right.totalTokens,
74
+ cachedInputTokens: left.cachedInputTokens + right.cachedInputTokens,
75
+ cacheCreationInputTokens: left.cacheCreationInputTokens + right.cacheCreationInputTokens
76
+ };
77
+ const details = addUsageDetails(left, right);
78
+ if (details !== void 0) {
79
+ result.details = details;
80
+ }
81
+ return result;
82
+ }
83
+ };
84
+ function addUsageDetails(left, right) {
85
+ if (isEmptyUsage(left) && left.details === void 0) {
86
+ return right.details === void 0 ? void 0 : { ...right.details };
87
+ }
88
+ if (isEmptyUsage(right) && right.details === void 0) {
89
+ return left.details === void 0 ? void 0 : { ...left.details };
90
+ }
91
+ if (left.details === void 0 || right.details === void 0) {
92
+ return void 0;
93
+ }
94
+ const details = { ...left.details };
95
+ for (const [key, value] of Object.entries(right.details)) {
96
+ details[key] = (details[key] ?? 0) + value;
97
+ }
98
+ return details;
99
+ }
100
+ function isEmptyUsage(usage) {
101
+ return usage.inputTokens === 0 && usage.outputTokens === 0 && usage.totalTokens === 0 && usage.cachedInputTokens === 0 && usage.cacheCreationInputTokens === 0;
102
+ }
103
+ function getAssistantGenerationMetadata(message) {
104
+ if (message.role !== "assistant" || !isJsonObjectValue(message.metadata)) {
105
+ return void 0;
106
+ }
107
+ const frameworkMetadata = message.metadata.anvia;
108
+ if (!isJsonObjectValue(frameworkMetadata)) {
109
+ return void 0;
110
+ }
111
+ const generation = frameworkMetadata.generation;
112
+ if (!isJsonObjectValue(generation) || typeof generation.provider !== "string" || typeof generation.modelId !== "string" || !isUsageValue(generation.usage)) {
113
+ return void 0;
114
+ }
115
+ const metadata = {
116
+ provider: generation.provider,
117
+ modelId: generation.modelId,
118
+ usage: {
119
+ ...generation.usage,
120
+ ...generation.usage.details === void 0 ? {} : { details: { ...generation.usage.details } }
121
+ }
122
+ };
123
+ if (isContextUsageValue(generation.contextUsage)) {
124
+ metadata.contextUsage = {
125
+ ...generation.contextUsage,
126
+ model: {
127
+ ...generation.contextUsage.model,
128
+ context: { ...generation.contextUsage.model.context }
129
+ }
130
+ };
131
+ }
132
+ if (isCompletionSourceArray(generation.sources)) {
133
+ metadata.sources = generation.sources.map((source) => ({ ...source }));
134
+ }
135
+ if (isProviderToolCallArray(generation.providerToolCalls)) {
136
+ metadata.providerToolCalls = generation.providerToolCalls.map((toolCall) => ({
137
+ ...toolCall,
138
+ ...toolCall.details === void 0 ? {} : { details: { ...toolCall.details } }
139
+ }));
140
+ }
141
+ return metadata;
142
+ }
143
+ function isJsonObjectValue(value) {
144
+ return typeof value === "object" && value !== null && !Array.isArray(value);
145
+ }
146
+ function isContextUsageValue(value) {
147
+ if (!isJsonObjectValue(value) || !isJsonObjectValue(value.model)) {
148
+ return false;
149
+ }
150
+ const context = value.model.context;
151
+ if (typeof value.model.modelId === "string" && isJsonObjectValue(context) && isPositiveFiniteNumber(context.contextWindow) && isOptionalPositiveFiniteNumber(context.maxInputTokens) && isOptionalPositiveFiniteNumber(context.maxOutputTokens) && isNonnegativeFiniteNumber(value.usedTokens) && isNonnegativeFiniteNumber(value.remainingTokens) && isPercentage(value.usedPercent) && isPercentage(value.remainingPercent)) {
152
+ const contextWindow = context.contextWindow;
153
+ const remainingTokens = Math.max(0, contextWindow - value.usedTokens);
154
+ const usedPercent = Math.min(100, value.usedTokens / contextWindow * 100);
155
+ const remainingPercent = remainingTokens / contextWindow * 100;
156
+ return value.remainingTokens === remainingTokens && approximatelyEqual(value.usedPercent, usedPercent) && approximatelyEqual(value.remainingPercent, remainingPercent);
157
+ }
158
+ return false;
159
+ }
160
+ function approximatelyEqual(left, right) {
161
+ const scale = Math.max(1, Math.abs(left), Math.abs(right));
162
+ return Math.abs(left - right) <= Number.EPSILON * scale * 8;
163
+ }
164
+ function isPositiveFiniteNumber(value) {
165
+ return isNonnegativeFiniteNumber(value) && value > 0;
166
+ }
167
+ function isOptionalPositiveFiniteNumber(value) {
168
+ return value === void 0 || isPositiveFiniteNumber(value);
169
+ }
170
+ function isPercentage(value) {
171
+ return isNonnegativeFiniteNumber(value) && value <= 100;
172
+ }
173
+ function isUsageValue(value) {
174
+ if (!isJsonObjectValue(value)) {
175
+ return false;
176
+ }
177
+ return isNonnegativeFiniteNumber(value.inputTokens) && isNonnegativeFiniteNumber(value.outputTokens) && isNonnegativeFiniteNumber(value.totalTokens) && isNonnegativeFiniteNumber(value.cachedInputTokens) && isNonnegativeFiniteNumber(value.cacheCreationInputTokens) && isUsageDetailsValue(value.details);
178
+ }
179
+ function isNonnegativeFiniteNumber(value) {
180
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
181
+ }
182
+ function isUsageDetailsValue(value) {
183
+ if (value === void 0) {
184
+ return true;
185
+ }
186
+ if (!isJsonObjectValue(value)) {
187
+ return false;
188
+ }
189
+ let total;
190
+ let bucketSum = 0;
191
+ for (const [key, detail] of Object.entries(value)) {
192
+ if (detail === void 0 || !isNonnegativeFiniteNumber(detail)) {
193
+ return false;
194
+ }
195
+ if (key === "total") {
196
+ total = detail;
197
+ } else {
198
+ bucketSum += detail;
199
+ }
200
+ }
201
+ return total !== void 0 && total === bucketSum;
202
+ }
203
+ function isCompletionSourceArray(value) {
204
+ return Array.isArray(value) && value.every(
205
+ (source) => isJsonObjectValue(source) && source.type === "url" && typeof source.url === "string" && (source.title === void 0 || typeof source.title === "string") && (source.id === void 0 || typeof source.id === "string") && (source.startIndex === void 0 || typeof source.startIndex === "number") && (source.endIndex === void 0 || typeof source.endIndex === "number")
206
+ );
207
+ }
208
+ function isProviderToolCallArray(value) {
209
+ return Array.isArray(value) && value.every(
210
+ (toolCall) => isJsonObjectValue(toolCall) && typeof toolCall.id === "string" && typeof toolCall.name === "string" && (toolCall.status === void 0 || typeof toolCall.status === "string") && (toolCall.details === void 0 || isJsonObjectValue(toolCall.details))
211
+ );
212
+ }
213
+ var CompletionCapabilityError = class extends Error {
214
+ constructor(message) {
215
+ super(message);
216
+ this.name = "CompletionCapabilityError";
217
+ }
218
+ };
219
+ function assertCompletionRequestSupported(model, request, options = {}) {
220
+ const modelLabel = `${model.provider}:${model.modelId}`;
221
+ const capabilities = model.capabilities;
222
+ if (options.streaming === true && !capabilities.streaming) {
223
+ throw new CompletionCapabilityError(`${modelLabel} does not support streaming completions.`);
224
+ }
225
+ if (request.tools.length > 0 && !capabilities.tools) {
226
+ throw new CompletionCapabilityError(`${modelLabel} does not support tool definitions.`);
227
+ }
228
+ if ((request.providerTools?.length ?? 0) > 0 && capabilities.providerTools !== true) {
229
+ throw new CompletionCapabilityError(`${modelLabel} does not support provider-executed tools.`);
230
+ }
231
+ if (request.toolChoice !== void 0 && !capabilities.toolChoice) {
232
+ throw new CompletionCapabilityError(`${modelLabel} does not support tool choice.`);
233
+ }
234
+ if (request.outputSchema !== void 0 && !capabilities.outputSchema) {
235
+ throw new CompletionCapabilityError(`${modelLabel} does not support output schemas.`);
236
+ }
237
+ if (!capabilities.imageInput && requestHasImageInput(request)) {
238
+ throw new CompletionCapabilityError(`${modelLabel} does not support image input.`);
239
+ }
240
+ if (!capabilities.documentInput && requestHasFileDocumentInput(request)) {
241
+ throw new CompletionCapabilityError(`${modelLabel} does not support document file input.`);
242
+ }
243
+ }
244
+ function textFromAssistantContent(content) {
245
+ return content.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n");
246
+ }
247
+ function requestHasImageInput(request) {
248
+ return request.chatHistory.some(
249
+ (message) => message.role === "system" || typeof message.content === "string" ? false : message.content.some((content) => content.type === "image")
250
+ );
251
+ }
252
+ function requestHasFileDocumentInput(request) {
253
+ return request.chatHistory.some(
254
+ (message) => message.role === "user" && typeof message.content !== "string" ? message.content.some((content) => content.type === "file" && content.data.type !== "text") : false
255
+ );
256
+ }
257
+
258
+ // src/internal/completion-request.ts
259
+ function createCompletionRequest(input, options) {
260
+ const configuredTools = options.tools ?? [];
261
+ const request = {
262
+ chatHistory: messagesFromInput(input),
263
+ documents: [...options.documents ?? []],
264
+ tools: configuredTools.filter((tool) => !isProviderTool(tool))
265
+ };
266
+ const providerTools = configuredTools.filter(isProviderTool);
267
+ if (providerTools.length > 0) request.providerTools = providerTools;
268
+ if (options.instructions !== void 0 && options.instructions.length > 0) {
269
+ request.instructions = options.instructions;
270
+ }
271
+ if (options.temperature !== void 0) request.temperature = options.temperature;
272
+ if (options.maxTokens !== void 0) request.maxTokens = options.maxTokens;
273
+ if (options.toolChoice !== void 0) request.toolChoice = options.toolChoice;
274
+ if (options.outputSchema !== void 0) request.outputSchema = options.outputSchema;
275
+ if (options.providerOptions !== void 0) request.providerOptions = options.providerOptions;
276
+ return request;
277
+ }
278
+ function messagesFromInput(input) {
279
+ if (typeof input === "string") {
280
+ return [{ role: "user", content: input }];
281
+ }
282
+ if (Array.isArray(input)) {
283
+ if (input.length === 0) {
284
+ throw new Error("input must contain at least one Message.");
285
+ }
286
+ return parseMessages(input);
287
+ }
288
+ return [parseMessage(input)];
289
+ }
290
+
291
+ // src/completion/generate-completion.ts
292
+ async function generateCompletion(options) {
293
+ throwIfAborted(options.abortSignal);
294
+ const request = requestFromOptions(options);
295
+ assertCompletionRequestSupported(options.model, request);
296
+ const retries = resolveOptionalRetries(options.retries);
297
+ const response = await sendCompletion(options.model, request, retries, options.abortSignal);
298
+ return resultFromResponse(response, structuredOutputSchema(options));
299
+ }
300
+ function streamCompletion(options) {
301
+ throwIfAborted(options.abortSignal);
302
+ const request = requestFromOptions(options);
303
+ if (!isStreamingCompletionModel(options.model) || !options.model.capabilities.streaming) {
304
+ throw new Error("This completion model does not support streaming");
305
+ }
306
+ assertCompletionRequestSupported(options.model, request, { streaming: true });
307
+ const retries = resolveOptionalRetries(options.retries);
308
+ return streamCompletionWithRetries(
309
+ options.model,
310
+ request,
311
+ retries,
312
+ options.abortSignal,
313
+ structuredOutputSchema(options)
314
+ );
315
+ }
316
+ async function sendCompletion(model, request, retries, abortSignal) {
317
+ const callOptions = modelCallOptions(abortSignal);
318
+ return runWithRetries(
319
+ () => {
320
+ throwIfAborted(abortSignal);
321
+ return model.completion(request, callOptions);
322
+ },
323
+ retries,
324
+ { streaming: false, abortSignal }
325
+ );
326
+ }
327
+ function resolveOptionalRetries(setting) {
328
+ return setting === void 0 || setting === false ? void 0 : resolveRetryOptions(setting);
329
+ }
330
+ async function* streamCompletionWithRetries(model, request, retries, abortSignal, outputSchema) {
331
+ let attempt = 1;
332
+ let swallowedUsage = Usage.empty();
333
+ const callOptions = modelCallOptions(abortSignal);
334
+ while (true) {
335
+ let exposedProgress = false;
336
+ let retryDelay;
337
+ try {
338
+ throwIfAborted(abortSignal);
339
+ const events = model.streamCompletion(request, callOptions);
340
+ for await (const event of events) {
341
+ if (event.type === "error" && !exposedProgress) {
342
+ const retryOptions = retryOptionsForFailure(retries, {
343
+ error: event.error,
344
+ attempt,
345
+ streaming: true
346
+ });
347
+ if (retryOptions !== void 0) {
348
+ swallowedUsage = Usage.add(swallowedUsage, event.usage ?? Usage.empty());
349
+ retryDelay = retryDelayMs(retryOptions, attempt);
350
+ break;
351
+ }
352
+ }
353
+ if (event.type === "error") {
354
+ yield {
355
+ type: "error",
356
+ error: event.error,
357
+ usage: Usage.add(swallowedUsage, event.usage ?? Usage.empty())
358
+ };
359
+ return;
360
+ }
361
+ if (event.type === "final") {
362
+ const response = swallowedUsage.totalTokens === 0 ? event.response : {
363
+ ...event.response,
364
+ usage: Usage.add(swallowedUsage, event.response.usage)
365
+ };
366
+ try {
367
+ yield {
368
+ type: "final",
369
+ result: resultFromResponse(response, outputSchema)
370
+ };
371
+ } catch (error) {
372
+ yield { type: "error", error, usage: response.usage };
373
+ }
374
+ return;
375
+ }
376
+ exposedProgress = true;
377
+ yield event;
378
+ }
379
+ if (retryDelay !== void 0) {
380
+ await waitForRetry(retryDelay, abortSignal);
381
+ attempt += 1;
382
+ continue;
383
+ }
384
+ yield {
385
+ type: "error",
386
+ error: new Error("The completion model stream ended without a final event."),
387
+ usage: swallowedUsage
388
+ };
389
+ return;
390
+ } catch (error) {
391
+ const normalizedError = abortSignal?.aborted === true ? abortError(abortSignal.reason) : error;
392
+ if (!exposedProgress) {
393
+ const retryOptions = retryOptionsForFailure(retries, {
394
+ error: normalizedError,
395
+ attempt,
396
+ streaming: true
397
+ });
398
+ if (retryOptions !== void 0) {
399
+ try {
400
+ await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);
401
+ attempt += 1;
402
+ continue;
403
+ } catch (waitError) {
404
+ yield { type: "error", error: waitError, usage: swallowedUsage };
405
+ return;
406
+ }
407
+ }
408
+ }
409
+ yield { type: "error", error: normalizedError, usage: swallowedUsage };
410
+ return;
411
+ }
412
+ }
413
+ }
414
+ function requestFromOptions(options) {
415
+ const input = inputFromOptions(options);
416
+ return createCompletionRequest(input, {
417
+ instructions: options.instructions,
418
+ documents: options.documents,
419
+ tools: options.tools,
420
+ temperature: options.temperature,
421
+ maxTokens: options.maxTokens,
422
+ toolChoice: options.toolChoice,
423
+ providerOptions: options.providerOptions,
424
+ outputSchema: "outputSchema" in options && options.outputSchema !== void 0 ? toProviderJsonSchema(options.outputSchema) : void 0
425
+ });
426
+ }
427
+ function inputFromOptions(options) {
428
+ const prompt = options.prompt;
429
+ const messages = options.messages;
430
+ const hasPrompt = prompt !== void 0;
431
+ const hasMessages = messages !== void 0;
432
+ if (hasPrompt === hasMessages) {
433
+ throw new TypeError("Exactly one of prompt or messages must be provided.");
434
+ }
435
+ if (hasPrompt) {
436
+ if (typeof prompt !== "string" || prompt.trim().length === 0) {
437
+ throw new TypeError("Completion prompt must be a non-empty string.");
438
+ }
439
+ return prompt;
440
+ }
441
+ if (!Array.isArray(messages)) {
442
+ throw new TypeError("Completion messages must be an array of Message values.");
443
+ }
444
+ return messages;
445
+ }
446
+ function structuredOutputSchema(options) {
447
+ return options.outputSchema;
448
+ }
449
+ function resultFromResponse(response, outputSchema) {
450
+ const text = textFromAssistantContent(response.choice);
451
+ const result = {
452
+ output: outputSchema === void 0 ? text : parseCompletionOutput(text, outputSchema),
453
+ text,
454
+ content: [...response.choice],
455
+ usage: response.usage,
456
+ rawResponse: response.rawResponse
457
+ };
458
+ if (response.contextUsage !== void 0) result.contextUsage = response.contextUsage;
459
+ if (response.messageId !== void 0) result.messageId = response.messageId;
460
+ if (response.sources !== void 0) result.sources = [...response.sources];
461
+ if (response.providerToolCalls !== void 0) {
462
+ result.providerToolCalls = [...response.providerToolCalls];
463
+ }
464
+ return result;
465
+ }
466
+ function parseCompletionOutput(text, schema) {
467
+ let json;
468
+ try {
469
+ json = JSON.parse(text);
470
+ } catch (error) {
471
+ throw new Error("generateCompletion expected the model response to be valid JSON.", {
472
+ cause: error
473
+ });
474
+ }
475
+ return schema.parse(json);
476
+ }
477
+ function modelCallOptions(abortSignal) {
478
+ return abortSignal === void 0 ? void 0 : { abortSignal };
479
+ }
480
+ function isStreamingCompletionModel(model) {
481
+ return typeof model.streamCompletion === "function";
482
+ }
483
+
484
+ export {
485
+ reasoningDisplayText,
486
+ isProviderTool,
487
+ calculateContextUsage,
488
+ withContextUsage,
489
+ resolveModelContextLimits,
490
+ Usage,
491
+ getAssistantGenerationMetadata,
492
+ CompletionCapabilityError,
493
+ assertCompletionRequestSupported,
494
+ textFromAssistantContent,
495
+ createCompletionRequest,
496
+ generateCompletion,
497
+ streamCompletion,
498
+ isStreamingCompletionModel
499
+ };
500
+ //# sourceMappingURL=chunk-KR3RCCHJ.js.map