@anvia/core 0.26.0 → 1.0.0-rc.10

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 (184) hide show
  1. package/README.md +400 -94
  2. package/dist/agent/index.d.ts +67 -71
  3. package/dist/agent/index.js +36 -18
  4. package/dist/agent/interactions/index.d.ts +122 -0
  5. package/dist/agent/interactions/index.js +20 -0
  6. package/dist/agent-DWzW9SoH.d.ts +150 -0
  7. package/dist/chunk-3RM57ZT2.js +31 -0
  8. package/dist/chunk-3RM57ZT2.js.map +1 -0
  9. package/dist/chunk-3RWESPUG.js +331 -0
  10. package/dist/chunk-3RWESPUG.js.map +1 -0
  11. package/dist/{chunk-NCPN4SJR.js → chunk-3SKZ2BKP.js} +15 -13
  12. package/dist/chunk-3SKZ2BKP.js.map +1 -0
  13. package/dist/chunk-3XQGVDU5.js +69 -0
  14. package/dist/chunk-3XQGVDU5.js.map +1 -0
  15. package/dist/{chunk-MRQLEK2B.js → chunk-5C6B6ZRH.js} +69 -51
  16. package/dist/chunk-5C6B6ZRH.js.map +1 -0
  17. package/dist/chunk-6BBOCFHV.js +323 -0
  18. package/dist/chunk-6BBOCFHV.js.map +1 -0
  19. package/dist/chunk-7JLAIN6E.js +15 -0
  20. package/dist/chunk-7JLAIN6E.js.map +1 -0
  21. package/dist/chunk-7PHMK7W4.js +1516 -0
  22. package/dist/chunk-7PHMK7W4.js.map +1 -0
  23. package/dist/{chunk-CWUJUSOS.js → chunk-AZB6N7P4.js} +94 -65
  24. package/dist/chunk-AZB6N7P4.js.map +1 -0
  25. package/dist/chunk-D4PACGPA.js +37 -0
  26. package/dist/chunk-D4PACGPA.js.map +1 -0
  27. package/dist/chunk-EFLT7XZD.js +51 -0
  28. package/dist/chunk-EFLT7XZD.js.map +1 -0
  29. package/dist/chunk-EMZKPRE6.js +667 -0
  30. package/dist/chunk-EMZKPRE6.js.map +1 -0
  31. package/dist/chunk-I3Q7XSBB.js +59 -0
  32. package/dist/chunk-I3Q7XSBB.js.map +1 -0
  33. package/dist/chunk-J6LVLV6P.js +13 -0
  34. package/dist/chunk-J6LVLV6P.js.map +1 -0
  35. package/dist/chunk-LTXABCOO.js +127 -0
  36. package/dist/chunk-LTXABCOO.js.map +1 -0
  37. package/dist/chunk-OJBFDBLG.js +164 -0
  38. package/dist/chunk-OJBFDBLG.js.map +1 -0
  39. package/dist/chunk-QGX73TSQ.js +177 -0
  40. package/dist/chunk-QGX73TSQ.js.map +1 -0
  41. package/dist/chunk-QOUPWOGW.js +29 -0
  42. package/dist/chunk-QOUPWOGW.js.map +1 -0
  43. package/dist/chunk-SJMSS5SI.js +171 -0
  44. package/dist/chunk-SJMSS5SI.js.map +1 -0
  45. package/dist/chunk-T2C3CGDQ.js +56 -0
  46. package/dist/chunk-T2C3CGDQ.js.map +1 -0
  47. package/dist/chunk-VX3HS6PE.js +4569 -0
  48. package/dist/chunk-VX3HS6PE.js.map +1 -0
  49. package/dist/chunk-X4LK4ODN.js +86 -0
  50. package/dist/chunk-X4LK4ODN.js.map +1 -0
  51. package/dist/chunk-ZA564323.js +331 -0
  52. package/dist/chunk-ZA564323.js.map +1 -0
  53. package/dist/completion/index.d.ts +6 -36
  54. package/dist/completion/index.js +34 -29
  55. package/dist/documents/index.d.ts +34 -0
  56. package/dist/documents/index.js +340 -0
  57. package/dist/documents/index.js.map +1 -0
  58. package/dist/dynamic-tools-aIZlg5x1.d.ts +45 -0
  59. package/dist/embeddings/index.d.ts +11 -9
  60. package/dist/embeddings/index.js +3 -4
  61. package/dist/evals/index.d.ts +57 -21
  62. package/dist/evals/index.js +209 -104
  63. package/dist/evals/index.js.map +1 -1
  64. package/dist/extractor/index.d.ts +27 -42
  65. package/dist/extractor/index.js +9 -22
  66. package/dist/guardrails/index.d.ts +7 -129
  67. package/dist/guardrails/index.js +1 -1
  68. package/dist/image-generation/index.d.ts +23 -23
  69. package/dist/image-generation/index.js +7 -39
  70. package/dist/image-generation/index.js.map +1 -1
  71. package/dist/index.d.ts +24 -22
  72. package/dist/index.js +85 -68
  73. package/dist/internal/agent.d.ts +156 -10
  74. package/dist/internal/agent.js +58 -18
  75. package/dist/internal/agent.js.map +1 -1
  76. package/dist/mcp/index.d.ts +7 -15
  77. package/dist/mcp/index.js +3 -348
  78. package/dist/mcp/index.js.map +1 -1
  79. package/dist/memory/index.d.ts +20 -6
  80. package/dist/memory/index.js +11 -10
  81. package/dist/middleware-kcF8AusP.d.ts +59 -0
  82. package/dist/model-call-options-CZkSw_xN.d.ts +6 -0
  83. package/dist/model-listing/index.d.ts +3 -1
  84. package/dist/observability/index.d.ts +23 -4
  85. package/dist/observability/index.js +10 -5
  86. package/dist/observability/index.js.map +1 -1
  87. package/dist/pipeline/index.d.ts +111 -73
  88. package/dist/pipeline/index.js +471 -286
  89. package/dist/pipeline/index.js.map +1 -1
  90. package/dist/provider-output-error-BEwDgVv3.d.ts +99 -0
  91. package/dist/retry-CjvSlKGW.d.ts +16 -0
  92. package/dist/skills/index.d.ts +5 -4
  93. package/dist/skills/index.js +8 -8
  94. package/dist/speech-generation/index.d.ts +37 -0
  95. package/dist/speech-generation/index.js +10 -0
  96. package/dist/streaming/index.js +37 -3
  97. package/dist/streaming/index.js.map +1 -1
  98. package/dist/text-ZLECpQE7.d.ts +32 -0
  99. package/dist/think-tool-BwCsJ365.d.ts +40 -0
  100. package/dist/tool/index.d.ts +11 -6
  101. package/dist/tool/index.js +21 -21
  102. package/dist/tool-BpqpoRSE.d.ts +58 -0
  103. package/dist/transcription/index.d.ts +29 -22
  104. package/dist/transcription/index.js +7 -57
  105. package/dist/transcription/index.js.map +1 -1
  106. package/dist/type-utils-CtHVDRn_.d.ts +6 -0
  107. package/dist/types-CXNE592e.d.ts +130 -0
  108. package/dist/types-Cr4uiYo5.d.ts +99 -0
  109. package/dist/{types-04LqWrmy.d.ts → types-DC1U1XwW.d.ts} +1 -1
  110. package/dist/types-DKOXVTcq.d.ts +155 -0
  111. package/dist/types-DgvozfPc.d.ts +349 -0
  112. package/dist/types-DhkodEft.d.ts +105 -0
  113. package/dist/types-DjqRHeAi.d.ts +31 -0
  114. package/dist/types-Sue2hb_L.d.ts +403 -0
  115. package/dist/vector-store/index.d.ts +34 -34
  116. package/dist/vector-store/index.js +10 -6
  117. package/package.json +22 -24
  118. package/dist/agent-x3YTyv5i.d.ts +0 -222
  119. package/dist/audio-generation/index.d.ts +0 -33
  120. package/dist/audio-generation/index.js +0 -42
  121. package/dist/audio-generation/index.js.map +0 -1
  122. package/dist/chunk-2ODTMRHP.js +0 -54
  123. package/dist/chunk-2ODTMRHP.js.map +0 -1
  124. package/dist/chunk-ADH7NNCS.js +0 -512
  125. package/dist/chunk-ADH7NNCS.js.map +0 -1
  126. package/dist/chunk-BALBBVI3.js +0 -2732
  127. package/dist/chunk-BALBBVI3.js.map +0 -1
  128. package/dist/chunk-CQNNSZPG.js +0 -9
  129. package/dist/chunk-CQNNSZPG.js.map +0 -1
  130. package/dist/chunk-CWUJUSOS.js.map +0 -1
  131. package/dist/chunk-DALYP4PX.js +0 -225
  132. package/dist/chunk-DALYP4PX.js.map +0 -1
  133. package/dist/chunk-HYUYZEAJ.js +0 -223
  134. package/dist/chunk-HYUYZEAJ.js.map +0 -1
  135. package/dist/chunk-I6XOQ4LK.js +0 -466
  136. package/dist/chunk-I6XOQ4LK.js.map +0 -1
  137. package/dist/chunk-JI5YZWNT.js +0 -220
  138. package/dist/chunk-JI5YZWNT.js.map +0 -1
  139. package/dist/chunk-MC3CCKEB.js +0 -221
  140. package/dist/chunk-MC3CCKEB.js.map +0 -1
  141. package/dist/chunk-MELYDKWQ.js +0 -337
  142. package/dist/chunk-MELYDKWQ.js.map +0 -1
  143. package/dist/chunk-MNWK2USR.js +0 -243
  144. package/dist/chunk-MNWK2USR.js.map +0 -1
  145. package/dist/chunk-MRQLEK2B.js.map +0 -1
  146. package/dist/chunk-NCPN4SJR.js.map +0 -1
  147. package/dist/chunk-OIMLU4SF.js +0 -20
  148. package/dist/chunk-OIMLU4SF.js.map +0 -1
  149. package/dist/chunk-Q25IWLBT.js +0 -138
  150. package/dist/chunk-Q25IWLBT.js.map +0 -1
  151. package/dist/chunk-UQX6EXWG.js +0 -33
  152. package/dist/chunk-UQX6EXWG.js.map +0 -1
  153. package/dist/chunk-WQKHFADH.js +0 -12
  154. package/dist/chunk-WQKHFADH.js.map +0 -1
  155. package/dist/chunk-XUUY2L2D.js +0 -42
  156. package/dist/chunk-XUUY2L2D.js.map +0 -1
  157. package/dist/chunk-XWUC7CIT.js +0 -1
  158. package/dist/chunk-XWUC7CIT.js.map +0 -1
  159. package/dist/chunk-YLMDBQO4.js +0 -141
  160. package/dist/chunk-YLMDBQO4.js.map +0 -1
  161. package/dist/errors-2moLDuuN.d.ts +0 -17
  162. package/dist/hooks/index.d.ts +0 -12
  163. package/dist/hooks/index.js +0 -17
  164. package/dist/index-BxSbmOMr.d.ts +0 -257
  165. package/dist/json-BVPssigK.d.ts +0 -39
  166. package/dist/loaders/index.d.ts +0 -91
  167. package/dist/loaders/index.js +0 -299
  168. package/dist/loaders/index.js.map +0 -1
  169. package/dist/middleware-Dp3d_pxi.d.ts +0 -90
  170. package/dist/request/index.d.ts +0 -28
  171. package/dist/request/index.js +0 -25
  172. package/dist/think-tool-DfCMuO8e.d.ts +0 -26
  173. package/dist/tool-Cohdv5GC.d.ts +0 -65
  174. package/dist/types-BCTRUGex.d.ts +0 -47
  175. package/dist/types-BrLbKnEz.d.ts +0 -119
  176. package/dist/types-D9JpeAPF.d.ts +0 -114
  177. package/dist/types-G12i56s2.d.ts +0 -354
  178. package/dist/types-JJCxRnaZ.d.ts +0 -70
  179. package/dist/types-O-abTIin.d.ts +0 -79
  180. package/dist/ui/index.d.ts +0 -107
  181. package/dist/ui/index.js +0 -10
  182. package/dist/ui/index.js.map +0 -1
  183. /package/dist/{hooks → agent/interactions}/index.js.map +0 -0
  184. /package/dist/{request → speech-generation}/index.js.map +0 -0
@@ -0,0 +1,1516 @@
1
+ import {
2
+ assertJsonObject
3
+ } from "./chunk-7JLAIN6E.js";
4
+ import {
5
+ parseMessage,
6
+ parseMessages,
7
+ toProviderJsonSchema
8
+ } from "./chunk-QGX73TSQ.js";
9
+ import {
10
+ isJsonValue
11
+ } from "./chunk-3XQGVDU5.js";
12
+ import {
13
+ abortError,
14
+ completionProviderOutputErrorUsage,
15
+ resolveRetryOptions,
16
+ retryDelayMs,
17
+ retryOptionsForFailure,
18
+ throwIfAborted,
19
+ waitForRetry
20
+ } from "./chunk-3RWESPUG.js";
21
+
22
+ // src/completion/types.ts
23
+ function reasoningDisplayText(reasoning) {
24
+ const details = "type" in reasoning ? reasoning.details : reasoning;
25
+ if (details === void 0) {
26
+ return "type" in reasoning ? reasoning.text : "";
27
+ }
28
+ return details.flatMap((item) => {
29
+ if (item.type === "text" || item.type === "summary") {
30
+ return [item.text];
31
+ }
32
+ return [];
33
+ }).join("");
34
+ }
35
+ function isProviderTool(value) {
36
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
37
+ return false;
38
+ }
39
+ const candidate = value;
40
+ 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));
41
+ }
42
+ function calculateContextUsage(usage, model) {
43
+ if (model === void 0 || !Number.isFinite(usage.inputTokens) || usage.inputTokens <= 0 || !Number.isFinite(model.context.contextWindow) || model.context.contextWindow <= 0) {
44
+ return void 0;
45
+ }
46
+ const usedTokens = Math.max(0, usage.inputTokens);
47
+ const remainingTokens = Math.max(0, model.context.contextWindow - usedTokens);
48
+ const usedPercent = Math.min(100, usedTokens / model.context.contextWindow * 100);
49
+ return {
50
+ model,
51
+ usedTokens,
52
+ remainingTokens,
53
+ usedPercent,
54
+ remainingPercent: 100 - usedPercent
55
+ };
56
+ }
57
+ function withContextUsage(response, model) {
58
+ const contextUsage = calculateContextUsage(response.usage, model);
59
+ return contextUsage === void 0 ? response : { ...response, contextUsage };
60
+ }
61
+ function resolveModelContextLimits(modelId, catalog, override) {
62
+ return override ?? catalog[modelId];
63
+ }
64
+ var Usage = {
65
+ empty() {
66
+ return {
67
+ inputTokens: 0,
68
+ outputTokens: 0,
69
+ totalTokens: 0,
70
+ cachedInputTokens: 0,
71
+ cacheCreationInputTokens: 0
72
+ };
73
+ },
74
+ add(left, right) {
75
+ const result = {
76
+ inputTokens: left.inputTokens + right.inputTokens,
77
+ outputTokens: left.outputTokens + right.outputTokens,
78
+ totalTokens: left.totalTokens + right.totalTokens,
79
+ cachedInputTokens: left.cachedInputTokens + right.cachedInputTokens,
80
+ cacheCreationInputTokens: left.cacheCreationInputTokens + right.cacheCreationInputTokens
81
+ };
82
+ const details = addUsageDetails(left, right);
83
+ if (details !== void 0) {
84
+ result.details = details;
85
+ }
86
+ return result;
87
+ },
88
+ isEmpty(usage) {
89
+ return isEmptyUsage(usage) && (usage.details === void 0 || Object.values(usage.details).every((value) => value === 0));
90
+ }
91
+ };
92
+ function addUsageDetails(left, right) {
93
+ if (isEmptyUsage(left) && left.details === void 0) {
94
+ return right.details === void 0 ? void 0 : { ...right.details };
95
+ }
96
+ if (isEmptyUsage(right) && right.details === void 0) {
97
+ return left.details === void 0 ? void 0 : { ...left.details };
98
+ }
99
+ if (left.details === void 0 || right.details === void 0) {
100
+ return void 0;
101
+ }
102
+ const details = { ...left.details };
103
+ for (const [key, value] of Object.entries(right.details)) {
104
+ details[key] = (details[key] ?? 0) + value;
105
+ }
106
+ return details;
107
+ }
108
+ function isEmptyUsage(usage) {
109
+ return usage.inputTokens === 0 && usage.outputTokens === 0 && usage.totalTokens === 0 && usage.cachedInputTokens === 0 && usage.cacheCreationInputTokens === 0;
110
+ }
111
+ function getAssistantGenerationMetadata(message) {
112
+ if (message.role !== "assistant" || !isJsonObjectValue(message.metadata)) {
113
+ return void 0;
114
+ }
115
+ const frameworkMetadata = message.metadata.anvia;
116
+ if (!isJsonObjectValue(frameworkMetadata)) {
117
+ return void 0;
118
+ }
119
+ const generation = frameworkMetadata.generation;
120
+ if (!isJsonObjectValue(generation) || typeof generation.provider !== "string" || typeof generation.modelId !== "string" || !isUsageValue(generation.usage)) {
121
+ return void 0;
122
+ }
123
+ let usage = { ...generation.usage };
124
+ if (generation.usage.details !== void 0) {
125
+ usage = { ...usage, details: { ...generation.usage.details } };
126
+ }
127
+ const metadata = {
128
+ provider: generation.provider,
129
+ modelId: generation.modelId,
130
+ usage
131
+ };
132
+ if (isCompletionFinishReason(generation.finishReason)) {
133
+ metadata.finishReason = generation.finishReason;
134
+ }
135
+ if (typeof generation.providerFinishReason === "string") {
136
+ metadata.providerFinishReason = generation.providerFinishReason;
137
+ }
138
+ if (isContextUsageValue(generation.contextUsage)) {
139
+ metadata.contextUsage = {
140
+ ...generation.contextUsage,
141
+ model: {
142
+ ...generation.contextUsage.model,
143
+ context: { ...generation.contextUsage.model.context }
144
+ }
145
+ };
146
+ }
147
+ if (isCompletionSourceArray(generation.sources)) {
148
+ metadata.sources = generation.sources.map((source) => ({ ...source }));
149
+ }
150
+ if (isProviderToolCallArray(generation.providerToolCalls)) {
151
+ metadata.providerToolCalls = generation.providerToolCalls.map((toolCall) => {
152
+ let copy = { ...toolCall };
153
+ if (toolCall.details !== void 0) {
154
+ copy = { ...copy, details: { ...toolCall.details } };
155
+ }
156
+ return copy;
157
+ });
158
+ }
159
+ return metadata;
160
+ }
161
+ function isJsonObjectValue(value) {
162
+ return typeof value === "object" && value !== null && !Array.isArray(value);
163
+ }
164
+ function isContextUsageValue(value) {
165
+ if (!isJsonObjectValue(value) || !isJsonObjectValue(value.model)) {
166
+ return false;
167
+ }
168
+ const context = value.model.context;
169
+ 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)) {
170
+ const contextWindow = context.contextWindow;
171
+ const remainingTokens = Math.max(0, contextWindow - value.usedTokens);
172
+ const usedPercent = Math.min(100, value.usedTokens / contextWindow * 100);
173
+ const remainingPercent = remainingTokens / contextWindow * 100;
174
+ return value.remainingTokens === remainingTokens && approximatelyEqual(value.usedPercent, usedPercent) && approximatelyEqual(value.remainingPercent, remainingPercent);
175
+ }
176
+ return false;
177
+ }
178
+ function approximatelyEqual(left, right) {
179
+ const scale = Math.max(1, Math.abs(left), Math.abs(right));
180
+ return Math.abs(left - right) <= Number.EPSILON * scale * 8;
181
+ }
182
+ function isPositiveFiniteNumber(value) {
183
+ return isNonnegativeFiniteNumber(value) && value > 0;
184
+ }
185
+ function isOptionalPositiveFiniteNumber(value) {
186
+ return value === void 0 || isPositiveFiniteNumber(value);
187
+ }
188
+ function isPercentage(value) {
189
+ return isNonnegativeFiniteNumber(value) && value <= 100;
190
+ }
191
+ function isUsageValue(value) {
192
+ if (!isJsonObjectValue(value)) {
193
+ return false;
194
+ }
195
+ return isNonnegativeFiniteNumber(value.inputTokens) && isNonnegativeFiniteNumber(value.outputTokens) && isNonnegativeFiniteNumber(value.totalTokens) && isNonnegativeFiniteNumber(value.cachedInputTokens) && isNonnegativeFiniteNumber(value.cacheCreationInputTokens) && isUsageDetailsValue(value.details);
196
+ }
197
+ function isNonnegativeFiniteNumber(value) {
198
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
199
+ }
200
+ function isUsageDetailsValue(value) {
201
+ if (value === void 0) {
202
+ return true;
203
+ }
204
+ if (!isJsonObjectValue(value)) {
205
+ return false;
206
+ }
207
+ let total;
208
+ let bucketSum = 0;
209
+ for (const [key, detail] of Object.entries(value)) {
210
+ if (detail === void 0 || !isNonnegativeFiniteNumber(detail)) {
211
+ return false;
212
+ }
213
+ if (key === "total") {
214
+ total = detail;
215
+ } else {
216
+ bucketSum += detail;
217
+ }
218
+ }
219
+ return total !== void 0 && total === bucketSum;
220
+ }
221
+ function isCompletionSourceArray(value) {
222
+ return Array.isArray(value) && value.every(
223
+ (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")
224
+ );
225
+ }
226
+ function isProviderToolCallArray(value) {
227
+ return Array.isArray(value) && value.every(
228
+ (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))
229
+ );
230
+ }
231
+ function isCompletionFinishReason(value) {
232
+ return value === "stop" || value === "length" || value === "content-filter" || value === "tool-calls" || value === "other";
233
+ }
234
+ var CompletionCapabilityError = class extends Error {
235
+ constructor(message) {
236
+ super(message);
237
+ this.name = "CompletionCapabilityError";
238
+ }
239
+ };
240
+ function assertCompletionRequestSupported(model, request, options = {}) {
241
+ const modelLabel = `${model.provider}:${model.modelId}`;
242
+ const capabilities = model.capabilities;
243
+ if (options.streaming === true && !capabilities.streaming) {
244
+ throw new CompletionCapabilityError(`${modelLabel} does not support streaming completions.`);
245
+ }
246
+ if (request.tools.length > 0 && !capabilities.tools) {
247
+ throw new CompletionCapabilityError(`${modelLabel} does not support tool definitions.`);
248
+ }
249
+ if ((request.providerTools?.length ?? 0) > 0 && capabilities.providerTools !== true) {
250
+ throw new CompletionCapabilityError(`${modelLabel} does not support provider-executed tools.`);
251
+ }
252
+ if (request.toolChoice !== void 0 && !capabilities.toolChoice) {
253
+ throw new CompletionCapabilityError(`${modelLabel} does not support tool choice.`);
254
+ }
255
+ if (request.outputSchema !== void 0 && !capabilities.outputSchema) {
256
+ throw new CompletionCapabilityError(`${modelLabel} does not support output schemas.`);
257
+ }
258
+ if (!capabilities.imageInput && requestHasImageInput(request)) {
259
+ throw new CompletionCapabilityError(`${modelLabel} does not support image input.`);
260
+ }
261
+ if (!capabilities.documentInput && requestHasFileDocumentInput(request)) {
262
+ throw new CompletionCapabilityError(`${modelLabel} does not support document file input.`);
263
+ }
264
+ }
265
+ function textFromAssistantContent(content) {
266
+ return content.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n");
267
+ }
268
+ function requestHasImageInput(request) {
269
+ return request.chatHistory.some(
270
+ (message) => message.role === "system" || typeof message.content === "string" ? false : message.content.some((content) => content.type === "image")
271
+ );
272
+ }
273
+ function requestHasFileDocumentInput(request) {
274
+ return request.chatHistory.some(
275
+ (message) => message.role === "user" && typeof message.content !== "string" ? message.content.some((content) => content.type === "file" && content.data.type !== "text") : false
276
+ );
277
+ }
278
+
279
+ // src/completion/provider-output-error.ts
280
+ var COMPLETION_PROVIDER_OUTPUT_ERROR_CODE = "ANVIA_COMPLETION_PROVIDER_OUTPUT";
281
+ var PROVIDER_OUTPUT_ERROR_KINDS = /* @__PURE__ */ new Set([
282
+ "malformed-tool-arguments",
283
+ "invalid-tool-arguments",
284
+ "invalid-stream-event",
285
+ "invalid-response",
286
+ "incomplete-stream",
287
+ "incomplete-tool-call",
288
+ "invalid-tool-call",
289
+ "truncated-tool-call",
290
+ "filtered-tool-call"
291
+ ]);
292
+ var CompletionProviderOutputError = class extends Error {
293
+ code = COMPLETION_PROVIDER_OUTPUT_ERROR_CODE;
294
+ kind;
295
+ toolCallId;
296
+ finishReason;
297
+ usage;
298
+ constructor(options) {
299
+ assertProviderOutputErrorOptions(options);
300
+ super(providerOutputErrorMessage(options.kind, options.toolCallId));
301
+ this.name = "CompletionProviderOutputError";
302
+ this.kind = options.kind;
303
+ this.toolCallId = options.toolCallId;
304
+ this.finishReason = options.finishReason;
305
+ this.usage = options.usage === void 0 ? void 0 : copyUsage(options.usage);
306
+ }
307
+ };
308
+ function assertCompletionResponseIntegrity(options) {
309
+ const { response } = options;
310
+ const toolCalls = response.choice.filter(
311
+ (content) => content.type === "tool-call"
312
+ );
313
+ if (toolCalls.length > 0) {
314
+ if (response.finishReason !== void 0 && !isCompletionFinishReason2(response.finishReason)) {
315
+ throw new CompletionProviderOutputError({
316
+ kind: "invalid-tool-call",
317
+ usage: response.usage
318
+ });
319
+ }
320
+ if (response.finishReason === "length") {
321
+ throw new CompletionProviderOutputError({
322
+ kind: "truncated-tool-call",
323
+ finishReason: response.finishReason,
324
+ usage: response.usage
325
+ });
326
+ }
327
+ if (response.finishReason === "content-filter") {
328
+ throw new CompletionProviderOutputError({
329
+ kind: "filtered-tool-call",
330
+ finishReason: response.finishReason,
331
+ usage: response.usage
332
+ });
333
+ }
334
+ if (response.finishReason === "other") {
335
+ throw new CompletionProviderOutputError({
336
+ kind: "invalid-tool-call",
337
+ finishReason: response.finishReason,
338
+ usage: response.usage
339
+ });
340
+ }
341
+ } else if (response.finishReason === "tool-calls") {
342
+ throw new CompletionProviderOutputError({
343
+ kind: "invalid-tool-call",
344
+ finishReason: response.finishReason,
345
+ usage: response.usage
346
+ });
347
+ }
348
+ const toolCallIds = /* @__PURE__ */ new Set();
349
+ const callIds = /* @__PURE__ */ new Set();
350
+ for (const toolCall of toolCalls) {
351
+ if (!isNonblankString(toolCall.toolCallId) || !isNonblankString(toolCall.toolName)) {
352
+ throw invalidToolCall(toolCall.toolCallId, response.usage);
353
+ }
354
+ if (toolCall.callId !== void 0 && !isNonblankString(toolCall.callId)) {
355
+ throw invalidToolCall(toolCall.toolCallId, response.usage);
356
+ }
357
+ if (toolCallIds.has(toolCall.toolCallId)) {
358
+ throw invalidToolCall(toolCall.toolCallId, response.usage);
359
+ }
360
+ toolCallIds.add(toolCall.toolCallId);
361
+ if (toolCall.callId !== void 0) {
362
+ if (callIds.has(toolCall.callId)) {
363
+ throw invalidToolCall(toolCall.toolCallId, response.usage);
364
+ }
365
+ callIds.add(toolCall.callId);
366
+ }
367
+ if (!isJsonValue(toolCall.input)) {
368
+ throw new CompletionProviderOutputError({
369
+ kind: "invalid-tool-arguments",
370
+ toolCallId: toolCall.toolCallId,
371
+ usage: response.usage
372
+ });
373
+ }
374
+ }
375
+ }
376
+ function invalidToolCall(toolCallId, usage) {
377
+ return new CompletionProviderOutputError({
378
+ kind: "invalid-tool-call",
379
+ toolCallId: isNonblankString(toolCallId) ? toolCallId : void 0,
380
+ usage
381
+ });
382
+ }
383
+ function assertProviderOutputErrorOptions(options) {
384
+ if (typeof options !== "object" || options === null) {
385
+ throw new TypeError("CompletionProviderOutputError options must be an object.");
386
+ }
387
+ if (!PROVIDER_OUTPUT_ERROR_KINDS.has(options.kind)) {
388
+ throw new TypeError("CompletionProviderOutputError kind is invalid.");
389
+ }
390
+ if (options.toolCallId !== void 0 && !isNonblankString(options.toolCallId)) {
391
+ throw new TypeError("CompletionProviderOutputError toolCallId must be a non-empty string.");
392
+ }
393
+ if (options.finishReason !== void 0 && !isCompletionFinishReason2(options.finishReason)) {
394
+ throw new TypeError("CompletionProviderOutputError finishReason is invalid.");
395
+ }
396
+ if (options.kind === "truncated-tool-call" && options.finishReason !== "length") {
397
+ throw new TypeError('CompletionProviderOutputError truncated-tool-call requires "length".');
398
+ }
399
+ if (options.kind === "filtered-tool-call" && options.finishReason !== "content-filter") {
400
+ throw new TypeError(
401
+ 'CompletionProviderOutputError filtered-tool-call requires "content-filter".'
402
+ );
403
+ }
404
+ if (options.finishReason === "length" && options.kind !== "truncated-tool-call") {
405
+ throw new TypeError(
406
+ 'CompletionProviderOutputError finishReason "length" requires truncated-tool-call.'
407
+ );
408
+ }
409
+ if (options.finishReason === "content-filter" && options.kind !== "filtered-tool-call") {
410
+ throw new TypeError(
411
+ 'CompletionProviderOutputError finishReason "content-filter" requires filtered-tool-call.'
412
+ );
413
+ }
414
+ if (options.usage !== void 0) {
415
+ assertUsage(options.usage);
416
+ }
417
+ }
418
+ function providerOutputErrorMessage(kind, toolCallId) {
419
+ const toolCall = toolCallId === void 0 ? "tool call" : `tool call ${JSON.stringify(displayId(toolCallId))}`;
420
+ if (kind === "malformed-tool-arguments") {
421
+ return `Completion provider returned ${toolCall} with malformed JSON arguments.`;
422
+ }
423
+ if (kind === "invalid-tool-arguments") {
424
+ return `Completion provider returned ${toolCall} with arguments that are not a JSON value.`;
425
+ }
426
+ if (kind === "invalid-stream-event") {
427
+ return "Completion provider returned an invalid stream event.";
428
+ }
429
+ if (kind === "invalid-response") {
430
+ return "Completion provider returned a response that cannot be consumed safely.";
431
+ }
432
+ if (kind === "incomplete-tool-call") {
433
+ return "Completion provider stream ended before its tool call was complete.";
434
+ }
435
+ if (kind === "incomplete-stream") {
436
+ return "Completion provider stream ended without a terminal response.";
437
+ }
438
+ if (kind === "truncated-tool-call") {
439
+ return "Completion provider stopped at its output limit before a tool call could be consumed safely.";
440
+ }
441
+ if (kind === "filtered-tool-call") {
442
+ return "Completion provider content filtering prevented a tool call from being consumed safely.";
443
+ }
444
+ return `Completion provider returned an invalid ${toolCall}.`;
445
+ }
446
+ function displayId(value) {
447
+ let sanitized = "";
448
+ for (const character of value) {
449
+ const code = character.charCodeAt(0);
450
+ sanitized += code <= 31 || code === 127 ? "\uFFFD" : character;
451
+ }
452
+ return sanitized.length <= 128 ? sanitized : `${sanitized.slice(0, 127)}\u2026`;
453
+ }
454
+ function isNonblankString(value) {
455
+ return typeof value === "string" && value.trim().length > 0;
456
+ }
457
+ function isCompletionFinishReason2(value) {
458
+ return value === "stop" || value === "length" || value === "content-filter" || value === "tool-calls" || value === "other";
459
+ }
460
+ function assertUsage(usage) {
461
+ for (const value of [
462
+ usage.inputTokens,
463
+ usage.outputTokens,
464
+ usage.totalTokens,
465
+ usage.cachedInputTokens,
466
+ usage.cacheCreationInputTokens
467
+ ]) {
468
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
469
+ throw new TypeError("CompletionProviderOutputError usage must contain finite token counts.");
470
+ }
471
+ }
472
+ if (usage.details !== void 0) {
473
+ for (const value of Object.values(usage.details)) {
474
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
475
+ throw new TypeError(
476
+ "CompletionProviderOutputError usage details must contain finite token counts."
477
+ );
478
+ }
479
+ }
480
+ }
481
+ }
482
+ function copyUsage(usage) {
483
+ const copied = {
484
+ inputTokens: usage.inputTokens,
485
+ outputTokens: usage.outputTokens,
486
+ totalTokens: usage.totalTokens,
487
+ cachedInputTokens: usage.cachedInputTokens,
488
+ cacheCreationInputTokens: usage.cacheCreationInputTokens
489
+ };
490
+ if (usage.details !== void 0) copied.details = { ...usage.details };
491
+ return copied;
492
+ }
493
+
494
+ // src/internal/completion-request.ts
495
+ function createCompletionRequest(input, options) {
496
+ const configuredTools = options.tools ?? [];
497
+ const chatHistory = messagesFromInput(input);
498
+ assertNoAgentInteractionParts(chatHistory);
499
+ const request = {
500
+ chatHistory,
501
+ documents: [...options.documents ?? []],
502
+ tools: configuredTools.filter((tool) => !isProviderTool(tool))
503
+ };
504
+ const providerTools = configuredTools.filter(isProviderTool);
505
+ if (providerTools.length > 0) request.providerTools = providerTools;
506
+ if (options.instructions !== void 0 && options.instructions.length > 0) {
507
+ request.instructions = options.instructions;
508
+ }
509
+ if (options.temperature !== void 0) request.temperature = options.temperature;
510
+ if (options.maxTokens !== void 0) request.maxTokens = options.maxTokens;
511
+ if (options.toolChoice !== void 0) request.toolChoice = options.toolChoice;
512
+ if (options.outputSchema !== void 0) request.outputSchema = options.outputSchema;
513
+ if (options.providerOptions !== void 0) {
514
+ assertJsonObject(options.providerOptions, "providerOptions");
515
+ request.providerOptions = options.providerOptions;
516
+ }
517
+ return request;
518
+ }
519
+ function assertNoAgentInteractionParts(messages) {
520
+ for (const message of messages) {
521
+ if (message.role === "tool" && message.content.some((part) => part.type !== "tool-result")) {
522
+ throw new TypeError(
523
+ "Completion messages contain an unresolved Agent interaction response. Resume the Agent with its continuation instead of sending interaction parts directly to a provider."
524
+ );
525
+ }
526
+ }
527
+ }
528
+ function messagesFromInput(input) {
529
+ if (typeof input === "string") {
530
+ return [{ role: "user", content: input }];
531
+ }
532
+ if (Array.isArray(input)) {
533
+ if (input.length === 0) {
534
+ throw new Error("input must contain at least one Message.");
535
+ }
536
+ return parseMessages(input);
537
+ }
538
+ return [parseMessage(input)];
539
+ }
540
+
541
+ // src/completion/stream-accumulator.ts
542
+ var CompletionStreamAccumulator = class {
543
+ orderedParts = [];
544
+ textParts = /* @__PURE__ */ new Map();
545
+ reasoningByKey = /* @__PURE__ */ new Map();
546
+ reasoningKeyById = /* @__PURE__ */ new Map();
547
+ toolCalls = /* @__PURE__ */ new Map();
548
+ sources = /* @__PURE__ */ new Map();
549
+ providerToolCalls = /* @__PURE__ */ new Map();
550
+ finalResponse;
551
+ messageId;
552
+ nextTextKey = 0;
553
+ nextReasoningKey = 0;
554
+ accept(event) {
555
+ if (event.type === "text_delta") {
556
+ if (typeof event.delta !== "string") {
557
+ throw new CompletionProviderOutputError({ kind: "invalid-stream-event" });
558
+ }
559
+ this.appendText(event.delta);
560
+ return { type: "text_delta", delta: event.delta };
561
+ }
562
+ if (event.type === "reasoning_delta") {
563
+ if (typeof event.delta !== "string" || event.id !== void 0 && !isNonblankString2(event.id) || event.signature !== void 0 && !isNonblankString2(event.signature) || event.contentType !== void 0 && !isReasoningContentType(event.contentType)) {
564
+ throw new CompletionProviderOutputError({ kind: "invalid-stream-event" });
565
+ }
566
+ const reasoning = this.reasoningStateForEvent(event);
567
+ this.appendReasoning(reasoning, event);
568
+ return reasoningDeltaEvent(event);
569
+ }
570
+ if (event.type === "tool_call_delta") {
571
+ if (!isNonblankString2(event.id)) {
572
+ throw new CompletionProviderOutputError({ kind: "invalid-tool-call" });
573
+ }
574
+ const toolCall = this.toolCallStateForId(event.id);
575
+ if (toolCall.fullCallSeen) {
576
+ throw new CompletionProviderOutputError({
577
+ kind: "invalid-tool-call",
578
+ toolCallId: toolCall.id
579
+ });
580
+ }
581
+ if (event.callId !== void 0) {
582
+ if (!isNonblankString2(event.callId)) {
583
+ throw new CompletionProviderOutputError({
584
+ kind: "invalid-tool-call",
585
+ toolCallId: toolCall.id
586
+ });
587
+ }
588
+ if (toolCall.callId !== void 0 && toolCall.callId !== event.callId) {
589
+ throw new CompletionProviderOutputError({
590
+ kind: "invalid-tool-call",
591
+ toolCallId: toolCall.id
592
+ });
593
+ }
594
+ toolCall.callId = event.callId;
595
+ }
596
+ if (event.name !== void 0) {
597
+ if (!isNonblankString2(event.name)) {
598
+ throw new CompletionProviderOutputError({
599
+ kind: "invalid-tool-call",
600
+ toolCallId: toolCall.id
601
+ });
602
+ }
603
+ if (toolCall.name.length > 0 && toolCall.name !== event.name) {
604
+ throw new CompletionProviderOutputError({
605
+ kind: "invalid-tool-call",
606
+ toolCallId: toolCall.id
607
+ });
608
+ }
609
+ toolCall.name = event.name;
610
+ }
611
+ if (event.signature !== void 0) {
612
+ if (!isNonblankString2(event.signature) || toolCall.signature !== void 0 && toolCall.signature !== event.signature) {
613
+ throw new CompletionProviderOutputError({
614
+ kind: "invalid-tool-call",
615
+ toolCallId: toolCall.id
616
+ });
617
+ }
618
+ toolCall.signature = event.signature;
619
+ }
620
+ if (event.argumentsMode !== void 0 && event.argumentsMode !== "append" && event.argumentsMode !== "replace") {
621
+ throw new CompletionProviderOutputError({
622
+ kind: "invalid-stream-event",
623
+ toolCallId: toolCall.id
624
+ });
625
+ }
626
+ if (event.argumentsMode !== void 0 && event.argumentsDelta === void 0) {
627
+ throw new CompletionProviderOutputError({
628
+ kind: "invalid-stream-event",
629
+ toolCallId: toolCall.id
630
+ });
631
+ }
632
+ if (event.argumentsDelta !== void 0) {
633
+ if (typeof event.argumentsDelta !== "string") {
634
+ throw new CompletionProviderOutputError({
635
+ kind: "invalid-tool-arguments",
636
+ toolCallId: toolCall.id
637
+ });
638
+ }
639
+ if (event.argumentsMode === "replace") {
640
+ if (toolCall.argumentsText.length > 0 && toolCall.argumentsText !== event.argumentsDelta && (toolCall.argumentsSnapshotSeen || !event.argumentsDelta.startsWith(toolCall.argumentsText))) {
641
+ throw new CompletionProviderOutputError({
642
+ kind: "invalid-tool-call",
643
+ toolCallId: toolCall.id
644
+ });
645
+ }
646
+ toolCall.argumentsText = event.argumentsDelta;
647
+ toolCall.argumentsSnapshotSeen = true;
648
+ } else {
649
+ if (toolCall.argumentsSnapshotSeen) {
650
+ throw new CompletionProviderOutputError({
651
+ kind: "invalid-tool-call",
652
+ toolCallId: toolCall.id
653
+ });
654
+ }
655
+ toolCall.argumentsText += event.argumentsDelta;
656
+ }
657
+ }
658
+ return void 0;
659
+ }
660
+ if (event.type === "tool_call") {
661
+ this.upsertToolCall(event.toolCall);
662
+ return { type: "tool_call", toolCall: event.toolCall };
663
+ }
664
+ if (event.type === "source") {
665
+ this.sources.set(sourceKey(event.source), event.source);
666
+ return { type: "source", source: event.source };
667
+ }
668
+ if (event.type === "provider_tool_call") {
669
+ this.providerToolCalls.set(event.toolCall.id, event.toolCall);
670
+ return { type: "provider_tool_call", toolCall: event.toolCall };
671
+ }
672
+ if (event.type === "message_id") {
673
+ if (!isNonblankString2(event.id)) {
674
+ throw new CompletionProviderOutputError({ kind: "invalid-stream-event" });
675
+ }
676
+ this.messageId = event.id;
677
+ return void 0;
678
+ }
679
+ if (event.type === "final") {
680
+ this.finalResponse = event.response;
681
+ return void 0;
682
+ }
683
+ return void 0;
684
+ }
685
+ response() {
686
+ this.assertAccumulatedFinishReason();
687
+ let accumulatedResponse;
688
+ try {
689
+ accumulatedResponse = this.buildAccumulatedResponse();
690
+ } catch (error) {
691
+ if (error instanceof CompletionProviderOutputError && this.finalResponse !== void 0) {
692
+ throw providerOutputErrorWithUsage(error, this.finalResponse.usage);
693
+ }
694
+ throw error;
695
+ }
696
+ if (this.finalResponse !== void 0) {
697
+ if (accumulatedResponse.choice.length === 0) {
698
+ return this.withAccumulatedArtifacts(this.finalResponse, accumulatedResponse);
699
+ }
700
+ return this.mergeFinalResponse(accumulatedResponse, this.finalResponse);
701
+ }
702
+ return accumulatedResponse;
703
+ }
704
+ assertAccumulatedFinishReason() {
705
+ if (this.finalResponse === void 0) {
706
+ if (this.toolCalls.size === 0) {
707
+ throw new CompletionProviderOutputError({ kind: "incomplete-stream" });
708
+ }
709
+ const toolCallId = this.toolCalls.size === 1 ? this.toolCalls.keys().next().value : void 0;
710
+ throw new CompletionProviderOutputError({
711
+ kind: "incomplete-tool-call",
712
+ toolCallId
713
+ });
714
+ }
715
+ if (this.toolCalls.size === 0) return;
716
+ const finishReason = this.finalResponse.finishReason;
717
+ if (finishReason === "length") {
718
+ throw new CompletionProviderOutputError({
719
+ kind: "truncated-tool-call",
720
+ finishReason,
721
+ usage: this.finalResponse.usage
722
+ });
723
+ }
724
+ if (finishReason === "content-filter") {
725
+ throw new CompletionProviderOutputError({
726
+ kind: "filtered-tool-call",
727
+ finishReason,
728
+ usage: this.finalResponse.usage
729
+ });
730
+ }
731
+ if (finishReason !== void 0 && finishReason !== "stop" && finishReason !== "tool-calls") {
732
+ throw new CompletionProviderOutputError({
733
+ kind: "invalid-tool-call",
734
+ usage: this.finalResponse.usage
735
+ });
736
+ }
737
+ }
738
+ buildAccumulatedResponse() {
739
+ const choice = [];
740
+ for (const part of this.orderedParts) {
741
+ if (part.type === "text") {
742
+ const text = this.textParts.get(part.key) ?? "";
743
+ if (text.length > 0) {
744
+ choice.push({ type: "text", text });
745
+ }
746
+ continue;
747
+ }
748
+ if (part.type === "reasoning") {
749
+ const reasoning = this.reasoningByKey.get(part.key);
750
+ if (reasoning !== void 0) {
751
+ choice.push(reasoningContent(reasoning));
752
+ }
753
+ continue;
754
+ }
755
+ const toolCall = this.toolCalls.get(part.key);
756
+ if (toolCall !== void 0) {
757
+ choice.push(toolCallContent(toolCall));
758
+ }
759
+ }
760
+ const response = {
761
+ choice,
762
+ usage: Usage.empty(),
763
+ rawResponse: void 0
764
+ };
765
+ if (this.messageId !== void 0) {
766
+ response.messageId = this.messageId;
767
+ }
768
+ const sources = [...this.sources.values()];
769
+ if (sources.length > 0) {
770
+ response.sources = sources;
771
+ }
772
+ const providerToolCalls = [...this.providerToolCalls.values()];
773
+ if (providerToolCalls.length > 0) {
774
+ response.providerToolCalls = providerToolCalls;
775
+ }
776
+ return response;
777
+ }
778
+ upsertToolCall(toolCall) {
779
+ if (!isNonblankString2(toolCall.toolCallId) || !isNonblankString2(toolCall.toolName) || toolCall.callId !== void 0 && !isNonblankString2(toolCall.callId) || toolCall.signature !== void 0 && !isNonblankString2(toolCall.signature)) {
780
+ throw new CompletionProviderOutputError({
781
+ kind: "invalid-tool-call",
782
+ toolCallId: isNonblankString2(toolCall.toolCallId) ? toolCall.toolCallId : void 0
783
+ });
784
+ }
785
+ if (!isJsonValue(toolCall.input)) {
786
+ throw new CompletionProviderOutputError({
787
+ kind: "invalid-tool-arguments",
788
+ toolCallId: toolCall.toolCallId
789
+ });
790
+ }
791
+ const existing = this.toolCalls.get(toolCall.toolCallId);
792
+ if (existing !== void 0) {
793
+ if (existing.fullCallSeen) {
794
+ throw new CompletionProviderOutputError({
795
+ kind: "invalid-tool-call",
796
+ toolCallId: toolCall.toolCallId
797
+ });
798
+ }
799
+ if (existing.name.length > 0 && existing.name !== toolCall.toolName || existing.callId !== void 0 && existing.callId !== toolCall.callId || existing.signature !== void 0 && toolCall.signature !== void 0 && existing.signature !== toolCall.signature) {
800
+ throw new CompletionProviderOutputError({
801
+ kind: "invalid-tool-call",
802
+ toolCallId: toolCall.toolCallId
803
+ });
804
+ }
805
+ if (existing.argumentsText.length > 0) {
806
+ const accumulatedInput = parseToolArguments(existing.id, existing.argumentsText);
807
+ if (!jsonValuesEqual(accumulatedInput, toolCall.input)) {
808
+ throw new CompletionProviderOutputError({
809
+ kind: "invalid-tool-call",
810
+ toolCallId: toolCall.toolCallId
811
+ });
812
+ }
813
+ }
814
+ }
815
+ if (!this.toolCalls.has(toolCall.toolCallId)) {
816
+ this.orderedParts.push({ type: "tool_call", key: toolCall.toolCallId });
817
+ }
818
+ const partial = {
819
+ id: toolCall.toolCallId,
820
+ name: toolCall.toolName,
821
+ argumentsText: JSON.stringify(toolCall.input),
822
+ argumentsSnapshotSeen: true,
823
+ fullCallSeen: true
824
+ };
825
+ if (toolCall.callId !== void 0) {
826
+ partial.callId = toolCall.callId;
827
+ }
828
+ const signature = toolCall.signature ?? existing?.signature;
829
+ if (signature !== void 0) {
830
+ partial.signature = signature;
831
+ }
832
+ this.toolCalls.set(toolCall.toolCallId, partial);
833
+ }
834
+ mergeFinalResponse(accumulatedResponse, finalResponse) {
835
+ if (finalResponse.choice.length === 0) {
836
+ const mergedResponse = {
837
+ ...accumulatedResponse,
838
+ usage: finalResponse.usage,
839
+ rawResponse: finalResponse.rawResponse
840
+ };
841
+ if (finalResponse.finishReason !== void 0) {
842
+ mergedResponse.finishReason = finalResponse.finishReason;
843
+ }
844
+ if (finalResponse.providerFinishReason !== void 0) {
845
+ mergedResponse.providerFinishReason = finalResponse.providerFinishReason;
846
+ }
847
+ if (finalResponse.messageId !== void 0) {
848
+ mergedResponse.messageId = finalResponse.messageId;
849
+ }
850
+ return this.withAccumulatedArtifacts(mergedResponse, accumulatedResponse);
851
+ }
852
+ const accumulatedNonTool = accumulatedResponse.choice.filter(
853
+ (content) => content.type !== "tool-call"
854
+ );
855
+ const finalNonTool = finalResponse.choice.filter((content) => content.type !== "tool-call");
856
+ if (accumulatedNonTool.length > 0 && !nonToolPartsEqual(accumulatedNonTool, finalNonTool)) {
857
+ throw new CompletionProviderOutputError({
858
+ kind: "invalid-stream-event",
859
+ usage: finalResponse.usage
860
+ });
861
+ }
862
+ const accumulatedById = /* @__PURE__ */ new Map();
863
+ const accumulatedByCallId = /* @__PURE__ */ new Map();
864
+ for (const content of accumulatedResponse.choice) {
865
+ if (content.type !== "tool-call") continue;
866
+ accumulatedById.set(content.toolCallId, content);
867
+ if (content.callId !== void 0) accumulatedByCallId.set(content.callId, content);
868
+ }
869
+ const matchedAccumulatedToolCalls = /* @__PURE__ */ new Set();
870
+ const choice = finalResponse.choice.map((content) => {
871
+ if (content.type !== "tool-call") return content;
872
+ const accumulated = accumulatedById.get(content.toolCallId);
873
+ if (accumulated === void 0) {
874
+ const changedIdentity = content.callId === void 0 ? void 0 : accumulatedByCallId.get(content.callId);
875
+ if (changedIdentity !== void 0) {
876
+ throw new CompletionProviderOutputError({
877
+ kind: "invalid-tool-call",
878
+ toolCallId: changedIdentity.toolCallId,
879
+ usage: finalResponse.usage
880
+ });
881
+ }
882
+ return content;
883
+ }
884
+ matchedAccumulatedToolCalls.add(accumulated);
885
+ return mergeFinalToolCall(accumulated, content, finalResponse.usage);
886
+ });
887
+ for (const accumulated of accumulatedById.values()) {
888
+ if (!matchedAccumulatedToolCalls.has(accumulated)) {
889
+ throw new CompletionProviderOutputError({
890
+ kind: "invalid-tool-call",
891
+ toolCallId: accumulated.toolCallId,
892
+ usage: finalResponse.usage
893
+ });
894
+ }
895
+ }
896
+ return this.withAccumulatedArtifacts({ ...finalResponse, choice }, accumulatedResponse);
897
+ }
898
+ appendText(delta) {
899
+ const lastPart = this.orderedParts.at(-1);
900
+ const key = lastPart?.type === "text" ? lastPart.key : this.createTextKey();
901
+ if (lastPart?.type !== "text") {
902
+ this.orderedParts.push({ type: "text", key });
903
+ }
904
+ this.textParts.set(key, `${this.textParts.get(key) ?? ""}${delta}`);
905
+ }
906
+ reasoningStateForEvent(event) {
907
+ if (event.id !== void 0) {
908
+ const existingKey = this.reasoningKeyById.get(event.id);
909
+ if (existingKey !== void 0) {
910
+ const existing = this.reasoningByKey.get(existingKey);
911
+ if (existing !== void 0) {
912
+ return existing;
913
+ }
914
+ }
915
+ const key2 = this.createReasoningKey();
916
+ const reasoning2 = { id: event.id, text: "" };
917
+ this.reasoningKeyById.set(event.id, key2);
918
+ this.reasoningByKey.set(key2, reasoning2);
919
+ this.orderedParts.push({ type: "reasoning", key: key2 });
920
+ return reasoning2;
921
+ }
922
+ const lastPart = this.orderedParts.at(-1);
923
+ if (lastPart?.type === "reasoning") {
924
+ const lastReasoning = this.reasoningByKey.get(lastPart.key);
925
+ if (lastReasoning !== void 0 && lastReasoning.id === void 0) {
926
+ return lastReasoning;
927
+ }
928
+ }
929
+ const key = this.createReasoningKey();
930
+ const reasoning = { text: "" };
931
+ this.reasoningByKey.set(key, reasoning);
932
+ this.orderedParts.push({ type: "reasoning", key });
933
+ return reasoning;
934
+ }
935
+ toolCallStateForId(id) {
936
+ const existing = this.toolCalls.get(id);
937
+ if (existing !== void 0) {
938
+ return existing;
939
+ }
940
+ const toolCall = {
941
+ id,
942
+ name: "",
943
+ argumentsText: "",
944
+ argumentsSnapshotSeen: false,
945
+ fullCallSeen: false
946
+ };
947
+ this.toolCalls.set(id, toolCall);
948
+ this.orderedParts.push({ type: "tool_call", key: id });
949
+ return toolCall;
950
+ }
951
+ withMessageIdFallback(response, accumulatedResponse) {
952
+ if (response.messageId !== void 0 || accumulatedResponse.messageId === void 0) {
953
+ return response;
954
+ }
955
+ return { ...response, messageId: accumulatedResponse.messageId };
956
+ }
957
+ withAccumulatedArtifacts(response, accumulatedResponse) {
958
+ const withMessageId = this.withMessageIdFallback(response, accumulatedResponse);
959
+ const sources = mergeSources(accumulatedResponse.sources, response.sources);
960
+ const providerToolCalls = mergeProviderToolCalls(
961
+ accumulatedResponse.providerToolCalls,
962
+ response.providerToolCalls
963
+ );
964
+ let accumulated = { ...withMessageId };
965
+ if (sources.length > 0) accumulated = { ...accumulated, sources };
966
+ if (providerToolCalls.length > 0) {
967
+ accumulated = { ...accumulated, providerToolCalls };
968
+ }
969
+ return accumulated;
970
+ }
971
+ createTextKey() {
972
+ this.nextTextKey += 1;
973
+ return `text_${this.nextTextKey.toString()}`;
974
+ }
975
+ createReasoningKey() {
976
+ this.nextReasoningKey += 1;
977
+ return `reasoning_${this.nextReasoningKey.toString()}`;
978
+ }
979
+ appendReasoning(reasoning, event) {
980
+ const contentType = event.contentType ?? "text";
981
+ if (contentType === "text" || contentType === "summary") {
982
+ reasoning.text += event.delta;
983
+ }
984
+ if (event.contentType === void 0 && event.signature === void 0) {
985
+ return;
986
+ }
987
+ reasoning.details ??= [];
988
+ const last = reasoning.details.at(-1);
989
+ if (contentType === "text") {
990
+ if (last?.type === "text") {
991
+ let detail = {
992
+ ...last,
993
+ text: `${last.text}${event.delta}`
994
+ };
995
+ if (event.signature !== void 0) detail = { ...detail, signature: event.signature };
996
+ reasoning.details[reasoning.details.length - 1] = detail;
997
+ } else {
998
+ reasoning.details.push(
999
+ event.signature === void 0 ? { type: "text", text: event.delta } : { type: "text", text: event.delta, signature: event.signature }
1000
+ );
1001
+ }
1002
+ return;
1003
+ }
1004
+ if (contentType === "summary") {
1005
+ if (last?.type === "summary") {
1006
+ reasoning.details[reasoning.details.length - 1] = {
1007
+ ...last,
1008
+ text: `${last.text}${event.delta}`
1009
+ };
1010
+ } else {
1011
+ reasoning.details.push({ type: "summary", text: event.delta });
1012
+ }
1013
+ return;
1014
+ }
1015
+ if (contentType === "encrypted") {
1016
+ reasoning.details.push({ type: "encrypted", data: event.delta });
1017
+ return;
1018
+ }
1019
+ reasoning.details.push({ type: "redacted", data: event.delta });
1020
+ }
1021
+ };
1022
+ function sourceKey(source) {
1023
+ return `${source.url}\0${source.startIndex ?? ""}\0${source.endIndex ?? ""}`;
1024
+ }
1025
+ function mergeSources(accumulated, final) {
1026
+ const sources = /* @__PURE__ */ new Map();
1027
+ for (const source of [...accumulated ?? [], ...final ?? []]) {
1028
+ sources.set(sourceKey(source), source);
1029
+ }
1030
+ return [...sources.values()];
1031
+ }
1032
+ function mergeProviderToolCalls(accumulated, final) {
1033
+ const toolCalls = /* @__PURE__ */ new Map();
1034
+ for (const toolCall of [...accumulated ?? [], ...final ?? []]) {
1035
+ toolCalls.set(toolCall.id, toolCall);
1036
+ }
1037
+ return [...toolCalls.values()];
1038
+ }
1039
+ function reasoningContent(reasoning) {
1040
+ const content = reasoning.details === void 0 ? { type: "reasoning", text: reasoning.text } : { type: "reasoning", text: reasoning.text, details: reasoning.details };
1041
+ return reasoning.id === void 0 ? content : { ...content, id: reasoning.id };
1042
+ }
1043
+ function toolCallContent(toolCall) {
1044
+ const argumentsValue = parseToolArguments(toolCall.id, toolCall.argumentsText);
1045
+ let content = {
1046
+ type: "tool-call",
1047
+ toolCallId: toolCall.id,
1048
+ toolName: toolCall.name,
1049
+ input: argumentsValue
1050
+ };
1051
+ if (toolCall.callId !== void 0) content = { ...content, callId: toolCall.callId };
1052
+ if (toolCall.signature !== void 0) content = { ...content, signature: toolCall.signature };
1053
+ return content;
1054
+ }
1055
+ function mergeFinalToolCall(accumulated, finalToolCall, usage) {
1056
+ if (finalToolCall.toolCallId !== accumulated.toolCallId || finalToolCall.toolName !== accumulated.toolName || accumulated.callId !== void 0 && finalToolCall.callId !== accumulated.callId || accumulated.signature !== void 0 && finalToolCall.signature !== void 0 && finalToolCall.signature !== accumulated.signature) {
1057
+ throw new CompletionProviderOutputError({
1058
+ kind: "invalid-tool-call",
1059
+ toolCallId: accumulated.toolCallId,
1060
+ usage
1061
+ });
1062
+ }
1063
+ if (!isJsonValue(finalToolCall.input)) {
1064
+ throw new CompletionProviderOutputError({
1065
+ kind: "invalid-tool-arguments",
1066
+ toolCallId: accumulated.toolCallId,
1067
+ usage
1068
+ });
1069
+ }
1070
+ if (!jsonValuesEqual(accumulated.input, finalToolCall.input)) {
1071
+ throw new CompletionProviderOutputError({
1072
+ kind: "invalid-tool-call",
1073
+ toolCallId: accumulated.toolCallId,
1074
+ usage
1075
+ });
1076
+ }
1077
+ let merged = {
1078
+ type: "tool-call",
1079
+ toolCallId: finalToolCall.toolCallId,
1080
+ toolName: finalToolCall.toolName,
1081
+ input: accumulated.input
1082
+ };
1083
+ const callId = finalToolCall.callId ?? accumulated.callId;
1084
+ if (callId !== void 0) merged = { ...merged, callId };
1085
+ const signature = finalToolCall.signature ?? accumulated.signature;
1086
+ if (signature !== void 0) merged = { ...merged, signature };
1087
+ return merged;
1088
+ }
1089
+ function reasoningDeltaEvent(event) {
1090
+ const mapped = { type: "reasoning_delta", delta: event.delta };
1091
+ if (event.id !== void 0) mapped.id = event.id;
1092
+ if (event.contentType !== void 0) mapped.contentType = event.contentType;
1093
+ if (event.signature !== void 0) mapped.signature = event.signature;
1094
+ return mapped;
1095
+ }
1096
+ function parseToolArguments(toolCallId, text) {
1097
+ let value;
1098
+ try {
1099
+ value = JSON.parse(text);
1100
+ } catch {
1101
+ throw new CompletionProviderOutputError({
1102
+ kind: "malformed-tool-arguments",
1103
+ toolCallId
1104
+ });
1105
+ }
1106
+ if (!isJsonValue(value)) {
1107
+ throw new CompletionProviderOutputError({
1108
+ kind: "invalid-tool-arguments",
1109
+ toolCallId
1110
+ });
1111
+ }
1112
+ return value;
1113
+ }
1114
+ function jsonValuesEqual(left, right) {
1115
+ if (left === right) {
1116
+ return true;
1117
+ }
1118
+ if (left === null || right === null || typeof left !== "object" || typeof right !== "object") {
1119
+ return false;
1120
+ }
1121
+ if (isJsonArray(left) || isJsonArray(right)) {
1122
+ if (!isJsonArray(left) || !isJsonArray(right) || left.length !== right.length) {
1123
+ return false;
1124
+ }
1125
+ return left.every((value, index) => {
1126
+ const rightValue = right[index];
1127
+ return rightValue !== void 0 && jsonValuesEqual(value, rightValue);
1128
+ });
1129
+ }
1130
+ const leftKeys = Object.keys(left);
1131
+ const rightKeys = Object.keys(right);
1132
+ if (leftKeys.length !== rightKeys.length) {
1133
+ return false;
1134
+ }
1135
+ for (const key of leftKeys) {
1136
+ if (!Object.hasOwn(right, key)) {
1137
+ return false;
1138
+ }
1139
+ const leftValue = left[key];
1140
+ const rightValue = right[key];
1141
+ if (leftValue === void 0 || rightValue === void 0 || !jsonValuesEqual(leftValue, rightValue)) {
1142
+ return false;
1143
+ }
1144
+ }
1145
+ return true;
1146
+ }
1147
+ function nonToolPartsEqual(accumulated, final) {
1148
+ if (accumulated.length !== final.length) return false;
1149
+ if (!isJsonValue(accumulated) || !isJsonValue(final)) return false;
1150
+ const unmatched = [...final];
1151
+ for (const part of accumulated) {
1152
+ const index = unmatched.findIndex((candidate) => jsonValuesEqual(part, candidate));
1153
+ if (index < 0) return false;
1154
+ unmatched.splice(index, 1);
1155
+ }
1156
+ return true;
1157
+ }
1158
+ function isJsonArray(value) {
1159
+ return Array.isArray(value);
1160
+ }
1161
+ function providerOutputErrorWithUsage(error, usage) {
1162
+ const shared = { usage };
1163
+ if (error.toolCallId !== void 0) shared.toolCallId = error.toolCallId;
1164
+ if (error.kind === "truncated-tool-call") {
1165
+ return new CompletionProviderOutputError({
1166
+ ...shared,
1167
+ kind: error.kind,
1168
+ finishReason: "length"
1169
+ });
1170
+ }
1171
+ if (error.kind === "filtered-tool-call") {
1172
+ return new CompletionProviderOutputError({
1173
+ ...shared,
1174
+ kind: error.kind,
1175
+ finishReason: "content-filter"
1176
+ });
1177
+ }
1178
+ if (error.finishReason === "length" || error.finishReason === "content-filter") {
1179
+ throw error;
1180
+ }
1181
+ return new CompletionProviderOutputError({
1182
+ ...shared,
1183
+ kind: error.kind,
1184
+ finishReason: error.finishReason
1185
+ });
1186
+ }
1187
+ function isNonblankString2(value) {
1188
+ return typeof value === "string" && value.trim().length > 0;
1189
+ }
1190
+ function isReasoningContentType(value) {
1191
+ return value === "text" || value === "summary" || value === "encrypted" || value === "redacted";
1192
+ }
1193
+
1194
+ // src/completion/generate-completion.ts
1195
+ var CompletionStructuredOutputError = class extends Error {
1196
+ phase;
1197
+ outputLength;
1198
+ usage;
1199
+ finishReason;
1200
+ providerFinishReason;
1201
+ constructor(options) {
1202
+ const failure = options.phase === "truncated" ? "because the provider reached its output limit" : options.phase === "content-filter" ? "because the provider filtered the response" : options.phase === "parse" ? "during JSON parsing" : "during schema validation";
1203
+ super(`Structured completion output failed ${failure}.`, { cause: options.cause });
1204
+ this.name = "CompletionStructuredOutputError";
1205
+ this.phase = options.phase;
1206
+ this.outputLength = options.outputLength;
1207
+ this.usage = options.usage;
1208
+ this.finishReason = options.finishReason;
1209
+ this.providerFinishReason = options.providerFinishReason;
1210
+ }
1211
+ };
1212
+ async function generateCompletion(options) {
1213
+ throwIfAborted(options.abortSignal);
1214
+ const request = requestFromOptions(options);
1215
+ assertCompletionRequestSupported(options.model, request);
1216
+ const retries = resolveOptionalRetries(options.retries);
1217
+ const response = await sendCompletion(options.model, request, retries, options.abortSignal);
1218
+ return resultFromResponse(response, structuredOutputSchema(options));
1219
+ }
1220
+ function streamCompletion(options) {
1221
+ throwIfAborted(options.abortSignal);
1222
+ const request = requestFromOptions(options);
1223
+ if (!isStreamingCompletionModel(options.model) || !options.model.capabilities.streaming) {
1224
+ throw new Error("This completion model does not support streaming");
1225
+ }
1226
+ assertCompletionRequestSupported(options.model, request, { streaming: true });
1227
+ const retries = resolveOptionalRetries(options.retries);
1228
+ return streamCompletionWithRetries(
1229
+ options.model,
1230
+ request,
1231
+ retries,
1232
+ options.abortSignal,
1233
+ structuredOutputSchema(options)
1234
+ );
1235
+ }
1236
+ async function sendCompletion(model, request, retries, abortSignal) {
1237
+ const callOptions = modelCallOptions(abortSignal);
1238
+ let attempt = 1;
1239
+ let failedUsage = Usage.empty();
1240
+ while (true) {
1241
+ try {
1242
+ throwIfAborted(abortSignal);
1243
+ const response = await model.completion(request, callOptions);
1244
+ assertCompletionResponseIntegrity({ response });
1245
+ return Usage.isEmpty(failedUsage) ? response : { ...response, usage: Usage.add(failedUsage, response.usage) };
1246
+ } catch (error) {
1247
+ const normalizedError = abortSignal?.aborted === true ? abortError(abortSignal.reason) : error;
1248
+ const attemptUsage = completionProviderOutputErrorUsage(normalizedError);
1249
+ if (attemptUsage !== void 0) failedUsage = Usage.add(failedUsage, attemptUsage);
1250
+ const retryOptions = retryOptionsForFailure(retries, {
1251
+ error: normalizedError,
1252
+ attempt,
1253
+ streaming: false
1254
+ });
1255
+ if (retryOptions === void 0) throw normalizedError;
1256
+ await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);
1257
+ attempt += 1;
1258
+ }
1259
+ }
1260
+ }
1261
+ function resolveOptionalRetries(setting) {
1262
+ return setting === void 0 || setting === false ? void 0 : resolveRetryOptions(setting);
1263
+ }
1264
+ async function* streamCompletionWithRetries(model, request, retries, abortSignal, outputSchema) {
1265
+ let attempt = 1;
1266
+ let swallowedUsage = Usage.empty();
1267
+ const callOptions = modelCallOptions(abortSignal);
1268
+ attemptLoop: while (true) {
1269
+ let exposedProgress = false;
1270
+ let retryDelay;
1271
+ const accumulator = new CompletionStreamAccumulator();
1272
+ try {
1273
+ throwIfAborted(abortSignal);
1274
+ const events = model.streamCompletion(request, callOptions);
1275
+ for await (const event of events) {
1276
+ if (event.type === "error" && !exposedProgress) {
1277
+ const eventError = abortSignal?.aborted === true ? abortError(abortSignal.reason) : event.error;
1278
+ const eventUsage = event.usage ?? completionProviderOutputErrorUsage(eventError) ?? Usage.empty();
1279
+ const retryOptions = retryOptionsForFailure(retries, {
1280
+ error: eventError,
1281
+ attempt,
1282
+ streaming: true
1283
+ });
1284
+ if (retryOptions !== void 0) {
1285
+ swallowedUsage = Usage.add(swallowedUsage, eventUsage);
1286
+ retryDelay = retryDelayMs(retryOptions, attempt);
1287
+ break;
1288
+ }
1289
+ }
1290
+ if (event.type === "error") {
1291
+ const eventError = abortSignal?.aborted === true ? abortError(abortSignal.reason) : event.error;
1292
+ const eventUsage = event.usage ?? completionProviderOutputErrorUsage(eventError) ?? Usage.empty();
1293
+ yield {
1294
+ type: "error",
1295
+ error: eventError,
1296
+ usage: Usage.add(swallowedUsage, eventUsage)
1297
+ };
1298
+ return;
1299
+ }
1300
+ if (event.type === "final") {
1301
+ const cumulativeUsage = Usage.add(swallowedUsage, event.response.usage);
1302
+ try {
1303
+ accumulator.accept(event);
1304
+ const accumulatedResponse = accumulator.response();
1305
+ const response = Usage.isEmpty(swallowedUsage) ? accumulatedResponse : { ...accumulatedResponse, usage: cumulativeUsage };
1306
+ assertCompletionResponseIntegrity({ response });
1307
+ yield {
1308
+ type: "final",
1309
+ result: resultFromResponse(response, outputSchema)
1310
+ };
1311
+ } catch (error) {
1312
+ const retryOptions = exposedProgress ? void 0 : retryOptionsForFailure(retries, {
1313
+ error,
1314
+ attempt,
1315
+ streaming: true
1316
+ });
1317
+ if (retryOptions !== void 0) {
1318
+ swallowedUsage = cumulativeUsage;
1319
+ await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);
1320
+ attempt += 1;
1321
+ continue attemptLoop;
1322
+ }
1323
+ yield { type: "error", error, usage: cumulativeUsage };
1324
+ }
1325
+ return;
1326
+ }
1327
+ accumulator.accept(event);
1328
+ exposedProgress = true;
1329
+ yield event;
1330
+ }
1331
+ if (retryDelay !== void 0) {
1332
+ await waitForRetry(retryDelay, abortSignal);
1333
+ attempt += 1;
1334
+ continue;
1335
+ }
1336
+ let incomplete;
1337
+ try {
1338
+ accumulator.response();
1339
+ incomplete = new CompletionProviderOutputError({ kind: "incomplete-stream" });
1340
+ } catch (error) {
1341
+ incomplete = error;
1342
+ }
1343
+ if (!exposedProgress) {
1344
+ const retryOptions = retryOptionsForFailure(retries, {
1345
+ error: incomplete,
1346
+ attempt,
1347
+ streaming: true
1348
+ });
1349
+ if (retryOptions !== void 0) {
1350
+ await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);
1351
+ attempt += 1;
1352
+ continue;
1353
+ }
1354
+ }
1355
+ yield { type: "error", error: incomplete, usage: swallowedUsage };
1356
+ return;
1357
+ } catch (error) {
1358
+ const normalizedError = abortSignal?.aborted === true ? abortError(abortSignal.reason) : error;
1359
+ const attemptUsage = completionProviderOutputErrorUsage(normalizedError);
1360
+ const cumulativeUsage = attemptUsage === void 0 ? swallowedUsage : Usage.add(swallowedUsage, attemptUsage);
1361
+ if (!exposedProgress) {
1362
+ const retryOptions = retryOptionsForFailure(retries, {
1363
+ error: normalizedError,
1364
+ attempt,
1365
+ streaming: true
1366
+ });
1367
+ if (retryOptions !== void 0) {
1368
+ try {
1369
+ swallowedUsage = cumulativeUsage;
1370
+ await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);
1371
+ attempt += 1;
1372
+ continue;
1373
+ } catch (waitError) {
1374
+ yield { type: "error", error: waitError, usage: cumulativeUsage };
1375
+ return;
1376
+ }
1377
+ }
1378
+ }
1379
+ yield { type: "error", error: normalizedError, usage: cumulativeUsage };
1380
+ return;
1381
+ }
1382
+ }
1383
+ }
1384
+ function requestFromOptions(options) {
1385
+ const input = inputFromOptions(options);
1386
+ return createCompletionRequest(input, {
1387
+ instructions: options.instructions,
1388
+ documents: options.documents,
1389
+ tools: options.tools,
1390
+ temperature: options.temperature,
1391
+ maxTokens: options.maxTokens,
1392
+ toolChoice: options.toolChoice,
1393
+ providerOptions: options.providerOptions,
1394
+ outputSchema: "outputSchema" in options && options.outputSchema !== void 0 ? toProviderJsonSchema(options.outputSchema) : void 0
1395
+ });
1396
+ }
1397
+ function inputFromOptions(options) {
1398
+ const prompt = options.prompt;
1399
+ const messages = options.messages;
1400
+ const hasPrompt = prompt !== void 0;
1401
+ const hasMessages = messages !== void 0;
1402
+ if (hasPrompt === hasMessages) {
1403
+ throw new TypeError("Exactly one of prompt or messages must be provided.");
1404
+ }
1405
+ if (hasPrompt) {
1406
+ if (typeof prompt !== "string" || prompt.trim().length === 0) {
1407
+ throw new TypeError("Completion prompt must be a non-empty string.");
1408
+ }
1409
+ return prompt;
1410
+ }
1411
+ if (!Array.isArray(messages)) {
1412
+ throw new TypeError("Completion messages must be an array of Message values.");
1413
+ }
1414
+ return messages;
1415
+ }
1416
+ function structuredOutputSchema(options) {
1417
+ return options.outputSchema;
1418
+ }
1419
+ function resultFromResponse(response, outputSchema) {
1420
+ const text = textFromAssistantContent(response.choice);
1421
+ const result = {
1422
+ output: outputSchema === void 0 ? text : parseCompletionOutput(text, outputSchema, response),
1423
+ text,
1424
+ content: [...response.choice],
1425
+ usage: response.usage,
1426
+ rawResponse: response.rawResponse
1427
+ };
1428
+ if (response.finishReason !== void 0) result.finishReason = response.finishReason;
1429
+ if (response.providerFinishReason !== void 0) {
1430
+ result.providerFinishReason = response.providerFinishReason;
1431
+ }
1432
+ if (response.contextUsage !== void 0) result.contextUsage = response.contextUsage;
1433
+ if (response.messageId !== void 0) result.messageId = response.messageId;
1434
+ if (response.sources !== void 0) result.sources = [...response.sources];
1435
+ if (response.providerToolCalls !== void 0) {
1436
+ result.providerToolCalls = [...response.providerToolCalls];
1437
+ }
1438
+ return result;
1439
+ }
1440
+ function parseCompletionOutput(text, schema, response) {
1441
+ if (response.finishReason === "content-filter") {
1442
+ throw new CompletionStructuredOutputError({
1443
+ phase: "content-filter",
1444
+ outputLength: text.length,
1445
+ usage: response.usage,
1446
+ finishReason: response.finishReason,
1447
+ providerFinishReason: response.providerFinishReason
1448
+ });
1449
+ }
1450
+ if (response.finishReason === "length") {
1451
+ throw new CompletionStructuredOutputError({
1452
+ phase: "truncated",
1453
+ outputLength: text.length,
1454
+ usage: response.usage,
1455
+ finishReason: response.finishReason,
1456
+ providerFinishReason: response.providerFinishReason
1457
+ });
1458
+ }
1459
+ let json;
1460
+ try {
1461
+ json = JSON.parse(text);
1462
+ if (!isJsonValue(json)) {
1463
+ throw new TypeError("Structured completion output is not a JSON value.");
1464
+ }
1465
+ } catch (error) {
1466
+ throw new CompletionStructuredOutputError({
1467
+ phase: "parse",
1468
+ outputLength: text.length,
1469
+ usage: response.usage,
1470
+ finishReason: response.finishReason,
1471
+ providerFinishReason: response.providerFinishReason,
1472
+ cause: error
1473
+ });
1474
+ }
1475
+ try {
1476
+ return schema.parse(json);
1477
+ } catch (error) {
1478
+ throw new CompletionStructuredOutputError({
1479
+ phase: "schema",
1480
+ outputLength: text.length,
1481
+ usage: response.usage,
1482
+ finishReason: response.finishReason,
1483
+ providerFinishReason: response.providerFinishReason,
1484
+ cause: error
1485
+ });
1486
+ }
1487
+ }
1488
+ function modelCallOptions(abortSignal) {
1489
+ return abortSignal === void 0 ? void 0 : { abortSignal };
1490
+ }
1491
+ function isStreamingCompletionModel(model) {
1492
+ return typeof model.streamCompletion === "function";
1493
+ }
1494
+
1495
+ export {
1496
+ reasoningDisplayText,
1497
+ isProviderTool,
1498
+ calculateContextUsage,
1499
+ withContextUsage,
1500
+ resolveModelContextLimits,
1501
+ Usage,
1502
+ getAssistantGenerationMetadata,
1503
+ CompletionCapabilityError,
1504
+ assertCompletionRequestSupported,
1505
+ textFromAssistantContent,
1506
+ createCompletionRequest,
1507
+ COMPLETION_PROVIDER_OUTPUT_ERROR_CODE,
1508
+ CompletionProviderOutputError,
1509
+ assertCompletionResponseIntegrity,
1510
+ CompletionStreamAccumulator,
1511
+ CompletionStructuredOutputError,
1512
+ generateCompletion,
1513
+ streamCompletion,
1514
+ isStreamingCompletionModel
1515
+ };
1516
+ //# sourceMappingURL=chunk-7PHMK7W4.js.map