@openrouter/ai-sdk-provider 0.7.2 → 1.0.0-beta.1

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.
@@ -1,10 +1,12 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __defProps = Object.defineProperties;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
6
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
7
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
8
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
8
10
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
11
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
12
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -20,21 +22,9 @@ var __spreadValues = (a, b) => {
20
22
  return a;
21
23
  };
22
24
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
- var __objRest = (source, exclude) => {
24
- var target = {};
25
- for (var prop in source)
26
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
27
- target[prop] = source[prop];
28
- if (source != null && __getOwnPropSymbols)
29
- for (var prop of __getOwnPropSymbols(source)) {
30
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
31
- target[prop] = source[prop];
32
- }
33
- return target;
34
- };
35
25
  var __export = (target, all) => {
36
- for (var name in all)
37
- __defProp(target, name, { get: all[name], enumerable: true });
26
+ for (var name14 in all)
27
+ __defProp(target, name14, { get: all[name14], enumerable: true });
38
28
  };
39
29
  var __copyProps = (to, from, except, desc) => {
40
30
  if (from && typeof from === "object" || typeof from === "function") {
@@ -44,6 +34,14 @@ var __copyProps = (to, from, except, desc) => {
44
34
  }
45
35
  return to;
46
36
  };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
+ mod
44
+ ));
47
45
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
48
46
 
49
47
  // src/internal/index.ts
@@ -54,72 +52,926 @@ __export(index_exports, {
54
52
  });
55
53
  module.exports = __toCommonJS(index_exports);
56
54
 
57
- // src/schemas/reasoning-details.ts
55
+ // node_modules/.pnpm/@ai-sdk+provider@2.0.0-beta.1/node_modules/@ai-sdk/provider/dist/index.mjs
56
+ var marker = "vercel.ai.error";
57
+ var symbol = Symbol.for(marker);
58
+ var _a;
59
+ var _AISDKError = class _AISDKError2 extends Error {
60
+ /**
61
+ * Creates an AI SDK Error.
62
+ *
63
+ * @param {Object} params - The parameters for creating the error.
64
+ * @param {string} params.name - The name of the error.
65
+ * @param {string} params.message - The error message.
66
+ * @param {unknown} [params.cause] - The underlying cause of the error.
67
+ */
68
+ constructor({
69
+ name: name14,
70
+ message,
71
+ cause
72
+ }) {
73
+ super(message);
74
+ this[_a] = true;
75
+ this.name = name14;
76
+ this.cause = cause;
77
+ }
78
+ /**
79
+ * Checks if the given error is an AI SDK Error.
80
+ * @param {unknown} error - The error to check.
81
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
82
+ */
83
+ static isInstance(error) {
84
+ return _AISDKError2.hasMarker(error, marker);
85
+ }
86
+ static hasMarker(error, marker15) {
87
+ const markerSymbol = Symbol.for(marker15);
88
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
89
+ }
90
+ };
91
+ _a = symbol;
92
+ var AISDKError = _AISDKError;
93
+ var name = "AI_APICallError";
94
+ var marker2 = `vercel.ai.error.${name}`;
95
+ var symbol2 = Symbol.for(marker2);
96
+ var _a2;
97
+ var APICallError = class extends AISDKError {
98
+ constructor({
99
+ message,
100
+ url,
101
+ requestBodyValues,
102
+ statusCode,
103
+ responseHeaders,
104
+ responseBody,
105
+ cause,
106
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
107
+ statusCode === 409 || // conflict
108
+ statusCode === 429 || // too many requests
109
+ statusCode >= 500),
110
+ // server error
111
+ data
112
+ }) {
113
+ super({ name, message, cause });
114
+ this[_a2] = true;
115
+ this.url = url;
116
+ this.requestBodyValues = requestBodyValues;
117
+ this.statusCode = statusCode;
118
+ this.responseHeaders = responseHeaders;
119
+ this.responseBody = responseBody;
120
+ this.isRetryable = isRetryable;
121
+ this.data = data;
122
+ }
123
+ static isInstance(error) {
124
+ return AISDKError.hasMarker(error, marker2);
125
+ }
126
+ };
127
+ _a2 = symbol2;
128
+ var name2 = "AI_EmptyResponseBodyError";
129
+ var marker3 = `vercel.ai.error.${name2}`;
130
+ var symbol3 = Symbol.for(marker3);
131
+ var _a3;
132
+ var EmptyResponseBodyError = class extends AISDKError {
133
+ // used in isInstance
134
+ constructor({ message = "Empty response body" } = {}) {
135
+ super({ name: name2, message });
136
+ this[_a3] = true;
137
+ }
138
+ static isInstance(error) {
139
+ return AISDKError.hasMarker(error, marker3);
140
+ }
141
+ };
142
+ _a3 = symbol3;
143
+ function getErrorMessage(error) {
144
+ if (error == null) {
145
+ return "unknown error";
146
+ }
147
+ if (typeof error === "string") {
148
+ return error;
149
+ }
150
+ if (error instanceof Error) {
151
+ return error.message;
152
+ }
153
+ return JSON.stringify(error);
154
+ }
155
+ var name3 = "AI_InvalidArgumentError";
156
+ var marker4 = `vercel.ai.error.${name3}`;
157
+ var symbol4 = Symbol.for(marker4);
158
+ var _a4;
159
+ var InvalidArgumentError = class extends AISDKError {
160
+ constructor({
161
+ message,
162
+ cause,
163
+ argument
164
+ }) {
165
+ super({ name: name3, message, cause });
166
+ this[_a4] = true;
167
+ this.argument = argument;
168
+ }
169
+ static isInstance(error) {
170
+ return AISDKError.hasMarker(error, marker4);
171
+ }
172
+ };
173
+ _a4 = symbol4;
174
+ var name4 = "AI_InvalidPromptError";
175
+ var marker5 = `vercel.ai.error.${name4}`;
176
+ var symbol5 = Symbol.for(marker5);
177
+ var _a5;
178
+ var InvalidPromptError = class extends AISDKError {
179
+ constructor({
180
+ prompt,
181
+ message,
182
+ cause
183
+ }) {
184
+ super({ name: name4, message: `Invalid prompt: ${message}`, cause });
185
+ this[_a5] = true;
186
+ this.prompt = prompt;
187
+ }
188
+ static isInstance(error) {
189
+ return AISDKError.hasMarker(error, marker5);
190
+ }
191
+ };
192
+ _a5 = symbol5;
193
+ var name5 = "AI_InvalidResponseDataError";
194
+ var marker6 = `vercel.ai.error.${name5}`;
195
+ var symbol6 = Symbol.for(marker6);
196
+ var _a6;
197
+ var InvalidResponseDataError = class extends AISDKError {
198
+ constructor({
199
+ data,
200
+ message = `Invalid response data: ${JSON.stringify(data)}.`
201
+ }) {
202
+ super({ name: name5, message });
203
+ this[_a6] = true;
204
+ this.data = data;
205
+ }
206
+ static isInstance(error) {
207
+ return AISDKError.hasMarker(error, marker6);
208
+ }
209
+ };
210
+ _a6 = symbol6;
211
+ var name6 = "AI_JSONParseError";
212
+ var marker7 = `vercel.ai.error.${name6}`;
213
+ var symbol7 = Symbol.for(marker7);
214
+ var _a7;
215
+ var JSONParseError = class extends AISDKError {
216
+ constructor({ text, cause }) {
217
+ super({
218
+ name: name6,
219
+ message: `JSON parsing failed: Text: ${text}.
220
+ Error message: ${getErrorMessage(cause)}`,
221
+ cause
222
+ });
223
+ this[_a7] = true;
224
+ this.text = text;
225
+ }
226
+ static isInstance(error) {
227
+ return AISDKError.hasMarker(error, marker7);
228
+ }
229
+ };
230
+ _a7 = symbol7;
231
+ var name7 = "AI_LoadAPIKeyError";
232
+ var marker8 = `vercel.ai.error.${name7}`;
233
+ var symbol8 = Symbol.for(marker8);
234
+ var _a8;
235
+ _a8 = symbol8;
236
+ var name8 = "AI_LoadSettingError";
237
+ var marker9 = `vercel.ai.error.${name8}`;
238
+ var symbol9 = Symbol.for(marker9);
239
+ var _a9;
240
+ _a9 = symbol9;
241
+ var name9 = "AI_NoContentGeneratedError";
242
+ var marker10 = `vercel.ai.error.${name9}`;
243
+ var symbol10 = Symbol.for(marker10);
244
+ var _a10;
245
+ _a10 = symbol10;
246
+ var name10 = "AI_NoSuchModelError";
247
+ var marker11 = `vercel.ai.error.${name10}`;
248
+ var symbol11 = Symbol.for(marker11);
249
+ var _a11;
250
+ _a11 = symbol11;
251
+ var name11 = "AI_TooManyEmbeddingValuesForCallError";
252
+ var marker12 = `vercel.ai.error.${name11}`;
253
+ var symbol12 = Symbol.for(marker12);
254
+ var _a12;
255
+ _a12 = symbol12;
256
+ var name12 = "AI_TypeValidationError";
257
+ var marker13 = `vercel.ai.error.${name12}`;
258
+ var symbol13 = Symbol.for(marker13);
259
+ var _a13;
260
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
261
+ constructor({ value, cause }) {
262
+ super({
263
+ name: name12,
264
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
265
+ Error message: ${getErrorMessage(cause)}`,
266
+ cause
267
+ });
268
+ this[_a13] = true;
269
+ this.value = value;
270
+ }
271
+ static isInstance(error) {
272
+ return AISDKError.hasMarker(error, marker13);
273
+ }
274
+ /**
275
+ * Wraps an error into a TypeValidationError.
276
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
277
+ * Otherwise, it creates a new TypeValidationError.
278
+ *
279
+ * @param {Object} params - The parameters for wrapping the error.
280
+ * @param {unknown} params.value - The value that failed validation.
281
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
282
+ * @returns {TypeValidationError} A TypeValidationError instance.
283
+ */
284
+ static wrap({
285
+ value,
286
+ cause
287
+ }) {
288
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
289
+ }
290
+ };
291
+ _a13 = symbol13;
292
+ var TypeValidationError = _TypeValidationError;
293
+ var name13 = "AI_UnsupportedFunctionalityError";
294
+ var marker14 = `vercel.ai.error.${name13}`;
295
+ var symbol14 = Symbol.for(marker14);
296
+ var _a14;
297
+ var UnsupportedFunctionalityError = class extends AISDKError {
298
+ constructor({
299
+ functionality,
300
+ message = `'${functionality}' functionality not supported.`
301
+ }) {
302
+ super({ name: name13, message });
303
+ this[_a14] = true;
304
+ this.functionality = functionality;
305
+ }
306
+ static isInstance(error) {
307
+ return AISDKError.hasMarker(error, marker14);
308
+ }
309
+ };
310
+ _a14 = symbol14;
311
+
312
+ // node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/dist/index.js
313
+ var ParseError = class extends Error {
314
+ constructor(message, options) {
315
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
316
+ }
317
+ };
318
+ function noop(_arg) {
319
+ }
320
+ function createParser(callbacks) {
321
+ if (typeof callbacks == "function")
322
+ throw new TypeError(
323
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
324
+ );
325
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
326
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
327
+ function feed(newChunk) {
328
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
329
+ for (const line of complete)
330
+ parseLine(line);
331
+ incompleteLine = incomplete, isFirstChunk = false;
332
+ }
333
+ function parseLine(line) {
334
+ if (line === "") {
335
+ dispatchEvent();
336
+ return;
337
+ }
338
+ if (line.startsWith(":")) {
339
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
340
+ return;
341
+ }
342
+ const fieldSeparatorIndex = line.indexOf(":");
343
+ if (fieldSeparatorIndex !== -1) {
344
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
345
+ processField(field, value, line);
346
+ return;
347
+ }
348
+ processField(line, "", line);
349
+ }
350
+ function processField(field, value, line) {
351
+ switch (field) {
352
+ case "event":
353
+ eventType = value;
354
+ break;
355
+ case "data":
356
+ data = `${data}${value}
357
+ `;
358
+ break;
359
+ case "id":
360
+ id = value.includes("\0") ? void 0 : value;
361
+ break;
362
+ case "retry":
363
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
364
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
365
+ type: "invalid-retry",
366
+ value,
367
+ line
368
+ })
369
+ );
370
+ break;
371
+ default:
372
+ onError(
373
+ new ParseError(
374
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
375
+ { type: "unknown-field", field, value, line }
376
+ )
377
+ );
378
+ break;
379
+ }
380
+ }
381
+ function dispatchEvent() {
382
+ data.length > 0 && onEvent({
383
+ id,
384
+ event: eventType || void 0,
385
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
386
+ // then remove the last character from the data buffer.
387
+ data: data.endsWith(`
388
+ `) ? data.slice(0, -1) : data
389
+ }), id = void 0, data = "", eventType = "";
390
+ }
391
+ function reset(options = {}) {
392
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
393
+ }
394
+ return { feed, reset };
395
+ }
396
+ function splitLines(chunk) {
397
+ const lines = [];
398
+ let incompleteLine = "", searchIndex = 0;
399
+ for (; searchIndex < chunk.length; ) {
400
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
401
+ `, searchIndex);
402
+ let lineEnd = -1;
403
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
404
+ incompleteLine = chunk.slice(searchIndex);
405
+ break;
406
+ } else {
407
+ const line = chunk.slice(searchIndex, lineEnd);
408
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
409
+ ` && searchIndex++;
410
+ }
411
+ }
412
+ return [lines, incompleteLine];
413
+ }
414
+
415
+ // node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/dist/stream.js
416
+ var EventSourceParserStream = class extends TransformStream {
417
+ constructor({ onError, onRetry, onComment } = {}) {
418
+ let parser;
419
+ super({
420
+ start(controller) {
421
+ parser = createParser({
422
+ onEvent: (event) => {
423
+ controller.enqueue(event);
424
+ },
425
+ onError(error) {
426
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
427
+ },
428
+ onRetry,
429
+ onComment
430
+ });
431
+ },
432
+ transform(chunk) {
433
+ parser.feed(chunk);
434
+ }
435
+ });
436
+ }
437
+ };
438
+
439
+ // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.0-beta.2_zod@3.25.74/node_modules/@ai-sdk/provider-utils/dist/index.mjs
440
+ var z4 = __toESM(require("zod/v4"), 1);
441
+
442
+ // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.74/node_modules/zod-to-json-schema/dist/esm/Options.js
443
+ var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
444
+
445
+ // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.74/node_modules/zod-to-json-schema/dist/esm/selectParser.js
446
+ var import_zod4 = require("zod");
447
+
448
+ // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.74/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
58
449
  var import_zod = require("zod");
59
- var ReasoningDetailSummarySchema = import_zod.z.object({
60
- type: import_zod.z.literal("reasoning.summary" /* Summary */),
61
- summary: import_zod.z.string()
450
+
451
+ // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.74/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
452
+ var import_zod2 = require("zod");
453
+
454
+ // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.74/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
455
+ var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
456
+
457
+ // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.74/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
458
+ var import_zod3 = require("zod");
459
+
460
+ // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.0-beta.2_zod@3.25.74/node_modules/@ai-sdk/provider-utils/dist/index.mjs
461
+ function combineHeaders(...headers) {
462
+ return headers.reduce(
463
+ (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
464
+ {}
465
+ );
466
+ }
467
+ function extractResponseHeaders(response) {
468
+ return Object.fromEntries([...response.headers]);
469
+ }
470
+ var createIdGenerator = ({
471
+ prefix,
472
+ size = 16,
473
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
474
+ separator = "-"
475
+ } = {}) => {
476
+ const generator = () => {
477
+ const alphabetLength = alphabet.length;
478
+ const chars = new Array(size);
479
+ for (let i = 0; i < size; i++) {
480
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
481
+ }
482
+ return chars.join("");
483
+ };
484
+ if (prefix == null) {
485
+ return generator;
486
+ }
487
+ if (alphabet.includes(separator)) {
488
+ throw new InvalidArgumentError({
489
+ argument: "separator",
490
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
491
+ });
492
+ }
493
+ return () => `${prefix}${separator}${generator()}`;
494
+ };
495
+ var generateId = createIdGenerator();
496
+ function isAbortError(error) {
497
+ return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
498
+ }
499
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
500
+ function handleFetchError({
501
+ error,
502
+ url,
503
+ requestBodyValues
504
+ }) {
505
+ if (isAbortError(error)) {
506
+ return error;
507
+ }
508
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
509
+ const cause = error.cause;
510
+ if (cause != null) {
511
+ return new APICallError({
512
+ message: `Cannot connect to API: ${cause.message}`,
513
+ cause,
514
+ url,
515
+ requestBodyValues,
516
+ isRetryable: true
517
+ // retry when network error
518
+ });
519
+ }
520
+ }
521
+ return error;
522
+ }
523
+ function removeUndefinedEntries(record) {
524
+ return Object.fromEntries(
525
+ Object.entries(record).filter(([_key, value]) => value != null)
526
+ );
527
+ }
528
+ var suspectProtoRx = /"__proto__"\s*:/;
529
+ var suspectConstructorRx = /"constructor"\s*:/;
530
+ function _parse(text) {
531
+ const obj = JSON.parse(text);
532
+ if (obj === null || typeof obj !== "object") {
533
+ return obj;
534
+ }
535
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
536
+ return obj;
537
+ }
538
+ return filter(obj);
539
+ }
540
+ function filter(obj) {
541
+ let next = [obj];
542
+ while (next.length) {
543
+ const nodes = next;
544
+ next = [];
545
+ for (const node of nodes) {
546
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
547
+ throw new SyntaxError("Object contains forbidden prototype property");
548
+ }
549
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
550
+ throw new SyntaxError("Object contains forbidden prototype property");
551
+ }
552
+ for (const key in node) {
553
+ const value = node[key];
554
+ if (value && typeof value === "object") {
555
+ next.push(value);
556
+ }
557
+ }
558
+ }
559
+ }
560
+ return obj;
561
+ }
562
+ function secureJsonParse(text) {
563
+ const { stackTraceLimit } = Error;
564
+ Error.stackTraceLimit = 0;
565
+ try {
566
+ return _parse(text);
567
+ } finally {
568
+ Error.stackTraceLimit = stackTraceLimit;
569
+ }
570
+ }
571
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
572
+ function validator(validate) {
573
+ return { [validatorSymbol]: true, validate };
574
+ }
575
+ function isValidator(value) {
576
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
577
+ }
578
+ function asValidator(value) {
579
+ return isValidator(value) ? value : standardSchemaValidator(value);
580
+ }
581
+ function standardSchemaValidator(standardSchema) {
582
+ return validator(async (value) => {
583
+ const result = await standardSchema["~standard"].validate(value);
584
+ return result.issues == null ? { success: true, value: result.value } : {
585
+ success: false,
586
+ error: new TypeValidationError({
587
+ value,
588
+ cause: result.issues
589
+ })
590
+ };
591
+ });
592
+ }
593
+ async function validateTypes({
594
+ value,
595
+ schema
596
+ }) {
597
+ const result = await safeValidateTypes({ value, schema });
598
+ if (!result.success) {
599
+ throw TypeValidationError.wrap({ value, cause: result.error });
600
+ }
601
+ return result.value;
602
+ }
603
+ async function safeValidateTypes({
604
+ value,
605
+ schema
606
+ }) {
607
+ const validator2 = asValidator(schema);
608
+ try {
609
+ if (validator2.validate == null) {
610
+ return { success: true, value, rawValue: value };
611
+ }
612
+ const result = await validator2.validate(value);
613
+ if (result.success) {
614
+ return { success: true, value: result.value, rawValue: value };
615
+ }
616
+ return {
617
+ success: false,
618
+ error: TypeValidationError.wrap({ value, cause: result.error }),
619
+ rawValue: value
620
+ };
621
+ } catch (error) {
622
+ return {
623
+ success: false,
624
+ error: TypeValidationError.wrap({ value, cause: error }),
625
+ rawValue: value
626
+ };
627
+ }
628
+ }
629
+ async function parseJSON({
630
+ text,
631
+ schema
632
+ }) {
633
+ try {
634
+ const value = secureJsonParse(text);
635
+ if (schema == null) {
636
+ return value;
637
+ }
638
+ return validateTypes({ value, schema });
639
+ } catch (error) {
640
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
641
+ throw error;
642
+ }
643
+ throw new JSONParseError({ text, cause: error });
644
+ }
645
+ }
646
+ async function safeParseJSON({
647
+ text,
648
+ schema
649
+ }) {
650
+ try {
651
+ const value = secureJsonParse(text);
652
+ if (schema == null) {
653
+ return { success: true, value, rawValue: value };
654
+ }
655
+ return await safeValidateTypes({ value, schema });
656
+ } catch (error) {
657
+ return {
658
+ success: false,
659
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
660
+ rawValue: void 0
661
+ };
662
+ }
663
+ }
664
+ function isParsableJson(input) {
665
+ try {
666
+ secureJsonParse(input);
667
+ return true;
668
+ } catch (e) {
669
+ return false;
670
+ }
671
+ }
672
+ function parseJsonEventStream({
673
+ stream,
674
+ schema
675
+ }) {
676
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
677
+ new TransformStream({
678
+ async transform({ data }, controller) {
679
+ if (data === "[DONE]") {
680
+ return;
681
+ }
682
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
683
+ }
684
+ })
685
+ );
686
+ }
687
+ var getOriginalFetch2 = () => globalThis.fetch;
688
+ var postJsonToApi = async ({
689
+ url,
690
+ headers,
691
+ body,
692
+ failedResponseHandler,
693
+ successfulResponseHandler,
694
+ abortSignal,
695
+ fetch
696
+ }) => postToApi({
697
+ url,
698
+ headers: __spreadValues({
699
+ "Content-Type": "application/json"
700
+ }, headers),
701
+ body: {
702
+ content: JSON.stringify(body),
703
+ values: body
704
+ },
705
+ failedResponseHandler,
706
+ successfulResponseHandler,
707
+ abortSignal,
708
+ fetch
709
+ });
710
+ var postToApi = async ({
711
+ url,
712
+ headers = {},
713
+ body,
714
+ successfulResponseHandler,
715
+ failedResponseHandler,
716
+ abortSignal,
717
+ fetch = getOriginalFetch2()
718
+ }) => {
719
+ try {
720
+ const response = await fetch(url, {
721
+ method: "POST",
722
+ headers: removeUndefinedEntries(headers),
723
+ body: body.content,
724
+ signal: abortSignal
725
+ });
726
+ const responseHeaders = extractResponseHeaders(response);
727
+ if (!response.ok) {
728
+ let errorInformation;
729
+ try {
730
+ errorInformation = await failedResponseHandler({
731
+ response,
732
+ url,
733
+ requestBodyValues: body.values
734
+ });
735
+ } catch (error) {
736
+ if (isAbortError(error) || APICallError.isInstance(error)) {
737
+ throw error;
738
+ }
739
+ throw new APICallError({
740
+ message: "Failed to process error response",
741
+ cause: error,
742
+ statusCode: response.status,
743
+ url,
744
+ responseHeaders,
745
+ requestBodyValues: body.values
746
+ });
747
+ }
748
+ throw errorInformation.value;
749
+ }
750
+ try {
751
+ return await successfulResponseHandler({
752
+ response,
753
+ url,
754
+ requestBodyValues: body.values
755
+ });
756
+ } catch (error) {
757
+ if (error instanceof Error) {
758
+ if (isAbortError(error) || APICallError.isInstance(error)) {
759
+ throw error;
760
+ }
761
+ }
762
+ throw new APICallError({
763
+ message: "Failed to process successful response",
764
+ cause: error,
765
+ statusCode: response.status,
766
+ url,
767
+ responseHeaders,
768
+ requestBodyValues: body.values
769
+ });
770
+ }
771
+ } catch (error) {
772
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
773
+ }
774
+ };
775
+ var createJsonErrorResponseHandler = ({
776
+ errorSchema,
777
+ errorToMessage,
778
+ isRetryable
779
+ }) => async ({ response, url, requestBodyValues }) => {
780
+ const responseBody = await response.text();
781
+ const responseHeaders = extractResponseHeaders(response);
782
+ if (responseBody.trim() === "") {
783
+ return {
784
+ responseHeaders,
785
+ value: new APICallError({
786
+ message: response.statusText,
787
+ url,
788
+ requestBodyValues,
789
+ statusCode: response.status,
790
+ responseHeaders,
791
+ responseBody,
792
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
793
+ })
794
+ };
795
+ }
796
+ try {
797
+ const parsedError = await parseJSON({
798
+ text: responseBody,
799
+ schema: errorSchema
800
+ });
801
+ return {
802
+ responseHeaders,
803
+ value: new APICallError({
804
+ message: errorToMessage(parsedError),
805
+ url,
806
+ requestBodyValues,
807
+ statusCode: response.status,
808
+ responseHeaders,
809
+ responseBody,
810
+ data: parsedError,
811
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
812
+ })
813
+ };
814
+ } catch (parseError) {
815
+ return {
816
+ responseHeaders,
817
+ value: new APICallError({
818
+ message: response.statusText,
819
+ url,
820
+ requestBodyValues,
821
+ statusCode: response.status,
822
+ responseHeaders,
823
+ responseBody,
824
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
825
+ })
826
+ };
827
+ }
828
+ };
829
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
830
+ const responseHeaders = extractResponseHeaders(response);
831
+ if (response.body == null) {
832
+ throw new EmptyResponseBodyError({});
833
+ }
834
+ return {
835
+ responseHeaders,
836
+ value: parseJsonEventStream({
837
+ stream: response.body,
838
+ schema: chunkSchema
839
+ })
840
+ };
841
+ };
842
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
843
+ const responseBody = await response.text();
844
+ const parsedResult = await safeParseJSON({
845
+ text: responseBody,
846
+ schema: responseSchema
847
+ });
848
+ const responseHeaders = extractResponseHeaders(response);
849
+ if (!parsedResult.success) {
850
+ throw new APICallError({
851
+ message: "Invalid JSON response",
852
+ cause: parsedResult.error,
853
+ statusCode: response.status,
854
+ responseHeaders,
855
+ responseBody,
856
+ url,
857
+ requestBodyValues
858
+ });
859
+ }
860
+ return {
861
+ responseHeaders,
862
+ value: parsedResult.value,
863
+ rawValue: parsedResult.rawValue
864
+ };
865
+ };
866
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
867
+ var { btoa, atob } = globalThis;
868
+ function convertUint8ArrayToBase64(array) {
869
+ let latin1string = "";
870
+ for (let i = 0; i < array.length; i++) {
871
+ latin1string += String.fromCodePoint(array[i]);
872
+ }
873
+ return btoa(latin1string);
874
+ }
875
+
876
+ // src/schemas/reasoning-details.ts
877
+ var import_v4 = require("zod/v4");
878
+ var ReasoningDetailSummarySchema = import_v4.z.object({
879
+ type: import_v4.z.literal("reasoning.summary" /* Summary */),
880
+ summary: import_v4.z.string()
62
881
  });
63
- var ReasoningDetailEncryptedSchema = import_zod.z.object({
64
- type: import_zod.z.literal("reasoning.encrypted" /* Encrypted */),
65
- data: import_zod.z.string()
882
+ var ReasoningDetailEncryptedSchema = import_v4.z.object({
883
+ type: import_v4.z.literal("reasoning.encrypted" /* Encrypted */),
884
+ data: import_v4.z.string()
66
885
  });
67
- var ReasoningDetailTextSchema = import_zod.z.object({
68
- type: import_zod.z.literal("reasoning.text" /* Text */),
69
- text: import_zod.z.string().nullish(),
70
- signature: import_zod.z.string().nullish()
886
+ var ReasoningDetailTextSchema = import_v4.z.object({
887
+ type: import_v4.z.literal("reasoning.text" /* Text */),
888
+ text: import_v4.z.string().nullish(),
889
+ signature: import_v4.z.string().nullish()
71
890
  });
72
- var ReasoningDetailUnionSchema = import_zod.z.union([
891
+ var ReasoningDetailUnionSchema = import_v4.z.union([
73
892
  ReasoningDetailSummarySchema,
74
893
  ReasoningDetailEncryptedSchema,
75
894
  ReasoningDetailTextSchema
76
895
  ]);
77
- var ReasoningDetailsWithUnknownSchema = import_zod.z.union([
896
+ var ReasoningDetailsWithUnknownSchema = import_v4.z.union([
78
897
  ReasoningDetailUnionSchema,
79
- import_zod.z.unknown().transform(() => null)
898
+ import_v4.z.unknown().transform(() => null)
80
899
  ]);
81
- var ReasoningDetailArraySchema = import_zod.z.array(ReasoningDetailsWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
900
+ var ReasoningDetailArraySchema = import_v4.z.array(ReasoningDetailsWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
82
901
 
83
- // src/openrouter-chat-language-model.ts
84
- var import_provider = require("@ai-sdk/provider");
85
- var import_provider_utils3 = require("@ai-sdk/provider-utils");
86
- var import_zod3 = require("zod");
902
+ // src/schemas/error-response.ts
903
+ var import_v42 = require("zod/v4");
904
+ var OpenRouterErrorResponseSchema = import_v42.z.object({
905
+ error: import_v42.z.object({
906
+ code: import_v42.z.union([import_v42.z.string(), import_v42.z.number()]).nullable(),
907
+ message: import_v42.z.string(),
908
+ type: import_v42.z.string().nullable(),
909
+ param: import_v42.z.any().nullable()
910
+ })
911
+ });
912
+ var openrouterFailedResponseHandler = createJsonErrorResponseHandler({
913
+ errorSchema: OpenRouterErrorResponseSchema,
914
+ errorToMessage: (data) => data.error.message
915
+ });
87
916
 
88
- // src/convert-to-openrouter-chat-messages.ts
89
- var import_provider_utils = require("@ai-sdk/provider-utils");
917
+ // src/utils/map-finish-reason.ts
918
+ function mapOpenRouterFinishReason(finishReason) {
919
+ switch (finishReason) {
920
+ case "stop":
921
+ return "stop";
922
+ case "length":
923
+ return "length";
924
+ case "content_filter":
925
+ return "content-filter";
926
+ case "function_call":
927
+ case "tool_calls":
928
+ return "tool-calls";
929
+ default:
930
+ return "unknown";
931
+ }
932
+ }
933
+
934
+ // src/chat/convert-to-openrouter-chat-messages.ts
90
935
  function getCacheControl(providerMetadata) {
91
- var _a, _b, _c;
936
+ var _a15, _b, _c;
92
937
  const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
93
938
  const openrouter = providerMetadata == null ? void 0 : providerMetadata.openrouter;
94
- return (_c = (_b = (_a = openrouter == null ? void 0 : openrouter.cacheControl) != null ? _a : openrouter == null ? void 0 : openrouter.cache_control) != null ? _b : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
939
+ return (_c = (_b = (_a15 = openrouter == null ? void 0 : openrouter.cacheControl) != null ? _a15 : openrouter == null ? void 0 : openrouter.cache_control) != null ? _b : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
95
940
  }
96
941
  function convertToOpenRouterChatMessages(prompt) {
97
- var _a, _b, _c;
942
+ var _a15, _b, _c;
98
943
  const messages = [];
99
- for (const { role, content, providerMetadata } of prompt) {
944
+ for (const { role, content, providerOptions } of prompt) {
100
945
  switch (role) {
101
946
  case "system": {
102
947
  messages.push({
103
948
  role: "system",
104
949
  content,
105
- cache_control: getCacheControl(providerMetadata)
950
+ cache_control: getCacheControl(providerOptions)
106
951
  });
107
952
  break;
108
953
  }
109
954
  case "user": {
110
- if (content.length === 1 && ((_a = content[0]) == null ? void 0 : _a.type) === "text") {
955
+ if (content.length === 1 && ((_a15 = content[0]) == null ? void 0 : _a15.type) === "text") {
956
+ const cacheControl = (_b = getCacheControl(providerOptions)) != null ? _b : getCacheControl(content[0].providerOptions);
957
+ const contentWithCacheControl = cacheControl ? [
958
+ {
959
+ type: "text",
960
+ text: content[0].text,
961
+ cache_control: cacheControl
962
+ }
963
+ ] : content[0].text;
111
964
  messages.push({
112
965
  role: "user",
113
- content: content[0].text,
114
- cache_control: (_b = getCacheControl(providerMetadata)) != null ? _b : getCacheControl(content[0].providerMetadata)
966
+ content: contentWithCacheControl
115
967
  });
116
968
  break;
117
969
  }
118
- const messageCacheControl = getCacheControl(providerMetadata);
970
+ const messageCacheControl = getCacheControl(providerOptions);
119
971
  const contentParts = content.map(
120
972
  (part) => {
121
- var _a2, _b2, _c2, _d;
122
- const cacheControl = (_a2 = getCacheControl(part.providerMetadata)) != null ? _a2 : messageCacheControl;
973
+ var _a16, _b2, _c2, _d, _e, _f, _g;
974
+ const cacheControl = (_a16 = getCacheControl(part.providerOptions)) != null ? _a16 : messageCacheControl;
123
975
  switch (part.type) {
124
976
  case "text":
125
977
  return {
@@ -128,33 +980,35 @@ function convertToOpenRouterChatMessages(prompt) {
128
980
  // For text parts, only use part-specific cache control
129
981
  cache_control: cacheControl
130
982
  };
131
- case "image":
132
- return {
133
- type: "image_url",
134
- image_url: {
135
- url: part.image instanceof URL ? part.image.toString() : `data:${(_b2 = part.mimeType) != null ? _b2 : "image/jpeg"};base64,${(0, import_provider_utils.convertUint8ArrayToBase64)(
136
- part.image
137
- )}`
138
- },
139
- // For image parts, use part-specific or message-level cache control
140
- cache_control: cacheControl
141
- };
142
983
  case "file":
984
+ if ((_b2 = part.mediaType) == null ? void 0 : _b2.startsWith("image/")) {
985
+ return {
986
+ type: "image_url",
987
+ image_url: {
988
+ url: part.data instanceof URL ? part.data.toString() : `data:${(_c2 = part.mediaType) != null ? _c2 : "image/jpeg"};base64,${convertUint8ArrayToBase64(
989
+ part.data instanceof Uint8Array ? part.data : new Uint8Array()
990
+ )}`
991
+ },
992
+ // For image parts, use part-specific or message-level cache control
993
+ cache_control: cacheControl
994
+ };
995
+ }
143
996
  return {
144
997
  type: "file",
145
998
  file: {
146
999
  filename: String(
147
- (_d = (_c2 = part.providerMetadata) == null ? void 0 : _c2.openrouter) == null ? void 0 : _d.filename
1000
+ (_g = (_f = (_e = (_d = part.providerOptions) == null ? void 0 : _d.openrouter) == null ? void 0 : _e.filename) != null ? _f : part.filename) != null ? _g : ""
148
1001
  ),
149
- file_data: part.data instanceof Uint8Array ? `data:${part.mimeType};base64,${(0, import_provider_utils.convertUint8ArrayToBase64)(part.data)}` : `data:${part.mimeType};base64,${part.data}`
1002
+ file_data: part.data instanceof Uint8Array ? `data:${part.mediaType};base64,${convertUint8ArrayToBase64(part.data)}` : `data:${part.mediaType};base64,${part.data}`
150
1003
  },
151
1004
  cache_control: cacheControl
152
1005
  };
153
1006
  default: {
154
- const _exhaustiveCheck = part;
155
- throw new Error(
156
- `Unsupported content part type: ${_exhaustiveCheck}`
157
- );
1007
+ return {
1008
+ type: "text",
1009
+ text: "",
1010
+ cache_control: cacheControl
1011
+ };
158
1012
  }
159
1013
  }
160
1014
  }
@@ -182,7 +1036,7 @@ function convertToOpenRouterChatMessages(prompt) {
182
1036
  type: "function",
183
1037
  function: {
184
1038
  name: part.toolName,
185
- arguments: JSON.stringify(part.args)
1039
+ arguments: JSON.stringify(part.input)
186
1040
  }
187
1041
  });
188
1042
  break;
@@ -191,23 +1045,14 @@ function convertToOpenRouterChatMessages(prompt) {
191
1045
  reasoning += part.text;
192
1046
  reasoningDetails.push({
193
1047
  type: "reasoning.text" /* Text */,
194
- text: part.text,
195
- signature: part.signature
196
- });
197
- break;
198
- }
199
- case "redacted-reasoning": {
200
- reasoningDetails.push({
201
- type: "reasoning.encrypted" /* Encrypted */,
202
- data: part.data
1048
+ text: part.text
203
1049
  });
204
1050
  break;
205
1051
  }
206
1052
  case "file":
207
1053
  break;
208
1054
  default: {
209
- const _exhaustiveCheck = part;
210
- throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
1055
+ break;
211
1056
  }
212
1057
  }
213
1058
  }
@@ -217,95 +1062,185 @@ function convertToOpenRouterChatMessages(prompt) {
217
1062
  tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
218
1063
  reasoning: reasoning || void 0,
219
1064
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
220
- cache_control: getCacheControl(providerMetadata)
1065
+ cache_control: getCacheControl(providerOptions)
221
1066
  });
222
1067
  break;
223
1068
  }
224
1069
  case "tool": {
225
1070
  for (const toolResponse of content) {
1071
+ const content2 = getToolResultContent(toolResponse);
226
1072
  messages.push({
227
1073
  role: "tool",
228
1074
  tool_call_id: toolResponse.toolCallId,
229
- content: JSON.stringify(toolResponse.result),
230
- cache_control: (_c = getCacheControl(providerMetadata)) != null ? _c : getCacheControl(toolResponse.providerMetadata)
1075
+ content: content2,
1076
+ cache_control: (_c = getCacheControl(providerOptions)) != null ? _c : getCacheControl(toolResponse.providerOptions)
231
1077
  });
232
1078
  }
233
1079
  break;
234
1080
  }
235
1081
  default: {
236
- const _exhaustiveCheck = role;
237
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
1082
+ break;
238
1083
  }
239
1084
  }
240
1085
  }
241
1086
  return messages;
242
1087
  }
243
-
244
- // src/map-openrouter-chat-logprobs.ts
245
- function mapOpenRouterChatLogProbsOutput(logprobs) {
246
- var _a, _b;
247
- return (_b = (_a = logprobs == null ? void 0 : logprobs.content) == null ? void 0 : _a.map(({ token, logprob, top_logprobs }) => ({
248
- token,
249
- logprob,
250
- topLogprobs: top_logprobs ? top_logprobs.map(({ token: token2, logprob: logprob2 }) => ({
251
- token: token2,
252
- logprob: logprob2
253
- })) : []
254
- }))) != null ? _b : void 0;
1088
+ function getToolResultContent(input) {
1089
+ return input.output.type === "text" ? input.output.value : JSON.stringify(input.output.value);
255
1090
  }
256
1091
 
257
- // src/map-openrouter-finish-reason.ts
258
- function mapOpenRouterFinishReason(finishReason) {
259
- switch (finishReason) {
260
- case "stop":
261
- return "stop";
262
- case "length":
263
- return "length";
264
- case "content_filter":
265
- return "content-filter";
266
- case "function_call":
267
- case "tool_calls":
268
- return "tool-calls";
269
- default:
270
- return "unknown";
1092
+ // src/chat/get-tool-choice.ts
1093
+ var import_v43 = require("zod/v4");
1094
+ var ChatCompletionToolChoiceSchema = import_v43.z.union([
1095
+ import_v43.z.literal("auto"),
1096
+ import_v43.z.literal("none"),
1097
+ import_v43.z.literal("required"),
1098
+ import_v43.z.object({
1099
+ type: import_v43.z.literal("function"),
1100
+ function: import_v43.z.object({
1101
+ name: import_v43.z.string()
1102
+ })
1103
+ })
1104
+ ]);
1105
+ function getChatCompletionToolChoice(toolChoice) {
1106
+ switch (toolChoice.type) {
1107
+ case "auto":
1108
+ case "none":
1109
+ case "required":
1110
+ return toolChoice.type;
1111
+ case "tool": {
1112
+ return {
1113
+ type: "function",
1114
+ function: { name: toolChoice.toolName }
1115
+ };
1116
+ }
1117
+ default: {
1118
+ toolChoice;
1119
+ throw new Error(`Invalid tool choice type: ${toolChoice}`);
1120
+ }
271
1121
  }
272
1122
  }
273
1123
 
274
- // src/openrouter-error.ts
275
- var import_provider_utils2 = require("@ai-sdk/provider-utils");
276
- var import_zod2 = require("zod");
277
- var OpenRouterErrorResponseSchema = import_zod2.z.object({
278
- error: import_zod2.z.object({
279
- code: import_zod2.z.union([import_zod2.z.string(), import_zod2.z.number()]).nullable(),
280
- message: import_zod2.z.string(),
281
- type: import_zod2.z.string().nullable(),
282
- param: import_zod2.z.any().nullable()
283
- })
1124
+ // src/chat/schemas.ts
1125
+ var import_v44 = require("zod/v4");
1126
+ var OpenRouterChatCompletionBaseResponseSchema = import_v44.z.object({
1127
+ id: import_v44.z.string().optional(),
1128
+ model: import_v44.z.string().optional(),
1129
+ usage: import_v44.z.object({
1130
+ prompt_tokens: import_v44.z.number(),
1131
+ prompt_tokens_details: import_v44.z.object({
1132
+ cached_tokens: import_v44.z.number()
1133
+ }).nullish(),
1134
+ completion_tokens: import_v44.z.number(),
1135
+ completion_tokens_details: import_v44.z.object({
1136
+ reasoning_tokens: import_v44.z.number()
1137
+ }).nullish(),
1138
+ total_tokens: import_v44.z.number(),
1139
+ cost: import_v44.z.number().optional()
1140
+ }).nullish()
284
1141
  });
285
- var openrouterFailedResponseHandler = (0, import_provider_utils2.createJsonErrorResponseHandler)({
286
- errorSchema: OpenRouterErrorResponseSchema,
287
- errorToMessage: (data) => data.error.message
1142
+ var OpenRouterNonStreamChatCompletionResponseSchema = OpenRouterChatCompletionBaseResponseSchema.extend({
1143
+ choices: import_v44.z.array(
1144
+ import_v44.z.object({
1145
+ message: import_v44.z.object({
1146
+ role: import_v44.z.literal("assistant"),
1147
+ content: import_v44.z.string().nullable().optional(),
1148
+ reasoning: import_v44.z.string().nullable().optional(),
1149
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
1150
+ tool_calls: import_v44.z.array(
1151
+ import_v44.z.object({
1152
+ id: import_v44.z.string().optional().nullable(),
1153
+ type: import_v44.z.literal("function"),
1154
+ function: import_v44.z.object({
1155
+ name: import_v44.z.string(),
1156
+ arguments: import_v44.z.string()
1157
+ })
1158
+ })
1159
+ ).optional()
1160
+ }),
1161
+ index: import_v44.z.number().nullish(),
1162
+ logprobs: import_v44.z.object({
1163
+ content: import_v44.z.array(
1164
+ import_v44.z.object({
1165
+ token: import_v44.z.string(),
1166
+ logprob: import_v44.z.number(),
1167
+ top_logprobs: import_v44.z.array(
1168
+ import_v44.z.object({
1169
+ token: import_v44.z.string(),
1170
+ logprob: import_v44.z.number()
1171
+ })
1172
+ )
1173
+ })
1174
+ ).nullable()
1175
+ }).nullable().optional(),
1176
+ finish_reason: import_v44.z.string().optional().nullable()
1177
+ })
1178
+ )
288
1179
  });
1180
+ var OpenRouterStreamChatCompletionChunkSchema = import_v44.z.union([
1181
+ OpenRouterChatCompletionBaseResponseSchema.extend({
1182
+ choices: import_v44.z.array(
1183
+ import_v44.z.object({
1184
+ delta: import_v44.z.object({
1185
+ role: import_v44.z.enum(["assistant"]).optional(),
1186
+ content: import_v44.z.string().nullish(),
1187
+ reasoning: import_v44.z.string().nullish().optional(),
1188
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
1189
+ tool_calls: import_v44.z.array(
1190
+ import_v44.z.object({
1191
+ index: import_v44.z.number().nullish(),
1192
+ id: import_v44.z.string().nullish(),
1193
+ type: import_v44.z.literal("function").optional(),
1194
+ function: import_v44.z.object({
1195
+ name: import_v44.z.string().nullish(),
1196
+ arguments: import_v44.z.string().nullish()
1197
+ })
1198
+ })
1199
+ ).nullish()
1200
+ }).nullish(),
1201
+ logprobs: import_v44.z.object({
1202
+ content: import_v44.z.array(
1203
+ import_v44.z.object({
1204
+ token: import_v44.z.string(),
1205
+ logprob: import_v44.z.number(),
1206
+ top_logprobs: import_v44.z.array(
1207
+ import_v44.z.object({
1208
+ token: import_v44.z.string(),
1209
+ logprob: import_v44.z.number()
1210
+ })
1211
+ )
1212
+ })
1213
+ ).nullable()
1214
+ }).nullish(),
1215
+ finish_reason: import_v44.z.string().nullable().optional(),
1216
+ index: import_v44.z.number().nullish()
1217
+ })
1218
+ )
1219
+ }),
1220
+ OpenRouterErrorResponseSchema
1221
+ ]);
289
1222
 
290
- // src/openrouter-chat-language-model.ts
291
- function isFunctionTool(tool) {
292
- return "parameters" in tool;
293
- }
1223
+ // src/chat/index.ts
294
1224
  var OpenRouterChatLanguageModel = class {
295
1225
  constructor(modelId, settings, config) {
296
- this.specificationVersion = "v1";
1226
+ this.specificationVersion = "v2";
1227
+ this.provider = "openrouter";
297
1228
  this.defaultObjectGenerationMode = "tool";
1229
+ this.supportedUrls = {
1230
+ "image/*": [
1231
+ /^data:image\/[a-zA-Z]+;base64,/,
1232
+ /^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i
1233
+ ],
1234
+ // 'text/*': [/^data:text\//, /^https?:\/\/.+$/],
1235
+ "application/*": [/^data:application\//, /^https?:\/\/.+$/]
1236
+ };
298
1237
  this.modelId = modelId;
299
1238
  this.settings = settings;
300
1239
  this.config = config;
301
1240
  }
302
- get provider() {
303
- return this.config.provider;
304
- }
305
1241
  getArgs({
306
- mode,
307
1242
  prompt,
308
- maxTokens,
1243
+ maxOutputTokens,
309
1244
  temperature,
310
1245
  topP,
311
1246
  frequencyPenalty,
@@ -314,12 +1249,10 @@ var OpenRouterChatLanguageModel = class {
314
1249
  stopSequences,
315
1250
  responseFormat,
316
1251
  topK,
317
- providerMetadata
1252
+ tools,
1253
+ toolChoice
318
1254
  }) {
319
- var _a;
320
- const type = mode.type;
321
- const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata.openrouter) != null ? _a : {};
322
- const baseArgs = __spreadValues(__spreadValues(__spreadValues({
1255
+ const baseArgs = __spreadValues(__spreadValues({
323
1256
  // model id:
324
1257
  model: this.modelId,
325
1258
  models: this.settings.models,
@@ -330,7 +1263,7 @@ var OpenRouterChatLanguageModel = class {
330
1263
  user: this.settings.user,
331
1264
  parallel_tool_calls: this.settings.parallelToolCalls,
332
1265
  // standardized settings:
333
- max_tokens: maxTokens,
1266
+ max_tokens: maxOutputTokens,
334
1267
  temperature,
335
1268
  top_p: topP,
336
1269
  frequency_penalty: frequencyPenalty,
@@ -345,97 +1278,74 @@ var OpenRouterChatLanguageModel = class {
345
1278
  include_reasoning: this.settings.includeReasoning,
346
1279
  reasoning: this.settings.reasoning,
347
1280
  usage: this.settings.usage
348
- }, this.config.extraBody), this.settings.extraBody), extraCallingBody);
349
- switch (type) {
350
- case "regular": {
351
- return __spreadValues(__spreadValues({}, baseArgs), prepareToolsAndToolChoice(mode));
352
- }
353
- case "object-json": {
354
- return __spreadProps(__spreadValues({}, baseArgs), {
355
- response_format: { type: "json_object" }
356
- });
357
- }
358
- case "object-tool": {
359
- return __spreadProps(__spreadValues({}, baseArgs), {
360
- tool_choice: { type: "function", function: { name: mode.tool.name } },
361
- tools: [
362
- {
363
- type: "function",
364
- function: {
365
- name: mode.tool.name,
366
- description: mode.tool.description,
367
- parameters: mode.tool.parameters
368
- }
369
- }
370
- ]
371
- });
372
- }
373
- // Handle all non-text types with a single default case
374
- default: {
375
- const _exhaustiveCheck = type;
376
- throw new import_provider.UnsupportedFunctionalityError({
377
- functionality: `${_exhaustiveCheck} mode`
378
- });
379
- }
1281
+ }, this.config.extraBody), this.settings.extraBody);
1282
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
1283
+ return __spreadProps(__spreadValues({}, baseArgs), {
1284
+ response_format: { type: "json_object" }
1285
+ });
1286
+ }
1287
+ if (tools && tools.length > 0) {
1288
+ const mappedTools = tools.filter((tool) => tool.type === "function").map((tool) => ({
1289
+ type: "function",
1290
+ function: {
1291
+ name: tool.name,
1292
+ description: tool.type,
1293
+ parameters: tool.inputSchema
1294
+ }
1295
+ }));
1296
+ return __spreadProps(__spreadValues({}, baseArgs), {
1297
+ tools: mappedTools,
1298
+ tool_choice: toolChoice ? getChatCompletionToolChoice(toolChoice) : void 0
1299
+ });
380
1300
  }
1301
+ return baseArgs;
381
1302
  }
382
1303
  async doGenerate(options) {
383
- var _b, _c, _d, _e, _f, _g, _h, _i, _j;
384
- const args = this.getArgs(options);
385
- const { responseHeaders, value: response } = await (0, import_provider_utils3.postJsonToApi)({
1304
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
1305
+ const providerOptions = options.providerOptions || {};
1306
+ const openrouterOptions = providerOptions.openrouter || {};
1307
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
1308
+ const { value: response, responseHeaders } = await postJsonToApi({
386
1309
  url: this.config.url({
387
1310
  path: "/chat/completions",
388
1311
  modelId: this.modelId
389
1312
  }),
390
- headers: (0, import_provider_utils3.combineHeaders)(this.config.headers(), options.headers),
1313
+ headers: combineHeaders(this.config.headers(), options.headers),
391
1314
  body: args,
392
1315
  failedResponseHandler: openrouterFailedResponseHandler,
393
- successfulResponseHandler: (0, import_provider_utils3.createJsonResponseHandler)(
1316
+ successfulResponseHandler: createJsonResponseHandler(
394
1317
  OpenRouterNonStreamChatCompletionResponseSchema
395
1318
  ),
396
1319
  abortSignal: options.abortSignal,
397
1320
  fetch: this.config.fetch
398
1321
  });
399
- const _a = args, { messages: rawPrompt } = _a, rawSettings = __objRest(_a, ["messages"]);
400
1322
  const choice = response.choices[0];
401
1323
  if (!choice) {
402
1324
  throw new Error("No choice in response");
403
1325
  }
404
1326
  const usageInfo = response.usage ? {
405
- promptTokens: (_b = response.usage.prompt_tokens) != null ? _b : 0,
406
- completionTokens: (_c = response.usage.completion_tokens) != null ? _c : 0
1327
+ inputTokens: (_a15 = response.usage.prompt_tokens) != null ? _a15 : 0,
1328
+ outputTokens: (_b = response.usage.completion_tokens) != null ? _b : 0,
1329
+ totalTokens: ((_c = response.usage.prompt_tokens) != null ? _c : 0) + ((_d = response.usage.completion_tokens) != null ? _d : 0),
1330
+ reasoningTokens: (_f = (_e = response.usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0,
1331
+ cachedInputTokens: (_h = (_g = response.usage.prompt_tokens_details) == null ? void 0 : _g.cached_tokens) != null ? _h : 0
407
1332
  } : {
408
- promptTokens: 0,
409
- completionTokens: 0
1333
+ inputTokens: 0,
1334
+ outputTokens: 0,
1335
+ totalTokens: 0,
1336
+ reasoningTokens: 0,
1337
+ cachedInputTokens: 0
410
1338
  };
411
- const providerMetadata = {};
412
- if (response.usage && ((_d = this.settings.usage) == null ? void 0 : _d.include)) {
413
- providerMetadata.openrouter = {
414
- usage: {
415
- promptTokens: response.usage.prompt_tokens,
416
- promptTokensDetails: response.usage.prompt_tokens_details ? {
417
- cachedTokens: (_e = response.usage.prompt_tokens_details.cached_tokens) != null ? _e : 0
418
- } : void 0,
419
- completionTokens: response.usage.completion_tokens,
420
- completionTokensDetails: response.usage.completion_tokens_details ? {
421
- reasoningTokens: (_f = response.usage.completion_tokens_details.reasoning_tokens) != null ? _f : 0
422
- } : void 0,
423
- cost: response.usage.cost,
424
- totalTokens: (_g = response.usage.total_tokens) != null ? _g : 0
425
- }
426
- };
427
- }
428
- const hasProviderMetadata = Object.keys(providerMetadata).length > 0;
429
- const reasoningDetails = (_h = choice.message.reasoning_details) != null ? _h : [];
430
- const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
431
- var _a2;
1339
+ const reasoningDetails = (_i = choice.message.reasoning_details) != null ? _i : [];
1340
+ reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
1341
+ var _a16;
432
1342
  switch (detail.type) {
433
1343
  case "reasoning.text" /* Text */: {
434
1344
  if (detail.text) {
435
1345
  return {
436
1346
  type: "text",
437
1347
  text: detail.text,
438
- signature: (_a2 = detail.signature) != null ? _a2 : void 0
1348
+ signature: (_a16 = detail.signature) != null ? _a16 : void 0
439
1349
  };
440
1350
  }
441
1351
  break;
@@ -469,68 +1379,92 @@ var OpenRouterChatLanguageModel = class {
469
1379
  text: choice.message.reasoning
470
1380
  }
471
1381
  ] : [];
472
- return __spreadValues({
473
- response: {
474
- id: response.id,
475
- modelId: response.model
476
- },
477
- text: (_i = choice.message.content) != null ? _i : void 0,
478
- reasoning,
479
- toolCalls: (_j = choice.message.tool_calls) == null ? void 0 : _j.map((toolCall) => {
480
- var _a2;
481
- return {
482
- toolCallType: "function",
483
- toolCallId: (_a2 = toolCall.id) != null ? _a2 : (0, import_provider_utils3.generateId)(),
1382
+ const content = [];
1383
+ if (choice.message.content) {
1384
+ content.push({
1385
+ type: "text",
1386
+ text: choice.message.content
1387
+ });
1388
+ }
1389
+ if (choice.message.tool_calls) {
1390
+ for (const toolCall of choice.message.tool_calls) {
1391
+ content.push({
1392
+ type: "tool-call",
1393
+ toolCallId: (_j = toolCall.id) != null ? _j : generateId(),
484
1394
  toolName: toolCall.function.name,
485
- args: toolCall.function.arguments
486
- };
487
- }),
1395
+ input: toolCall.function.arguments
1396
+ });
1397
+ }
1398
+ }
1399
+ return {
1400
+ content,
488
1401
  finishReason: mapOpenRouterFinishReason(choice.finish_reason),
489
1402
  usage: usageInfo,
490
- rawCall: { rawPrompt, rawSettings },
491
- rawResponse: { headers: responseHeaders },
492
1403
  warnings: [],
493
- logprobs: mapOpenRouterChatLogProbsOutput(choice.logprobs)
494
- }, hasProviderMetadata ? { providerMetadata } : {});
1404
+ providerMetadata: {
1405
+ openrouter: {
1406
+ usage: {
1407
+ promptTokens: (_k = usageInfo.inputTokens) != null ? _k : 0,
1408
+ completionTokens: (_l = usageInfo.outputTokens) != null ? _l : 0,
1409
+ totalTokens: (_m = usageInfo.totalTokens) != null ? _m : 0,
1410
+ cost: (_n = response.usage) == null ? void 0 : _n.cost,
1411
+ promptTokensDetails: {
1412
+ cachedTokens: (_q = (_p = (_o = response.usage) == null ? void 0 : _o.prompt_tokens_details) == null ? void 0 : _p.cached_tokens) != null ? _q : 0
1413
+ },
1414
+ completionTokensDetails: {
1415
+ reasoningTokens: (_t = (_s = (_r = response.usage) == null ? void 0 : _r.completion_tokens_details) == null ? void 0 : _s.reasoning_tokens) != null ? _t : 0
1416
+ }
1417
+ }
1418
+ }
1419
+ },
1420
+ request: { body: args },
1421
+ response: {
1422
+ id: response.id,
1423
+ modelId: response.model,
1424
+ headers: responseHeaders
1425
+ }
1426
+ };
495
1427
  }
496
1428
  async doStream(options) {
497
- var _a, _c;
498
- const args = this.getArgs(options);
499
- const { responseHeaders, value: response } = await (0, import_provider_utils3.postJsonToApi)({
1429
+ var _a15;
1430
+ const providerOptions = options.providerOptions || {};
1431
+ const openrouterOptions = providerOptions.openrouter || {};
1432
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
1433
+ const { value: response, responseHeaders } = await postJsonToApi({
500
1434
  url: this.config.url({
501
1435
  path: "/chat/completions",
502
1436
  modelId: this.modelId
503
1437
  }),
504
- headers: (0, import_provider_utils3.combineHeaders)(this.config.headers(), options.headers),
1438
+ headers: combineHeaders(this.config.headers(), options.headers),
505
1439
  body: __spreadProps(__spreadValues({}, args), {
506
1440
  stream: true,
507
1441
  // only include stream_options when in strict compatibility mode:
508
1442
  stream_options: this.config.compatibility === "strict" ? __spreadValues({
509
1443
  include_usage: true
510
- }, ((_a = this.settings.usage) == null ? void 0 : _a.include) ? { include_usage: true } : {}) : void 0
1444
+ }, ((_a15 = this.settings.usage) == null ? void 0 : _a15.include) ? { include_usage: true } : {}) : void 0
511
1445
  }),
512
1446
  failedResponseHandler: openrouterFailedResponseHandler,
513
- successfulResponseHandler: (0, import_provider_utils3.createEventSourceResponseHandler)(
1447
+ successfulResponseHandler: createEventSourceResponseHandler(
514
1448
  OpenRouterStreamChatCompletionChunkSchema
515
1449
  ),
516
1450
  abortSignal: options.abortSignal,
517
1451
  fetch: this.config.fetch
518
1452
  });
519
- const _b = args, { messages: rawPrompt } = _b, rawSettings = __objRest(_b, ["messages"]);
520
1453
  const toolCalls = [];
521
1454
  let finishReason = "other";
522
- let usage = {
523
- promptTokens: Number.NaN,
524
- completionTokens: Number.NaN
1455
+ const usage = {
1456
+ inputTokens: Number.NaN,
1457
+ outputTokens: Number.NaN,
1458
+ totalTokens: Number.NaN,
1459
+ reasoningTokens: Number.NaN,
1460
+ cachedInputTokens: Number.NaN
525
1461
  };
526
- let logprobs;
527
1462
  const openrouterUsage = {};
528
- const shouldIncludeUsageAccounting = !!((_c = this.settings.usage) == null ? void 0 : _c.include);
529
1463
  return {
530
1464
  stream: response.pipeThrough(
531
1465
  new TransformStream({
532
1466
  transform(chunk, controller) {
533
- var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
1467
+ var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
534
1468
  if (!chunk.success) {
535
1469
  finishReason = "error";
536
1470
  controller.enqueue({ type: "error", error: chunk.error });
@@ -555,20 +1489,23 @@ var OpenRouterChatLanguageModel = class {
555
1489
  });
556
1490
  }
557
1491
  if (value.usage != null) {
558
- usage = {
559
- promptTokens: value.usage.prompt_tokens,
560
- completionTokens: value.usage.completion_tokens
561
- };
1492
+ usage.inputTokens = value.usage.prompt_tokens;
1493
+ usage.outputTokens = value.usage.completion_tokens;
1494
+ usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
562
1495
  openrouterUsage.promptTokens = value.usage.prompt_tokens;
563
1496
  if (value.usage.prompt_tokens_details) {
1497
+ const cachedInputTokens = (_a16 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a16 : 0;
1498
+ usage.cachedInputTokens = cachedInputTokens;
564
1499
  openrouterUsage.promptTokensDetails = {
565
- cachedTokens: (_a2 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a2 : 0
1500
+ cachedTokens: cachedInputTokens
566
1501
  };
567
1502
  }
568
1503
  openrouterUsage.completionTokens = value.usage.completion_tokens;
569
1504
  if (value.usage.completion_tokens_details) {
1505
+ const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
1506
+ usage.reasoningTokens = reasoningTokens;
570
1507
  openrouterUsage.completionTokensDetails = {
571
- reasoningTokens: (_b2 = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b2 : 0
1508
+ reasoningTokens
572
1509
  };
573
1510
  }
574
1511
  openrouterUsage.cost = value.usage.cost;
@@ -585,13 +1522,15 @@ var OpenRouterChatLanguageModel = class {
585
1522
  if (delta.content != null) {
586
1523
  controller.enqueue({
587
1524
  type: "text-delta",
588
- textDelta: delta.content
1525
+ delta: delta.content,
1526
+ id: generateId()
589
1527
  });
590
1528
  }
591
1529
  if (delta.reasoning != null) {
592
1530
  controller.enqueue({
593
- type: "reasoning",
594
- textDelta: delta.reasoning
1531
+ type: "reasoning-delta",
1532
+ delta: delta.reasoning,
1533
+ id: generateId()
595
1534
  });
596
1535
  }
597
1536
  if (delta.reasoning_details && delta.reasoning_details.length > 0) {
@@ -600,14 +1539,15 @@ var OpenRouterChatLanguageModel = class {
600
1539
  case "reasoning.text" /* Text */: {
601
1540
  if (detail.text) {
602
1541
  controller.enqueue({
603
- type: "reasoning",
604
- textDelta: detail.text
1542
+ type: "reasoning-delta",
1543
+ delta: detail.text,
1544
+ id: generateId()
605
1545
  });
606
1546
  }
607
1547
  if (detail.signature) {
608
1548
  controller.enqueue({
609
- type: "reasoning-signature",
610
- signature: detail.signature
1549
+ type: "reasoning-end",
1550
+ id: generateId()
611
1551
  });
612
1552
  }
613
1553
  break;
@@ -615,8 +1555,9 @@ var OpenRouterChatLanguageModel = class {
615
1555
  case "reasoning.encrypted" /* Encrypted */: {
616
1556
  if (detail.data) {
617
1557
  controller.enqueue({
618
- type: "redacted-reasoning",
619
- data: detail.data
1558
+ type: "reasoning-delta",
1559
+ delta: "[REDACTED]",
1560
+ id: generateId()
620
1561
  });
621
1562
  }
622
1563
  break;
@@ -624,8 +1565,9 @@ var OpenRouterChatLanguageModel = class {
624
1565
  case "reasoning.summary" /* Summary */: {
625
1566
  if (detail.summary) {
626
1567
  controller.enqueue({
627
- type: "reasoning",
628
- textDelta: detail.summary
1568
+ type: "reasoning-delta",
1569
+ delta: detail.summary,
1570
+ id: generateId()
629
1571
  });
630
1572
  }
631
1573
  break;
@@ -637,33 +1579,24 @@ var OpenRouterChatLanguageModel = class {
637
1579
  }
638
1580
  }
639
1581
  }
640
- const mappedLogprobs = mapOpenRouterChatLogProbsOutput(
641
- choice == null ? void 0 : choice.logprobs
642
- );
643
- if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
644
- if (logprobs === void 0) {
645
- logprobs = [];
646
- }
647
- logprobs.push(...mappedLogprobs);
648
- }
649
1582
  if (delta.tool_calls != null) {
650
1583
  for (const toolCallDelta of delta.tool_calls) {
651
- const index = toolCallDelta.index;
1584
+ const index = (_c = toolCallDelta.index) != null ? _c : toolCalls.length - 1;
652
1585
  if (toolCalls[index] == null) {
653
1586
  if (toolCallDelta.type !== "function") {
654
- throw new import_provider.InvalidResponseDataError({
1587
+ throw new InvalidResponseDataError({
655
1588
  data: toolCallDelta,
656
1589
  message: `Expected 'function' type.`
657
1590
  });
658
1591
  }
659
1592
  if (toolCallDelta.id == null) {
660
- throw new import_provider.InvalidResponseDataError({
1593
+ throw new InvalidResponseDataError({
661
1594
  data: toolCallDelta,
662
1595
  message: `Expected 'id' to be a string.`
663
1596
  });
664
1597
  }
665
- if (((_c2 = toolCallDelta.function) == null ? void 0 : _c2.name) == null) {
666
- throw new import_provider.InvalidResponseDataError({
1598
+ if (((_d = toolCallDelta.function) == null ? void 0 : _d.name) == null) {
1599
+ throw new InvalidResponseDataError({
667
1600
  data: toolCallDelta,
668
1601
  message: `Expected 'function.name' to be a string.`
669
1602
  });
@@ -673,7 +1606,7 @@ var OpenRouterChatLanguageModel = class {
673
1606
  type: "function",
674
1607
  function: {
675
1608
  name: toolCallDelta.function.name,
676
- arguments: (_d = toolCallDelta.function.arguments) != null ? _d : ""
1609
+ arguments: (_e = toolCallDelta.function.arguments) != null ? _e : ""
677
1610
  },
678
1611
  sent: false
679
1612
  };
@@ -681,20 +1614,26 @@ var OpenRouterChatLanguageModel = class {
681
1614
  if (toolCall2 == null) {
682
1615
  throw new Error("Tool call is missing");
683
1616
  }
684
- if (((_e = toolCall2.function) == null ? void 0 : _e.name) != null && ((_f = toolCall2.function) == null ? void 0 : _f.arguments) != null && (0, import_provider_utils3.isParsableJson)(toolCall2.function.arguments)) {
1617
+ if (((_f = toolCall2.function) == null ? void 0 : _f.name) != null && ((_g = toolCall2.function) == null ? void 0 : _g.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
685
1618
  controller.enqueue({
686
- type: "tool-call-delta",
687
- toolCallType: "function",
688
- toolCallId: toolCall2.id,
689
- toolName: toolCall2.function.name,
690
- argsTextDelta: toolCall2.function.arguments
1619
+ type: "tool-input-start",
1620
+ id: toolCall2.id,
1621
+ toolName: toolCall2.function.name
1622
+ });
1623
+ controller.enqueue({
1624
+ type: "tool-input-delta",
1625
+ id: toolCall2.id,
1626
+ delta: toolCall2.function.arguments
1627
+ });
1628
+ controller.enqueue({
1629
+ type: "tool-input-end",
1630
+ id: toolCall2.id
691
1631
  });
692
1632
  controller.enqueue({
693
1633
  type: "tool-call",
694
- toolCallType: "function",
695
- toolCallId: (_g = toolCall2.id) != null ? _g : (0, import_provider_utils3.generateId)(),
1634
+ toolCallId: toolCall2.id,
696
1635
  toolName: toolCall2.function.name,
697
- args: toolCall2.function.arguments
1636
+ input: toolCall2.function.arguments
698
1637
  });
699
1638
  toolCall2.sent = true;
700
1639
  }
@@ -704,23 +1643,27 @@ var OpenRouterChatLanguageModel = class {
704
1643
  if (toolCall == null) {
705
1644
  throw new Error("Tool call is missing");
706
1645
  }
707
- if (((_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null) {
708
- toolCall.function.arguments += (_j = (_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null ? _j : "";
1646
+ if (((_h = toolCallDelta.function) == null ? void 0 : _h.name) != null) {
1647
+ controller.enqueue({
1648
+ type: "tool-input-start",
1649
+ id: toolCall.id,
1650
+ toolName: toolCall.function.name
1651
+ });
1652
+ }
1653
+ if (((_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null) {
1654
+ toolCall.function.arguments += (_k = (_j = toolCallDelta.function) == null ? void 0 : _j.arguments) != null ? _k : "";
709
1655
  }
710
1656
  controller.enqueue({
711
- type: "tool-call-delta",
712
- toolCallType: "function",
713
- toolCallId: toolCall.id,
714
- toolName: toolCall.function.name,
715
- argsTextDelta: (_k = toolCallDelta.function.arguments) != null ? _k : ""
1657
+ type: "tool-input-delta",
1658
+ id: toolCall.id,
1659
+ delta: (_l = toolCallDelta.function.arguments) != null ? _l : ""
716
1660
  });
717
- if (((_l = toolCall.function) == null ? void 0 : _l.name) != null && ((_m = toolCall.function) == null ? void 0 : _m.arguments) != null && (0, import_provider_utils3.isParsableJson)(toolCall.function.arguments)) {
1661
+ if (((_m = toolCall.function) == null ? void 0 : _m.name) != null && ((_n = toolCall.function) == null ? void 0 : _n.arguments) != null && isParsableJson(toolCall.function.arguments)) {
718
1662
  controller.enqueue({
719
1663
  type: "tool-call",
720
- toolCallType: "function",
721
- toolCallId: (_n = toolCall.id) != null ? _n : (0, import_provider_utils3.generateId)(),
1664
+ toolCallId: (_o = toolCall.id) != null ? _o : generateId(),
722
1665
  toolName: toolCall.function.name,
723
- args: toolCall.function.arguments
1666
+ input: toolCall.function.arguments
724
1667
  });
725
1668
  toolCall.sent = true;
726
1669
  }
@@ -728,198 +1671,42 @@ var OpenRouterChatLanguageModel = class {
728
1671
  }
729
1672
  },
730
1673
  flush(controller) {
731
- var _a2;
1674
+ var _a16;
732
1675
  if (finishReason === "tool-calls") {
733
1676
  for (const toolCall of toolCalls) {
734
1677
  if (!toolCall.sent) {
735
1678
  controller.enqueue({
736
1679
  type: "tool-call",
737
- toolCallType: "function",
738
- toolCallId: (_a2 = toolCall.id) != null ? _a2 : (0, import_provider_utils3.generateId)(),
1680
+ toolCallId: (_a16 = toolCall.id) != null ? _a16 : generateId(),
739
1681
  toolName: toolCall.function.name,
740
1682
  // Coerce invalid arguments to an empty JSON object
741
- args: (0, import_provider_utils3.isParsableJson)(toolCall.function.arguments) ? toolCall.function.arguments : "{}"
1683
+ input: isParsableJson(toolCall.function.arguments) ? toolCall.function.arguments : "{}"
742
1684
  });
743
1685
  toolCall.sent = true;
744
1686
  }
745
1687
  }
746
1688
  }
747
- const providerMetadata = {};
748
- if (shouldIncludeUsageAccounting && (openrouterUsage.totalTokens !== void 0 || openrouterUsage.cost !== void 0 || openrouterUsage.promptTokensDetails !== void 0 || openrouterUsage.completionTokensDetails !== void 0)) {
749
- providerMetadata.openrouter = {
750
- usage: openrouterUsage
751
- };
752
- }
753
- const hasProviderMetadata = Object.keys(providerMetadata).length > 0 && shouldIncludeUsageAccounting;
754
- controller.enqueue(__spreadValues({
1689
+ controller.enqueue({
755
1690
  type: "finish",
756
1691
  finishReason,
757
- logprobs,
758
- usage
759
- }, hasProviderMetadata ? { providerMetadata } : {}));
1692
+ usage,
1693
+ providerMetadata: {
1694
+ openrouter: {
1695
+ usage: openrouterUsage
1696
+ }
1697
+ }
1698
+ });
760
1699
  }
761
1700
  })
762
1701
  ),
763
- rawCall: { rawPrompt, rawSettings },
764
- rawResponse: { headers: responseHeaders },
765
- warnings: []
1702
+ warnings: [],
1703
+ request: { body: args },
1704
+ response: { headers: responseHeaders }
766
1705
  };
767
1706
  }
768
1707
  };
769
- var OpenRouterChatCompletionBaseResponseSchema = import_zod3.z.object({
770
- id: import_zod3.z.string().optional(),
771
- model: import_zod3.z.string().optional(),
772
- usage: import_zod3.z.object({
773
- prompt_tokens: import_zod3.z.number(),
774
- prompt_tokens_details: import_zod3.z.object({
775
- cached_tokens: import_zod3.z.number()
776
- }).nullish(),
777
- completion_tokens: import_zod3.z.number(),
778
- completion_tokens_details: import_zod3.z.object({
779
- reasoning_tokens: import_zod3.z.number()
780
- }).nullish(),
781
- total_tokens: import_zod3.z.number(),
782
- cost: import_zod3.z.number().optional()
783
- }).nullish()
784
- });
785
- var OpenRouterNonStreamChatCompletionResponseSchema = OpenRouterChatCompletionBaseResponseSchema.extend({
786
- choices: import_zod3.z.array(
787
- import_zod3.z.object({
788
- message: import_zod3.z.object({
789
- role: import_zod3.z.literal("assistant"),
790
- content: import_zod3.z.string().nullable().optional(),
791
- reasoning: import_zod3.z.string().nullable().optional(),
792
- reasoning_details: ReasoningDetailArraySchema.nullish(),
793
- tool_calls: import_zod3.z.array(
794
- import_zod3.z.object({
795
- id: import_zod3.z.string().optional().nullable(),
796
- type: import_zod3.z.literal("function"),
797
- function: import_zod3.z.object({
798
- name: import_zod3.z.string(),
799
- arguments: import_zod3.z.string()
800
- })
801
- })
802
- ).optional()
803
- }),
804
- index: import_zod3.z.number(),
805
- logprobs: import_zod3.z.object({
806
- content: import_zod3.z.array(
807
- import_zod3.z.object({
808
- token: import_zod3.z.string(),
809
- logprob: import_zod3.z.number(),
810
- top_logprobs: import_zod3.z.array(
811
- import_zod3.z.object({
812
- token: import_zod3.z.string(),
813
- logprob: import_zod3.z.number()
814
- })
815
- )
816
- })
817
- ).nullable()
818
- }).nullable().optional(),
819
- finish_reason: import_zod3.z.string().optional().nullable()
820
- })
821
- )
822
- });
823
- var OpenRouterStreamChatCompletionChunkSchema = import_zod3.z.union([
824
- OpenRouterChatCompletionBaseResponseSchema.extend({
825
- choices: import_zod3.z.array(
826
- import_zod3.z.object({
827
- delta: import_zod3.z.object({
828
- role: import_zod3.z.enum(["assistant"]).optional(),
829
- content: import_zod3.z.string().nullish(),
830
- reasoning: import_zod3.z.string().nullish().optional(),
831
- reasoning_details: ReasoningDetailArraySchema.nullish(),
832
- tool_calls: import_zod3.z.array(
833
- import_zod3.z.object({
834
- index: import_zod3.z.number(),
835
- id: import_zod3.z.string().nullish(),
836
- type: import_zod3.z.literal("function").optional(),
837
- function: import_zod3.z.object({
838
- name: import_zod3.z.string().nullish(),
839
- arguments: import_zod3.z.string().nullish()
840
- })
841
- })
842
- ).nullish()
843
- }).nullish(),
844
- logprobs: import_zod3.z.object({
845
- content: import_zod3.z.array(
846
- import_zod3.z.object({
847
- token: import_zod3.z.string(),
848
- logprob: import_zod3.z.number(),
849
- top_logprobs: import_zod3.z.array(
850
- import_zod3.z.object({
851
- token: import_zod3.z.string(),
852
- logprob: import_zod3.z.number()
853
- })
854
- )
855
- })
856
- ).nullable()
857
- }).nullish(),
858
- finish_reason: import_zod3.z.string().nullable().optional(),
859
- index: import_zod3.z.number()
860
- })
861
- )
862
- }),
863
- OpenRouterErrorResponseSchema
864
- ]);
865
- function prepareToolsAndToolChoice(mode) {
866
- var _a;
867
- const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
868
- if (tools == null) {
869
- return { tools: void 0, tool_choice: void 0 };
870
- }
871
- const mappedTools = tools.map((tool) => {
872
- if (isFunctionTool(tool)) {
873
- return {
874
- type: "function",
875
- function: {
876
- name: tool.name,
877
- description: tool.description,
878
- parameters: tool.parameters
879
- }
880
- };
881
- }
882
- return {
883
- type: "function",
884
- function: {
885
- name: tool.name
886
- }
887
- };
888
- });
889
- const toolChoice = mode.toolChoice;
890
- if (toolChoice == null) {
891
- return { tools: mappedTools, tool_choice: void 0 };
892
- }
893
- const type = toolChoice.type;
894
- switch (type) {
895
- case "auto":
896
- case "none":
897
- case "required":
898
- return { tools: mappedTools, tool_choice: type };
899
- case "tool":
900
- return {
901
- tools: mappedTools,
902
- tool_choice: {
903
- type: "function",
904
- function: {
905
- name: toolChoice.toolName
906
- }
907
- }
908
- };
909
- default: {
910
- const _exhaustiveCheck = type;
911
- throw new Error(`Unsupported tool choice type: ${_exhaustiveCheck}`);
912
- }
913
- }
914
- }
915
-
916
- // src/openrouter-completion-language-model.ts
917
- var import_provider3 = require("@ai-sdk/provider");
918
- var import_provider_utils4 = require("@ai-sdk/provider-utils");
919
- var import_zod4 = require("zod");
920
1708
 
921
- // src/convert-to-openrouter-completion-prompt.ts
922
- var import_provider2 = require("@ai-sdk/provider");
1709
+ // src/completion/convert-to-openrouter-completion-prompt.ts
923
1710
  function convertToOpenRouterCompletionPrompt({
924
1711
  prompt,
925
1712
  inputFormat,
@@ -939,8 +1726,8 @@ function convertToOpenRouterCompletionPrompt({
939
1726
  for (const { role, content } of prompt) {
940
1727
  switch (role) {
941
1728
  case "system": {
942
- throw new import_provider2.InvalidPromptError({
943
- message: "Unexpected system message in prompt: ${content}",
1729
+ throw new InvalidPromptError({
1730
+ message: `Unexpected system message in prompt: ${content}`,
944
1731
  prompt
945
1732
  });
946
1733
  }
@@ -950,21 +1737,13 @@ function convertToOpenRouterCompletionPrompt({
950
1737
  case "text": {
951
1738
  return part.text;
952
1739
  }
953
- case "image": {
954
- throw new import_provider2.UnsupportedFunctionalityError({
955
- functionality: "images"
956
- });
957
- }
958
1740
  case "file": {
959
- throw new import_provider2.UnsupportedFunctionalityError({
1741
+ throw new UnsupportedFunctionalityError({
960
1742
  functionality: "file attachments"
961
1743
  });
962
1744
  }
963
1745
  default: {
964
- const _exhaustiveCheck = part;
965
- throw new Error(
966
- `Unsupported content type: ${_exhaustiveCheck}`
967
- );
1746
+ return "";
968
1747
  }
969
1748
  }
970
1749
  }).join("");
@@ -975,39 +1754,38 @@ ${userMessage}
975
1754
  break;
976
1755
  }
977
1756
  case "assistant": {
978
- const assistantMessage = content.map((part) => {
979
- switch (part.type) {
980
- case "text": {
981
- return part.text;
982
- }
983
- case "tool-call": {
984
- throw new import_provider2.UnsupportedFunctionalityError({
985
- functionality: "tool-call messages"
986
- });
987
- }
988
- case "reasoning": {
989
- throw new import_provider2.UnsupportedFunctionalityError({
990
- functionality: "reasoning messages"
991
- });
992
- }
993
- case "redacted-reasoning": {
994
- throw new import_provider2.UnsupportedFunctionalityError({
995
- functionality: "redacted reasoning messages"
996
- });
997
- }
998
- case "file": {
999
- throw new import_provider2.UnsupportedFunctionalityError({
1000
- functionality: "file attachments"
1001
- });
1002
- }
1003
- default: {
1004
- const _exhaustiveCheck = part;
1005
- throw new Error(
1006
- `Unsupported content type: ${_exhaustiveCheck}`
1007
- );
1757
+ const assistantMessage = content.map(
1758
+ (part) => {
1759
+ switch (part.type) {
1760
+ case "text": {
1761
+ return part.text;
1762
+ }
1763
+ case "tool-call": {
1764
+ throw new UnsupportedFunctionalityError({
1765
+ functionality: "tool-call messages"
1766
+ });
1767
+ }
1768
+ case "tool-result": {
1769
+ throw new UnsupportedFunctionalityError({
1770
+ functionality: "tool-result messages"
1771
+ });
1772
+ }
1773
+ case "reasoning": {
1774
+ throw new UnsupportedFunctionalityError({
1775
+ functionality: "reasoning messages"
1776
+ });
1777
+ }
1778
+ case "file": {
1779
+ throw new UnsupportedFunctionalityError({
1780
+ functionality: "file attachments"
1781
+ });
1782
+ }
1783
+ default: {
1784
+ return "";
1785
+ }
1008
1786
  }
1009
1787
  }
1010
- }).join("");
1788
+ ).join("");
1011
1789
  text += `${assistant}:
1012
1790
  ${assistantMessage}
1013
1791
 
@@ -1015,13 +1793,12 @@ ${assistantMessage}
1015
1793
  break;
1016
1794
  }
1017
1795
  case "tool": {
1018
- throw new import_provider2.UnsupportedFunctionalityError({
1796
+ throw new UnsupportedFunctionalityError({
1019
1797
  functionality: "tool messages"
1020
1798
  });
1021
1799
  }
1022
1800
  default: {
1023
- const _exhaustiveCheck = role;
1024
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
1801
+ break;
1025
1802
  }
1026
1803
  }
1027
1804
  }
@@ -1032,40 +1809,63 @@ ${assistantMessage}
1032
1809
  };
1033
1810
  }
1034
1811
 
1035
- // src/map-openrouter-completion-logprobs.ts
1036
- function mapOpenRouterCompletionLogProbs(logprobs) {
1037
- return logprobs == null ? void 0 : logprobs.tokens.map((token, index) => {
1038
- var _a, _b;
1039
- return {
1040
- token,
1041
- logprob: (_a = logprobs.token_logprobs[index]) != null ? _a : 0,
1042
- topLogprobs: logprobs.top_logprobs ? Object.entries((_b = logprobs.top_logprobs[index]) != null ? _b : {}).map(
1043
- ([token2, logprob]) => ({
1044
- token: token2,
1045
- logprob
1046
- })
1047
- ) : []
1048
- };
1049
- });
1050
- }
1812
+ // src/completion/schemas.ts
1813
+ var import_v45 = require("zod/v4");
1814
+ var OpenRouterCompletionChunkSchema = import_v45.z.union([
1815
+ import_v45.z.object({
1816
+ id: import_v45.z.string().optional(),
1817
+ model: import_v45.z.string().optional(),
1818
+ choices: import_v45.z.array(
1819
+ import_v45.z.object({
1820
+ text: import_v45.z.string(),
1821
+ reasoning: import_v45.z.string().nullish().optional(),
1822
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
1823
+ finish_reason: import_v45.z.string().nullish(),
1824
+ index: import_v45.z.number().nullish(),
1825
+ logprobs: import_v45.z.object({
1826
+ tokens: import_v45.z.array(import_v45.z.string()),
1827
+ token_logprobs: import_v45.z.array(import_v45.z.number()),
1828
+ top_logprobs: import_v45.z.array(import_v45.z.record(import_v45.z.string(), import_v45.z.number())).nullable()
1829
+ }).nullable().optional()
1830
+ })
1831
+ ),
1832
+ usage: import_v45.z.object({
1833
+ prompt_tokens: import_v45.z.number(),
1834
+ prompt_tokens_details: import_v45.z.object({
1835
+ cached_tokens: import_v45.z.number()
1836
+ }).nullish(),
1837
+ completion_tokens: import_v45.z.number(),
1838
+ completion_tokens_details: import_v45.z.object({
1839
+ reasoning_tokens: import_v45.z.number()
1840
+ }).nullish(),
1841
+ total_tokens: import_v45.z.number(),
1842
+ cost: import_v45.z.number().optional()
1843
+ }).nullish()
1844
+ }),
1845
+ OpenRouterErrorResponseSchema
1846
+ ]);
1051
1847
 
1052
- // src/openrouter-completion-language-model.ts
1848
+ // src/completion/index.ts
1053
1849
  var OpenRouterCompletionLanguageModel = class {
1054
1850
  constructor(modelId, settings, config) {
1055
- this.specificationVersion = "v1";
1851
+ this.specificationVersion = "v2";
1852
+ this.provider = "openrouter";
1853
+ this.supportedUrls = {
1854
+ "image/*": [
1855
+ /^data:image\/[a-zA-Z]+;base64,/,
1856
+ /^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i
1857
+ ],
1858
+ "text/*": [/^data:text\//, /^https?:\/\/.+$/],
1859
+ "application/*": [/^data:application\//, /^https?:\/\/.+$/]
1860
+ };
1056
1861
  this.defaultObjectGenerationMode = void 0;
1057
1862
  this.modelId = modelId;
1058
1863
  this.settings = settings;
1059
1864
  this.config = config;
1060
1865
  }
1061
- get provider() {
1062
- return this.config.provider;
1063
- }
1064
1866
  getArgs({
1065
- mode,
1066
- inputFormat,
1067
1867
  prompt,
1068
- maxTokens,
1868
+ maxOutputTokens,
1069
1869
  temperature,
1070
1870
  topP,
1071
1871
  frequencyPenalty,
@@ -1074,16 +1874,24 @@ var OpenRouterCompletionLanguageModel = class {
1074
1874
  responseFormat,
1075
1875
  topK,
1076
1876
  stopSequences,
1077
- providerMetadata
1877
+ tools,
1878
+ toolChoice
1078
1879
  }) {
1079
- var _a, _b;
1080
- const type = mode.type;
1081
- const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata.openrouter) != null ? _a : {};
1082
1880
  const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({
1083
1881
  prompt,
1084
- inputFormat
1882
+ inputFormat: "prompt"
1085
1883
  });
1086
- const baseArgs = __spreadValues(__spreadValues(__spreadValues({
1884
+ if (tools == null ? void 0 : tools.length) {
1885
+ throw new UnsupportedFunctionalityError({
1886
+ functionality: "tools"
1887
+ });
1888
+ }
1889
+ if (toolChoice) {
1890
+ throw new UnsupportedFunctionalityError({
1891
+ functionality: "toolChoice"
1892
+ });
1893
+ }
1894
+ return __spreadValues(__spreadValues({
1087
1895
  // model id:
1088
1896
  model: this.modelId,
1089
1897
  models: this.settings.models,
@@ -1093,7 +1901,7 @@ var OpenRouterCompletionLanguageModel = class {
1093
1901
  suffix: this.settings.suffix,
1094
1902
  user: this.settings.user,
1095
1903
  // standardized settings:
1096
- max_tokens: maxTokens,
1904
+ max_tokens: maxOutputTokens,
1097
1905
  temperature,
1098
1906
  top_p: topP,
1099
1907
  frequency_penalty: frequencyPenalty,
@@ -1107,58 +1915,27 @@ var OpenRouterCompletionLanguageModel = class {
1107
1915
  // OpenRouter specific settings:
1108
1916
  include_reasoning: this.settings.includeReasoning,
1109
1917
  reasoning: this.settings.reasoning
1110
- }, this.config.extraBody), this.settings.extraBody), extraCallingBody);
1111
- switch (type) {
1112
- case "regular": {
1113
- if ((_b = mode.tools) == null ? void 0 : _b.length) {
1114
- throw new import_provider3.UnsupportedFunctionalityError({
1115
- functionality: "tools"
1116
- });
1117
- }
1118
- if (mode.toolChoice) {
1119
- throw new import_provider3.UnsupportedFunctionalityError({
1120
- functionality: "toolChoice"
1121
- });
1122
- }
1123
- return baseArgs;
1124
- }
1125
- case "object-json": {
1126
- throw new import_provider3.UnsupportedFunctionalityError({
1127
- functionality: "object-json mode"
1128
- });
1129
- }
1130
- case "object-tool": {
1131
- throw new import_provider3.UnsupportedFunctionalityError({
1132
- functionality: "object-tool mode"
1133
- });
1134
- }
1135
- // Handle all non-text types with a single default case
1136
- default: {
1137
- const _exhaustiveCheck = type;
1138
- throw new import_provider3.UnsupportedFunctionalityError({
1139
- functionality: `${_exhaustiveCheck} mode`
1140
- });
1141
- }
1142
- }
1918
+ }, this.config.extraBody), this.settings.extraBody);
1143
1919
  }
1144
1920
  async doGenerate(options) {
1145
- var _b, _c, _d, _e, _f;
1146
- const args = this.getArgs(options);
1147
- const { responseHeaders, value: response } = await (0, import_provider_utils4.postJsonToApi)({
1921
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
1922
+ const providerOptions = options.providerOptions || {};
1923
+ const openrouterOptions = providerOptions.openrouter || {};
1924
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
1925
+ const { value: response, responseHeaders } = await postJsonToApi({
1148
1926
  url: this.config.url({
1149
1927
  path: "/completions",
1150
1928
  modelId: this.modelId
1151
1929
  }),
1152
- headers: (0, import_provider_utils4.combineHeaders)(this.config.headers(), options.headers),
1930
+ headers: combineHeaders(this.config.headers(), options.headers),
1153
1931
  body: args,
1154
1932
  failedResponseHandler: openrouterFailedResponseHandler,
1155
- successfulResponseHandler: (0, import_provider_utils4.createJsonResponseHandler)(
1933
+ successfulResponseHandler: createJsonResponseHandler(
1156
1934
  OpenRouterCompletionChunkSchema
1157
1935
  ),
1158
1936
  abortSignal: options.abortSignal,
1159
1937
  fetch: this.config.fetch
1160
1938
  });
1161
- const _a = args, { prompt: rawPrompt } = _a, rawSettings = __objRest(_a, ["prompt"]);
1162
1939
  if ("error" in response) {
1163
1940
  throw new Error(`${response.error.message}`);
1164
1941
  }
@@ -1167,54 +1944,62 @@ var OpenRouterCompletionLanguageModel = class {
1167
1944
  throw new Error("No choice in OpenRouter completion response");
1168
1945
  }
1169
1946
  return {
1170
- response: {
1171
- id: response.id,
1172
- modelId: response.model
1173
- },
1174
- text: (_b = choice.text) != null ? _b : "",
1175
- reasoning: choice.reasoning || void 0,
1947
+ content: [
1948
+ {
1949
+ type: "text",
1950
+ text: (_a15 = choice.text) != null ? _a15 : ""
1951
+ }
1952
+ ],
1953
+ finishReason: mapOpenRouterFinishReason(choice.finish_reason),
1176
1954
  usage: {
1177
- promptTokens: (_d = (_c = response.usage) == null ? void 0 : _c.prompt_tokens) != null ? _d : 0,
1178
- completionTokens: (_f = (_e = response.usage) == null ? void 0 : _e.completion_tokens) != null ? _f : 0
1955
+ inputTokens: (_c = (_b = response.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : 0,
1956
+ outputTokens: (_e = (_d = response.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : 0,
1957
+ totalTokens: ((_g = (_f = response.usage) == null ? void 0 : _f.prompt_tokens) != null ? _g : 0) + ((_i = (_h = response.usage) == null ? void 0 : _h.completion_tokens) != null ? _i : 0),
1958
+ reasoningTokens: (_l = (_k = (_j = response.usage) == null ? void 0 : _j.completion_tokens_details) == null ? void 0 : _k.reasoning_tokens) != null ? _l : 0,
1959
+ cachedInputTokens: (_o = (_n = (_m = response.usage) == null ? void 0 : _m.prompt_tokens_details) == null ? void 0 : _n.cached_tokens) != null ? _o : 0
1179
1960
  },
1180
- finishReason: mapOpenRouterFinishReason(choice.finish_reason),
1181
- logprobs: mapOpenRouterCompletionLogProbs(choice.logprobs),
1182
- rawCall: { rawPrompt, rawSettings },
1183
- rawResponse: { headers: responseHeaders },
1184
- warnings: []
1961
+ warnings: [],
1962
+ response: {
1963
+ headers: responseHeaders
1964
+ }
1185
1965
  };
1186
1966
  }
1187
1967
  async doStream(options) {
1188
- const args = this.getArgs(options);
1189
- const { responseHeaders, value: response } = await (0, import_provider_utils4.postJsonToApi)({
1968
+ const providerOptions = options.providerOptions || {};
1969
+ const openrouterOptions = providerOptions.openrouter || {};
1970
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
1971
+ const { value: response, responseHeaders } = await postJsonToApi({
1190
1972
  url: this.config.url({
1191
1973
  path: "/completions",
1192
1974
  modelId: this.modelId
1193
1975
  }),
1194
- headers: (0, import_provider_utils4.combineHeaders)(this.config.headers(), options.headers),
1195
- body: __spreadProps(__spreadValues({}, this.getArgs(options)), {
1976
+ headers: combineHeaders(this.config.headers(), options.headers),
1977
+ body: __spreadProps(__spreadValues({}, args), {
1196
1978
  stream: true,
1197
1979
  // only include stream_options when in strict compatibility mode:
1198
1980
  stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
1199
1981
  }),
1200
1982
  failedResponseHandler: openrouterFailedResponseHandler,
1201
- successfulResponseHandler: (0, import_provider_utils4.createEventSourceResponseHandler)(
1983
+ successfulResponseHandler: createEventSourceResponseHandler(
1202
1984
  OpenRouterCompletionChunkSchema
1203
1985
  ),
1204
1986
  abortSignal: options.abortSignal,
1205
1987
  fetch: this.config.fetch
1206
1988
  });
1207
- const _a = args, { prompt: rawPrompt } = _a, rawSettings = __objRest(_a, ["prompt"]);
1208
1989
  let finishReason = "other";
1209
- let usage = {
1210
- promptTokens: Number.NaN,
1211
- completionTokens: Number.NaN
1990
+ const usage = {
1991
+ inputTokens: Number.NaN,
1992
+ outputTokens: Number.NaN,
1993
+ totalTokens: Number.NaN,
1994
+ reasoningTokens: Number.NaN,
1995
+ cachedInputTokens: Number.NaN
1212
1996
  };
1213
- let logprobs;
1997
+ const openrouterUsage = {};
1214
1998
  return {
1215
1999
  stream: response.pipeThrough(
1216
2000
  new TransformStream({
1217
2001
  transform(chunk, controller) {
2002
+ var _a15, _b;
1218
2003
  if (!chunk.success) {
1219
2004
  finishReason = "error";
1220
2005
  controller.enqueue({ type: "error", error: chunk.error });
@@ -1227,10 +2012,27 @@ var OpenRouterCompletionLanguageModel = class {
1227
2012
  return;
1228
2013
  }
1229
2014
  if (value.usage != null) {
1230
- usage = {
1231
- promptTokens: value.usage.prompt_tokens,
1232
- completionTokens: value.usage.completion_tokens
1233
- };
2015
+ usage.inputTokens = value.usage.prompt_tokens;
2016
+ usage.outputTokens = value.usage.completion_tokens;
2017
+ usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
2018
+ openrouterUsage.promptTokens = value.usage.prompt_tokens;
2019
+ if (value.usage.prompt_tokens_details) {
2020
+ const cachedInputTokens = (_a15 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a15 : 0;
2021
+ usage.cachedInputTokens = cachedInputTokens;
2022
+ openrouterUsage.promptTokensDetails = {
2023
+ cachedTokens: cachedInputTokens
2024
+ };
2025
+ }
2026
+ openrouterUsage.completionTokens = value.usage.completion_tokens;
2027
+ if (value.usage.completion_tokens_details) {
2028
+ const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
2029
+ usage.reasoningTokens = reasoningTokens;
2030
+ openrouterUsage.completionTokensDetails = {
2031
+ reasoningTokens
2032
+ };
2033
+ }
2034
+ openrouterUsage.cost = value.usage.cost;
2035
+ openrouterUsage.totalTokens = value.usage.total_tokens;
1234
2036
  }
1235
2037
  const choice = value.choices[0];
1236
2038
  if ((choice == null ? void 0 : choice.finish_reason) != null) {
@@ -1239,60 +2041,31 @@ var OpenRouterCompletionLanguageModel = class {
1239
2041
  if ((choice == null ? void 0 : choice.text) != null) {
1240
2042
  controller.enqueue({
1241
2043
  type: "text-delta",
1242
- textDelta: choice.text
2044
+ delta: choice.text,
2045
+ id: generateId()
1243
2046
  });
1244
2047
  }
1245
- const mappedLogprobs = mapOpenRouterCompletionLogProbs(
1246
- choice == null ? void 0 : choice.logprobs
1247
- );
1248
- if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
1249
- if (logprobs === void 0) {
1250
- logprobs = [];
1251
- }
1252
- logprobs.push(...mappedLogprobs);
1253
- }
1254
2048
  },
1255
2049
  flush(controller) {
1256
2050
  controller.enqueue({
1257
2051
  type: "finish",
1258
2052
  finishReason,
1259
- logprobs,
1260
- usage
2053
+ usage,
2054
+ providerMetadata: {
2055
+ openrouter: {
2056
+ usage: openrouterUsage
2057
+ }
2058
+ }
1261
2059
  });
1262
2060
  }
1263
2061
  })
1264
2062
  ),
1265
- rawCall: { rawPrompt, rawSettings },
1266
- rawResponse: { headers: responseHeaders },
1267
- warnings: []
2063
+ response: {
2064
+ headers: responseHeaders
2065
+ }
1268
2066
  };
1269
2067
  }
1270
2068
  };
1271
- var OpenRouterCompletionChunkSchema = import_zod4.z.union([
1272
- import_zod4.z.object({
1273
- id: import_zod4.z.string().optional(),
1274
- model: import_zod4.z.string().optional(),
1275
- choices: import_zod4.z.array(
1276
- import_zod4.z.object({
1277
- text: import_zod4.z.string(),
1278
- reasoning: import_zod4.z.string().nullish().optional(),
1279
- reasoning_details: ReasoningDetailArraySchema.nullish(),
1280
- finish_reason: import_zod4.z.string().nullish(),
1281
- index: import_zod4.z.number(),
1282
- logprobs: import_zod4.z.object({
1283
- tokens: import_zod4.z.array(import_zod4.z.string()),
1284
- token_logprobs: import_zod4.z.array(import_zod4.z.number()),
1285
- top_logprobs: import_zod4.z.array(import_zod4.z.record(import_zod4.z.string(), import_zod4.z.number())).nullable()
1286
- }).nullable().optional()
1287
- })
1288
- ),
1289
- usage: import_zod4.z.object({
1290
- prompt_tokens: import_zod4.z.number(),
1291
- completion_tokens: import_zod4.z.number()
1292
- }).optional().nullable()
1293
- }),
1294
- OpenRouterErrorResponseSchema
1295
- ]);
1296
2069
  // Annotate the CommonJS export names for ESM import in node:
1297
2070
  0 && (module.exports = {
1298
2071
  OpenRouterChatLanguageModel,