@agentdocumentformat/cli 0.7.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 (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +45 -0
  3. package/dist/adf.mjs +162 -0
  4. package/dist/chunks/APEv2Parser-2CNNHMXV.mjs +22 -0
  5. package/dist/chunks/AiffParser-7BR4RL6G.mjs +162 -0
  6. package/dist/chunks/App-L5L37JI5.mjs +16747 -0
  7. package/dist/chunks/AsfParser-VVRSLFOM.mjs +538 -0
  8. package/dist/chunks/DsdiffParser-CMD4AX7A.mjs +156 -0
  9. package/dist/chunks/DsfParser-UOGZDS2M.mjs +94 -0
  10. package/dist/chunks/FlacParser-HB3T3CD4.mjs +23 -0
  11. package/dist/chunks/MP4Parser-66HBRUSX.mjs +973 -0
  12. package/dist/chunks/MatroskaParser-J3HUIMEW.mjs +579 -0
  13. package/dist/chunks/MpegParser-YW6LIUEW.mjs +442 -0
  14. package/dist/chunks/MusepackParser-PAUSXP7D.mjs +252 -0
  15. package/dist/chunks/OggParser-NUBV3GWC.mjs +359 -0
  16. package/dist/chunks/WavPackParser-WQAGT7TC.mjs +171 -0
  17. package/dist/chunks/WaveParser-EWLQVDX4.mjs +238 -0
  18. package/dist/chunks/adf-schema-JRU2BTOG.mjs +62 -0
  19. package/dist/chunks/build-QF5W473T.mjs +60 -0
  20. package/dist/chunks/chatgpt-subscription-BQGWYZXE.mjs +23 -0
  21. package/dist/chunks/chunk-2DIECGFL.mjs +6 -0
  22. package/dist/chunks/chunk-2NAP2ZF7.mjs +60 -0
  23. package/dist/chunks/chunk-3AT7IIP7.mjs +25696 -0
  24. package/dist/chunks/chunk-3GNIDM53.mjs +35 -0
  25. package/dist/chunks/chunk-3M4ZPOA3.mjs +1477 -0
  26. package/dist/chunks/chunk-4MQPTCXY.mjs +510 -0
  27. package/dist/chunks/chunk-5PO5PKRV.mjs +366 -0
  28. package/dist/chunks/chunk-5QU5VY7N.mjs +52 -0
  29. package/dist/chunks/chunk-5W7KES6P.mjs +436 -0
  30. package/dist/chunks/chunk-62NE4LG4.mjs +61 -0
  31. package/dist/chunks/chunk-64OKE4X3.mjs +45 -0
  32. package/dist/chunks/chunk-6GJ4QHRI.mjs +1278 -0
  33. package/dist/chunks/chunk-6VQEXLE2.mjs +144 -0
  34. package/dist/chunks/chunk-6XUV6EK6.mjs +41 -0
  35. package/dist/chunks/chunk-776TSXEP.mjs +43 -0
  36. package/dist/chunks/chunk-7CV2SA3H.mjs +285 -0
  37. package/dist/chunks/chunk-7MTRVW2U.mjs +3103 -0
  38. package/dist/chunks/chunk-7N2R2VCG.mjs +1434 -0
  39. package/dist/chunks/chunk-7T2YMTWL.mjs +374 -0
  40. package/dist/chunks/chunk-7XYNI52E.mjs +149 -0
  41. package/dist/chunks/chunk-APHX6HSV.mjs +7731 -0
  42. package/dist/chunks/chunk-APRU6PHC.mjs +40 -0
  43. package/dist/chunks/chunk-AUYKRQPJ.mjs +499 -0
  44. package/dist/chunks/chunk-DXWDD5XJ.mjs +136 -0
  45. package/dist/chunks/chunk-EWL5FG4I.mjs +39 -0
  46. package/dist/chunks/chunk-EYX2YLJW.mjs +117 -0
  47. package/dist/chunks/chunk-F5ELW46V.mjs +27 -0
  48. package/dist/chunks/chunk-G426FACA.mjs +49 -0
  49. package/dist/chunks/chunk-GEKSJHIV.mjs +2472 -0
  50. package/dist/chunks/chunk-HBUENVQL.mjs +570 -0
  51. package/dist/chunks/chunk-HPVFJYXR.mjs +112 -0
  52. package/dist/chunks/chunk-HWLWPXQ7.mjs +721 -0
  53. package/dist/chunks/chunk-I2HJYHFT.mjs +665 -0
  54. package/dist/chunks/chunk-I3UYSITV.mjs +68 -0
  55. package/dist/chunks/chunk-IC4JDZCI.mjs +3864 -0
  56. package/dist/chunks/chunk-IHDDCZBS.mjs +112 -0
  57. package/dist/chunks/chunk-IIGMZHQQ.mjs +10416 -0
  58. package/dist/chunks/chunk-KWFOS5WC.mjs +41 -0
  59. package/dist/chunks/chunk-LAZIXV2F.mjs +5290 -0
  60. package/dist/chunks/chunk-LFMB4PAA.mjs +10814 -0
  61. package/dist/chunks/chunk-M2RX3S2T.mjs +49 -0
  62. package/dist/chunks/chunk-M3WPIJYM.mjs +65 -0
  63. package/dist/chunks/chunk-NBTUWMGP.mjs +263 -0
  64. package/dist/chunks/chunk-NGK6PVSF.mjs +2676 -0
  65. package/dist/chunks/chunk-NZ7JTHEO.mjs +85 -0
  66. package/dist/chunks/chunk-OQN33RGQ.mjs +52 -0
  67. package/dist/chunks/chunk-RIX34QHC.mjs +2935 -0
  68. package/dist/chunks/chunk-SGUTYISF.mjs +16 -0
  69. package/dist/chunks/chunk-SLJ5L7PY.mjs +1473 -0
  70. package/dist/chunks/chunk-SLUKGXKH.mjs +68 -0
  71. package/dist/chunks/chunk-TMT32MXT.mjs +419 -0
  72. package/dist/chunks/chunk-UYY5M2PB.mjs +151 -0
  73. package/dist/chunks/chunk-VAUOM3IN.mjs +298 -0
  74. package/dist/chunks/chunk-VMHTYDH4.mjs +172 -0
  75. package/dist/chunks/chunk-VZS54AA5.mjs +200 -0
  76. package/dist/chunks/chunk-WFQUVXML.mjs +295 -0
  77. package/dist/chunks/chunk-X34PDRUH.mjs +809 -0
  78. package/dist/chunks/chunk-XNPZBLYL.mjs +33 -0
  79. package/dist/chunks/chunk-XX7OSWTO.mjs +157 -0
  80. package/dist/chunks/chunk-XYTWGHFS.mjs +600 -0
  81. package/dist/chunks/chunk-XYV3VCIX.mjs +336 -0
  82. package/dist/chunks/chunk-Y5ZLKFLE.mjs +1469 -0
  83. package/dist/chunks/chunk-ZJKXHM4Q.mjs +230 -0
  84. package/dist/chunks/cli-TCMBNZF6.mjs +1030 -0
  85. package/dist/chunks/commands-DTEKM4ZL.mjs +20 -0
  86. package/dist/chunks/daemon-ZC3FZ2P4.mjs +112449 -0
  87. package/dist/chunks/daemon-control-WDX7PMTC.mjs +300 -0
  88. package/dist/chunks/daemon-token-WRSULP7G.mjs +23 -0
  89. package/dist/chunks/devtools-H7CI2ZVG.mjs +85 -0
  90. package/dist/chunks/discord-IWDQJA7A.mjs +70588 -0
  91. package/dist/chunks/dist-C57KYFS2.mjs +4952 -0
  92. package/dist/chunks/dist-I3XBAGDL.mjs +11 -0
  93. package/dist/chunks/email-V4Q4VJON.mjs +58679 -0
  94. package/dist/chunks/environment-NX277MQG.mjs +15 -0
  95. package/dist/chunks/grok-subscription-4PYX7TBF.mjs +19 -0
  96. package/dist/chunks/layout-EPJQNFAI.mjs +22 -0
  97. package/dist/chunks/lib-N7FCZWKH.mjs +4038 -0
  98. package/dist/chunks/open-OTQDGDH5.mjs +36 -0
  99. package/dist/chunks/parser-JVY2PWSM.mjs +19 -0
  100. package/dist/chunks/pipeline-executor-BHBSJX2K.mjs +19 -0
  101. package/dist/chunks/react-IUIDQ5LX.mjs +11 -0
  102. package/dist/chunks/screen-54BUTYCW.mjs +27 -0
  103. package/dist/chunks/slack-3L5QTDZX.mjs +8113 -0
  104. package/dist/chunks/store-WR7TZJZS.mjs +32 -0
  105. package/dist/chunks/telegram-5ISVFBV3.mjs +14918 -0
  106. package/dist/chunks/terminal-O5WO7C5U.mjs +48 -0
  107. package/dist/chunks/theme-NORU4J74.mjs +20 -0
  108. package/dist/chunks/themes-F2FKU7CP.mjs +23 -0
  109. package/dist/chunks/token-6G3HCMNX.mjs +54 -0
  110. package/dist/chunks/token-util-UXYSDQIW.mjs +12 -0
  111. package/dist/chunks/tui-ODVYUIMT.mjs +197 -0
  112. package/dist/chunks/welcome-XHXFV7SH.mjs +32 -0
  113. package/dist/chunks/whatsapp-XSAMNGPJ.mjs +85412 -0
  114. package/dist/chunks/xterm-headless-YF53XWXE.mjs +3353 -0
  115. package/package.json +53 -0
  116. package/resources/wasm/coreutils.LICENSE +18 -0
  117. package/resources/wasm/coreutils.wasm +0 -0
@@ -0,0 +1,1469 @@
1
+ import { createRequire as __adfCreateRequire } from 'node:module';
2
+ import { fileURLToPath as __adfFileURLToPath } from 'node:url';
3
+ import { dirname as __adfDirname } from 'node:path';
4
+ const require = __adfCreateRequire(import.meta.url);
5
+ const __filename = __adfFileURLToPath(import.meta.url);
6
+ const __dirname = __adfDirname(__filename);
7
+ import {
8
+ InvalidPromptError,
9
+ InvalidResponseDataError,
10
+ TooManyEmbeddingValuesForCallError,
11
+ UnsupportedFunctionalityError,
12
+ combineHeaders,
13
+ convertBase64ToUint8Array,
14
+ convertToBase64,
15
+ convertToFormData,
16
+ createEventSourceResponseHandler,
17
+ createJsonErrorResponseHandler,
18
+ createJsonResponseHandler,
19
+ downloadBlob,
20
+ external_exports,
21
+ generateId,
22
+ isParsableJson,
23
+ parseProviderOptions,
24
+ postFormDataToApi,
25
+ postJsonToApi,
26
+ withUserAgentSuffix,
27
+ withoutTrailingSlash
28
+ } from "./chunk-LFMB4PAA.mjs";
29
+
30
+ // node_modules/@ai-sdk/openai-compatible/dist/index.mjs
31
+ var openaiCompatibleErrorDataSchema = external_exports.object({
32
+ error: external_exports.object({
33
+ message: external_exports.string(),
34
+ // The additional information below is handled loosely to support
35
+ // OpenAI-compatible providers that have slightly different error
36
+ // responses:
37
+ type: external_exports.string().nullish(),
38
+ param: external_exports.any().nullish(),
39
+ code: external_exports.union([external_exports.string(), external_exports.number()]).nullish()
40
+ })
41
+ }), defaultOpenAICompatibleErrorStructure = {
42
+ errorSchema: openaiCompatibleErrorDataSchema,
43
+ errorToMessage: (data) => data.error.message
44
+ };
45
+ function convertOpenAICompatibleChatUsage(usage) {
46
+ var _a, _b, _c, _d, _e, _f;
47
+ if (usage == null)
48
+ return {
49
+ inputTokens: {
50
+ total: void 0,
51
+ noCache: void 0,
52
+ cacheRead: void 0,
53
+ cacheWrite: void 0
54
+ },
55
+ outputTokens: {
56
+ total: void 0,
57
+ text: void 0,
58
+ reasoning: void 0
59
+ },
60
+ raw: void 0
61
+ };
62
+ let promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0, completionTokens = (_b = usage.completion_tokens) != null ? _b : 0, cacheReadTokens = (_d = (_c = usage.prompt_tokens_details) == null ? void 0 : _c.cached_tokens) != null ? _d : 0, reasoningTokens = (_f = (_e = usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0;
63
+ return {
64
+ inputTokens: {
65
+ total: promptTokens,
66
+ noCache: promptTokens - cacheReadTokens,
67
+ cacheRead: cacheReadTokens,
68
+ cacheWrite: void 0
69
+ },
70
+ outputTokens: {
71
+ total: completionTokens,
72
+ text: completionTokens - reasoningTokens,
73
+ reasoning: reasoningTokens
74
+ },
75
+ raw: usage
76
+ };
77
+ }
78
+ function getOpenAIMetadata(message) {
79
+ var _a, _b;
80
+ return (_b = (_a = message?.providerOptions) == null ? void 0 : _a.openaiCompatible) != null ? _b : {};
81
+ }
82
+ function getAudioFormat(mediaType) {
83
+ switch (mediaType) {
84
+ case "audio/wav":
85
+ return "wav";
86
+ case "audio/mp3":
87
+ case "audio/mpeg":
88
+ return "mp3";
89
+ default:
90
+ return null;
91
+ }
92
+ }
93
+ function convertToOpenAICompatibleChatMessages(prompt) {
94
+ var _a, _b, _c;
95
+ let messages = [];
96
+ for (let { role, content, ...message } of prompt) {
97
+ let metadata = getOpenAIMetadata({ ...message });
98
+ switch (role) {
99
+ case "system": {
100
+ messages.push({ role: "system", content, ...metadata });
101
+ break;
102
+ }
103
+ case "user": {
104
+ if (content.length === 1 && content[0].type === "text") {
105
+ messages.push({
106
+ role: "user",
107
+ content: content[0].text,
108
+ ...getOpenAIMetadata(content[0])
109
+ });
110
+ break;
111
+ }
112
+ messages.push({
113
+ role: "user",
114
+ content: content.map((part) => {
115
+ var _a2;
116
+ let partMetadata = getOpenAIMetadata(part);
117
+ switch (part.type) {
118
+ case "text":
119
+ return { type: "text", text: part.text, ...partMetadata };
120
+ case "file": {
121
+ if (part.mediaType.startsWith("image/")) {
122
+ let mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
123
+ return {
124
+ type: "image_url",
125
+ image_url: {
126
+ url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`
127
+ },
128
+ ...partMetadata
129
+ };
130
+ }
131
+ if (part.mediaType.startsWith("audio/")) {
132
+ if (part.data instanceof URL)
133
+ throw new UnsupportedFunctionalityError({
134
+ functionality: "audio file parts with URLs"
135
+ });
136
+ let format = getAudioFormat(part.mediaType);
137
+ if (format === null)
138
+ throw new UnsupportedFunctionalityError({
139
+ functionality: `audio media type ${part.mediaType}`
140
+ });
141
+ return {
142
+ type: "input_audio",
143
+ input_audio: {
144
+ data: convertToBase64(part.data),
145
+ format
146
+ },
147
+ ...partMetadata
148
+ };
149
+ }
150
+ if (part.mediaType === "application/pdf") {
151
+ if (part.data instanceof URL)
152
+ throw new UnsupportedFunctionalityError({
153
+ functionality: "PDF file parts with URLs"
154
+ });
155
+ return {
156
+ type: "file",
157
+ file: {
158
+ filename: (_a2 = part.filename) != null ? _a2 : "document.pdf",
159
+ file_data: `data:application/pdf;base64,${convertToBase64(part.data)}`
160
+ },
161
+ ...partMetadata
162
+ };
163
+ }
164
+ if (part.mediaType.startsWith("text/"))
165
+ return {
166
+ type: "text",
167
+ text: part.data instanceof URL ? part.data.toString() : typeof part.data == "string" ? part.data : new TextDecoder().decode(part.data),
168
+ ...partMetadata
169
+ };
170
+ throw new UnsupportedFunctionalityError({
171
+ functionality: `file part media type ${part.mediaType}`
172
+ });
173
+ }
174
+ }
175
+ }),
176
+ ...metadata
177
+ });
178
+ break;
179
+ }
180
+ case "assistant": {
181
+ let text = "", reasoning = "", toolCalls = [];
182
+ for (let part of content) {
183
+ let partMetadata = getOpenAIMetadata(part);
184
+ switch (part.type) {
185
+ case "text": {
186
+ text += part.text;
187
+ break;
188
+ }
189
+ case "reasoning": {
190
+ reasoning += part.text;
191
+ break;
192
+ }
193
+ case "tool-call": {
194
+ let thoughtSignature = (_b = (_a = part.providerOptions) == null ? void 0 : _a.google) == null ? void 0 : _b.thoughtSignature;
195
+ toolCalls.push({
196
+ id: part.toolCallId,
197
+ type: "function",
198
+ function: {
199
+ name: part.toolName,
200
+ arguments: JSON.stringify(part.input)
201
+ },
202
+ ...partMetadata,
203
+ // Include extra_content for Google Gemini thought signatures
204
+ ...thoughtSignature ? {
205
+ extra_content: {
206
+ google: {
207
+ thought_signature: String(thoughtSignature)
208
+ }
209
+ }
210
+ } : {}
211
+ });
212
+ break;
213
+ }
214
+ }
215
+ }
216
+ messages.push({
217
+ role: "assistant",
218
+ content: text,
219
+ ...reasoning.length > 0 ? { reasoning_content: reasoning } : {},
220
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
221
+ ...metadata
222
+ });
223
+ break;
224
+ }
225
+ case "tool": {
226
+ for (let toolResponse of content) {
227
+ if (toolResponse.type === "tool-approval-response")
228
+ continue;
229
+ let output = toolResponse.output, contentValue;
230
+ switch (output.type) {
231
+ case "text":
232
+ case "error-text":
233
+ contentValue = output.value;
234
+ break;
235
+ case "execution-denied":
236
+ contentValue = (_c = output.reason) != null ? _c : "Tool execution denied.";
237
+ break;
238
+ case "content":
239
+ case "json":
240
+ case "error-json":
241
+ contentValue = JSON.stringify(output.value);
242
+ break;
243
+ }
244
+ let toolResponseMetadata = getOpenAIMetadata(toolResponse);
245
+ messages.push({
246
+ role: "tool",
247
+ tool_call_id: toolResponse.toolCallId,
248
+ content: contentValue,
249
+ ...toolResponseMetadata
250
+ });
251
+ }
252
+ break;
253
+ }
254
+ default: {
255
+ let _exhaustiveCheck = role;
256
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
257
+ }
258
+ }
259
+ }
260
+ return messages;
261
+ }
262
+ function getResponseMetadata({
263
+ id,
264
+ model,
265
+ created
266
+ }) {
267
+ return {
268
+ id: id ?? void 0,
269
+ modelId: model ?? void 0,
270
+ timestamp: created != null ? new Date(created * 1e3) : void 0
271
+ };
272
+ }
273
+ function mapOpenAICompatibleFinishReason(finishReason) {
274
+ switch (finishReason) {
275
+ case "stop":
276
+ return "stop";
277
+ case "length":
278
+ return "length";
279
+ case "content_filter":
280
+ return "content-filter";
281
+ case "function_call":
282
+ case "tool_calls":
283
+ return "tool-calls";
284
+ default:
285
+ return "other";
286
+ }
287
+ }
288
+ var openaiCompatibleProviderOptions = external_exports.object({
289
+ /**
290
+ * A unique identifier representing your end-user, which can help the provider to
291
+ * monitor and detect abuse.
292
+ */
293
+ user: external_exports.string().optional(),
294
+ /**
295
+ * Reasoning effort for reasoning models. Defaults to `medium`.
296
+ */
297
+ reasoningEffort: external_exports.string().optional(),
298
+ /**
299
+ * Controls the verbosity of the generated text. Defaults to `medium`.
300
+ */
301
+ textVerbosity: external_exports.string().optional(),
302
+ /**
303
+ * Whether to use strict JSON schema validation.
304
+ * When true, the model uses constrained decoding to guarantee schema compliance.
305
+ * Only used when the provider supports structured outputs and a schema is provided.
306
+ *
307
+ * @default true
308
+ */
309
+ strictJsonSchema: external_exports.boolean().optional()
310
+ });
311
+ function prepareTools({
312
+ tools,
313
+ toolChoice
314
+ }) {
315
+ tools = tools?.length ? tools : void 0;
316
+ let toolWarnings = [];
317
+ if (tools == null)
318
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
319
+ let openaiCompatTools = [];
320
+ for (let tool of tools)
321
+ tool.type === "provider" ? toolWarnings.push({
322
+ type: "unsupported",
323
+ feature: `provider-defined tool ${tool.id}`
324
+ }) : openaiCompatTools.push({
325
+ type: "function",
326
+ function: {
327
+ name: tool.name,
328
+ description: tool.description,
329
+ parameters: tool.inputSchema,
330
+ ...tool.strict != null ? { strict: tool.strict } : {}
331
+ }
332
+ });
333
+ if (toolChoice == null)
334
+ return { tools: openaiCompatTools, toolChoice: void 0, toolWarnings };
335
+ let type = toolChoice.type;
336
+ switch (type) {
337
+ case "auto":
338
+ case "none":
339
+ case "required":
340
+ return { tools: openaiCompatTools, toolChoice: type, toolWarnings };
341
+ case "tool":
342
+ return {
343
+ tools: openaiCompatTools,
344
+ toolChoice: {
345
+ type: "function",
346
+ function: { name: toolChoice.toolName }
347
+ },
348
+ toolWarnings
349
+ };
350
+ default: {
351
+ let _exhaustiveCheck = type;
352
+ throw new UnsupportedFunctionalityError({
353
+ functionality: `tool choice type: ${_exhaustiveCheck}`
354
+ });
355
+ }
356
+ }
357
+ }
358
+ var OpenAICompatibleChatLanguageModel = class {
359
+ // type inferred via constructor
360
+ constructor(modelId, config) {
361
+ this.specificationVersion = "v3";
362
+ var _a, _b;
363
+ this.modelId = modelId, this.config = config;
364
+ let errorStructure = (_a = config.errorStructure) != null ? _a : defaultOpenAICompatibleErrorStructure;
365
+ this.chunkSchema = createOpenAICompatibleChatChunkSchema(
366
+ errorStructure.errorSchema
367
+ ), this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure), this.supportsStructuredOutputs = (_b = config.supportsStructuredOutputs) != null ? _b : !1;
368
+ }
369
+ get provider() {
370
+ return this.config.provider;
371
+ }
372
+ get providerOptionsName() {
373
+ return this.config.provider.split(".")[0].trim();
374
+ }
375
+ get supportedUrls() {
376
+ var _a, _b, _c;
377
+ return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
378
+ }
379
+ transformRequestBody(args) {
380
+ var _a, _b, _c;
381
+ return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args)) != null ? _c : args;
382
+ }
383
+ async getArgs({
384
+ prompt,
385
+ maxOutputTokens,
386
+ temperature,
387
+ topP,
388
+ topK,
389
+ frequencyPenalty,
390
+ presencePenalty,
391
+ providerOptions,
392
+ stopSequences,
393
+ responseFormat,
394
+ seed,
395
+ toolChoice,
396
+ tools
397
+ }) {
398
+ var _a, _b, _c, _d, _e;
399
+ let warnings = [], deprecatedOptions = await parseProviderOptions({
400
+ provider: "openai-compatible",
401
+ providerOptions,
402
+ schema: openaiCompatibleProviderOptions
403
+ });
404
+ deprecatedOptions != null && warnings.push({
405
+ type: "other",
406
+ message: "The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead."
407
+ });
408
+ let compatibleOptions = Object.assign(
409
+ deprecatedOptions ?? {},
410
+ (_a = await parseProviderOptions({
411
+ provider: "openaiCompatible",
412
+ providerOptions,
413
+ schema: openaiCompatibleProviderOptions
414
+ })) != null ? _a : {},
415
+ (_b = await parseProviderOptions({
416
+ provider: this.providerOptionsName,
417
+ providerOptions,
418
+ schema: openaiCompatibleProviderOptions
419
+ })) != null ? _b : {}
420
+ ), strictJsonSchema = (_c = compatibleOptions?.strictJsonSchema) != null ? _c : !0;
421
+ topK != null && warnings.push({ type: "unsupported", feature: "topK" }), responseFormat?.type === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs && warnings.push({
422
+ type: "unsupported",
423
+ feature: "responseFormat",
424
+ details: "JSON response format schema is only supported with structuredOutputs"
425
+ });
426
+ let {
427
+ tools: openaiTools,
428
+ toolChoice: openaiToolChoice,
429
+ toolWarnings
430
+ } = prepareTools({
431
+ tools,
432
+ toolChoice
433
+ });
434
+ return {
435
+ args: {
436
+ // model id:
437
+ model: this.modelId,
438
+ // model specific settings:
439
+ user: compatibleOptions.user,
440
+ // standardized settings:
441
+ max_tokens: maxOutputTokens,
442
+ temperature,
443
+ top_p: topP,
444
+ frequency_penalty: frequencyPenalty,
445
+ presence_penalty: presencePenalty,
446
+ response_format: responseFormat?.type === "json" ? this.supportsStructuredOutputs === !0 && responseFormat.schema != null ? {
447
+ type: "json_schema",
448
+ json_schema: {
449
+ schema: responseFormat.schema,
450
+ strict: strictJsonSchema,
451
+ name: (_d = responseFormat.name) != null ? _d : "response",
452
+ description: responseFormat.description
453
+ }
454
+ } : { type: "json_object" } : void 0,
455
+ stop: stopSequences,
456
+ seed,
457
+ ...Object.fromEntries(
458
+ Object.entries(
459
+ (_e = providerOptions?.[this.providerOptionsName]) != null ? _e : {}
460
+ ).filter(
461
+ ([key]) => !Object.keys(openaiCompatibleProviderOptions.shape).includes(key)
462
+ )
463
+ ),
464
+ reasoning_effort: compatibleOptions.reasoningEffort,
465
+ verbosity: compatibleOptions.textVerbosity,
466
+ // messages:
467
+ messages: convertToOpenAICompatibleChatMessages(prompt),
468
+ // tools:
469
+ tools: openaiTools,
470
+ tool_choice: openaiToolChoice
471
+ },
472
+ warnings: [...warnings, ...toolWarnings]
473
+ };
474
+ }
475
+ async doGenerate(options) {
476
+ var _a, _b, _c, _d, _e, _f, _g, _h;
477
+ let { args, warnings } = await this.getArgs({ ...options }), transformedBody = this.transformRequestBody(args), body = JSON.stringify(transformedBody), {
478
+ responseHeaders,
479
+ value: responseBody,
480
+ rawValue: rawResponse
481
+ } = await postJsonToApi({
482
+ url: this.config.url({
483
+ path: "/chat/completions",
484
+ modelId: this.modelId
485
+ }),
486
+ headers: combineHeaders(this.config.headers(), options.headers),
487
+ body: transformedBody,
488
+ failedResponseHandler: this.failedResponseHandler,
489
+ successfulResponseHandler: createJsonResponseHandler(
490
+ OpenAICompatibleChatResponseSchema
491
+ ),
492
+ abortSignal: options.abortSignal,
493
+ fetch: this.config.fetch
494
+ }), choice = responseBody.choices[0], content = [], text = choice.message.content;
495
+ text != null && text.length > 0 && content.push({ type: "text", text });
496
+ let reasoning = (_a = choice.message.reasoning_content) != null ? _a : choice.message.reasoning;
497
+ if (reasoning != null && reasoning.length > 0 && content.push({
498
+ type: "reasoning",
499
+ text: reasoning
500
+ }), choice.message.tool_calls != null)
501
+ for (let toolCall of choice.message.tool_calls) {
502
+ let thoughtSignature = (_c = (_b = toolCall.extra_content) == null ? void 0 : _b.google) == null ? void 0 : _c.thought_signature;
503
+ content.push({
504
+ type: "tool-call",
505
+ toolCallId: (_d = toolCall.id) != null ? _d : generateId(),
506
+ toolName: toolCall.function.name,
507
+ input: toolCall.function.arguments,
508
+ ...thoughtSignature ? {
509
+ providerMetadata: {
510
+ [this.providerOptionsName]: { thoughtSignature }
511
+ }
512
+ } : {}
513
+ });
514
+ }
515
+ let providerMetadata = {
516
+ [this.providerOptionsName]: {},
517
+ ...await ((_f = (_e = this.config.metadataExtractor) == null ? void 0 : _e.extractMetadata) == null ? void 0 : _f.call(_e, {
518
+ parsedBody: rawResponse
519
+ }))
520
+ }, completionTokenDetails = (_g = responseBody.usage) == null ? void 0 : _g.completion_tokens_details;
521
+ return completionTokenDetails?.accepted_prediction_tokens != null && (providerMetadata[this.providerOptionsName].acceptedPredictionTokens = completionTokenDetails?.accepted_prediction_tokens), completionTokenDetails?.rejected_prediction_tokens != null && (providerMetadata[this.providerOptionsName].rejectedPredictionTokens = completionTokenDetails?.rejected_prediction_tokens), {
522
+ content,
523
+ finishReason: {
524
+ unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
525
+ raw: (_h = choice.finish_reason) != null ? _h : void 0
526
+ },
527
+ usage: convertOpenAICompatibleChatUsage(responseBody.usage),
528
+ providerMetadata,
529
+ request: { body },
530
+ response: {
531
+ ...getResponseMetadata(responseBody),
532
+ headers: responseHeaders,
533
+ body: rawResponse
534
+ },
535
+ warnings
536
+ };
537
+ }
538
+ async doStream(options) {
539
+ var _a;
540
+ let { args, warnings } = await this.getArgs({ ...options }), body = this.transformRequestBody({
541
+ ...args,
542
+ stream: !0,
543
+ // only include stream_options when in strict compatibility mode:
544
+ stream_options: this.config.includeUsage ? { include_usage: !0 } : void 0
545
+ }), metadataExtractor = (_a = this.config.metadataExtractor) == null ? void 0 : _a.createStreamExtractor(), { responseHeaders, value: response } = await postJsonToApi({
546
+ url: this.config.url({
547
+ path: "/chat/completions",
548
+ modelId: this.modelId
549
+ }),
550
+ headers: combineHeaders(this.config.headers(), options.headers),
551
+ body,
552
+ failedResponseHandler: this.failedResponseHandler,
553
+ successfulResponseHandler: createEventSourceResponseHandler(
554
+ this.chunkSchema
555
+ ),
556
+ abortSignal: options.abortSignal,
557
+ fetch: this.config.fetch
558
+ }), toolCalls = [], finishReason = {
559
+ unified: "other",
560
+ raw: void 0
561
+ }, usage, isFirstChunk = !0, providerOptionsName = this.providerOptionsName, isActiveReasoning = !1, isActiveText = !1;
562
+ return {
563
+ stream: response.pipeThrough(
564
+ new TransformStream({
565
+ start(controller) {
566
+ controller.enqueue({ type: "stream-start", warnings });
567
+ },
568
+ transform(chunk, controller) {
569
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
570
+ if (options.includeRawChunks && controller.enqueue({ type: "raw", rawValue: chunk.rawValue }), !chunk.success) {
571
+ finishReason = { unified: "error", raw: void 0 }, controller.enqueue({ type: "error", error: chunk.error });
572
+ return;
573
+ }
574
+ if (metadataExtractor?.processChunk(chunk.rawValue), "error" in chunk.value) {
575
+ finishReason = { unified: "error", raw: void 0 }, controller.enqueue({
576
+ type: "error",
577
+ error: chunk.value.error.message
578
+ });
579
+ return;
580
+ }
581
+ let value = chunk.value;
582
+ isFirstChunk && (isFirstChunk = !1, controller.enqueue({
583
+ type: "response-metadata",
584
+ ...getResponseMetadata(value)
585
+ })), value.usage != null && (usage = value.usage);
586
+ let choice = value.choices[0];
587
+ if (choice?.finish_reason != null && (finishReason = {
588
+ unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
589
+ raw: (_a2 = choice.finish_reason) != null ? _a2 : void 0
590
+ }), choice?.delta == null)
591
+ return;
592
+ let delta = choice.delta, reasoningContent = (_b = delta.reasoning_content) != null ? _b : delta.reasoning;
593
+ if (reasoningContent && (isActiveReasoning || (controller.enqueue({
594
+ type: "reasoning-start",
595
+ id: "reasoning-0"
596
+ }), isActiveReasoning = !0), controller.enqueue({
597
+ type: "reasoning-delta",
598
+ id: "reasoning-0",
599
+ delta: reasoningContent
600
+ })), delta.content && (isActiveReasoning && (controller.enqueue({
601
+ type: "reasoning-end",
602
+ id: "reasoning-0"
603
+ }), isActiveReasoning = !1), isActiveText || (controller.enqueue({ type: "text-start", id: "txt-0" }), isActiveText = !0), controller.enqueue({
604
+ type: "text-delta",
605
+ id: "txt-0",
606
+ delta: delta.content
607
+ })), delta.tool_calls != null) {
608
+ isActiveReasoning && (controller.enqueue({
609
+ type: "reasoning-end",
610
+ id: "reasoning-0"
611
+ }), isActiveReasoning = !1);
612
+ for (let toolCallDelta of delta.tool_calls) {
613
+ let index = (_c = toolCallDelta.index) != null ? _c : toolCalls.length;
614
+ if (toolCalls[index] == null) {
615
+ if (toolCallDelta.id == null)
616
+ throw new InvalidResponseDataError({
617
+ data: toolCallDelta,
618
+ message: "Expected 'id' to be a string."
619
+ });
620
+ if (((_d = toolCallDelta.function) == null ? void 0 : _d.name) == null)
621
+ throw new InvalidResponseDataError({
622
+ data: toolCallDelta,
623
+ message: "Expected 'function.name' to be a string."
624
+ });
625
+ controller.enqueue({
626
+ type: "tool-input-start",
627
+ id: toolCallDelta.id,
628
+ toolName: toolCallDelta.function.name
629
+ }), toolCalls[index] = {
630
+ id: toolCallDelta.id,
631
+ type: "function",
632
+ function: {
633
+ name: toolCallDelta.function.name,
634
+ arguments: (_e = toolCallDelta.function.arguments) != null ? _e : ""
635
+ },
636
+ hasFinished: !1,
637
+ thoughtSignature: (_h = (_g = (_f = toolCallDelta.extra_content) == null ? void 0 : _f.google) == null ? void 0 : _g.thought_signature) != null ? _h : void 0
638
+ };
639
+ let toolCall2 = toolCalls[index];
640
+ ((_i = toolCall2.function) == null ? void 0 : _i.name) != null && ((_j = toolCall2.function) == null ? void 0 : _j.arguments) != null && (toolCall2.function.arguments.length > 0 && controller.enqueue({
641
+ type: "tool-input-delta",
642
+ id: toolCall2.id,
643
+ delta: toolCall2.function.arguments
644
+ }), isParsableJson(toolCall2.function.arguments) && (controller.enqueue({
645
+ type: "tool-input-end",
646
+ id: toolCall2.id
647
+ }), controller.enqueue({
648
+ type: "tool-call",
649
+ toolCallId: (_k = toolCall2.id) != null ? _k : generateId(),
650
+ toolName: toolCall2.function.name,
651
+ input: toolCall2.function.arguments,
652
+ ...toolCall2.thoughtSignature ? {
653
+ providerMetadata: {
654
+ [providerOptionsName]: {
655
+ thoughtSignature: toolCall2.thoughtSignature
656
+ }
657
+ }
658
+ } : {}
659
+ }), toolCall2.hasFinished = !0));
660
+ continue;
661
+ }
662
+ let toolCall = toolCalls[index];
663
+ toolCall.hasFinished || (((_l = toolCallDelta.function) == null ? void 0 : _l.arguments) != null && (toolCall.function.arguments += (_n = (_m = toolCallDelta.function) == null ? void 0 : _m.arguments) != null ? _n : ""), controller.enqueue({
664
+ type: "tool-input-delta",
665
+ id: toolCall.id,
666
+ delta: (_o = toolCallDelta.function.arguments) != null ? _o : ""
667
+ }), ((_p = toolCall.function) == null ? void 0 : _p.name) != null && ((_q = toolCall.function) == null ? void 0 : _q.arguments) != null && isParsableJson(toolCall.function.arguments) && (controller.enqueue({
668
+ type: "tool-input-end",
669
+ id: toolCall.id
670
+ }), controller.enqueue({
671
+ type: "tool-call",
672
+ toolCallId: (_r = toolCall.id) != null ? _r : generateId(),
673
+ toolName: toolCall.function.name,
674
+ input: toolCall.function.arguments,
675
+ ...toolCall.thoughtSignature ? {
676
+ providerMetadata: {
677
+ [providerOptionsName]: {
678
+ thoughtSignature: toolCall.thoughtSignature
679
+ }
680
+ }
681
+ } : {}
682
+ }), toolCall.hasFinished = !0));
683
+ }
684
+ }
685
+ },
686
+ flush(controller) {
687
+ var _a2, _b, _c, _d, _e;
688
+ isActiveReasoning && controller.enqueue({ type: "reasoning-end", id: "reasoning-0" }), isActiveText && controller.enqueue({ type: "text-end", id: "txt-0" });
689
+ for (let toolCall of toolCalls.filter(
690
+ (toolCall2) => !toolCall2.hasFinished
691
+ ))
692
+ controller.enqueue({
693
+ type: "tool-input-end",
694
+ id: toolCall.id
695
+ }), controller.enqueue({
696
+ type: "tool-call",
697
+ toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
698
+ toolName: toolCall.function.name,
699
+ input: toolCall.function.arguments,
700
+ ...toolCall.thoughtSignature ? {
701
+ providerMetadata: {
702
+ [providerOptionsName]: {
703
+ thoughtSignature: toolCall.thoughtSignature
704
+ }
705
+ }
706
+ } : {}
707
+ });
708
+ let providerMetadata = {
709
+ [providerOptionsName]: {},
710
+ ...metadataExtractor?.buildMetadata()
711
+ };
712
+ ((_b = usage?.completion_tokens_details) == null ? void 0 : _b.accepted_prediction_tokens) != null && (providerMetadata[providerOptionsName].acceptedPredictionTokens = (_c = usage?.completion_tokens_details) == null ? void 0 : _c.accepted_prediction_tokens), ((_d = usage?.completion_tokens_details) == null ? void 0 : _d.rejected_prediction_tokens) != null && (providerMetadata[providerOptionsName].rejectedPredictionTokens = (_e = usage?.completion_tokens_details) == null ? void 0 : _e.rejected_prediction_tokens), controller.enqueue({
713
+ type: "finish",
714
+ finishReason,
715
+ usage: convertOpenAICompatibleChatUsage(usage),
716
+ providerMetadata
717
+ });
718
+ }
719
+ })
720
+ ),
721
+ request: { body },
722
+ response: { headers: responseHeaders }
723
+ };
724
+ }
725
+ }, openaiCompatibleTokenUsageSchema = external_exports.looseObject({
726
+ prompt_tokens: external_exports.number().nullish(),
727
+ completion_tokens: external_exports.number().nullish(),
728
+ total_tokens: external_exports.number().nullish(),
729
+ prompt_tokens_details: external_exports.object({
730
+ cached_tokens: external_exports.number().nullish()
731
+ }).nullish(),
732
+ completion_tokens_details: external_exports.object({
733
+ reasoning_tokens: external_exports.number().nullish(),
734
+ accepted_prediction_tokens: external_exports.number().nullish(),
735
+ rejected_prediction_tokens: external_exports.number().nullish()
736
+ }).nullish()
737
+ }).nullish(), OpenAICompatibleChatResponseSchema = external_exports.looseObject({
738
+ id: external_exports.string().nullish(),
739
+ created: external_exports.number().nullish(),
740
+ model: external_exports.string().nullish(),
741
+ choices: external_exports.array(
742
+ external_exports.object({
743
+ message: external_exports.object({
744
+ role: external_exports.literal("assistant").nullish(),
745
+ content: external_exports.string().nullish(),
746
+ reasoning_content: external_exports.string().nullish(),
747
+ reasoning: external_exports.string().nullish(),
748
+ tool_calls: external_exports.array(
749
+ external_exports.object({
750
+ id: external_exports.string().nullish(),
751
+ function: external_exports.object({
752
+ name: external_exports.string(),
753
+ arguments: external_exports.string()
754
+ }),
755
+ // Support for Google Gemini thought signatures via OpenAI compatibility
756
+ extra_content: external_exports.object({
757
+ google: external_exports.object({
758
+ thought_signature: external_exports.string().nullish()
759
+ }).nullish()
760
+ }).nullish()
761
+ })
762
+ ).nullish()
763
+ }),
764
+ finish_reason: external_exports.string().nullish()
765
+ })
766
+ ),
767
+ usage: openaiCompatibleTokenUsageSchema
768
+ }), chunkBaseSchema = external_exports.looseObject({
769
+ id: external_exports.string().nullish(),
770
+ created: external_exports.number().nullish(),
771
+ model: external_exports.string().nullish(),
772
+ choices: external_exports.array(
773
+ external_exports.object({
774
+ delta: external_exports.object({
775
+ role: external_exports.enum(["assistant"]).nullish(),
776
+ content: external_exports.string().nullish(),
777
+ // Most openai-compatible models set `reasoning_content`, but some
778
+ // providers serving `gpt-oss` set `reasoning`. See #7866
779
+ reasoning_content: external_exports.string().nullish(),
780
+ reasoning: external_exports.string().nullish(),
781
+ tool_calls: external_exports.array(
782
+ external_exports.object({
783
+ index: external_exports.number().nullish(),
784
+ //google does not send index
785
+ id: external_exports.string().nullish(),
786
+ function: external_exports.object({
787
+ name: external_exports.string().nullish(),
788
+ arguments: external_exports.string().nullish()
789
+ }),
790
+ // Support for Google Gemini thought signatures via OpenAI compatibility
791
+ extra_content: external_exports.object({
792
+ google: external_exports.object({
793
+ thought_signature: external_exports.string().nullish()
794
+ }).nullish()
795
+ }).nullish()
796
+ })
797
+ ).nullish()
798
+ }).nullish(),
799
+ finish_reason: external_exports.string().nullish()
800
+ })
801
+ ),
802
+ usage: openaiCompatibleTokenUsageSchema
803
+ }), createOpenAICompatibleChatChunkSchema = (errorSchema) => external_exports.union([chunkBaseSchema, errorSchema]);
804
+ function convertOpenAICompatibleCompletionUsage(usage) {
805
+ var _a, _b;
806
+ if (usage == null)
807
+ return {
808
+ inputTokens: {
809
+ total: void 0,
810
+ noCache: void 0,
811
+ cacheRead: void 0,
812
+ cacheWrite: void 0
813
+ },
814
+ outputTokens: {
815
+ total: void 0,
816
+ text: void 0,
817
+ reasoning: void 0
818
+ },
819
+ raw: void 0
820
+ };
821
+ let promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0, completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
822
+ return {
823
+ inputTokens: {
824
+ total: promptTokens,
825
+ noCache: promptTokens,
826
+ cacheRead: void 0,
827
+ cacheWrite: void 0
828
+ },
829
+ outputTokens: {
830
+ total: completionTokens,
831
+ text: completionTokens,
832
+ reasoning: void 0
833
+ },
834
+ raw: usage
835
+ };
836
+ }
837
+ function convertToOpenAICompatibleCompletionPrompt({
838
+ prompt,
839
+ user = "user",
840
+ assistant = "assistant"
841
+ }) {
842
+ let text = "";
843
+ prompt[0].role === "system" && (text += `${prompt[0].content}
844
+
845
+ `, prompt = prompt.slice(1));
846
+ for (let { role, content } of prompt)
847
+ switch (role) {
848
+ case "system":
849
+ throw new InvalidPromptError({
850
+ message: "Unexpected system message in prompt: ${content}",
851
+ prompt
852
+ });
853
+ case "user": {
854
+ let userMessage = content.map((part) => {
855
+ if (part.type === "text")
856
+ return part.text;
857
+ }).filter(Boolean).join("");
858
+ text += `${user}:
859
+ ${userMessage}
860
+
861
+ `;
862
+ break;
863
+ }
864
+ case "assistant": {
865
+ let assistantMessage = content.map((part) => {
866
+ switch (part.type) {
867
+ case "text":
868
+ return part.text;
869
+ case "tool-call":
870
+ throw new UnsupportedFunctionalityError({
871
+ functionality: "tool-call messages"
872
+ });
873
+ }
874
+ }).join("");
875
+ text += `${assistant}:
876
+ ${assistantMessage}
877
+
878
+ `;
879
+ break;
880
+ }
881
+ case "tool":
882
+ throw new UnsupportedFunctionalityError({
883
+ functionality: "tool messages"
884
+ });
885
+ default: {
886
+ let _exhaustiveCheck = role;
887
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
888
+ }
889
+ }
890
+ return text += `${assistant}:
891
+ `, {
892
+ prompt: text,
893
+ stopSequences: [`
894
+ ${user}:`]
895
+ };
896
+ }
897
+ function getResponseMetadata2({
898
+ id,
899
+ model,
900
+ created
901
+ }) {
902
+ return {
903
+ id: id ?? void 0,
904
+ modelId: model ?? void 0,
905
+ timestamp: created != null ? new Date(created * 1e3) : void 0
906
+ };
907
+ }
908
+ function mapOpenAICompatibleFinishReason2(finishReason) {
909
+ switch (finishReason) {
910
+ case "stop":
911
+ return "stop";
912
+ case "length":
913
+ return "length";
914
+ case "content_filter":
915
+ return "content-filter";
916
+ case "function_call":
917
+ case "tool_calls":
918
+ return "tool-calls";
919
+ default:
920
+ return "other";
921
+ }
922
+ }
923
+ var openaiCompatibleCompletionProviderOptions = external_exports.object({
924
+ /**
925
+ * Echo back the prompt in addition to the completion.
926
+ */
927
+ echo: external_exports.boolean().optional(),
928
+ /**
929
+ * Modify the likelihood of specified tokens appearing in the completion.
930
+ *
931
+ * Accepts a JSON object that maps tokens (specified by their token ID in
932
+ * the GPT tokenizer) to an associated bias value from -100 to 100.
933
+ */
934
+ logitBias: external_exports.record(external_exports.string(), external_exports.number()).optional(),
935
+ /**
936
+ * The suffix that comes after a completion of inserted text.
937
+ */
938
+ suffix: external_exports.string().optional(),
939
+ /**
940
+ * A unique identifier representing your end-user, which can help providers to
941
+ * monitor and detect abuse.
942
+ */
943
+ user: external_exports.string().optional()
944
+ }), OpenAICompatibleCompletionLanguageModel = class {
945
+ // type inferred via constructor
946
+ constructor(modelId, config) {
947
+ this.specificationVersion = "v3";
948
+ var _a;
949
+ this.modelId = modelId, this.config = config;
950
+ let errorStructure = (_a = config.errorStructure) != null ? _a : defaultOpenAICompatibleErrorStructure;
951
+ this.chunkSchema = createOpenAICompatibleCompletionChunkSchema(
952
+ errorStructure.errorSchema
953
+ ), this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure);
954
+ }
955
+ get provider() {
956
+ return this.config.provider;
957
+ }
958
+ get providerOptionsName() {
959
+ return this.config.provider.split(".")[0].trim();
960
+ }
961
+ get supportedUrls() {
962
+ var _a, _b, _c;
963
+ return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
964
+ }
965
+ async getArgs({
966
+ prompt,
967
+ maxOutputTokens,
968
+ temperature,
969
+ topP,
970
+ topK,
971
+ frequencyPenalty,
972
+ presencePenalty,
973
+ stopSequences: userStopSequences,
974
+ responseFormat,
975
+ seed,
976
+ providerOptions,
977
+ tools,
978
+ toolChoice
979
+ }) {
980
+ var _a;
981
+ let warnings = [], completionOptions = (_a = await parseProviderOptions({
982
+ provider: this.providerOptionsName,
983
+ providerOptions,
984
+ schema: openaiCompatibleCompletionProviderOptions
985
+ })) != null ? _a : {};
986
+ topK != null && warnings.push({ type: "unsupported", feature: "topK" }), tools?.length && warnings.push({ type: "unsupported", feature: "tools" }), toolChoice != null && warnings.push({ type: "unsupported", feature: "toolChoice" }), responseFormat != null && responseFormat.type !== "text" && warnings.push({
987
+ type: "unsupported",
988
+ feature: "responseFormat",
989
+ details: "JSON response format is not supported."
990
+ });
991
+ let { prompt: completionPrompt, stopSequences } = convertToOpenAICompatibleCompletionPrompt({ prompt }), stop = [...stopSequences ?? [], ...userStopSequences ?? []];
992
+ return {
993
+ args: {
994
+ // model id:
995
+ model: this.modelId,
996
+ // model specific settings:
997
+ echo: completionOptions.echo,
998
+ logit_bias: completionOptions.logitBias,
999
+ suffix: completionOptions.suffix,
1000
+ user: completionOptions.user,
1001
+ // standardized settings:
1002
+ max_tokens: maxOutputTokens,
1003
+ temperature,
1004
+ top_p: topP,
1005
+ frequency_penalty: frequencyPenalty,
1006
+ presence_penalty: presencePenalty,
1007
+ seed,
1008
+ ...providerOptions?.[this.providerOptionsName],
1009
+ // prompt:
1010
+ prompt: completionPrompt,
1011
+ // stop sequences:
1012
+ stop: stop.length > 0 ? stop : void 0
1013
+ },
1014
+ warnings
1015
+ };
1016
+ }
1017
+ async doGenerate(options) {
1018
+ let { args, warnings } = await this.getArgs(options), {
1019
+ responseHeaders,
1020
+ value: response,
1021
+ rawValue: rawResponse
1022
+ } = await postJsonToApi({
1023
+ url: this.config.url({
1024
+ path: "/completions",
1025
+ modelId: this.modelId
1026
+ }),
1027
+ headers: combineHeaders(this.config.headers(), options.headers),
1028
+ body: args,
1029
+ failedResponseHandler: this.failedResponseHandler,
1030
+ successfulResponseHandler: createJsonResponseHandler(
1031
+ openaiCompatibleCompletionResponseSchema
1032
+ ),
1033
+ abortSignal: options.abortSignal,
1034
+ fetch: this.config.fetch
1035
+ }), choice = response.choices[0], content = [];
1036
+ return choice.text != null && choice.text.length > 0 && content.push({ type: "text", text: choice.text }), {
1037
+ content,
1038
+ usage: convertOpenAICompatibleCompletionUsage(response.usage),
1039
+ finishReason: {
1040
+ unified: mapOpenAICompatibleFinishReason2(choice.finish_reason),
1041
+ raw: choice.finish_reason
1042
+ },
1043
+ request: { body: args },
1044
+ response: {
1045
+ ...getResponseMetadata2(response),
1046
+ headers: responseHeaders,
1047
+ body: rawResponse
1048
+ },
1049
+ warnings
1050
+ };
1051
+ }
1052
+ async doStream(options) {
1053
+ let { args, warnings } = await this.getArgs(options), body = {
1054
+ ...args,
1055
+ stream: !0,
1056
+ // only include stream_options when in strict compatibility mode:
1057
+ stream_options: this.config.includeUsage ? { include_usage: !0 } : void 0
1058
+ }, { responseHeaders, value: response } = await postJsonToApi({
1059
+ url: this.config.url({
1060
+ path: "/completions",
1061
+ modelId: this.modelId
1062
+ }),
1063
+ headers: combineHeaders(this.config.headers(), options.headers),
1064
+ body,
1065
+ failedResponseHandler: this.failedResponseHandler,
1066
+ successfulResponseHandler: createEventSourceResponseHandler(
1067
+ this.chunkSchema
1068
+ ),
1069
+ abortSignal: options.abortSignal,
1070
+ fetch: this.config.fetch
1071
+ }), finishReason = {
1072
+ unified: "other",
1073
+ raw: void 0
1074
+ }, usage, isFirstChunk = !0;
1075
+ return {
1076
+ stream: response.pipeThrough(
1077
+ new TransformStream({
1078
+ start(controller) {
1079
+ controller.enqueue({ type: "stream-start", warnings });
1080
+ },
1081
+ transform(chunk, controller) {
1082
+ var _a;
1083
+ if (options.includeRawChunks && controller.enqueue({ type: "raw", rawValue: chunk.rawValue }), !chunk.success) {
1084
+ finishReason = { unified: "error", raw: void 0 }, controller.enqueue({ type: "error", error: chunk.error });
1085
+ return;
1086
+ }
1087
+ let value = chunk.value;
1088
+ if ("error" in value) {
1089
+ finishReason = { unified: "error", raw: void 0 }, controller.enqueue({ type: "error", error: value.error });
1090
+ return;
1091
+ }
1092
+ isFirstChunk && (isFirstChunk = !1, controller.enqueue({
1093
+ type: "response-metadata",
1094
+ ...getResponseMetadata2(value)
1095
+ }), controller.enqueue({
1096
+ type: "text-start",
1097
+ id: "0"
1098
+ })), value.usage != null && (usage = value.usage);
1099
+ let choice = value.choices[0];
1100
+ choice?.finish_reason != null && (finishReason = {
1101
+ unified: mapOpenAICompatibleFinishReason2(choice.finish_reason),
1102
+ raw: (_a = choice.finish_reason) != null ? _a : void 0
1103
+ }), choice?.text != null && controller.enqueue({
1104
+ type: "text-delta",
1105
+ id: "0",
1106
+ delta: choice.text
1107
+ });
1108
+ },
1109
+ flush(controller) {
1110
+ isFirstChunk || controller.enqueue({ type: "text-end", id: "0" }), controller.enqueue({
1111
+ type: "finish",
1112
+ finishReason,
1113
+ usage: convertOpenAICompatibleCompletionUsage(usage)
1114
+ });
1115
+ }
1116
+ })
1117
+ ),
1118
+ request: { body },
1119
+ response: { headers: responseHeaders }
1120
+ };
1121
+ }
1122
+ }, usageSchema = external_exports.object({
1123
+ prompt_tokens: external_exports.number(),
1124
+ completion_tokens: external_exports.number(),
1125
+ total_tokens: external_exports.number()
1126
+ }), openaiCompatibleCompletionResponseSchema = external_exports.object({
1127
+ id: external_exports.string().nullish(),
1128
+ created: external_exports.number().nullish(),
1129
+ model: external_exports.string().nullish(),
1130
+ choices: external_exports.array(
1131
+ external_exports.object({
1132
+ text: external_exports.string(),
1133
+ finish_reason: external_exports.string()
1134
+ })
1135
+ ),
1136
+ usage: usageSchema.nullish()
1137
+ }), createOpenAICompatibleCompletionChunkSchema = (errorSchema) => external_exports.union([
1138
+ external_exports.object({
1139
+ id: external_exports.string().nullish(),
1140
+ created: external_exports.number().nullish(),
1141
+ model: external_exports.string().nullish(),
1142
+ choices: external_exports.array(
1143
+ external_exports.object({
1144
+ text: external_exports.string(),
1145
+ finish_reason: external_exports.string().nullish(),
1146
+ index: external_exports.number()
1147
+ })
1148
+ ),
1149
+ usage: usageSchema.nullish()
1150
+ }),
1151
+ errorSchema
1152
+ ]), openaiCompatibleEmbeddingProviderOptions = external_exports.object({
1153
+ /**
1154
+ * The number of dimensions the resulting output embeddings should have.
1155
+ * Only supported in text-embedding-3 and later models.
1156
+ */
1157
+ dimensions: external_exports.number().optional(),
1158
+ /**
1159
+ * A unique identifier representing your end-user, which can help providers to
1160
+ * monitor and detect abuse.
1161
+ */
1162
+ user: external_exports.string().optional()
1163
+ }), OpenAICompatibleEmbeddingModel = class {
1164
+ constructor(modelId, config) {
1165
+ this.specificationVersion = "v3", this.modelId = modelId, this.config = config;
1166
+ }
1167
+ get provider() {
1168
+ return this.config.provider;
1169
+ }
1170
+ get maxEmbeddingsPerCall() {
1171
+ var _a;
1172
+ return (_a = this.config.maxEmbeddingsPerCall) != null ? _a : 2048;
1173
+ }
1174
+ get supportsParallelCalls() {
1175
+ var _a;
1176
+ return (_a = this.config.supportsParallelCalls) != null ? _a : !0;
1177
+ }
1178
+ get providerOptionsName() {
1179
+ return this.config.provider.split(".")[0].trim();
1180
+ }
1181
+ async doEmbed({
1182
+ values,
1183
+ headers,
1184
+ abortSignal,
1185
+ providerOptions
1186
+ }) {
1187
+ var _a, _b, _c;
1188
+ let warnings = [], deprecatedOptions = await parseProviderOptions({
1189
+ provider: "openai-compatible",
1190
+ providerOptions,
1191
+ schema: openaiCompatibleEmbeddingProviderOptions
1192
+ });
1193
+ deprecatedOptions != null && warnings.push({
1194
+ type: "other",
1195
+ message: "The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead."
1196
+ });
1197
+ let compatibleOptions = Object.assign(
1198
+ deprecatedOptions ?? {},
1199
+ (_a = await parseProviderOptions({
1200
+ provider: "openaiCompatible",
1201
+ providerOptions,
1202
+ schema: openaiCompatibleEmbeddingProviderOptions
1203
+ })) != null ? _a : {},
1204
+ (_b = await parseProviderOptions({
1205
+ provider: this.providerOptionsName,
1206
+ providerOptions,
1207
+ schema: openaiCompatibleEmbeddingProviderOptions
1208
+ })) != null ? _b : {}
1209
+ );
1210
+ if (values.length > this.maxEmbeddingsPerCall)
1211
+ throw new TooManyEmbeddingValuesForCallError({
1212
+ provider: this.provider,
1213
+ modelId: this.modelId,
1214
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
1215
+ values
1216
+ });
1217
+ let {
1218
+ responseHeaders,
1219
+ value: response,
1220
+ rawValue
1221
+ } = await postJsonToApi({
1222
+ url: this.config.url({
1223
+ path: "/embeddings",
1224
+ modelId: this.modelId
1225
+ }),
1226
+ headers: combineHeaders(this.config.headers(), headers),
1227
+ body: {
1228
+ model: this.modelId,
1229
+ input: values,
1230
+ encoding_format: "float",
1231
+ dimensions: compatibleOptions.dimensions,
1232
+ user: compatibleOptions.user
1233
+ },
1234
+ failedResponseHandler: createJsonErrorResponseHandler(
1235
+ (_c = this.config.errorStructure) != null ? _c : defaultOpenAICompatibleErrorStructure
1236
+ ),
1237
+ successfulResponseHandler: createJsonResponseHandler(
1238
+ openaiTextEmbeddingResponseSchema
1239
+ ),
1240
+ abortSignal,
1241
+ fetch: this.config.fetch
1242
+ });
1243
+ return {
1244
+ warnings,
1245
+ embeddings: response.data.map((item) => item.embedding),
1246
+ usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
1247
+ providerMetadata: response.providerMetadata,
1248
+ response: { headers: responseHeaders, body: rawValue }
1249
+ };
1250
+ }
1251
+ }, openaiTextEmbeddingResponseSchema = external_exports.object({
1252
+ data: external_exports.array(external_exports.object({ embedding: external_exports.array(external_exports.number()) })),
1253
+ usage: external_exports.object({ prompt_tokens: external_exports.number() }).nullish(),
1254
+ providerMetadata: external_exports.record(external_exports.string(), external_exports.record(external_exports.string(), external_exports.any())).optional()
1255
+ }), OpenAICompatibleImageModel = class {
1256
+ constructor(modelId, config) {
1257
+ this.modelId = modelId, this.config = config, this.specificationVersion = "v3", this.maxImagesPerCall = 10;
1258
+ }
1259
+ get provider() {
1260
+ return this.config.provider;
1261
+ }
1262
+ /**
1263
+ * The provider options key used to extract provider-specific options.
1264
+ */
1265
+ get providerOptionsKey() {
1266
+ return this.config.provider.split(".")[0].trim();
1267
+ }
1268
+ // TODO: deprecate non-camelCase keys and remove in future major version
1269
+ getArgs(providerOptions) {
1270
+ return {
1271
+ ...providerOptions[this.providerOptionsKey],
1272
+ ...providerOptions[toCamelCase(this.providerOptionsKey)]
1273
+ };
1274
+ }
1275
+ async doGenerate({
1276
+ prompt,
1277
+ n,
1278
+ size,
1279
+ aspectRatio,
1280
+ seed,
1281
+ providerOptions,
1282
+ headers,
1283
+ abortSignal,
1284
+ files,
1285
+ mask
1286
+ }) {
1287
+ var _a, _b, _c, _d, _e;
1288
+ let warnings = [];
1289
+ aspectRatio != null && warnings.push({
1290
+ type: "unsupported",
1291
+ feature: "aspectRatio",
1292
+ details: "This model does not support aspect ratio. Use `size` instead."
1293
+ }), seed != null && warnings.push({ type: "unsupported", feature: "seed" });
1294
+ let currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date(), args = this.getArgs(providerOptions);
1295
+ if (files != null && files.length > 0) {
1296
+ let { value: response2, responseHeaders: responseHeaders2 } = await postFormDataToApi({
1297
+ url: this.config.url({
1298
+ path: "/images/edits",
1299
+ modelId: this.modelId
1300
+ }),
1301
+ headers: combineHeaders(this.config.headers(), headers),
1302
+ formData: convertToFormData({
1303
+ model: this.modelId,
1304
+ prompt,
1305
+ image: await Promise.all(files.map((file) => fileToBlob(file))),
1306
+ mask: mask != null ? await fileToBlob(mask) : void 0,
1307
+ n,
1308
+ size,
1309
+ ...args
1310
+ }),
1311
+ failedResponseHandler: createJsonErrorResponseHandler(
1312
+ (_d = this.config.errorStructure) != null ? _d : defaultOpenAICompatibleErrorStructure
1313
+ ),
1314
+ successfulResponseHandler: createJsonResponseHandler(
1315
+ openaiCompatibleImageResponseSchema
1316
+ ),
1317
+ abortSignal,
1318
+ fetch: this.config.fetch
1319
+ });
1320
+ return {
1321
+ images: response2.data.map((item) => item.b64_json),
1322
+ warnings,
1323
+ response: {
1324
+ timestamp: currentDate,
1325
+ modelId: this.modelId,
1326
+ headers: responseHeaders2
1327
+ }
1328
+ };
1329
+ }
1330
+ let { value: response, responseHeaders } = await postJsonToApi({
1331
+ url: this.config.url({
1332
+ path: "/images/generations",
1333
+ modelId: this.modelId
1334
+ }),
1335
+ headers: combineHeaders(this.config.headers(), headers),
1336
+ body: {
1337
+ model: this.modelId,
1338
+ prompt,
1339
+ n,
1340
+ size,
1341
+ ...args,
1342
+ response_format: "b64_json"
1343
+ },
1344
+ failedResponseHandler: createJsonErrorResponseHandler(
1345
+ (_e = this.config.errorStructure) != null ? _e : defaultOpenAICompatibleErrorStructure
1346
+ ),
1347
+ successfulResponseHandler: createJsonResponseHandler(
1348
+ openaiCompatibleImageResponseSchema
1349
+ ),
1350
+ abortSignal,
1351
+ fetch: this.config.fetch
1352
+ });
1353
+ return {
1354
+ images: response.data.map((item) => item.b64_json),
1355
+ warnings,
1356
+ response: {
1357
+ timestamp: currentDate,
1358
+ modelId: this.modelId,
1359
+ headers: responseHeaders
1360
+ }
1361
+ };
1362
+ }
1363
+ }, openaiCompatibleImageResponseSchema = external_exports.object({
1364
+ data: external_exports.array(external_exports.object({ b64_json: external_exports.string() }))
1365
+ });
1366
+ async function fileToBlob(file) {
1367
+ if (file.type === "url")
1368
+ return downloadBlob(file.url);
1369
+ let data = file.data instanceof Uint8Array ? file.data : convertBase64ToUint8Array(file.data);
1370
+ return new Blob([data], { type: file.mediaType });
1371
+ }
1372
+ function toCamelCase(str) {
1373
+ return str.replace(/[_-]([a-z])/g, (g) => g[1].toUpperCase());
1374
+ }
1375
+ var VERSION = "2.0.27";
1376
+ function createOpenAICompatible(options) {
1377
+ let baseURL = withoutTrailingSlash(options.baseURL), providerName = options.name, headers = {
1378
+ ...options.apiKey && { Authorization: `Bearer ${options.apiKey}` },
1379
+ ...options.headers
1380
+ }, getHeaders = () => withUserAgentSuffix(headers, `ai-sdk/openai-compatible/${VERSION}`), getCommonModelConfig = (modelType) => ({
1381
+ provider: `${providerName}.${modelType}`,
1382
+ url: ({ path }) => {
1383
+ let url = new URL(`${baseURL}${path}`);
1384
+ return options.queryParams && (url.search = new URLSearchParams(options.queryParams).toString()), url.toString();
1385
+ },
1386
+ headers: getHeaders,
1387
+ fetch: options.fetch
1388
+ }), createLanguageModel = (modelId) => createChatModel(modelId), createChatModel = (modelId) => new OpenAICompatibleChatLanguageModel(modelId, {
1389
+ ...getCommonModelConfig("chat"),
1390
+ includeUsage: options.includeUsage,
1391
+ supportsStructuredOutputs: options.supportsStructuredOutputs,
1392
+ transformRequestBody: options.transformRequestBody,
1393
+ metadataExtractor: options.metadataExtractor
1394
+ }), createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel(modelId, {
1395
+ ...getCommonModelConfig("completion"),
1396
+ includeUsage: options.includeUsage
1397
+ }), createEmbeddingModel = (modelId) => new OpenAICompatibleEmbeddingModel(modelId, {
1398
+ ...getCommonModelConfig("embedding")
1399
+ }), createImageModel = (modelId) => new OpenAICompatibleImageModel(modelId, getCommonModelConfig("image")), provider = (modelId) => createLanguageModel(modelId);
1400
+ return provider.specificationVersion = "v3", provider.languageModel = createLanguageModel, provider.chatModel = createChatModel, provider.completionModel = createCompletionModel, provider.embeddingModel = createEmbeddingModel, provider.textEmbeddingModel = createEmbeddingModel, provider.imageModel = createImageModel, provider;
1401
+ }
1402
+
1403
+ // src/main/providers/grok-subscription/index.ts
1404
+ var BASE_URL = "https://api.x.ai/v1";
1405
+ function createGrokSubscriptionProvider(authManager, extraParams) {
1406
+ return { provider: createOpenAICompatible({
1407
+ name: "xai",
1408
+ baseURL: BASE_URL,
1409
+ apiKey: "grok-subscription",
1410
+ // placeholder, overridden by customFetch
1411
+ // stream_options.include_usage — without it xAI streams carry no usage
1412
+ // chunk and every turn falls back to a char-based token estimate.
1413
+ includeUsage: !0,
1414
+ fetch: async (input, init) => {
1415
+ let token;
1416
+ try {
1417
+ token = await authManager.getValidAccessToken();
1418
+ } catch (err) {
1419
+ throw console.error("[Grok Fetch] Failed to get access token:", err), err;
1420
+ }
1421
+ let headers = new Headers(init?.headers);
1422
+ headers.set("Authorization", `Bearer ${token}`);
1423
+ let patchedInit = init;
1424
+ if (extraParams && init?.body && typeof init.body == "string")
1425
+ try {
1426
+ let body = JSON.parse(init.body);
1427
+ for (let [k, v] of Object.entries(extraParams))
1428
+ v === null ? delete body[k] : body[k] = v;
1429
+ patchedInit = { ...init, body: JSON.stringify(body) };
1430
+ } catch {
1431
+ }
1432
+ let response = await globalThis.fetch(input, { ...patchedInit, headers });
1433
+ if (!response.ok)
1434
+ try {
1435
+ let errBody = await response.clone().text();
1436
+ console.error(`[Grok Subscription] ${response.status}: ${errBody.slice(0, 500)}`);
1437
+ } catch {
1438
+ }
1439
+ return response;
1440
+ }
1441
+ }) };
1442
+ }
1443
+ var GROK_SUBSCRIPTION_MODELS = [
1444
+ "grok-4.5",
1445
+ "grok-4.3",
1446
+ "grok-build-0.1",
1447
+ "grok-4.20-0309-reasoning",
1448
+ "grok-4.20-0309-non-reasoning"
1449
+ ];
1450
+ async function listGrokSubscriptionModels(authManager) {
1451
+ try {
1452
+ let token = await authManager.getValidAccessToken(), response = await fetch(`${BASE_URL}/models`, {
1453
+ headers: { Authorization: `Bearer ${token}` },
1454
+ signal: AbortSignal.timeout(5e3)
1455
+ });
1456
+ if (!response.ok) return [...GROK_SUBSCRIPTION_MODELS];
1457
+ let models = ((await response.json()).data ?? []).map((m) => m.id).filter((id) => !!id);
1458
+ return models.length > 0 ? models : [...GROK_SUBSCRIPTION_MODELS];
1459
+ } catch {
1460
+ return [...GROK_SUBSCRIPTION_MODELS];
1461
+ }
1462
+ }
1463
+
1464
+ export {
1465
+ createOpenAICompatible,
1466
+ createGrokSubscriptionProvider,
1467
+ GROK_SUBSCRIPTION_MODELS,
1468
+ listGrokSubscriptionModels
1469
+ };