@mastra/fastembed 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/LICENSE-fastembed +21 -0
  3. package/README.md +26 -17
  4. package/dist/_types/@internal_ai-sdk-v5/dist/index.d.ts +466 -1768
  5. package/dist/fastembed.d.ts +115 -0
  6. package/dist/fastembed.d.ts.map +1 -0
  7. package/dist/index.cjs +1801 -691
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.ts +3 -1
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +1790 -690
  12. package/dist/index.js.map +1 -1
  13. package/package.json +22 -15
  14. package/LICENSE.md +0 -30
  15. package/dist/chunk-23EXJLET.cjs +0 -84
  16. package/dist/chunk-23EXJLET.cjs.map +0 -1
  17. package/dist/chunk-BSDWQEU3.js +0 -79
  18. package/dist/chunk-BSDWQEU3.js.map +0 -1
  19. package/dist/chunk-DGUM43GV.js +0 -10
  20. package/dist/chunk-DGUM43GV.js.map +0 -1
  21. package/dist/chunk-EQ4M72KU.js +0 -439
  22. package/dist/chunk-EQ4M72KU.js.map +0 -1
  23. package/dist/chunk-HJYHDIOC.js +0 -250
  24. package/dist/chunk-HJYHDIOC.js.map +0 -1
  25. package/dist/chunk-IDRQZVB4.cjs +0 -84
  26. package/dist/chunk-IDRQZVB4.cjs.map +0 -1
  27. package/dist/chunk-JEQ2X3Z6.cjs +0 -12
  28. package/dist/chunk-JEQ2X3Z6.cjs.map +0 -1
  29. package/dist/chunk-LIBOSOHM.cjs +0 -252
  30. package/dist/chunk-LIBOSOHM.cjs.map +0 -1
  31. package/dist/chunk-RC6RZVYE.js +0 -79
  32. package/dist/chunk-RC6RZVYE.js.map +0 -1
  33. package/dist/chunk-ZD3BKU5O.cjs +0 -441
  34. package/dist/chunk-ZD3BKU5O.cjs.map +0 -1
  35. package/dist/token-6GSAFR2W-ABXTQD64.js +0 -61
  36. package/dist/token-6GSAFR2W-ABXTQD64.js.map +0 -1
  37. package/dist/token-6GSAFR2W-TW2P7HCS.cjs +0 -63
  38. package/dist/token-6GSAFR2W-TW2P7HCS.cjs.map +0 -1
  39. package/dist/token-APYSY3BW-2DN6RAUY.js +0 -61
  40. package/dist/token-APYSY3BW-2DN6RAUY.js.map +0 -1
  41. package/dist/token-APYSY3BW-ZQ7TMBY7.cjs +0 -63
  42. package/dist/token-APYSY3BW-ZQ7TMBY7.cjs.map +0 -1
  43. package/dist/token-util-NEHG7TUY-GYFEVMWP.cjs +0 -10
  44. package/dist/token-util-NEHG7TUY-GYFEVMWP.cjs.map +0 -1
  45. package/dist/token-util-NEHG7TUY-XQP3QSPX.js +0 -8
  46. package/dist/token-util-NEHG7TUY-XQP3QSPX.js.map +0 -1
  47. package/dist/token-util-RMHT2CPJ-6TGPE335.cjs +0 -10
  48. package/dist/token-util-RMHT2CPJ-6TGPE335.cjs.map +0 -1
  49. package/dist/token-util-RMHT2CPJ-RJEA3FAN.js +0 -8
  50. package/dist/token-util-RMHT2CPJ-RJEA3FAN.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,14 +1,18 @@
1
1
  'use strict';
2
2
 
3
- var chunk23EXJLET_cjs = require('./chunk-23EXJLET.cjs');
4
- var chunkIDRQZVB4_cjs = require('./chunk-IDRQZVB4.cjs');
5
3
  var fsp = require('fs/promises');
6
4
  var os = require('os');
7
5
  var path = require('path');
8
6
  var z4 = require('zod/v4');
9
7
  var v3 = require('zod/v3');
10
8
  var zod = require('zod');
11
- var fastembed$1 = require('fastembed');
9
+ var tokenizers = require('@anush008/tokenizers');
10
+ var fs = require('fs');
11
+ var https = require('https');
12
+ var ort = require('onnxruntime-node');
13
+ var Progress = require('progress');
14
+ var tar = require('tar');
15
+ var hub = require('@huggingface/hub');
12
16
 
13
17
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
18
 
@@ -34,11 +38,18 @@ var fsp__default = /*#__PURE__*/_interopDefault(fsp);
34
38
  var os__default = /*#__PURE__*/_interopDefault(os);
35
39
  var path__default = /*#__PURE__*/_interopDefault(path);
36
40
  var z4__namespace = /*#__PURE__*/_interopNamespace(z4);
41
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
42
+ var https__default = /*#__PURE__*/_interopDefault(https);
43
+ var ort__namespace = /*#__PURE__*/_interopNamespace(ort);
44
+ var Progress__default = /*#__PURE__*/_interopDefault(Progress);
45
+ var tar__namespace = /*#__PURE__*/_interopNamespace(tar);
37
46
 
47
+ // src/index.ts
38
48
  var marker = "vercel.ai.error";
39
49
  var symbol = Symbol.for(marker);
40
50
  var _a;
41
- var _AISDKError = class _AISDKError2 extends Error {
51
+ var _b;
52
+ var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
42
53
  /**
43
54
  * Creates an AI SDK Error.
44
55
  *
@@ -48,13 +59,13 @@ var _AISDKError = class _AISDKError2 extends Error {
48
59
  * @param {unknown} [params.cause] - The underlying cause of the error.
49
60
  */
50
61
  constructor({
51
- name: name146,
62
+ name: name1422,
52
63
  message,
53
64
  cause
54
65
  }) {
55
66
  super(message);
56
67
  this[_a] = true;
57
- this.name = name146;
68
+ this.name = name1422;
58
69
  this.cause = cause;
59
70
  }
60
71
  /**
@@ -63,20 +74,19 @@ var _AISDKError = class _AISDKError2 extends Error {
63
74
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
64
75
  */
65
76
  static isInstance(error) {
66
- return _AISDKError2.hasMarker(error, marker);
77
+ return _AISDKError.hasMarker(error, marker);
67
78
  }
68
- static hasMarker(error, marker156) {
69
- const markerSymbol = Symbol.for(marker156);
79
+ static hasMarker(error, marker1522) {
80
+ const markerSymbol = Symbol.for(marker1522);
70
81
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
71
82
  }
72
83
  };
73
- _a = symbol;
74
- var AISDKError = _AISDKError;
75
84
  var name = "AI_APICallError";
76
85
  var marker2 = `vercel.ai.error.${name}`;
77
86
  var symbol2 = Symbol.for(marker2);
78
87
  var _a2;
79
- var APICallError = class extends AISDKError {
88
+ var _b2;
89
+ var APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {
80
90
  constructor({
81
91
  message,
82
92
  url,
@@ -106,12 +116,12 @@ var APICallError = class extends AISDKError {
106
116
  return AISDKError.hasMarker(error, marker2);
107
117
  }
108
118
  };
109
- _a2 = symbol2;
110
119
  var name2 = "AI_EmptyResponseBodyError";
111
120
  var marker3 = `vercel.ai.error.${name2}`;
112
121
  var symbol3 = Symbol.for(marker3);
113
122
  var _a3;
114
- var EmptyResponseBodyError = class extends AISDKError {
123
+ var _b3;
124
+ var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {
115
125
  // used in isInstance
116
126
  constructor({ message = "Empty response body" } = {}) {
117
127
  super({ name: name2, message });
@@ -121,7 +131,6 @@ var EmptyResponseBodyError = class extends AISDKError {
121
131
  return AISDKError.hasMarker(error, marker3);
122
132
  }
123
133
  };
124
- _a3 = symbol3;
125
134
  function getErrorMessage(error) {
126
135
  if (error == null) {
127
136
  return "unknown error";
@@ -138,7 +147,8 @@ var name3 = "AI_InvalidArgumentError";
138
147
  var marker4 = `vercel.ai.error.${name3}`;
139
148
  var symbol4 = Symbol.for(marker4);
140
149
  var _a4;
141
- var InvalidArgumentError = class extends AISDKError {
150
+ var _b4;
151
+ var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {
142
152
  constructor({
143
153
  message,
144
154
  cause,
@@ -152,12 +162,12 @@ var InvalidArgumentError = class extends AISDKError {
152
162
  return AISDKError.hasMarker(error, marker4);
153
163
  }
154
164
  };
155
- _a4 = symbol4;
156
165
  var name6 = "AI_JSONParseError";
157
166
  var marker7 = `vercel.ai.error.${name6}`;
158
167
  var symbol7 = Symbol.for(marker7);
159
168
  var _a7;
160
- var JSONParseError = class extends AISDKError {
169
+ var _b7;
170
+ var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {
161
171
  constructor({ text: text4, cause }) {
162
172
  super({
163
173
  name: name6,
@@ -172,12 +182,12 @@ Error message: ${getErrorMessage(cause)}`,
172
182
  return AISDKError.hasMarker(error, marker7);
173
183
  }
174
184
  };
175
- _a7 = symbol7;
176
185
  var name10 = "AI_NoSuchModelError";
177
186
  var marker11 = `vercel.ai.error.${name10}`;
178
187
  var symbol11 = Symbol.for(marker11);
179
188
  var _a11;
180
- var NoSuchModelError = class extends AISDKError {
189
+ var _b11;
190
+ var NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {
181
191
  constructor({
182
192
  errorName = name10,
183
193
  modelId,
@@ -193,12 +203,12 @@ var NoSuchModelError = class extends AISDKError {
193
203
  return AISDKError.hasMarker(error, marker11);
194
204
  }
195
205
  };
196
- _a11 = symbol11;
197
206
  var name12 = "AI_TypeValidationError";
198
207
  var marker13 = `vercel.ai.error.${name12}`;
199
208
  var symbol13 = Symbol.for(marker13);
200
209
  var _a13;
201
- var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
210
+ var _b13;
211
+ var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
202
212
  constructor({ value, cause }) {
203
213
  super({
204
214
  name: name12,
@@ -226,11 +236,9 @@ Error message: ${getErrorMessage(cause)}`,
226
236
  value,
227
237
  cause
228
238
  }) {
229
- return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
239
+ return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
230
240
  }
231
241
  };
232
- _a13 = symbol13;
233
- var TypeValidationError = _TypeValidationError;
234
242
  var ParseError = class extends Error {
235
243
  constructor(message, options) {
236
244
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
@@ -421,14 +429,14 @@ function handleFetchError({
421
429
  return error;
422
430
  }
423
431
  function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
424
- var _a156, _b17, _c;
432
+ var _a224, _b222, _c;
425
433
  if (globalThisAny.window) {
426
434
  return `runtime/browser`;
427
435
  }
428
- if ((_a156 = globalThisAny.navigator) == null ? void 0 : _a156.userAgent) {
436
+ if ((_a224 = globalThisAny.navigator) == null ? void 0 : _a224.userAgent) {
429
437
  return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
430
438
  }
431
- if ((_c = (_b17 = globalThisAny.process) == null ? void 0 : _b17.versions) == null ? void 0 : _c.node) {
439
+ if ((_c = (_b222 = globalThisAny.process) == null ? void 0 : _b222.versions) == null ? void 0 : _c.node) {
432
440
  return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
433
441
  }
434
442
  if (globalThisAny.EdgeRuntime) {
@@ -466,7 +474,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
466
474
  );
467
475
  return Object.fromEntries(normalizedHeaders.entries());
468
476
  }
469
- var VERSION = "3.0.17";
477
+ var VERSION = "3.0.25";
470
478
  var getOriginalFetch = () => globalThis.fetch;
471
479
  var getFromApi = async ({
472
480
  url,
@@ -551,8 +559,8 @@ function loadOptionalSetting({
551
559
  }
552
560
  return settingValue;
553
561
  }
554
- var suspectProtoRx = /"__proto__"\s*:/;
555
- var suspectConstructorRx = /"constructor"\s*:/;
562
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
563
+ var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
556
564
  function _parse(text4) {
557
565
  const obj = JSON.parse(text4);
558
566
  if (obj === null || typeof obj !== "object") {
@@ -572,7 +580,7 @@ function filter(obj) {
572
580
  if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
573
581
  throw new SyntaxError("Object contains forbidden prototype property");
574
582
  }
575
- if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
583
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
576
584
  throw new SyntaxError("Object contains forbidden prototype property");
577
585
  }
578
586
  for (const key in node) {
@@ -808,6 +816,36 @@ var postToApi = async ({
808
816
  throw handleFetchError({ error, url, requestBodyValues: body.values });
809
817
  }
810
818
  };
819
+ function tool(tool22) {
820
+ return tool22;
821
+ }
822
+ function createProviderDefinedToolFactoryWithOutputSchema({
823
+ id,
824
+ name: name224,
825
+ inputSchema,
826
+ outputSchema: outputSchema3
827
+ }) {
828
+ return ({
829
+ execute,
830
+ toModelOutput,
831
+ onInputStart,
832
+ onInputDelta,
833
+ onInputAvailable,
834
+ ...args
835
+ }) => tool({
836
+ type: "provider-defined",
837
+ id,
838
+ name: name224,
839
+ args,
840
+ inputSchema,
841
+ outputSchema: outputSchema3,
842
+ execute,
843
+ toModelOutput,
844
+ onInputStart,
845
+ onInputDelta,
846
+ onInputAvailable
847
+ });
848
+ }
811
849
  async function resolve(value) {
812
850
  if (typeof value === "function") {
813
851
  value = value();
@@ -905,13 +943,58 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
905
943
  rawValue: parsedResult.rawValue
906
944
  };
907
945
  };
908
- var getRelativePath = (pathA, pathB) => {
909
- let i = 0;
910
- for (; i < pathA.length && i < pathB.length; i++) {
911
- if (pathA[i] !== pathB[i]) break;
946
+ var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
947
+ function lazySchema(createSchema) {
948
+ let schema;
949
+ return () => {
950
+ if (schema == null) {
951
+ schema = createSchema();
952
+ }
953
+ return schema;
954
+ };
955
+ }
956
+ function jsonSchema(jsonSchema22, {
957
+ validate
958
+ } = {}) {
959
+ return {
960
+ [schemaSymbol]: true,
961
+ _type: void 0,
962
+ // should never be used directly
963
+ [validatorSymbol]: true,
964
+ get jsonSchema() {
965
+ if (typeof jsonSchema22 === "function") {
966
+ jsonSchema22 = jsonSchema22();
967
+ }
968
+ return jsonSchema22;
969
+ },
970
+ validate
971
+ };
972
+ }
973
+ function addAdditionalPropertiesToJsonSchema(jsonSchema22) {
974
+ if (jsonSchema22.type === "object") {
975
+ jsonSchema22.additionalProperties = false;
976
+ const properties = jsonSchema22.properties;
977
+ if (properties != null) {
978
+ for (const property in properties) {
979
+ properties[property] = addAdditionalPropertiesToJsonSchema(
980
+ properties[property]
981
+ );
982
+ }
983
+ }
912
984
  }
913
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
914
- };
985
+ if (jsonSchema22.type === "array" && jsonSchema22.items != null) {
986
+ if (Array.isArray(jsonSchema22.items)) {
987
+ jsonSchema22.items = jsonSchema22.items.map(
988
+ (item) => addAdditionalPropertiesToJsonSchema(item)
989
+ );
990
+ } else {
991
+ jsonSchema22.items = addAdditionalPropertiesToJsonSchema(
992
+ jsonSchema22.items
993
+ );
994
+ }
995
+ }
996
+ return jsonSchema22;
997
+ }
915
998
  var ignoreOverride = /* @__PURE__ */ Symbol(
916
999
  "Let zodToJsonSchema decide on which parser to use"
917
1000
  );
@@ -947,11 +1030,11 @@ function parseAnyDef() {
947
1030
  return {};
948
1031
  }
949
1032
  function parseArrayDef(def, refs) {
950
- var _a156, _b17, _c;
1033
+ var _a224, _b222, _c;
951
1034
  const res = {
952
1035
  type: "array"
953
1036
  };
954
- if (((_a156 = def.type) == null ? void 0 : _a156._def) && ((_c = (_b17 = def.type) == null ? void 0 : _b17._def) == null ? void 0 : _c.typeName) !== v3.ZodFirstPartyTypeKind.ZodAny) {
1037
+ if (((_a224 = def.type) == null ? void 0 : _a224._def) && ((_c = (_b222 = def.type) == null ? void 0 : _b222._def) == null ? void 0 : _c.typeName) !== v3.ZodFirstPartyTypeKind.ZodAny) {
955
1038
  res.items = parseDef(def.type._def, {
956
1039
  ...refs,
957
1040
  currentPath: [...refs.currentPath, "items"]
@@ -1076,7 +1159,7 @@ function parseIntersectionDef(def, refs) {
1076
1159
  ...refs,
1077
1160
  currentPath: [...refs.currentPath, "allOf", "1"]
1078
1161
  })
1079
- ].filter((x) => !!x);
1162
+ ].filter((x2) => !!x2);
1080
1163
  const mergedAllOf = [];
1081
1164
  allOf.forEach((schema) => {
1082
1165
  if (isJsonSchema7AllOfType(schema)) {
@@ -1310,8 +1393,8 @@ function escapeNonAlphaNumeric(source) {
1310
1393
  return result;
1311
1394
  }
1312
1395
  function addFormat(schema, value, message, refs) {
1313
- var _a156;
1314
- if (schema.format || ((_a156 = schema.anyOf) == null ? void 0 : _a156.some((x) => x.format))) {
1396
+ var _a224;
1397
+ if (schema.format || ((_a224 = schema.anyOf) == null ? void 0 : _a224.some((x2) => x2.format))) {
1315
1398
  if (!schema.anyOf) {
1316
1399
  schema.anyOf = [];
1317
1400
  }
@@ -1330,8 +1413,8 @@ function addFormat(schema, value, message, refs) {
1330
1413
  }
1331
1414
  }
1332
1415
  function addPattern(schema, regex, message, refs) {
1333
- var _a156;
1334
- if (schema.pattern || ((_a156 = schema.allOf) == null ? void 0 : _a156.some((x) => x.pattern))) {
1416
+ var _a224;
1417
+ if (schema.pattern || ((_a224 = schema.allOf) == null ? void 0 : _a224.some((x2) => x2.pattern))) {
1335
1418
  if (!schema.allOf) {
1336
1419
  schema.allOf = [];
1337
1420
  }
@@ -1350,7 +1433,7 @@ function addPattern(schema, regex, message, refs) {
1350
1433
  }
1351
1434
  }
1352
1435
  function stringifyRegExpWithFlags(regex, refs) {
1353
- var _a156;
1436
+ var _a224;
1354
1437
  if (!refs.applyRegexFlags || !regex.flags) {
1355
1438
  return regex.source;
1356
1439
  }
@@ -1380,7 +1463,7 @@ function stringifyRegExpWithFlags(regex, refs) {
1380
1463
  pattern += source[i];
1381
1464
  pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1382
1465
  inCharRange = false;
1383
- } else if (source[i + 1] === "-" && ((_a156 = source[i + 2]) == null ? void 0 : _a156.match(/[a-z]/))) {
1466
+ } else if (source[i + 1] === "-" && ((_a224 = source[i + 2]) == null ? void 0 : _a224.match(/[a-z]/))) {
1384
1467
  pattern += source[i];
1385
1468
  inCharRange = true;
1386
1469
  } else {
@@ -1422,15 +1505,15 @@ function stringifyRegExpWithFlags(regex, refs) {
1422
1505
  return pattern;
1423
1506
  }
1424
1507
  function parseRecordDef(def, refs) {
1425
- var _a156, _b17, _c, _d, _e, _f;
1508
+ var _a224, _b222, _c, _d, _e, _f;
1426
1509
  const schema = {
1427
1510
  type: "object",
1428
- additionalProperties: (_a156 = parseDef(def.valueType._def, {
1511
+ additionalProperties: (_a224 = parseDef(def.valueType._def, {
1429
1512
  ...refs,
1430
1513
  currentPath: [...refs.currentPath, "additionalProperties"]
1431
- })) != null ? _a156 : refs.allowedAdditionalProperties
1514
+ })) != null ? _a224 : refs.allowedAdditionalProperties
1432
1515
  };
1433
- if (((_b17 = def.keyType) == null ? void 0 : _b17._def.typeName) === v3.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1516
+ if (((_b222 = def.keyType) == null ? void 0 : _b222._def.typeName) === v3.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1434
1517
  const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1435
1518
  return {
1436
1519
  ...schema,
@@ -1510,19 +1593,19 @@ var primitiveMappings = {
1510
1593
  function parseUnionDef(def, refs) {
1511
1594
  const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1512
1595
  if (options.every(
1513
- (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1596
+ (x2) => x2._def.typeName in primitiveMappings && (!x2._def.checks || !x2._def.checks.length)
1514
1597
  )) {
1515
- const types = options.reduce((types2, x) => {
1516
- const type = primitiveMappings[x._def.typeName];
1598
+ const types = options.reduce((types2, x2) => {
1599
+ const type = primitiveMappings[x2._def.typeName];
1517
1600
  return type && !types2.includes(type) ? [...types2, type] : types2;
1518
1601
  }, []);
1519
1602
  return {
1520
1603
  type: types.length > 1 ? types : types[0]
1521
1604
  };
1522
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1605
+ } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
1523
1606
  const types = options.reduce(
1524
- (acc, x) => {
1525
- const type = typeof x._def.value;
1607
+ (acc, x2) => {
1608
+ const type = typeof x2._def.value;
1526
1609
  switch (type) {
1527
1610
  case "string":
1528
1611
  case "number":
@@ -1531,7 +1614,7 @@ function parseUnionDef(def, refs) {
1531
1614
  case "bigint":
1532
1615
  return [...acc, "integer"];
1533
1616
  case "object":
1534
- if (x._def.value === null) return [...acc, "null"];
1617
+ if (x2._def.value === null) return [...acc, "null"];
1535
1618
  case "symbol":
1536
1619
  case "undefined":
1537
1620
  case "function":
@@ -1542,24 +1625,24 @@ function parseUnionDef(def, refs) {
1542
1625
  []
1543
1626
  );
1544
1627
  if (types.length === options.length) {
1545
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1628
+ const uniqueTypes = types.filter((x2, i, a) => a.indexOf(x2) === i);
1546
1629
  return {
1547
1630
  type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1548
1631
  enum: options.reduce(
1549
- (acc, x) => {
1550
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1632
+ (acc, x2) => {
1633
+ return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
1551
1634
  },
1552
1635
  []
1553
1636
  )
1554
1637
  };
1555
1638
  }
1556
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1639
+ } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
1557
1640
  return {
1558
1641
  type: "string",
1559
1642
  enum: options.reduce(
1560
- (acc, x) => [
1643
+ (acc, x2) => [
1561
1644
  ...acc,
1562
- ...x._def.values.filter((x2) => !acc.includes(x2))
1645
+ ...x2._def.values.filter((x22) => !acc.includes(x22))
1563
1646
  ],
1564
1647
  []
1565
1648
  )
@@ -1569,12 +1652,12 @@ function parseUnionDef(def, refs) {
1569
1652
  }
1570
1653
  var asAnyOf = (def, refs) => {
1571
1654
  const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1572
- (x, i) => parseDef(x._def, {
1655
+ (x2, i) => parseDef(x2._def, {
1573
1656
  ...refs,
1574
1657
  currentPath: [...refs.currentPath, "anyOf", `${i}`]
1575
1658
  })
1576
1659
  ).filter(
1577
- (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1660
+ (x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0)
1578
1661
  );
1579
1662
  return anyOf.length ? { anyOf } : void 0;
1580
1663
  };
@@ -1685,8 +1768,8 @@ function safeIsOptional(schema) {
1685
1768
  }
1686
1769
  }
1687
1770
  var parseOptionalDef = (def, refs) => {
1688
- var _a156;
1689
- if (refs.currentPath.toString() === ((_a156 = refs.propertyPath) == null ? void 0 : _a156.toString())) {
1771
+ var _a224;
1772
+ if (refs.currentPath.toString() === ((_a224 = refs.propertyPath) == null ? void 0 : _a224.toString())) {
1690
1773
  return parseDef(def.innerType._def, refs);
1691
1774
  }
1692
1775
  const innerSchema = parseDef(def.innerType._def, {
@@ -1710,7 +1793,7 @@ var parsePipelineDef = (def, refs) => {
1710
1793
  currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1711
1794
  });
1712
1795
  return {
1713
- allOf: [a, b].filter((x) => x !== void 0)
1796
+ allOf: [a, b].filter((x2) => x2 !== void 0)
1714
1797
  };
1715
1798
  };
1716
1799
  function parsePromiseDef(def, refs) {
@@ -1740,12 +1823,12 @@ function parseTupleDef(def, refs) {
1740
1823
  type: "array",
1741
1824
  minItems: def.items.length,
1742
1825
  items: def.items.map(
1743
- (x, i) => parseDef(x._def, {
1826
+ (x2, i) => parseDef(x2._def, {
1744
1827
  ...refs,
1745
1828
  currentPath: [...refs.currentPath, "items", `${i}`]
1746
1829
  })
1747
1830
  ).reduce(
1748
- (acc, x) => x === void 0 ? acc : [...acc, x],
1831
+ (acc, x2) => x2 === void 0 ? acc : [...acc, x2],
1749
1832
  []
1750
1833
  ),
1751
1834
  additionalItems: parseDef(def.rest._def, {
@@ -1759,12 +1842,12 @@ function parseTupleDef(def, refs) {
1759
1842
  minItems: def.items.length,
1760
1843
  maxItems: def.items.length,
1761
1844
  items: def.items.map(
1762
- (x, i) => parseDef(x._def, {
1845
+ (x2, i) => parseDef(x2._def, {
1763
1846
  ...refs,
1764
1847
  currentPath: [...refs.currentPath, "items", `${i}`]
1765
1848
  })
1766
1849
  ).reduce(
1767
- (acc, x) => x === void 0 ? acc : [...acc, x],
1850
+ (acc, x2) => x2 === void 0 ? acc : [...acc, x2],
1768
1851
  []
1769
1852
  )
1770
1853
  };
@@ -1855,11 +1938,18 @@ var selectParser = (def, typeName, refs) => {
1855
1938
  return /* @__PURE__ */ ((_) => void 0)();
1856
1939
  }
1857
1940
  };
1941
+ var getRelativePath = (pathA, pathB) => {
1942
+ let i = 0;
1943
+ for (; i < pathA.length && i < pathB.length; i++) {
1944
+ if (pathA[i] !== pathB[i]) break;
1945
+ }
1946
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1947
+ };
1858
1948
  function parseDef(def, refs, forceResolution = false) {
1859
- var _a156;
1949
+ var _a224;
1860
1950
  const seenItem = refs.seen.get(def);
1861
1951
  if (refs.override) {
1862
- const overrideResult = (_a156 = refs.override) == null ? void 0 : _a156.call(
1952
+ const overrideResult = (_a224 = refs.override) == null ? void 0 : _a224.call(
1863
1953
  refs,
1864
1954
  def,
1865
1955
  refs,
@@ -1925,11 +2015,11 @@ var getRefs = (options) => {
1925
2015
  currentPath,
1926
2016
  propertyPath: void 0,
1927
2017
  seen: new Map(
1928
- Object.entries(_options.definitions).map(([name146, def]) => [
2018
+ Object.entries(_options.definitions).map(([name224, def]) => [
1929
2019
  def._def,
1930
2020
  {
1931
2021
  def: def._def,
1932
- path: [..._options.basePath, _options.definitionPath, name146],
2022
+ path: [..._options.basePath, _options.definitionPath, name224],
1933
2023
  // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1934
2024
  jsonSchema: void 0
1935
2025
  }
@@ -1938,50 +2028,50 @@ var getRefs = (options) => {
1938
2028
  };
1939
2029
  };
1940
2030
  var zodToJsonSchema = (schema, options) => {
1941
- var _a156;
2031
+ var _a224;
1942
2032
  const refs = getRefs(options);
1943
2033
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1944
- (acc, [name224, schema2]) => {
1945
- var _a224;
2034
+ (acc, [name324, schema2]) => {
2035
+ var _a324;
1946
2036
  return {
1947
2037
  ...acc,
1948
- [name224]: (_a224 = parseDef(
2038
+ [name324]: (_a324 = parseDef(
1949
2039
  schema2._def,
1950
2040
  {
1951
2041
  ...refs,
1952
- currentPath: [...refs.basePath, refs.definitionPath, name224]
2042
+ currentPath: [...refs.basePath, refs.definitionPath, name324]
1953
2043
  },
1954
2044
  true
1955
- )) != null ? _a224 : parseAnyDef()
2045
+ )) != null ? _a324 : parseAnyDef()
1956
2046
  };
1957
2047
  },
1958
2048
  {}
1959
2049
  ) : void 0;
1960
- const name146 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1961
- const main = (_a156 = parseDef(
2050
+ const name224 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
2051
+ const main = (_a224 = parseDef(
1962
2052
  schema._def,
1963
- name146 === void 0 ? refs : {
2053
+ name224 === void 0 ? refs : {
1964
2054
  ...refs,
1965
- currentPath: [...refs.basePath, refs.definitionPath, name146]
2055
+ currentPath: [...refs.basePath, refs.definitionPath, name224]
1966
2056
  },
1967
2057
  false
1968
- )) != null ? _a156 : parseAnyDef();
2058
+ )) != null ? _a224 : parseAnyDef();
1969
2059
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1970
2060
  if (title !== void 0) {
1971
2061
  main.title = title;
1972
2062
  }
1973
- const combined = name146 === void 0 ? definitions ? {
2063
+ const combined = name224 === void 0 ? definitions ? {
1974
2064
  ...main,
1975
2065
  [refs.definitionPath]: definitions
1976
2066
  } : main : {
1977
2067
  $ref: [
1978
2068
  ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1979
2069
  refs.definitionPath,
1980
- name146
2070
+ name224
1981
2071
  ].join("/"),
1982
2072
  [refs.definitionPath]: {
1983
2073
  ...definitions,
1984
- [name146]: main
2074
+ [name224]: main
1985
2075
  }
1986
2076
  };
1987
2077
  combined.$schema = "http://json-schema.org/draft-07/schema#";
@@ -1989,8 +2079,8 @@ var zodToJsonSchema = (schema, options) => {
1989
2079
  };
1990
2080
  var zod_to_json_schema_default = zodToJsonSchema;
1991
2081
  function zod3Schema(zodSchema22, options) {
1992
- var _a156;
1993
- const useReferences = (_a156 = void 0 ) != null ? _a156 : false;
2082
+ var _a224;
2083
+ const useReferences = (_a224 = void 0 ) != null ? _a224 : false;
1994
2084
  return jsonSchema(
1995
2085
  // defer json schema creation to avoid unnecessary computation when only validation is needed
1996
2086
  () => zod_to_json_schema_default(zodSchema22, {
@@ -2005,15 +2095,17 @@ function zod3Schema(zodSchema22, options) {
2005
2095
  );
2006
2096
  }
2007
2097
  function zod4Schema(zodSchema22, options) {
2008
- var _a156;
2009
- const useReferences = (_a156 = void 0 ) != null ? _a156 : false;
2098
+ var _a224;
2099
+ const useReferences = (_a224 = void 0 ) != null ? _a224 : false;
2010
2100
  return jsonSchema(
2011
2101
  // defer json schema creation to avoid unnecessary computation when only validation is needed
2012
- () => z4__namespace.toJSONSchema(zodSchema22, {
2013
- target: "draft-7",
2014
- io: "output",
2015
- reused: useReferences ? "ref" : "inline"
2016
- }),
2102
+ () => addAdditionalPropertiesToJsonSchema(
2103
+ z4__namespace.toJSONSchema(zodSchema22, {
2104
+ target: "draft-7",
2105
+ io: "input",
2106
+ reused: useReferences ? "ref" : "inline"
2107
+ })
2108
+ ),
2017
2109
  {
2018
2110
  validate: async (value) => {
2019
2111
  const result = await z4__namespace.safeParseAsync(zodSchema22, value);
@@ -2032,24 +2124,6 @@ function zodSchema(zodSchema22, options) {
2032
2124
  return zod3Schema(zodSchema22);
2033
2125
  }
2034
2126
  }
2035
- var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
2036
- function jsonSchema(jsonSchema22, {
2037
- validate
2038
- } = {}) {
2039
- return {
2040
- [schemaSymbol]: true,
2041
- _type: void 0,
2042
- // should never be used directly
2043
- [validatorSymbol]: true,
2044
- get jsonSchema() {
2045
- if (typeof jsonSchema22 === "function") {
2046
- jsonSchema22 = jsonSchema22();
2047
- }
2048
- return jsonSchema22;
2049
- },
2050
- validate
2051
- };
2052
- }
2053
2127
  function isSchema(value) {
2054
2128
  return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2055
2129
  }
@@ -2062,146 +2136,29 @@ function asSchema(schema) {
2062
2136
  function withoutTrailingSlash(url) {
2063
2137
  return url == null ? void 0 : url.replace(/\/$/, "");
2064
2138
  }
2065
- var require_get_context = chunk23EXJLET_cjs.__commonJS({
2066
- "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-context.js"(exports$1, module) {
2067
- var __defProp22 = Object.defineProperty;
2068
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
2069
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
2070
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2071
- var __export22 = (target, all) => {
2072
- for (var name164 in all)
2073
- __defProp22(target, name164, { get: all[name164], enumerable: true });
2074
- };
2075
- var __copyProps2 = (to, from, except, desc) => {
2076
- if (from && typeof from === "object" || typeof from === "function") {
2077
- for (let key of __getOwnPropNames2(from))
2078
- if (!__hasOwnProp2.call(to, key) && key !== except)
2079
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
2080
- }
2081
- return to;
2082
- };
2083
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
2084
- var get_context_exports = {};
2085
- __export22(get_context_exports, {
2086
- SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
2087
- getContext: () => getContext3
2088
- });
2089
- module.exports = __toCommonJS(get_context_exports);
2090
- var SYMBOL_FOR_REQ_CONTEXT = /* @__PURE__ */ Symbol.for("@vercel/request-context");
2091
- function getContext3() {
2092
- const fromSymbol = globalThis;
2093
- return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
2094
- }
2095
- }
2096
- });
2097
- var require_get_vercel_oidc_token = chunk23EXJLET_cjs.__commonJS({
2098
- "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports$1, module) {
2099
- var __defProp22 = Object.defineProperty;
2100
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
2101
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
2102
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2103
- var __export22 = (target, all) => {
2104
- for (var name164 in all)
2105
- __defProp22(target, name164, { get: all[name164], enumerable: true });
2106
- };
2107
- var __copyProps2 = (to, from, except, desc) => {
2108
- if (from && typeof from === "object" || typeof from === "function") {
2109
- for (let key of __getOwnPropNames2(from))
2110
- if (!__hasOwnProp2.call(to, key) && key !== except)
2111
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
2112
- }
2113
- return to;
2114
- };
2115
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
2116
- var get_vercel_oidc_token_exports = {};
2117
- __export22(get_vercel_oidc_token_exports, {
2118
- getVercelOidcToken: () => getVercelOidcToken3,
2119
- getVercelOidcTokenSync: () => getVercelOidcTokenSync2
2120
- });
2121
- module.exports = __toCommonJS(get_vercel_oidc_token_exports);
2122
- var import_get_context = require_get_context();
2123
- var import_token_error = chunk23EXJLET_cjs.require_token_error();
2124
- async function getVercelOidcToken3() {
2125
- let token = "";
2126
- let err;
2127
- try {
2128
- token = getVercelOidcTokenSync2();
2129
- } catch (error) {
2130
- err = error;
2131
- }
2132
- try {
2133
- const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
2134
- await import('./token-util-NEHG7TUY-GYFEVMWP.cjs'),
2135
- await import('./token-6GSAFR2W-TW2P7HCS.cjs')
2136
- ]);
2137
- if (!token || isExpired(getTokenPayload(token))) {
2138
- await refreshToken();
2139
- token = getVercelOidcTokenSync2();
2140
- }
2141
- } catch (error) {
2142
- if (err?.message && error instanceof Error) {
2143
- error.message = `${err.message}
2144
- ${error.message}`;
2145
- }
2146
- throw new import_token_error.VercelOidcTokenError(`Failed to refresh OIDC token`, error);
2147
- }
2148
- return token;
2149
- }
2150
- function getVercelOidcTokenSync2() {
2151
- const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
2152
- if (!token) {
2153
- throw new Error(
2154
- `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
2155
- );
2156
- }
2157
- return token;
2158
- }
2159
- }
2160
- });
2161
- var require_dist = chunk23EXJLET_cjs.__commonJS({
2162
- "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/index.js"(exports$1, module) {
2163
- var __defProp22 = Object.defineProperty;
2164
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
2165
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
2166
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2167
- var __export22 = (target, all) => {
2168
- for (var name164 in all)
2169
- __defProp22(target, name164, { get: all[name164], enumerable: true });
2170
- };
2171
- var __copyProps2 = (to, from, except, desc) => {
2172
- if (from && typeof from === "object" || typeof from === "function") {
2173
- for (let key of __getOwnPropNames2(from))
2174
- if (!__hasOwnProp2.call(to, key) && key !== except)
2175
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
2176
- }
2177
- return to;
2178
- };
2179
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
2180
- var src_exports = {};
2181
- __export22(src_exports, {
2182
- getContext: () => import_get_context.getContext,
2183
- getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
2184
- getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
2185
- });
2186
- module.exports = __toCommonJS(src_exports);
2187
- var import_get_vercel_oidc_token = require_get_vercel_oidc_token();
2188
- var import_get_context = require_get_context();
2139
+ function getContext() {
2140
+ return {
2141
+ headers: {}
2142
+ };
2143
+ }
2144
+ async function getVercelOidcToken() {
2145
+ if (process.env.VERCEL_OIDC_TOKEN) {
2146
+ return process.env.VERCEL_OIDC_TOKEN ?? "";
2189
2147
  }
2190
- });
2191
- var import_oidc = chunk23EXJLET_cjs.__toESM(require_dist(), 1);
2192
- var import_oidc2 = chunk23EXJLET_cjs.__toESM(require_dist(), 1);
2193
- var marker15 = "vercel.ai.gateway.error";
2194
- var symbol15 = Symbol.for(marker15);
2195
- var _a15;
2196
- var _b;
2197
- var GatewayError = class _GatewayError extends (_b = Error, _a15 = symbol15, _b) {
2148
+ throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
2149
+ }
2150
+ var marker16 = "vercel.ai.gateway.error";
2151
+ var symbol16 = Symbol.for(marker16);
2152
+ var _a16;
2153
+ var _b16;
2154
+ var GatewayError = class _GatewayError extends (_b16 = Error, _a16 = symbol16, _b16) {
2198
2155
  constructor({
2199
2156
  message,
2200
2157
  statusCode = 500,
2201
2158
  cause
2202
2159
  }) {
2203
2160
  super(message);
2204
- this[_a15] = true;
2161
+ this[_a16] = true;
2205
2162
  this.statusCode = statusCode;
2206
2163
  this.cause = cause;
2207
2164
  }
@@ -2214,15 +2171,15 @@ var GatewayError = class _GatewayError extends (_b = Error, _a15 = symbol15, _b)
2214
2171
  return _GatewayError.hasMarker(error);
2215
2172
  }
2216
2173
  static hasMarker(error) {
2217
- return typeof error === "object" && error !== null && symbol15 in error && error[symbol15] === true;
2174
+ return typeof error === "object" && error !== null && symbol16 in error && error[symbol16] === true;
2218
2175
  }
2219
2176
  };
2220
- var name14 = "GatewayAuthenticationError";
2221
- var marker22 = `vercel.ai.gateway.error.${name14}`;
2177
+ var name15 = "GatewayAuthenticationError";
2178
+ var marker22 = `vercel.ai.gateway.error.${name15}`;
2222
2179
  var symbol22 = Symbol.for(marker22);
2223
2180
  var _a22;
2224
- var _b2;
2225
- var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a22 = symbol22, _b2) {
2181
+ var _b22;
2182
+ var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b22 = GatewayError, _a22 = symbol22, _b22) {
2226
2183
  constructor({
2227
2184
  message = "Authentication failed",
2228
2185
  statusCode = 401,
@@ -2230,7 +2187,7 @@ var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2
2230
2187
  } = {}) {
2231
2188
  super({ message, statusCode, cause });
2232
2189
  this[_a22] = true;
2233
- this.name = name14;
2190
+ this.name = name15;
2234
2191
  this.type = "authentication_error";
2235
2192
  }
2236
2193
  static isInstance(error) {
@@ -2280,8 +2237,8 @@ var name22 = "GatewayInvalidRequestError";
2280
2237
  var marker32 = `vercel.ai.gateway.error.${name22}`;
2281
2238
  var symbol32 = Symbol.for(marker32);
2282
2239
  var _a32;
2283
- var _b3;
2284
- var GatewayInvalidRequestError = class extends (_b3 = GatewayError, _a32 = symbol32, _b3) {
2240
+ var _b32;
2241
+ var GatewayInvalidRequestError = class extends (_b32 = GatewayError, _a32 = symbol32, _b32) {
2285
2242
  constructor({
2286
2243
  message = "Invalid request",
2287
2244
  statusCode = 400,
@@ -2300,8 +2257,8 @@ var name32 = "GatewayRateLimitError";
2300
2257
  var marker42 = `vercel.ai.gateway.error.${name32}`;
2301
2258
  var symbol42 = Symbol.for(marker42);
2302
2259
  var _a42;
2303
- var _b4;
2304
- var GatewayRateLimitError = class extends (_b4 = GatewayError, _a42 = symbol42, _b4) {
2260
+ var _b42;
2261
+ var GatewayRateLimitError = class extends (_b42 = GatewayError, _a42 = symbol42, _b42) {
2305
2262
  constructor({
2306
2263
  message = "Rate limit exceeded",
2307
2264
  statusCode = 429,
@@ -2327,8 +2284,8 @@ var modelNotFoundParamSchema = lazyValidator(
2327
2284
  )
2328
2285
  );
2329
2286
  var _a52;
2330
- var _b5;
2331
- var GatewayModelNotFoundError = class extends (_b5 = GatewayError, _a52 = symbol52, _b5) {
2287
+ var _b52;
2288
+ var GatewayModelNotFoundError = class extends (_b52 = GatewayError, _a52 = symbol52, _b52) {
2332
2289
  constructor({
2333
2290
  message = "Model not found",
2334
2291
  statusCode = 404,
@@ -2349,8 +2306,8 @@ var name52 = "GatewayInternalServerError";
2349
2306
  var marker62 = `vercel.ai.gateway.error.${name52}`;
2350
2307
  var symbol62 = Symbol.for(marker62);
2351
2308
  var _a62;
2352
- var _b6;
2353
- var GatewayInternalServerError = class extends (_b6 = GatewayError, _a62 = symbol62, _b6) {
2309
+ var _b62;
2310
+ var GatewayInternalServerError = class extends (_b62 = GatewayError, _a62 = symbol62, _b62) {
2354
2311
  constructor({
2355
2312
  message = "Internal server error",
2356
2313
  statusCode = 500,
@@ -2369,8 +2326,8 @@ var name62 = "GatewayResponseError";
2369
2326
  var marker72 = `vercel.ai.gateway.error.${name62}`;
2370
2327
  var symbol72 = Symbol.for(marker72);
2371
2328
  var _a72;
2372
- var _b7;
2373
- var GatewayResponseError = class extends (_b7 = GatewayError, _a72 = symbol72, _b7) {
2329
+ var _b72;
2330
+ var GatewayResponseError = class extends (_b72 = GatewayError, _a72 = symbol72, _b72) {
2374
2331
  constructor({
2375
2332
  message = "Invalid response from Gateway",
2376
2333
  statusCode = 502,
@@ -2454,21 +2411,98 @@ var gatewayErrorResponseSchema = lazyValidator(
2454
2411
  })
2455
2412
  )
2456
2413
  );
2457
- function asGatewayError(error, authMethod) {
2458
- var _a832;
2414
+ function extractApiCallResponse(error) {
2415
+ if (error.data !== void 0) {
2416
+ return error.data;
2417
+ }
2418
+ if (error.responseBody != null) {
2419
+ try {
2420
+ return JSON.parse(error.responseBody);
2421
+ } catch (e) {
2422
+ return error.responseBody;
2423
+ }
2424
+ }
2425
+ return {};
2426
+ }
2427
+ var name72 = "GatewayTimeoutError";
2428
+ var marker82 = `vercel.ai.gateway.error.${name72}`;
2429
+ var symbol82 = Symbol.for(marker82);
2430
+ var _a82;
2431
+ var _b82;
2432
+ var GatewayTimeoutError = class _GatewayTimeoutError extends (_b82 = GatewayError, _a82 = symbol82, _b82) {
2433
+ constructor({
2434
+ message = "Request timed out",
2435
+ statusCode = 408,
2436
+ cause
2437
+ } = {}) {
2438
+ super({ message, statusCode, cause });
2439
+ this[_a82] = true;
2440
+ this.name = name72;
2441
+ this.type = "timeout_error";
2442
+ }
2443
+ static isInstance(error) {
2444
+ return GatewayError.hasMarker(error) && symbol82 in error;
2445
+ }
2446
+ /**
2447
+ * Creates a helpful timeout error message with troubleshooting guidance
2448
+ */
2449
+ static createTimeoutError({
2450
+ originalMessage,
2451
+ statusCode = 408,
2452
+ cause
2453
+ }) {
2454
+ const message = `Gateway request timed out: ${originalMessage}
2455
+
2456
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;
2457
+ return new _GatewayTimeoutError({
2458
+ message,
2459
+ statusCode,
2460
+ cause
2461
+ });
2462
+ }
2463
+ };
2464
+ function isTimeoutError(error) {
2465
+ if (!(error instanceof Error)) {
2466
+ return false;
2467
+ }
2468
+ const errorCode = error.code;
2469
+ if (typeof errorCode === "string") {
2470
+ const undiciTimeoutCodes = [
2471
+ "UND_ERR_HEADERS_TIMEOUT",
2472
+ "UND_ERR_BODY_TIMEOUT",
2473
+ "UND_ERR_CONNECT_TIMEOUT"
2474
+ ];
2475
+ return undiciTimeoutCodes.includes(errorCode);
2476
+ }
2477
+ return false;
2478
+ }
2479
+ async function asGatewayError(error, authMethod) {
2480
+ var _a932;
2459
2481
  if (GatewayError.isInstance(error)) {
2460
2482
  return error;
2461
2483
  }
2484
+ if (isTimeoutError(error)) {
2485
+ return GatewayTimeoutError.createTimeoutError({
2486
+ originalMessage: error instanceof Error ? error.message : "Unknown error",
2487
+ cause: error
2488
+ });
2489
+ }
2462
2490
  if (APICallError.isInstance(error)) {
2463
- return createGatewayErrorFromResponse({
2491
+ if (error.cause && isTimeoutError(error.cause)) {
2492
+ return GatewayTimeoutError.createTimeoutError({
2493
+ originalMessage: error.message,
2494
+ cause: error
2495
+ });
2496
+ }
2497
+ return await createGatewayErrorFromResponse({
2464
2498
  response: extractApiCallResponse(error),
2465
- statusCode: (_a832 = error.statusCode) != null ? _a832 : 500,
2499
+ statusCode: (_a932 = error.statusCode) != null ? _a932 : 500,
2466
2500
  defaultMessage: "Gateway request failed",
2467
2501
  cause: error,
2468
2502
  authMethod
2469
2503
  });
2470
2504
  }
2471
- return createGatewayErrorFromResponse({
2505
+ return await createGatewayErrorFromResponse({
2472
2506
  response: {},
2473
2507
  statusCode: 500,
2474
2508
  defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
@@ -2476,19 +2510,6 @@ function asGatewayError(error, authMethod) {
2476
2510
  authMethod
2477
2511
  });
2478
2512
  }
2479
- function extractApiCallResponse(error) {
2480
- if (error.data !== void 0) {
2481
- return error.data;
2482
- }
2483
- if (error.responseBody != null) {
2484
- try {
2485
- return JSON.parse(error.responseBody);
2486
- } catch (e) {
2487
- return error.responseBody;
2488
- }
2489
- }
2490
- return {};
2491
- }
2492
2513
  var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
2493
2514
  async function parseAuthMethod(headers) {
2494
2515
  const result = await safeValidateTypes({
@@ -2500,6 +2521,7 @@ async function parseAuthMethod(headers) {
2500
2521
  var gatewayAuthMethodSchema = lazyValidator(
2501
2522
  () => zodSchema(z4.z.union([z4.z.literal("api-key"), z4.z.literal("oidc")]))
2502
2523
  );
2524
+ var KNOWN_MODEL_TYPES = ["embedding", "image", "language"];
2503
2525
  var GatewayFetchMetadata = class {
2504
2526
  constructor(config) {
2505
2527
  this.config = config;
@@ -2570,8 +2592,12 @@ var gatewayAvailableModelsResponseSchema = lazyValidator(
2570
2592
  provider: z4.z.string(),
2571
2593
  modelId: z4.z.string()
2572
2594
  }),
2573
- modelType: z4.z.enum(["language", "embedding", "image"]).nullish()
2595
+ modelType: z4.z.string().nullish()
2574
2596
  })
2597
+ ).transform(
2598
+ (models) => models.filter(
2599
+ (m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType)
2600
+ )
2575
2601
  )
2576
2602
  })
2577
2603
  )
@@ -2587,6 +2613,187 @@ var gatewayCreditsResponseSchema = lazyValidator(
2587
2613
  }))
2588
2614
  )
2589
2615
  );
2616
+ var GatewaySpendReport = class {
2617
+ constructor(config) {
2618
+ this.config = config;
2619
+ }
2620
+ async getSpendReport(params) {
2621
+ try {
2622
+ const baseUrl = new URL(this.config.baseURL);
2623
+ const searchParams = new URLSearchParams();
2624
+ searchParams.set("start_date", params.startDate);
2625
+ searchParams.set("end_date", params.endDate);
2626
+ if (params.groupBy) {
2627
+ searchParams.set("group_by", params.groupBy);
2628
+ }
2629
+ if (params.datePart) {
2630
+ searchParams.set("date_part", params.datePart);
2631
+ }
2632
+ if (params.userId) {
2633
+ searchParams.set("user_id", params.userId);
2634
+ }
2635
+ if (params.model) {
2636
+ searchParams.set("model", params.model);
2637
+ }
2638
+ if (params.provider) {
2639
+ searchParams.set("provider", params.provider);
2640
+ }
2641
+ if (params.credentialType) {
2642
+ searchParams.set("credential_type", params.credentialType);
2643
+ }
2644
+ if (params.tags && params.tags.length > 0) {
2645
+ searchParams.set("tags", params.tags.join(","));
2646
+ }
2647
+ const { value } = await getFromApi({
2648
+ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
2649
+ headers: await resolve(this.config.headers()),
2650
+ successfulResponseHandler: createJsonResponseHandler(
2651
+ gatewaySpendReportResponseSchema
2652
+ ),
2653
+ failedResponseHandler: createJsonErrorResponseHandler({
2654
+ errorSchema: z4.z.any(),
2655
+ errorToMessage: (data) => data
2656
+ }),
2657
+ fetch: this.config.fetch
2658
+ });
2659
+ return value;
2660
+ } catch (error) {
2661
+ throw await asGatewayError(error);
2662
+ }
2663
+ }
2664
+ };
2665
+ var gatewaySpendReportResponseSchema = lazySchema(
2666
+ () => zodSchema(
2667
+ z4.z.object({
2668
+ results: z4.z.array(
2669
+ z4.z.object({
2670
+ day: z4.z.string().optional(),
2671
+ hour: z4.z.string().optional(),
2672
+ user: z4.z.string().optional(),
2673
+ model: z4.z.string().optional(),
2674
+ tag: z4.z.string().optional(),
2675
+ provider: z4.z.string().optional(),
2676
+ credential_type: z4.z.enum(["byok", "system"]).optional(),
2677
+ total_cost: z4.z.number(),
2678
+ market_cost: z4.z.number().optional(),
2679
+ input_tokens: z4.z.number().optional(),
2680
+ output_tokens: z4.z.number().optional(),
2681
+ cached_input_tokens: z4.z.number().optional(),
2682
+ cache_creation_input_tokens: z4.z.number().optional(),
2683
+ reasoning_tokens: z4.z.number().optional(),
2684
+ request_count: z4.z.number().optional()
2685
+ }).transform(
2686
+ ({
2687
+ credential_type,
2688
+ total_cost,
2689
+ market_cost,
2690
+ input_tokens,
2691
+ output_tokens,
2692
+ cached_input_tokens,
2693
+ cache_creation_input_tokens,
2694
+ reasoning_tokens,
2695
+ request_count,
2696
+ ...rest
2697
+ }) => ({
2698
+ ...rest,
2699
+ ...credential_type !== void 0 ? { credentialType: credential_type } : {},
2700
+ totalCost: total_cost,
2701
+ ...market_cost !== void 0 ? { marketCost: market_cost } : {},
2702
+ ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
2703
+ ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
2704
+ ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
2705
+ ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
2706
+ ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
2707
+ ...request_count !== void 0 ? { requestCount: request_count } : {}
2708
+ })
2709
+ )
2710
+ )
2711
+ })
2712
+ )
2713
+ );
2714
+ var GatewayGenerationInfoFetcher = class {
2715
+ constructor(config) {
2716
+ this.config = config;
2717
+ }
2718
+ async getGenerationInfo(params) {
2719
+ try {
2720
+ const baseUrl = new URL(this.config.baseURL);
2721
+ const { value } = await getFromApi({
2722
+ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
2723
+ headers: await resolve(this.config.headers()),
2724
+ successfulResponseHandler: createJsonResponseHandler(
2725
+ gatewayGenerationInfoResponseSchema
2726
+ ),
2727
+ failedResponseHandler: createJsonErrorResponseHandler({
2728
+ errorSchema: z4.z.any(),
2729
+ errorToMessage: (data) => data
2730
+ }),
2731
+ fetch: this.config.fetch
2732
+ });
2733
+ return value;
2734
+ } catch (error) {
2735
+ throw await asGatewayError(error);
2736
+ }
2737
+ }
2738
+ };
2739
+ var gatewayGenerationInfoResponseSchema = lazySchema(
2740
+ () => zodSchema(
2741
+ z4.z.object({
2742
+ data: z4.z.object({
2743
+ id: z4.z.string(),
2744
+ total_cost: z4.z.number(),
2745
+ upstream_inference_cost: z4.z.number(),
2746
+ usage: z4.z.number(),
2747
+ created_at: z4.z.string(),
2748
+ model: z4.z.string(),
2749
+ is_byok: z4.z.boolean(),
2750
+ provider_name: z4.z.string(),
2751
+ streamed: z4.z.boolean(),
2752
+ finish_reason: z4.z.string(),
2753
+ latency: z4.z.number(),
2754
+ generation_time: z4.z.number(),
2755
+ native_tokens_prompt: z4.z.number(),
2756
+ native_tokens_completion: z4.z.number(),
2757
+ native_tokens_reasoning: z4.z.number(),
2758
+ native_tokens_cached: z4.z.number(),
2759
+ native_tokens_cache_creation: z4.z.number(),
2760
+ billable_web_search_calls: z4.z.number()
2761
+ }).transform(
2762
+ ({
2763
+ total_cost,
2764
+ upstream_inference_cost,
2765
+ created_at,
2766
+ is_byok,
2767
+ provider_name,
2768
+ finish_reason,
2769
+ generation_time,
2770
+ native_tokens_prompt,
2771
+ native_tokens_completion,
2772
+ native_tokens_reasoning,
2773
+ native_tokens_cached,
2774
+ native_tokens_cache_creation,
2775
+ billable_web_search_calls,
2776
+ ...rest
2777
+ }) => ({
2778
+ ...rest,
2779
+ totalCost: total_cost,
2780
+ upstreamInferenceCost: upstream_inference_cost,
2781
+ createdAt: created_at,
2782
+ isByok: is_byok,
2783
+ providerName: provider_name,
2784
+ finishReason: finish_reason,
2785
+ generationTime: generation_time,
2786
+ promptTokens: native_tokens_prompt,
2787
+ completionTokens: native_tokens_completion,
2788
+ reasoningTokens: native_tokens_reasoning,
2789
+ cachedTokens: native_tokens_cached,
2790
+ cacheCreationTokens: native_tokens_cache_creation,
2791
+ billableWebSearchCalls: billable_web_search_calls
2792
+ })
2793
+ )
2794
+ }).transform(({ data }) => data)
2795
+ )
2796
+ );
2590
2797
  var GatewayLanguageModel = class {
2591
2798
  constructor(modelId, config) {
2592
2799
  this.modelId = modelId;
@@ -2749,7 +2956,7 @@ var GatewayEmbeddingModel = class {
2749
2956
  abortSignal,
2750
2957
  providerOptions
2751
2958
  }) {
2752
- var _a832;
2959
+ var _a932;
2753
2960
  const resolvedHeaders = await resolve(this.config.headers());
2754
2961
  try {
2755
2962
  const {
@@ -2780,7 +2987,7 @@ var GatewayEmbeddingModel = class {
2780
2987
  });
2781
2988
  return {
2782
2989
  embeddings: responseBody.embeddings,
2783
- usage: (_a832 = responseBody.usage) != null ? _a832 : void 0,
2990
+ usage: (_a932 = responseBody.usage) != null ? _a932 : void 0,
2784
2991
  providerMetadata: responseBody.providerMetadata,
2785
2992
  response: { headers: responseHeaders, body: rawValue }
2786
2993
  };
@@ -2827,7 +3034,7 @@ var GatewayImageModel = class {
2827
3034
  headers,
2828
3035
  abortSignal
2829
3036
  }) {
2830
- var _a832;
3037
+ var _a932, _b93, _c, _d;
2831
3038
  const resolvedHeaders = await resolve(this.config.headers());
2832
3039
  try {
2833
3040
  const {
@@ -2862,16 +3069,23 @@ var GatewayImageModel = class {
2862
3069
  return {
2863
3070
  images: responseBody.images,
2864
3071
  // Always base64 strings from server
2865
- warnings: (_a832 = responseBody.warnings) != null ? _a832 : [],
3072
+ warnings: (_a932 = responseBody.warnings) != null ? _a932 : [],
2866
3073
  providerMetadata: responseBody.providerMetadata,
2867
3074
  response: {
2868
3075
  timestamp: /* @__PURE__ */ new Date(),
2869
3076
  modelId: this.modelId,
2870
3077
  headers: responseHeaders
3078
+ },
3079
+ ...responseBody.usage != null && {
3080
+ usage: {
3081
+ inputTokens: (_b93 = responseBody.usage.inputTokens) != null ? _b93 : void 0,
3082
+ outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,
3083
+ totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0
3084
+ }
2871
3085
  }
2872
3086
  };
2873
3087
  } catch (error) {
2874
- throw asGatewayError(error, await parseAuthMethod(resolvedHeaders));
3088
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
2875
3089
  }
2876
3090
  }
2877
3091
  getUrl() {
@@ -2887,6 +3101,11 @@ var GatewayImageModel = class {
2887
3101
  var providerMetadataEntrySchema = z4.z.object({
2888
3102
  images: z4.z.array(z4.z.unknown()).optional()
2889
3103
  }).catchall(z4.z.unknown());
3104
+ var gatewayImageUsageSchema = z4.z.object({
3105
+ inputTokens: z4.z.number().nullish(),
3106
+ outputTokens: z4.z.number().nullish(),
3107
+ totalTokens: z4.z.number().nullish()
3108
+ });
2890
3109
  var gatewayImageResponseSchema = z4.z.object({
2891
3110
  images: z4.z.array(z4.z.string()),
2892
3111
  // Always base64 strings over the wire
@@ -2895,22 +3114,197 @@ var gatewayImageResponseSchema = z4.z.object({
2895
3114
  type: z4.z.literal("other"),
2896
3115
  message: z4.z.string()
2897
3116
  })
2898
- ).optional(),
2899
- providerMetadata: z4.z.record(z4.z.string(), providerMetadataEntrySchema).optional()
3117
+ ).optional(),
3118
+ providerMetadata: z4.z.record(z4.z.string(), providerMetadataEntrySchema).optional(),
3119
+ usage: gatewayImageUsageSchema.optional()
3120
+ });
3121
+ var parallelSearchInputSchema = lazySchema(
3122
+ () => zodSchema(
3123
+ zod.z.object({
3124
+ objective: zod.z.string().describe(
3125
+ "Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."
3126
+ ),
3127
+ search_queries: zod.z.array(zod.z.string()).optional().describe(
3128
+ "Optional search queries to supplement the objective. Maximum 200 characters per query."
3129
+ ),
3130
+ mode: zod.z.enum(["one-shot", "agentic"]).optional().describe(
3131
+ 'Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'
3132
+ ),
3133
+ max_results: zod.z.number().optional().describe(
3134
+ "Maximum number of results to return (1-20). Defaults to 10 if not specified."
3135
+ ),
3136
+ source_policy: zod.z.object({
3137
+ include_domains: zod.z.array(zod.z.string()).optional().describe("List of domains to include in search results."),
3138
+ exclude_domains: zod.z.array(zod.z.string()).optional().describe("List of domains to exclude from search results."),
3139
+ after_date: zod.z.string().optional().describe(
3140
+ "Only include results published after this date (ISO 8601 format)."
3141
+ )
3142
+ }).optional().describe(
3143
+ "Source policy for controlling which domains to include/exclude and freshness."
3144
+ ),
3145
+ excerpts: zod.z.object({
3146
+ max_chars_per_result: zod.z.number().optional().describe("Maximum characters per result."),
3147
+ max_chars_total: zod.z.number().optional().describe("Maximum total characters across all results.")
3148
+ }).optional().describe("Excerpt configuration for controlling result length."),
3149
+ fetch_policy: zod.z.object({
3150
+ max_age_seconds: zod.z.number().optional().describe(
3151
+ "Maximum age in seconds for cached content. Set to 0 to always fetch fresh content."
3152
+ )
3153
+ }).optional().describe("Fetch policy for controlling content freshness.")
3154
+ })
3155
+ )
3156
+ );
3157
+ var parallelSearchOutputSchema = lazySchema(
3158
+ () => zodSchema(
3159
+ zod.z.union([
3160
+ // Success response
3161
+ zod.z.object({
3162
+ searchId: zod.z.string(),
3163
+ results: zod.z.array(
3164
+ zod.z.object({
3165
+ url: zod.z.string(),
3166
+ title: zod.z.string(),
3167
+ excerpt: zod.z.string(),
3168
+ publishDate: zod.z.string().nullable().optional(),
3169
+ relevanceScore: zod.z.number().optional()
3170
+ })
3171
+ )
3172
+ }),
3173
+ // Error response
3174
+ zod.z.object({
3175
+ error: zod.z.enum([
3176
+ "api_error",
3177
+ "rate_limit",
3178
+ "timeout",
3179
+ "invalid_input",
3180
+ "configuration_error",
3181
+ "unknown"
3182
+ ]),
3183
+ statusCode: zod.z.number().optional(),
3184
+ message: zod.z.string()
3185
+ })
3186
+ ])
3187
+ )
3188
+ );
3189
+ var parallelSearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
3190
+ id: "gateway.parallel_search",
3191
+ name: "parallel_search",
3192
+ inputSchema: parallelSearchInputSchema,
3193
+ outputSchema: parallelSearchOutputSchema
3194
+ });
3195
+ var parallelSearch = (config = {}) => parallelSearchToolFactory(config);
3196
+ var perplexitySearchInputSchema = lazySchema(
3197
+ () => zodSchema(
3198
+ zod.z.object({
3199
+ query: zod.z.union([zod.z.string(), zod.z.array(zod.z.string())]).describe(
3200
+ "Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."
3201
+ ),
3202
+ max_results: zod.z.number().optional().describe(
3203
+ "Maximum number of search results to return (1-20, default: 10)"
3204
+ ),
3205
+ max_tokens_per_page: zod.z.number().optional().describe(
3206
+ "Maximum number of tokens to extract per search result page (256-2048, default: 2048)"
3207
+ ),
3208
+ max_tokens: zod.z.number().optional().describe(
3209
+ "Maximum total tokens across all search results (default: 25000, max: 1000000)"
3210
+ ),
3211
+ country: zod.z.string().optional().describe(
3212
+ "Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"
3213
+ ),
3214
+ search_domain_filter: zod.z.array(zod.z.string()).optional().describe(
3215
+ "List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"
3216
+ ),
3217
+ search_language_filter: zod.z.array(zod.z.string()).optional().describe(
3218
+ "List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"
3219
+ ),
3220
+ search_after_date: zod.z.string().optional().describe(
3221
+ "Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."
3222
+ ),
3223
+ search_before_date: zod.z.string().optional().describe(
3224
+ "Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."
3225
+ ),
3226
+ last_updated_after_filter: zod.z.string().optional().describe(
3227
+ "Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."
3228
+ ),
3229
+ last_updated_before_filter: zod.z.string().optional().describe(
3230
+ "Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."
3231
+ ),
3232
+ search_recency_filter: zod.z.enum(["day", "week", "month", "year"]).optional().describe(
3233
+ "Filter results by relative time period. Cannot be used with search_after_date or search_before_date."
3234
+ )
3235
+ })
3236
+ )
3237
+ );
3238
+ var perplexitySearchOutputSchema = lazySchema(
3239
+ () => zodSchema(
3240
+ zod.z.union([
3241
+ // Success response
3242
+ zod.z.object({
3243
+ results: zod.z.array(
3244
+ zod.z.object({
3245
+ title: zod.z.string(),
3246
+ url: zod.z.string(),
3247
+ snippet: zod.z.string(),
3248
+ date: zod.z.string().optional(),
3249
+ lastUpdated: zod.z.string().optional()
3250
+ })
3251
+ ),
3252
+ id: zod.z.string()
3253
+ }),
3254
+ // Error response
3255
+ zod.z.object({
3256
+ error: zod.z.enum([
3257
+ "api_error",
3258
+ "rate_limit",
3259
+ "timeout",
3260
+ "invalid_input",
3261
+ "unknown"
3262
+ ]),
3263
+ statusCode: zod.z.number().optional(),
3264
+ message: zod.z.string()
3265
+ })
3266
+ ])
3267
+ )
3268
+ );
3269
+ var perplexitySearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
3270
+ id: "gateway.perplexity_search",
3271
+ name: "perplexity_search",
3272
+ inputSchema: perplexitySearchInputSchema,
3273
+ outputSchema: perplexitySearchOutputSchema
2900
3274
  });
3275
+ var perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);
3276
+ var gatewayTools = {
3277
+ /**
3278
+ * Search the web using Parallel AI's Search API for LLM-optimized excerpts.
3279
+ *
3280
+ * Takes a natural language objective and returns relevant excerpts,
3281
+ * replacing multiple keyword searches with a single call for broad
3282
+ * or complex queries. Supports different search types for depth vs
3283
+ * breadth tradeoffs.
3284
+ */
3285
+ parallelSearch,
3286
+ /**
3287
+ * Search the web using Perplexity's Search API for real-time information,
3288
+ * news, research papers, and articles.
3289
+ *
3290
+ * Provides ranked search results with advanced filtering options including
3291
+ * domain, language, date range, and recency filters.
3292
+ */
3293
+ perplexitySearch
3294
+ };
2901
3295
  async function getVercelRequestId() {
2902
- var _a832;
2903
- return (_a832 = (0, import_oidc.getContext)().headers) == null ? void 0 : _a832["x-vercel-id"];
3296
+ var _a932;
3297
+ return (_a932 = getContext().headers) == null ? void 0 : _a932["x-vercel-id"];
2904
3298
  }
2905
- var VERSION2 = "2.0.15";
3299
+ var VERSION2 = "2.0.88";
2906
3300
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
2907
3301
  function createGatewayProvider(options = {}) {
2908
- var _a832, _b84;
3302
+ var _a932, _b93;
2909
3303
  let pendingMetadata = null;
2910
3304
  let metadataCache = null;
2911
- const cacheRefreshMillis = (_a832 = options.metadataCacheRefreshMillis) != null ? _a832 : 1e3 * 60 * 5;
3305
+ const cacheRefreshMillis = (_a932 = options.metadataCacheRefreshMillis) != null ? _a932 : 1e3 * 60 * 5;
2912
3306
  let lastFetchTime = 0;
2913
- const baseURL = (_b84 = withoutTrailingSlash(options.baseURL)) != null ? _b84 : "https://ai-gateway.vercel.sh/v1/ai";
3307
+ const baseURL = (_b93 = withoutTrailingSlash(options.baseURL)) != null ? _b93 : "https://ai-gateway.vercel.sh/v1/ai";
2914
3308
  const getHeaders = async () => {
2915
3309
  const auth = await getGatewayAuthToken(options);
2916
3310
  if (auth) {
@@ -2943,13 +3337,18 @@ function createGatewayProvider(options = {}) {
2943
3337
  settingValue: void 0,
2944
3338
  environmentVariableName: "VERCEL_REGION"
2945
3339
  });
3340
+ const projectId = loadOptionalSetting({
3341
+ settingValue: void 0,
3342
+ environmentVariableName: "VERCEL_PROJECT_ID"
3343
+ });
2946
3344
  return async () => {
2947
3345
  const requestId = await getVercelRequestId();
2948
3346
  return {
2949
3347
  ...deploymentId && { "ai-o11y-deployment-id": deploymentId },
2950
3348
  ...environment && { "ai-o11y-environment": environment },
2951
3349
  ...region && { "ai-o11y-region": region },
2952
- ...requestId && { "ai-o11y-request-id": requestId }
3350
+ ...requestId && { "ai-o11y-request-id": requestId },
3351
+ ...projectId && { "ai-o11y-project-id": projectId }
2953
3352
  };
2954
3353
  };
2955
3354
  };
@@ -2963,8 +3362,8 @@ function createGatewayProvider(options = {}) {
2963
3362
  });
2964
3363
  };
2965
3364
  const getAvailableModels = async () => {
2966
- var _a923, _b92, _c;
2967
- const now2 = (_c = (_b92 = (_a923 = options._internal) == null ? void 0 : _a923.currentDate) == null ? void 0 : _b92.call(_a923).getTime()) != null ? _c : Date.now();
3365
+ var _a1022, _b103, _c;
3366
+ const now2 = (_c = (_b103 = (_a1022 = options._internal) == null ? void 0 : _a1022.currentDate) == null ? void 0 : _b103.call(_a1022).getTime()) != null ? _c : Date.now();
2968
3367
  if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) {
2969
3368
  lastFetchTime = now2;
2970
3369
  pendingMetadata = new GatewayFetchMetadata({
@@ -2995,6 +3394,30 @@ function createGatewayProvider(options = {}) {
2995
3394
  );
2996
3395
  });
2997
3396
  };
3397
+ const getSpendReport = async (params) => {
3398
+ return new GatewaySpendReport({
3399
+ baseURL,
3400
+ headers: getHeaders,
3401
+ fetch: options.fetch
3402
+ }).getSpendReport(params).catch(async (error) => {
3403
+ throw await asGatewayError(
3404
+ error,
3405
+ await parseAuthMethod(await getHeaders())
3406
+ );
3407
+ });
3408
+ };
3409
+ const getGenerationInfo = async (params) => {
3410
+ return new GatewayGenerationInfoFetcher({
3411
+ baseURL,
3412
+ headers: getHeaders,
3413
+ fetch: options.fetch
3414
+ }).getGenerationInfo(params).catch(async (error) => {
3415
+ throw await asGatewayError(
3416
+ error,
3417
+ await parseAuthMethod(await getHeaders())
3418
+ );
3419
+ });
3420
+ };
2998
3421
  const provider = function(modelId) {
2999
3422
  if (new.target) {
3000
3423
  throw new Error(
@@ -3005,6 +3428,8 @@ function createGatewayProvider(options = {}) {
3005
3428
  };
3006
3429
  provider.getAvailableModels = getAvailableModels;
3007
3430
  provider.getCredits = getCredits;
3431
+ provider.getSpendReport = getSpendReport;
3432
+ provider.getGenerationInfo = getGenerationInfo;
3008
3433
  provider.imageModel = (modelId) => {
3009
3434
  return new GatewayImageModel(modelId, {
3010
3435
  provider: "gateway",
@@ -3024,6 +3449,7 @@ function createGatewayProvider(options = {}) {
3024
3449
  o11yHeaders: createO11yHeaders()
3025
3450
  });
3026
3451
  };
3452
+ provider.tools = gatewayTools;
3027
3453
  return provider;
3028
3454
  }
3029
3455
  createGatewayProvider();
@@ -3039,7 +3465,7 @@ async function getGatewayAuthToken(options) {
3039
3465
  };
3040
3466
  }
3041
3467
  try {
3042
- const oidcToken = await (0, import_oidc2.getVercelOidcToken)();
3468
+ const oidcToken = await getVercelOidcToken();
3043
3469
  return {
3044
3470
  token: oidcToken,
3045
3471
  authMethod: "oidc"
@@ -3141,12 +3567,12 @@ function registerGlobal(type, instance, diag, allowOverride) {
3141
3567
  return true;
3142
3568
  }
3143
3569
  function getGlobal(type) {
3144
- var _a164, _b84;
3570
+ var _a164, _b93;
3145
3571
  var globalVersion = (_a164 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a164 === void 0 ? void 0 : _a164.version;
3146
3572
  if (!globalVersion || !isCompatible(globalVersion)) {
3147
3573
  return;
3148
3574
  }
3149
- return (_b84 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b84 === void 0 ? void 0 : _b84[type];
3575
+ return (_b93 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b93 === void 0 ? void 0 : _b93[type];
3150
3576
  }
3151
3577
  function unregisterGlobal(type, diag) {
3152
3578
  diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION22 + ".");
@@ -3311,7 +3737,7 @@ var DiagAPI = (
3311
3737
  }
3312
3738
  var self = this;
3313
3739
  var setLogger = function(logger, optionsOrLogLevel) {
3314
- var _a164, _b84, _c;
3740
+ var _a164, _b93, _c;
3315
3741
  if (optionsOrLogLevel === void 0) {
3316
3742
  optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
3317
3743
  }
@@ -3326,7 +3752,7 @@ var DiagAPI = (
3326
3752
  };
3327
3753
  }
3328
3754
  var oldLogger = getGlobal("diag");
3329
- var newLogger = createLogLevelDiagLogger((_b84 = optionsOrLogLevel.logLevel) !== null && _b84 !== void 0 ? _b84 : DiagLogLevel.INFO, logger);
3755
+ var newLogger = createLogLevelDiagLogger((_b93 = optionsOrLogLevel.logLevel) !== null && _b93 !== void 0 ? _b93 : DiagLogLevel.INFO, logger);
3330
3756
  if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
3331
3757
  var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
3332
3758
  oldLogger.warn("Current logger will be overwritten from " + stack);
@@ -3790,8 +4216,8 @@ var dataContentSchema = z4.z.union([
3790
4216
  z4.z.custom(
3791
4217
  // Buffer might not be available in some environments such as CloudFlare:
3792
4218
  (value) => {
3793
- var _a164, _b84;
3794
- return (_b84 = (_a164 = globalThis.Buffer) == null ? void 0 : _a164.isBuffer(value)) != null ? _b84 : false;
4219
+ var _a164, _b93;
4220
+ return (_b93 = (_a164 = globalThis.Buffer) == null ? void 0 : _a164.isBuffer(value)) != null ? _b93 : false;
3795
4221
  },
3796
4222
  { message: "Must be a Buffer" }
3797
4223
  )
@@ -4401,7 +4827,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4401
4827
  var __getOwnPropNames = Object.getOwnPropertyNames;
4402
4828
  var __getProtoOf = Object.getPrototypeOf;
4403
4829
  var __hasOwnProp = Object.prototype.hasOwnProperty;
4404
- var __commonJS3 = (cb, mod) => function __require2() {
4830
+ var __commonJS = (cb, mod) => function __require2() {
4405
4831
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
4406
4832
  };
4407
4833
  var __copyProps = (to, from, except, desc) => {
@@ -4412,7 +4838,7 @@ var __copyProps = (to, from, except, desc) => {
4412
4838
  }
4413
4839
  return to;
4414
4840
  };
4415
- var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
4841
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
4416
4842
  // If the importer is in node compatibility mode or this is not an ESM
4417
4843
  // file that has been converted to a CommonJS file using a Babel-
4418
4844
  // compatible transform (i.e. "__esModule" has not been set), then set
@@ -4420,8 +4846,8 @@ var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create(__g
4420
4846
  __defProp2(target, "default", { value: mod, enumerable: true }),
4421
4847
  mod
4422
4848
  ));
4423
- var require_secure_json_parse = __commonJS3({
4424
- "../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports$1, module) {
4849
+ var require_secure_json_parse = __commonJS({
4850
+ "../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports, module) {
4425
4851
  var hasBuffer = typeof Buffer !== "undefined";
4426
4852
  var suspectProtoRx3 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
4427
4853
  var suspectConstructorRx3 = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
@@ -4521,10 +4947,10 @@ var require_secure_json_parse = __commonJS3({
4521
4947
  module.exports.scan = filter3;
4522
4948
  }
4523
4949
  });
4524
- var marker16 = "vercel.ai.error";
4525
- var symbol16 = Symbol.for(marker16);
4526
- var _a16;
4527
- var _AISDKError3 = class _AISDKError22 extends Error {
4950
+ var marker17 = "vercel.ai.error";
4951
+ var symbol17 = Symbol.for(marker17);
4952
+ var _a17;
4953
+ var _AISDKError2 = class _AISDKError22 extends Error {
4528
4954
  /**
4529
4955
  * Creates an AI SDK Error.
4530
4956
  *
@@ -4539,7 +4965,7 @@ var _AISDKError3 = class _AISDKError22 extends Error {
4539
4965
  cause
4540
4966
  }) {
4541
4967
  super(message);
4542
- this[_a16] = true;
4968
+ this[_a17] = true;
4543
4969
  this.name = name146;
4544
4970
  this.cause = cause;
4545
4971
  }
@@ -4549,15 +4975,15 @@ var _AISDKError3 = class _AISDKError22 extends Error {
4549
4975
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
4550
4976
  */
4551
4977
  static isInstance(error) {
4552
- return _AISDKError22.hasMarker(error, marker16);
4978
+ return _AISDKError22.hasMarker(error, marker17);
4553
4979
  }
4554
4980
  static hasMarker(error, marker156) {
4555
4981
  const markerSymbol = Symbol.for(marker156);
4556
4982
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
4557
4983
  }
4558
4984
  };
4559
- _a16 = symbol16;
4560
- var AISDKError2 = _AISDKError3;
4985
+ _a17 = symbol17;
4986
+ var AISDKError2 = _AISDKError2;
4561
4987
  function getErrorMessage3(error) {
4562
4988
  if (error == null) {
4563
4989
  return "unknown error";
@@ -4634,7 +5060,7 @@ var name123 = "AI_TypeValidationError";
4634
5060
  var marker133 = `vercel.ai.error.${name123}`;
4635
5061
  var symbol133 = Symbol.for(marker133);
4636
5062
  var _a133;
4637
- var _TypeValidationError3 = class _TypeValidationError22 extends AISDKError2 {
5063
+ var _TypeValidationError2 = class _TypeValidationError22 extends AISDKError2 {
4638
5064
  constructor({ value, cause }) {
4639
5065
  super({
4640
5066
  name: name123,
@@ -4666,7 +5092,7 @@ Error message: ${getErrorMessage3(cause)}`,
4666
5092
  }
4667
5093
  };
4668
5094
  _a133 = symbol133;
4669
- var TypeValidationError2 = _TypeValidationError3;
5095
+ var TypeValidationError2 = _TypeValidationError2;
4670
5096
  var customAlphabet = (alphabet, defaultSize = 21) => {
4671
5097
  return (size = defaultSize) => {
4672
5098
  let id = "";
@@ -4677,7 +5103,7 @@ var customAlphabet = (alphabet, defaultSize = 21) => {
4677
5103
  return id;
4678
5104
  };
4679
5105
  };
4680
- var import_secure_json_parse = __toESM3(require_secure_json_parse());
5106
+ var import_secure_json_parse = __toESM(require_secure_json_parse());
4681
5107
  function convertAsyncIteratorToReadableStream(iterator) {
4682
5108
  return new ReadableStream({
4683
5109
  /**
@@ -5033,7 +5459,7 @@ function parseIntersectionDef2(def, refs) {
5033
5459
  ...refs,
5034
5460
  currentPath: [...refs.currentPath, "allOf", "1"]
5035
5461
  })
5036
- ].filter((x) => !!x);
5462
+ ].filter((x2) => !!x2);
5037
5463
  let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
5038
5464
  const mergedAllOf = [];
5039
5465
  allOf.forEach((schema) => {
@@ -5262,7 +5688,7 @@ function escapeNonAlphaNumeric2(source) {
5262
5688
  return result;
5263
5689
  }
5264
5690
  function addFormat2(schema, value, message, refs) {
5265
- if (schema.format || schema.anyOf?.some((x) => x.format)) {
5691
+ if (schema.format || schema.anyOf?.some((x2) => x2.format)) {
5266
5692
  if (!schema.anyOf) {
5267
5693
  schema.anyOf = [];
5268
5694
  }
@@ -5290,7 +5716,7 @@ function addFormat2(schema, value, message, refs) {
5290
5716
  }
5291
5717
  }
5292
5718
  function addPattern2(schema, regex, message, refs) {
5293
- if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
5719
+ if (schema.pattern || schema.allOf?.some((x2) => x2.pattern)) {
5294
5720
  if (!schema.allOf) {
5295
5721
  schema.allOf = [];
5296
5722
  }
@@ -5498,17 +5924,17 @@ function parseUnionDef2(def, refs) {
5498
5924
  if (refs.target === "openApi3")
5499
5925
  return asAnyOf2(def, refs);
5500
5926
  const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
5501
- if (options.every((x) => x._def.typeName in primitiveMappings2 && (!x._def.checks || !x._def.checks.length))) {
5502
- const types = options.reduce((types2, x) => {
5503
- const type = primitiveMappings2[x._def.typeName];
5927
+ if (options.every((x2) => x2._def.typeName in primitiveMappings2 && (!x2._def.checks || !x2._def.checks.length))) {
5928
+ const types = options.reduce((types2, x2) => {
5929
+ const type = primitiveMappings2[x2._def.typeName];
5504
5930
  return type && !types2.includes(type) ? [...types2, type] : types2;
5505
5931
  }, []);
5506
5932
  return {
5507
5933
  type: types.length > 1 ? types : types[0]
5508
5934
  };
5509
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
5510
- const types = options.reduce((acc, x) => {
5511
- const type = typeof x._def.value;
5935
+ } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
5936
+ const types = options.reduce((acc, x2) => {
5937
+ const type = typeof x2._def.value;
5512
5938
  switch (type) {
5513
5939
  case "string":
5514
5940
  case "number":
@@ -5517,7 +5943,7 @@ function parseUnionDef2(def, refs) {
5517
5943
  case "bigint":
5518
5944
  return [...acc, "integer"];
5519
5945
  case "object":
5520
- if (x._def.value === null)
5946
+ if (x2._def.value === null)
5521
5947
  return [...acc, "null"];
5522
5948
  case "symbol":
5523
5949
  case "undefined":
@@ -5527,30 +5953,30 @@ function parseUnionDef2(def, refs) {
5527
5953
  }
5528
5954
  }, []);
5529
5955
  if (types.length === options.length) {
5530
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
5956
+ const uniqueTypes = types.filter((x2, i, a) => a.indexOf(x2) === i);
5531
5957
  return {
5532
5958
  type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
5533
- enum: options.reduce((acc, x) => {
5534
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
5959
+ enum: options.reduce((acc, x2) => {
5960
+ return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
5535
5961
  }, [])
5536
5962
  };
5537
5963
  }
5538
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
5964
+ } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
5539
5965
  return {
5540
5966
  type: "string",
5541
- enum: options.reduce((acc, x) => [
5967
+ enum: options.reduce((acc, x2) => [
5542
5968
  ...acc,
5543
- ...x._def.values.filter((x2) => !acc.includes(x2))
5969
+ ...x2._def.values.filter((x22) => !acc.includes(x22))
5544
5970
  ], [])
5545
5971
  };
5546
5972
  }
5547
5973
  return asAnyOf2(def, refs);
5548
5974
  }
5549
5975
  var asAnyOf2 = (def, refs) => {
5550
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef2(x._def, {
5976
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i) => parseDef2(x2._def, {
5551
5977
  ...refs,
5552
5978
  currentPath: [...refs.currentPath, "anyOf", `${i}`]
5553
- })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
5979
+ })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0));
5554
5980
  return anyOf.length ? { anyOf } : void 0;
5555
5981
  };
5556
5982
  function parseNullableDef2(def, refs) {
@@ -5730,7 +6156,7 @@ var parsePipelineDef2 = (def, refs) => {
5730
6156
  currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
5731
6157
  });
5732
6158
  return {
5733
- allOf: [a, b].filter((x) => x !== void 0)
6159
+ allOf: [a, b].filter((x2) => x2 !== void 0)
5734
6160
  };
5735
6161
  };
5736
6162
  function parsePromiseDef2(def, refs) {
@@ -5759,10 +6185,10 @@ function parseTupleDef2(def, refs) {
5759
6185
  return {
5760
6186
  type: "array",
5761
6187
  minItems: def.items.length,
5762
- items: def.items.map((x, i) => parseDef2(x._def, {
6188
+ items: def.items.map((x2, i) => parseDef2(x2._def, {
5763
6189
  ...refs,
5764
6190
  currentPath: [...refs.currentPath, "items", `${i}`]
5765
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
6191
+ })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []),
5766
6192
  additionalItems: parseDef2(def.rest._def, {
5767
6193
  ...refs,
5768
6194
  currentPath: [...refs.currentPath, "additionalItems"]
@@ -5773,10 +6199,10 @@ function parseTupleDef2(def, refs) {
5773
6199
  type: "array",
5774
6200
  minItems: def.items.length,
5775
6201
  maxItems: def.items.length,
5776
- items: def.items.map((x, i) => parseDef2(x._def, {
6202
+ items: def.items.map((x2, i) => parseDef2(x2._def, {
5777
6203
  ...refs,
5778
6204
  currentPath: [...refs.currentPath, "items", `${i}`]
5779
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
6205
+ })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], [])
5780
6206
  };
5781
6207
  }
5782
6208
  }
@@ -6610,7 +7036,7 @@ function asSchema2(schema) {
6610
7036
  return isSchema2(schema) ? schema : zodSchema2(schema);
6611
7037
  }
6612
7038
  var _globalThis2 = typeof globalThis === "object" ? globalThis : global;
6613
- var VERSION3 = "1.9.0";
7039
+ var VERSION4 = "1.9.0";
6614
7040
  var re2 = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
6615
7041
  function _makeCompatibilityCheck2(ownVersion) {
6616
7042
  var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
@@ -6675,8 +7101,8 @@ function _makeCompatibilityCheck2(ownVersion) {
6675
7101
  return _reject(globalVersion);
6676
7102
  };
6677
7103
  }
6678
- var isCompatible2 = _makeCompatibilityCheck2(VERSION3);
6679
- var major2 = VERSION3.split(".")[0];
7104
+ var isCompatible2 = _makeCompatibilityCheck2(VERSION4);
7105
+ var major2 = VERSION4.split(".")[0];
6680
7106
  var GLOBAL_OPENTELEMETRY_API_KEY2 = /* @__PURE__ */ Symbol.for("opentelemetry.js.api." + major2);
6681
7107
  var _global2 = _globalThis2;
6682
7108
  function registerGlobal2(type, instance, diag, allowOverride) {
@@ -6685,32 +7111,32 @@ function registerGlobal2(type, instance, diag, allowOverride) {
6685
7111
  allowOverride = false;
6686
7112
  }
6687
7113
  var api = _global2[GLOBAL_OPENTELEMETRY_API_KEY2] = (_a173 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) !== null && _a173 !== void 0 ? _a173 : {
6688
- version: VERSION3
7114
+ version: VERSION4
6689
7115
  };
6690
7116
  if (!allowOverride && api[type]) {
6691
7117
  var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
6692
7118
  diag.error(err.stack || err.message);
6693
7119
  return false;
6694
7120
  }
6695
- if (api.version !== VERSION3) {
6696
- var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION3);
7121
+ if (api.version !== VERSION4) {
7122
+ var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION4);
6697
7123
  diag.error(err.stack || err.message);
6698
7124
  return false;
6699
7125
  }
6700
7126
  api[type] = instance;
6701
- diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION3 + ".");
7127
+ diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION4 + ".");
6702
7128
  return true;
6703
7129
  }
6704
7130
  function getGlobal2(type) {
6705
- var _a173, _b17;
7131
+ var _a173, _b19;
6706
7132
  var globalVersion = (_a173 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) === null || _a173 === void 0 ? void 0 : _a173.version;
6707
7133
  if (!globalVersion || !isCompatible2(globalVersion)) {
6708
7134
  return;
6709
7135
  }
6710
- return (_b17 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) === null || _b17 === void 0 ? void 0 : _b17[type];
7136
+ return (_b19 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) === null || _b19 === void 0 ? void 0 : _b19[type];
6711
7137
  }
6712
7138
  function unregisterGlobal2(type, diag) {
6713
- diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION3 + ".");
7139
+ diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION4 + ".");
6714
7140
  var api = _global2[GLOBAL_OPENTELEMETRY_API_KEY2];
6715
7141
  if (api) {
6716
7142
  delete api[type];
@@ -6872,7 +7298,7 @@ var DiagAPI2 = (
6872
7298
  }
6873
7299
  var self = this;
6874
7300
  var setLogger = function(logger, optionsOrLogLevel) {
6875
- var _a173, _b17, _c;
7301
+ var _a173, _b19, _c;
6876
7302
  if (optionsOrLogLevel === void 0) {
6877
7303
  optionsOrLogLevel = { logLevel: DiagLogLevel2.INFO };
6878
7304
  }
@@ -6887,7 +7313,7 @@ var DiagAPI2 = (
6887
7313
  };
6888
7314
  }
6889
7315
  var oldLogger = getGlobal2("diag");
6890
- var newLogger = createLogLevelDiagLogger2((_b17 = optionsOrLogLevel.logLevel) !== null && _b17 !== void 0 ? _b17 : DiagLogLevel2.INFO, logger);
7316
+ var newLogger = createLogLevelDiagLogger2((_b19 = optionsOrLogLevel.logLevel) !== null && _b19 !== void 0 ? _b19 : DiagLogLevel2.INFO, logger);
6891
7317
  if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
6892
7318
  var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
6893
7319
  oldLogger.warn("Current logger will be overwritten from " + stack);
@@ -7364,8 +7790,8 @@ var dataContentSchema2 = zod.z.union([
7364
7790
  zod.z.custom(
7365
7791
  // Buffer might not be available in some environments such as CloudFlare:
7366
7792
  (value) => {
7367
- var _a173, _b17;
7368
- return (_b17 = (_a173 = globalThis.Buffer) == null ? void 0 : _a173.isBuffer(value)) != null ? _b17 : false;
7793
+ var _a173, _b19;
7794
+ return (_b19 = (_a173 = globalThis.Buffer) == null ? void 0 : _a173.isBuffer(value)) != null ? _b19 : false;
7369
7795
  },
7370
7796
  { message: "Must be a Buffer" }
7371
7797
  )
@@ -8010,11 +8436,11 @@ function trimStartOfStream() {
8010
8436
  return text22;
8011
8437
  };
8012
8438
  }
8013
- var marker18 = "vercel.ai.error";
8014
- var symbol18 = Symbol.for(marker18);
8015
- var _a18;
8016
- var _b8;
8017
- var AISDKError3 = class _AISDKError4 extends (_b8 = Error, _a18 = symbol18, _b8) {
8439
+ var marker19 = "vercel.ai.error";
8440
+ var symbol19 = Symbol.for(marker19);
8441
+ var _a19;
8442
+ var _b17;
8443
+ var AISDKError3 = class _AISDKError3 extends (_b17 = Error, _a19 = symbol19, _b17) {
8018
8444
  /**
8019
8445
  * Creates an AI SDK Error.
8020
8446
  *
@@ -8029,7 +8455,7 @@ var AISDKError3 = class _AISDKError4 extends (_b8 = Error, _a18 = symbol18, _b8)
8029
8455
  cause
8030
8456
  }) {
8031
8457
  super(message);
8032
- this[_a18] = true;
8458
+ this[_a19] = true;
8033
8459
  this.name = name1422;
8034
8460
  this.cause = cause;
8035
8461
  }
@@ -8039,7 +8465,7 @@ var AISDKError3 = class _AISDKError4 extends (_b8 = Error, _a18 = symbol18, _b8)
8039
8465
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
8040
8466
  */
8041
8467
  static isInstance(error) {
8042
- return _AISDKError4.hasMarker(error, marker18);
8468
+ return _AISDKError3.hasMarker(error, marker19);
8043
8469
  }
8044
8470
  static hasMarker(error, marker1522) {
8045
8471
  const markerSymbol = Symbol.for(marker1522);
@@ -8050,8 +8476,8 @@ var name18 = "AI_APICallError";
8050
8476
  var marker25 = `vercel.ai.error.${name18}`;
8051
8477
  var symbol25 = Symbol.for(marker25);
8052
8478
  var _a25;
8053
- var _b22;
8054
- var APICallError3 = class extends (_b22 = AISDKError3, _a25 = symbol25, _b22) {
8479
+ var _b23;
8480
+ var APICallError3 = class extends (_b23 = AISDKError3, _a25 = symbol25, _b23) {
8055
8481
  constructor({
8056
8482
  message,
8057
8483
  url,
@@ -8085,8 +8511,8 @@ var name25 = "AI_EmptyResponseBodyError";
8085
8511
  var marker35 = `vercel.ai.error.${name25}`;
8086
8512
  var symbol35 = Symbol.for(marker35);
8087
8513
  var _a35;
8088
- var _b32;
8089
- var EmptyResponseBodyError2 = class extends (_b32 = AISDKError3, _a35 = symbol35, _b32) {
8514
+ var _b33;
8515
+ var EmptyResponseBodyError2 = class extends (_b33 = AISDKError3, _a35 = symbol35, _b33) {
8090
8516
  // used in isInstance
8091
8517
  constructor({ message = "Empty response body" } = {}) {
8092
8518
  super({ name: name25, message });
@@ -8112,8 +8538,8 @@ var name35 = "AI_InvalidArgumentError";
8112
8538
  var marker45 = `vercel.ai.error.${name35}`;
8113
8539
  var symbol45 = Symbol.for(marker45);
8114
8540
  var _a45;
8115
- var _b42;
8116
- var InvalidArgumentError3 = class extends (_b42 = AISDKError3, _a45 = symbol45, _b42) {
8541
+ var _b43;
8542
+ var InvalidArgumentError3 = class extends (_b43 = AISDKError3, _a45 = symbol45, _b43) {
8117
8543
  constructor({
8118
8544
  message,
8119
8545
  cause,
@@ -8131,8 +8557,8 @@ var name65 = "AI_JSONParseError";
8131
8557
  var marker75 = `vercel.ai.error.${name65}`;
8132
8558
  var symbol75 = Symbol.for(marker75);
8133
8559
  var _a75;
8134
- var _b72;
8135
- var JSONParseError3 = class extends (_b72 = AISDKError3, _a75 = symbol75, _b72) {
8560
+ var _b73;
8561
+ var JSONParseError3 = class extends (_b73 = AISDKError3, _a75 = symbol75, _b73) {
8136
8562
  constructor({ text: text4, cause }) {
8137
8563
  super({
8138
8564
  name: name65,
@@ -8151,8 +8577,8 @@ var name105 = "AI_NoSuchModelError";
8151
8577
  var marker115 = `vercel.ai.error.${name105}`;
8152
8578
  var symbol115 = Symbol.for(marker115);
8153
8579
  var _a115;
8154
- var _b11;
8155
- var NoSuchModelError3 = class extends (_b11 = AISDKError3, _a115 = symbol115, _b11) {
8580
+ var _b112;
8581
+ var NoSuchModelError3 = class extends (_b112 = AISDKError3, _a115 = symbol115, _b112) {
8156
8582
  constructor({
8157
8583
  errorName = name105,
8158
8584
  modelId,
@@ -8172,8 +8598,8 @@ var name125 = "AI_TypeValidationError";
8172
8598
  var marker135 = `vercel.ai.error.${name125}`;
8173
8599
  var symbol135 = Symbol.for(marker135);
8174
8600
  var _a135;
8175
- var _b13;
8176
- var TypeValidationError3 = class _TypeValidationError4 extends (_b13 = AISDKError3, _a135 = symbol135, _b13) {
8601
+ var _b132;
8602
+ var TypeValidationError3 = class _TypeValidationError3 extends (_b132 = AISDKError3, _a135 = symbol135, _b132) {
8177
8603
  constructor({
8178
8604
  value,
8179
8605
  cause,
@@ -8224,11 +8650,11 @@ Error message: ${getErrorMessage4(cause)}`,
8224
8650
  cause,
8225
8651
  context: context2
8226
8652
  }) {
8227
- var _a1522, _b152, _c;
8228
- if (_TypeValidationError4.isInstance(cause) && cause.value === value && ((_a1522 = cause.context) == null ? void 0 : _a1522.field) === (context2 == null ? void 0 : context2.field) && ((_b152 = cause.context) == null ? void 0 : _b152.entityName) === (context2 == null ? void 0 : context2.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context2 == null ? void 0 : context2.entityId)) {
8653
+ var _a1522, _b1522, _c;
8654
+ if (_TypeValidationError3.isInstance(cause) && cause.value === value && ((_a1522 = cause.context) == null ? void 0 : _a1522.field) === (context2 == null ? void 0 : context2.field) && ((_b1522 = cause.context) == null ? void 0 : _b1522.entityName) === (context2 == null ? void 0 : context2.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context2 == null ? void 0 : context2.entityId)) {
8229
8655
  return cause;
8230
8656
  }
8231
- return new _TypeValidationError4({ value, cause, context: context2 });
8657
+ return new _TypeValidationError3({ value, cause, context: context2 });
8232
8658
  }
8233
8659
  };
8234
8660
  var ParseError2 = class extends Error {
@@ -8236,6 +8662,9 @@ var ParseError2 = class extends Error {
8236
8662
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
8237
8663
  }
8238
8664
  };
8665
+ var LF = 10;
8666
+ var CR = 13;
8667
+ var SPACE = 32;
8239
8668
  function noop2(_arg) {
8240
8669
  }
8241
8670
  function createParser2(callbacks) {
@@ -8243,39 +8672,109 @@ function createParser2(callbacks) {
8243
8672
  throw new TypeError(
8244
8673
  "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
8245
8674
  );
8246
- const { onEvent = noop2, onError = noop2, onRetry = noop2, onComment } = callbacks;
8247
- let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
8248
- function feed(newChunk) {
8249
- const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines2(`${incompleteLine}${chunk}`);
8250
- for (const line of complete)
8251
- parseLine(line);
8252
- incompleteLine = incomplete, isFirstChunk = false;
8675
+ const { onEvent = noop2, onError = noop2, onRetry = noop2, onComment } = callbacks, pendingFragments = [];
8676
+ let isFirstChunk = true, id, data = "", dataLines = 0, eventType;
8677
+ function feed(chunk) {
8678
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
8679
+ const trailing2 = processLines(chunk);
8680
+ trailing2 !== "" && pendingFragments.push(trailing2);
8681
+ return;
8682
+ }
8683
+ if (chunk.indexOf(`
8684
+ `) === -1 && chunk.indexOf("\r") === -1) {
8685
+ pendingFragments.push(chunk);
8686
+ return;
8687
+ }
8688
+ pendingFragments.push(chunk);
8689
+ const input = pendingFragments.join("");
8690
+ pendingFragments.length = 0;
8691
+ const trailing = processLines(input);
8692
+ trailing !== "" && pendingFragments.push(trailing);
8253
8693
  }
8254
- function parseLine(line) {
8255
- if (line === "") {
8694
+ function processLines(chunk) {
8695
+ let searchIndex = 0;
8696
+ if (chunk.indexOf("\r") === -1) {
8697
+ let lfIndex = chunk.indexOf(`
8698
+ `, searchIndex);
8699
+ for (; lfIndex !== -1; ) {
8700
+ if (searchIndex === lfIndex) {
8701
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
8702
+ `, searchIndex);
8703
+ continue;
8704
+ }
8705
+ const firstCharCode = chunk.charCodeAt(searchIndex);
8706
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
8707
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
8708
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
8709
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
8710
+ `, searchIndex);
8711
+ continue;
8712
+ }
8713
+ data = dataLines === 0 ? value : `${data}
8714
+ ${value}`, dataLines++;
8715
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
8716
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
8717
+ lfIndex
8718
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
8719
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
8720
+ `, searchIndex);
8721
+ }
8722
+ return chunk.slice(searchIndex);
8723
+ }
8724
+ for (; searchIndex < chunk.length; ) {
8725
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
8726
+ `, searchIndex);
8727
+ let lineEnd = -1;
8728
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
8729
+ break;
8730
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
8731
+ }
8732
+ return chunk.slice(searchIndex);
8733
+ }
8734
+ function parseLine(chunk, start, end) {
8735
+ if (start === end) {
8256
8736
  dispatchEvent();
8257
8737
  return;
8258
8738
  }
8259
- if (line.startsWith(":")) {
8260
- onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
8739
+ const firstCharCode = chunk.charCodeAt(start);
8740
+ if (isDataPrefix(chunk, start, firstCharCode)) {
8741
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
8742
+ data = dataLines === 0 ? value2 : `${data}
8743
+ ${value2}`, dataLines++;
8261
8744
  return;
8262
8745
  }
8263
- const fieldSeparatorIndex = line.indexOf(":");
8264
- if (fieldSeparatorIndex !== -1) {
8265
- const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
8266
- processField(field, value, line);
8746
+ if (isEventPrefix(chunk, start, firstCharCode)) {
8747
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
8267
8748
  return;
8268
8749
  }
8269
- processField(line, "", line);
8750
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
8751
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
8752
+ id = value2.includes("\0") ? void 0 : value2;
8753
+ return;
8754
+ }
8755
+ if (firstCharCode === 58) {
8756
+ if (onComment) {
8757
+ const line2 = chunk.slice(start, end);
8758
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
8759
+ }
8760
+ return;
8761
+ }
8762
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
8763
+ if (fieldSeparatorIndex === -1) {
8764
+ processField(line, "", line);
8765
+ return;
8766
+ }
8767
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
8768
+ processField(field, value, line);
8270
8769
  }
8271
8770
  function processField(field, value, line) {
8272
8771
  switch (field) {
8273
8772
  case "event":
8274
- eventType = value;
8773
+ eventType = value || void 0;
8275
8774
  break;
8276
8775
  case "data":
8277
- data = `${data}${value}
8278
- `;
8776
+ data = dataLines === 0 ? value : `${data}
8777
+ ${value}`, dataLines++;
8279
8778
  break;
8280
8779
  case "id":
8281
8780
  id = value.includes("\0") ? void 0 : value;
@@ -8300,37 +8799,26 @@ function createParser2(callbacks) {
8300
8799
  }
8301
8800
  }
8302
8801
  function dispatchEvent() {
8303
- data.length > 0 && onEvent({
8802
+ dataLines > 0 && onEvent({
8304
8803
  id,
8305
- event: eventType || void 0,
8306
- // If the data buffer's last character is a U+000A LINE FEED (LF) character,
8307
- // then remove the last character from the data buffer.
8308
- data: data.endsWith(`
8309
- `) ? data.slice(0, -1) : data
8310
- }), id = void 0, data = "", eventType = "";
8804
+ event: eventType,
8805
+ data
8806
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
8311
8807
  }
8312
8808
  function reset(options = {}) {
8313
- incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
8809
+ if (options.consume && pendingFragments.length > 0) {
8810
+ const incompleteLine = pendingFragments.join("");
8811
+ parseLine(incompleteLine, 0, incompleteLine.length);
8812
+ }
8813
+ isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0;
8314
8814
  }
8315
8815
  return { feed, reset };
8316
8816
  }
8317
- function splitLines2(chunk) {
8318
- const lines = [];
8319
- let incompleteLine = "", searchIndex = 0;
8320
- for (; searchIndex < chunk.length; ) {
8321
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
8322
- `, searchIndex);
8323
- let lineEnd = -1;
8324
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
8325
- incompleteLine = chunk.slice(searchIndex);
8326
- break;
8327
- } else {
8328
- const line = chunk.slice(searchIndex, lineEnd);
8329
- lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
8330
- ` && searchIndex++;
8331
- }
8332
- }
8333
- return [lines, incompleteLine];
8817
+ function isDataPrefix(chunk, i, firstCharCode) {
8818
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
8819
+ }
8820
+ function isEventPrefix(chunk, i, firstCharCode) {
8821
+ return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
8334
8822
  }
8335
8823
  var EventSourceParserStream2 = class extends TransformStream {
8336
8824
  constructor({ onError, onRetry, onComment } = {}) {
@@ -8502,7 +8990,7 @@ function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
8502
8990
  );
8503
8991
  return Object.fromEntries(normalizedHeaders.entries());
8504
8992
  }
8505
- var VERSION4 = "4.0.19";
8993
+ var VERSION5 = "4.0.27";
8506
8994
  var getOriginalFetch3 = () => globalThis.fetch;
8507
8995
  var getFromApi2 = async ({
8508
8996
  url,
@@ -8517,7 +9005,7 @@ var getFromApi2 = async ({
8517
9005
  method: "GET",
8518
9006
  headers: withUserAgentSuffix2(
8519
9007
  headers,
8520
- `ai-sdk/provider-utils/${VERSION4}`,
9008
+ `ai-sdk/provider-utils/${VERSION5}`,
8521
9009
  getRuntimeEnvironmentUserAgent2()
8522
9010
  ),
8523
9011
  signal: abortSignal
@@ -8634,7 +9122,7 @@ function secureJsonParse2(text4) {
8634
9122
  Error.stackTraceLimit = stackTraceLimit;
8635
9123
  }
8636
9124
  }
8637
- function addAdditionalPropertiesToJsonSchema(jsonSchema22) {
9125
+ function addAdditionalPropertiesToJsonSchema2(jsonSchema22) {
8638
9126
  if (jsonSchema22.type === "object" || Array.isArray(jsonSchema22.type) && jsonSchema22.type.includes("object")) {
8639
9127
  jsonSchema22.additionalProperties = false;
8640
9128
  const { properties } = jsonSchema22;
@@ -8666,7 +9154,7 @@ function addAdditionalPropertiesToJsonSchema(jsonSchema22) {
8666
9154
  }
8667
9155
  function visit(def) {
8668
9156
  if (typeof def === "boolean") return def;
8669
- return addAdditionalPropertiesToJsonSchema(def);
9157
+ return addAdditionalPropertiesToJsonSchema2(def);
8670
9158
  }
8671
9159
  var ignoreOverride3 = /* @__PURE__ */ Symbol(
8672
9160
  "Let zodToJsonSchema decide on which parser to use"
@@ -8832,7 +9320,7 @@ function parseIntersectionDef3(def, refs) {
8832
9320
  ...refs,
8833
9321
  currentPath: [...refs.currentPath, "allOf", "1"]
8834
9322
  })
8835
- ].filter((x) => !!x);
9323
+ ].filter((x2) => !!x2);
8836
9324
  const mergedAllOf = [];
8837
9325
  allOf.forEach((schema) => {
8838
9326
  if (isJsonSchema7AllOfType3(schema)) {
@@ -9067,7 +9555,7 @@ function escapeNonAlphaNumeric3(source) {
9067
9555
  }
9068
9556
  function addFormat3(schema, value, message, refs) {
9069
9557
  var _a224;
9070
- if (schema.format || ((_a224 = schema.anyOf) == null ? void 0 : _a224.some((x) => x.format))) {
9558
+ if (schema.format || ((_a224 = schema.anyOf) == null ? void 0 : _a224.some((x2) => x2.format))) {
9071
9559
  if (!schema.anyOf) {
9072
9560
  schema.anyOf = [];
9073
9561
  }
@@ -9087,7 +9575,7 @@ function addFormat3(schema, value, message, refs) {
9087
9575
  }
9088
9576
  function addPattern3(schema, regex, message, refs) {
9089
9577
  var _a224;
9090
- if (schema.pattern || ((_a224 = schema.allOf) == null ? void 0 : _a224.some((x) => x.pattern))) {
9578
+ if (schema.pattern || ((_a224 = schema.allOf) == null ? void 0 : _a224.some((x2) => x2.pattern))) {
9091
9579
  if (!schema.allOf) {
9092
9580
  schema.allOf = [];
9093
9581
  }
@@ -9266,19 +9754,19 @@ var primitiveMappings3 = {
9266
9754
  function parseUnionDef3(def, refs) {
9267
9755
  const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
9268
9756
  if (options.every(
9269
- (x) => x._def.typeName in primitiveMappings3 && (!x._def.checks || !x._def.checks.length)
9757
+ (x2) => x2._def.typeName in primitiveMappings3 && (!x2._def.checks || !x2._def.checks.length)
9270
9758
  )) {
9271
- const types = options.reduce((types2, x) => {
9272
- const type = primitiveMappings3[x._def.typeName];
9759
+ const types = options.reduce((types2, x2) => {
9760
+ const type = primitiveMappings3[x2._def.typeName];
9273
9761
  return type && !types2.includes(type) ? [...types2, type] : types2;
9274
9762
  }, []);
9275
9763
  return {
9276
9764
  type: types.length > 1 ? types : types[0]
9277
9765
  };
9278
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
9766
+ } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
9279
9767
  const types = options.reduce(
9280
- (acc, x) => {
9281
- const type = typeof x._def.value;
9768
+ (acc, x2) => {
9769
+ const type = typeof x2._def.value;
9282
9770
  switch (type) {
9283
9771
  case "string":
9284
9772
  case "number":
@@ -9287,7 +9775,7 @@ function parseUnionDef3(def, refs) {
9287
9775
  case "bigint":
9288
9776
  return [...acc, "integer"];
9289
9777
  case "object":
9290
- if (x._def.value === null) return [...acc, "null"];
9778
+ if (x2._def.value === null) return [...acc, "null"];
9291
9779
  case "symbol":
9292
9780
  case "undefined":
9293
9781
  case "function":
@@ -9298,24 +9786,24 @@ function parseUnionDef3(def, refs) {
9298
9786
  []
9299
9787
  );
9300
9788
  if (types.length === options.length) {
9301
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
9789
+ const uniqueTypes = types.filter((x2, i, a) => a.indexOf(x2) === i);
9302
9790
  return {
9303
9791
  type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
9304
9792
  enum: options.reduce(
9305
- (acc, x) => {
9306
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
9793
+ (acc, x2) => {
9794
+ return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
9307
9795
  },
9308
9796
  []
9309
9797
  )
9310
9798
  };
9311
9799
  }
9312
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
9800
+ } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
9313
9801
  return {
9314
9802
  type: "string",
9315
9803
  enum: options.reduce(
9316
- (acc, x) => [
9804
+ (acc, x2) => [
9317
9805
  ...acc,
9318
- ...x._def.values.filter((x2) => !acc.includes(x2))
9806
+ ...x2._def.values.filter((x22) => !acc.includes(x22))
9319
9807
  ],
9320
9808
  []
9321
9809
  )
@@ -9325,12 +9813,12 @@ function parseUnionDef3(def, refs) {
9325
9813
  }
9326
9814
  var asAnyOf3 = (def, refs) => {
9327
9815
  const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
9328
- (x, i) => parseDef3(x._def, {
9816
+ (x2, i) => parseDef3(x2._def, {
9329
9817
  ...refs,
9330
9818
  currentPath: [...refs.currentPath, "anyOf", `${i}`]
9331
9819
  })
9332
9820
  ).filter(
9333
- (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
9821
+ (x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0)
9334
9822
  );
9335
9823
  return anyOf.length ? { anyOf } : void 0;
9336
9824
  };
@@ -9466,7 +9954,7 @@ var parsePipelineDef3 = (def, refs) => {
9466
9954
  currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
9467
9955
  });
9468
9956
  return {
9469
- allOf: [a, b].filter((x) => x !== void 0)
9957
+ allOf: [a, b].filter((x2) => x2 !== void 0)
9470
9958
  };
9471
9959
  };
9472
9960
  function parsePromiseDef3(def, refs) {
@@ -9496,12 +9984,12 @@ function parseTupleDef3(def, refs) {
9496
9984
  type: "array",
9497
9985
  minItems: def.items.length,
9498
9986
  items: def.items.map(
9499
- (x, i) => parseDef3(x._def, {
9987
+ (x2, i) => parseDef3(x2._def, {
9500
9988
  ...refs,
9501
9989
  currentPath: [...refs.currentPath, "items", `${i}`]
9502
9990
  })
9503
9991
  ).reduce(
9504
- (acc, x) => x === void 0 ? acc : [...acc, x],
9992
+ (acc, x2) => x2 === void 0 ? acc : [...acc, x2],
9505
9993
  []
9506
9994
  ),
9507
9995
  additionalItems: parseDef3(def.rest._def, {
@@ -9515,12 +10003,12 @@ function parseTupleDef3(def, refs) {
9515
10003
  minItems: def.items.length,
9516
10004
  maxItems: def.items.length,
9517
10005
  items: def.items.map(
9518
- (x, i) => parseDef3(x._def, {
10006
+ (x2, i) => parseDef3(x2._def, {
9519
10007
  ...refs,
9520
10008
  currentPath: [...refs.currentPath, "items", `${i}`]
9521
10009
  })
9522
10010
  ).reduce(
9523
- (acc, x) => x === void 0 ? acc : [...acc, x],
10011
+ (acc, x2) => x2 === void 0 ? acc : [...acc, x2],
9524
10012
  []
9525
10013
  )
9526
10014
  };
@@ -9751,7 +10239,7 @@ var zod3ToJsonSchema = (schema, options) => {
9751
10239
  return combined;
9752
10240
  };
9753
10241
  var schemaSymbol3 = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
9754
- function lazySchema(createSchema) {
10242
+ function lazySchema2(createSchema) {
9755
10243
  let schema;
9756
10244
  return () => {
9757
10245
  if (schema == null) {
@@ -9784,7 +10272,7 @@ function asSchema3(schema) {
9784
10272
  }
9785
10273
  function standardSchema(standardSchema2) {
9786
10274
  return jsonSchema3(
9787
- () => addAdditionalPropertiesToJsonSchema(
10275
+ () => addAdditionalPropertiesToJsonSchema2(
9788
10276
  standardSchema2["~standard"].jsonSchema.input({
9789
10277
  target: "draft-07"
9790
10278
  })
@@ -9824,7 +10312,7 @@ function zod4Schema2(zodSchema22, options) {
9824
10312
  const useReferences = (_a224 = void 0 ) != null ? _a224 : false;
9825
10313
  return jsonSchema3(
9826
10314
  // defer json schema creation to avoid unnecessary computation when only validation is needed
9827
- () => addAdditionalPropertiesToJsonSchema(
10315
+ () => addAdditionalPropertiesToJsonSchema2(
9828
10316
  z4__namespace.toJSONSchema(zodSchema22, {
9829
10317
  target: "draft-7",
9830
10318
  io: "input",
@@ -9975,7 +10463,7 @@ var postToApi2 = async ({
9975
10463
  method: "POST",
9976
10464
  headers: withUserAgentSuffix2(
9977
10465
  headers,
9978
- `ai-sdk/provider-utils/${VERSION4}`,
10466
+ `ai-sdk/provider-utils/${VERSION5}`,
9979
10467
  getRuntimeEnvironmentUserAgent2()
9980
10468
  ),
9981
10469
  body: body.content,
@@ -10030,8 +10518,8 @@ var postToApi2 = async ({
10030
10518
  throw handleFetchError2({ error, url, requestBodyValues: body.values });
10031
10519
  }
10032
10520
  };
10033
- function tool(tool2) {
10034
- return tool2;
10521
+ function tool2(tool22) {
10522
+ return tool22;
10035
10523
  }
10036
10524
  function createProviderToolFactoryWithOutputSchema({
10037
10525
  id,
@@ -10047,7 +10535,7 @@ function createProviderToolFactoryWithOutputSchema({
10047
10535
  onInputDelta,
10048
10536
  onInputAvailable,
10049
10537
  ...args
10050
- }) => tool({
10538
+ }) => tool2({
10051
10539
  type: "provider",
10052
10540
  id,
10053
10541
  args,
@@ -10162,143 +10650,22 @@ var createJsonResponseHandler2 = (responseSchema) => async ({ response, url, req
10162
10650
  function withoutTrailingSlash2(url) {
10163
10651
  return url == null ? void 0 : url.replace(/\/$/, "");
10164
10652
  }
10165
- var require_get_context2 = chunkIDRQZVB4_cjs.__commonJS({
10166
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-context.js"(exports$1, module) {
10167
- var __defProp22 = Object.defineProperty;
10168
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
10169
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
10170
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
10171
- var __export22 = (target, all) => {
10172
- for (var name21 in all)
10173
- __defProp22(target, name21, { get: all[name21], enumerable: true });
10174
- };
10175
- var __copyProps2 = (to, from, except, desc) => {
10176
- if (from && typeof from === "object" || typeof from === "function") {
10177
- for (let key of __getOwnPropNames2(from))
10178
- if (!__hasOwnProp2.call(to, key) && key !== except)
10179
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
10180
- }
10181
- return to;
10182
- };
10183
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
10184
- var get_context_exports = {};
10185
- __export22(get_context_exports, {
10186
- SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
10187
- getContext: () => getContext3
10188
- });
10189
- module.exports = __toCommonJS(get_context_exports);
10190
- var SYMBOL_FOR_REQ_CONTEXT = /* @__PURE__ */ Symbol.for("@vercel/request-context");
10191
- function getContext3() {
10192
- const fromSymbol = globalThis;
10193
- return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
10194
- }
10195
- }
10196
- });
10197
- var require_get_vercel_oidc_token2 = chunkIDRQZVB4_cjs.__commonJS({
10198
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports$1, module) {
10199
- var __defProp22 = Object.defineProperty;
10200
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
10201
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
10202
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
10203
- var __export22 = (target, all) => {
10204
- for (var name21 in all)
10205
- __defProp22(target, name21, { get: all[name21], enumerable: true });
10206
- };
10207
- var __copyProps2 = (to, from, except, desc) => {
10208
- if (from && typeof from === "object" || typeof from === "function") {
10209
- for (let key of __getOwnPropNames2(from))
10210
- if (!__hasOwnProp2.call(to, key) && key !== except)
10211
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
10212
- }
10213
- return to;
10214
- };
10215
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
10216
- var get_vercel_oidc_token_exports = {};
10217
- __export22(get_vercel_oidc_token_exports, {
10218
- getVercelOidcToken: () => getVercelOidcToken3,
10219
- getVercelOidcTokenSync: () => getVercelOidcTokenSync2
10220
- });
10221
- module.exports = __toCommonJS(get_vercel_oidc_token_exports);
10222
- var import_get_context = require_get_context2();
10223
- var import_token_error = chunkIDRQZVB4_cjs.require_token_error();
10224
- async function getVercelOidcToken3() {
10225
- let token = "";
10226
- let err;
10227
- try {
10228
- token = getVercelOidcTokenSync2();
10229
- } catch (error) {
10230
- err = error;
10231
- }
10232
- try {
10233
- const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
10234
- await import('./token-util-RMHT2CPJ-6TGPE335.cjs'),
10235
- await import('./token-APYSY3BW-ZQ7TMBY7.cjs')
10236
- ]);
10237
- if (!token || isExpired(getTokenPayload(token))) {
10238
- await refreshToken();
10239
- token = getVercelOidcTokenSync2();
10240
- }
10241
- } catch (error) {
10242
- let message = err instanceof Error ? err.message : "";
10243
- if (error instanceof Error) {
10244
- message = `${message}
10245
- ${error.message}`;
10246
- }
10247
- if (message) {
10248
- throw new import_token_error.VercelOidcTokenError(message);
10249
- }
10250
- throw error;
10251
- }
10252
- return token;
10253
- }
10254
- function getVercelOidcTokenSync2() {
10255
- const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
10256
- if (!token) {
10257
- throw new Error(
10258
- `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
10259
- );
10260
- }
10261
- return token;
10262
- }
10263
- }
10264
- });
10265
- var require_dist2 = chunkIDRQZVB4_cjs.__commonJS({
10266
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/index.js"(exports$1, module) {
10267
- var __defProp22 = Object.defineProperty;
10268
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
10269
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
10270
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
10271
- var __export22 = (target, all) => {
10272
- for (var name21 in all)
10273
- __defProp22(target, name21, { get: all[name21], enumerable: true });
10274
- };
10275
- var __copyProps2 = (to, from, except, desc) => {
10276
- if (from && typeof from === "object" || typeof from === "function") {
10277
- for (let key of __getOwnPropNames2(from))
10278
- if (!__hasOwnProp2.call(to, key) && key !== except)
10279
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
10280
- }
10281
- return to;
10282
- };
10283
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
10284
- var src_exports = {};
10285
- __export22(src_exports, {
10286
- getContext: () => import_get_context.getContext,
10287
- getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
10288
- getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
10289
- });
10290
- module.exports = __toCommonJS(src_exports);
10291
- var import_get_vercel_oidc_token = require_get_vercel_oidc_token2();
10292
- var import_get_context = require_get_context2();
10653
+ function getContext2() {
10654
+ return {
10655
+ headers: {}
10656
+ };
10657
+ }
10658
+ async function getVercelOidcToken2() {
10659
+ if (process.env.VERCEL_OIDC_TOKEN) {
10660
+ return process.env.VERCEL_OIDC_TOKEN ?? "";
10293
10661
  }
10294
- });
10295
- var import_oidc3 = chunkIDRQZVB4_cjs.__toESM(require_dist2(), 1);
10296
- var import_oidc22 = chunkIDRQZVB4_cjs.__toESM(require_dist2(), 1);
10297
- var marker19 = "vercel.ai.gateway.error";
10298
- var symbol19 = Symbol.for(marker19);
10299
- var _a19;
10300
- var _b16;
10301
- var GatewayError2 = class _GatewayError2 extends (_b16 = Error, _a19 = symbol19, _b16) {
10662
+ throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
10663
+ }
10664
+ var marker20 = "vercel.ai.gateway.error";
10665
+ var symbol20 = Symbol.for(marker20);
10666
+ var _a20;
10667
+ var _b18;
10668
+ var GatewayError2 = class _GatewayError2 extends (_b18 = Error, _a20 = symbol20, _b18) {
10302
10669
  constructor({
10303
10670
  message,
10304
10671
  statusCode = 500,
@@ -10306,7 +10673,7 @@ var GatewayError2 = class _GatewayError2 extends (_b16 = Error, _a19 = symbol19,
10306
10673
  generationId
10307
10674
  }) {
10308
10675
  super(generationId ? `${message} [${generationId}]` : message);
10309
- this[_a19] = true;
10676
+ this[_a20] = true;
10310
10677
  this.statusCode = statusCode;
10311
10678
  this.cause = cause;
10312
10679
  this.generationId = generationId;
@@ -10320,15 +10687,15 @@ var GatewayError2 = class _GatewayError2 extends (_b16 = Error, _a19 = symbol19,
10320
10687
  return _GatewayError2.hasMarker(error);
10321
10688
  }
10322
10689
  static hasMarker(error) {
10323
- return typeof error === "object" && error !== null && symbol19 in error && error[symbol19] === true;
10690
+ return typeof error === "object" && error !== null && symbol20 in error && error[symbol20] === true;
10324
10691
  }
10325
10692
  };
10326
10693
  var name19 = "GatewayAuthenticationError";
10327
10694
  var marker26 = `vercel.ai.gateway.error.${name19}`;
10328
10695
  var symbol26 = Symbol.for(marker26);
10329
10696
  var _a26;
10330
- var _b23;
10331
- var GatewayAuthenticationError2 = class _GatewayAuthenticationError2 extends (_b23 = GatewayError2, _a26 = symbol26, _b23) {
10697
+ var _b24;
10698
+ var GatewayAuthenticationError2 = class _GatewayAuthenticationError2 extends (_b24 = GatewayError2, _a26 = symbol26, _b24) {
10332
10699
  constructor({
10333
10700
  message = "Authentication failed",
10334
10701
  statusCode = 401,
@@ -10389,8 +10756,8 @@ var name26 = "GatewayInvalidRequestError";
10389
10756
  var marker36 = `vercel.ai.gateway.error.${name26}`;
10390
10757
  var symbol36 = Symbol.for(marker36);
10391
10758
  var _a36;
10392
- var _b33;
10393
- var GatewayInvalidRequestError2 = class extends (_b33 = GatewayError2, _a36 = symbol36, _b33) {
10759
+ var _b34;
10760
+ var GatewayInvalidRequestError2 = class extends (_b34 = GatewayError2, _a36 = symbol36, _b34) {
10394
10761
  constructor({
10395
10762
  message = "Invalid request",
10396
10763
  statusCode = 400,
@@ -10410,8 +10777,8 @@ var name36 = "GatewayRateLimitError";
10410
10777
  var marker46 = `vercel.ai.gateway.error.${name36}`;
10411
10778
  var symbol46 = Symbol.for(marker46);
10412
10779
  var _a46;
10413
- var _b43;
10414
- var GatewayRateLimitError2 = class extends (_b43 = GatewayError2, _a46 = symbol46, _b43) {
10780
+ var _b44;
10781
+ var GatewayRateLimitError2 = class extends (_b44 = GatewayError2, _a46 = symbol46, _b44) {
10415
10782
  constructor({
10416
10783
  message = "Rate limit exceeded",
10417
10784
  statusCode = 429,
@@ -10430,7 +10797,7 @@ var GatewayRateLimitError2 = class extends (_b43 = GatewayError2, _a46 = symbol4
10430
10797
  var name46 = "GatewayModelNotFoundError";
10431
10798
  var marker56 = `vercel.ai.gateway.error.${name46}`;
10432
10799
  var symbol56 = Symbol.for(marker56);
10433
- var modelNotFoundParamSchema2 = lazySchema(
10800
+ var modelNotFoundParamSchema2 = lazySchema2(
10434
10801
  () => zodSchema3(
10435
10802
  z4.z.object({
10436
10803
  modelId: z4.z.string()
@@ -10438,8 +10805,8 @@ var modelNotFoundParamSchema2 = lazySchema(
10438
10805
  )
10439
10806
  );
10440
10807
  var _a56;
10441
- var _b53;
10442
- var GatewayModelNotFoundError2 = class extends (_b53 = GatewayError2, _a56 = symbol56, _b53) {
10808
+ var _b54;
10809
+ var GatewayModelNotFoundError2 = class extends (_b54 = GatewayError2, _a56 = symbol56, _b54) {
10443
10810
  constructor({
10444
10811
  message = "Model not found",
10445
10812
  statusCode = 404,
@@ -10461,8 +10828,8 @@ var name56 = "GatewayInternalServerError";
10461
10828
  var marker66 = `vercel.ai.gateway.error.${name56}`;
10462
10829
  var symbol66 = Symbol.for(marker66);
10463
10830
  var _a66;
10464
- var _b63;
10465
- var GatewayInternalServerError2 = class extends (_b63 = GatewayError2, _a66 = symbol66, _b63) {
10831
+ var _b64;
10832
+ var GatewayInternalServerError2 = class extends (_b64 = GatewayError2, _a66 = symbol66, _b64) {
10466
10833
  constructor({
10467
10834
  message = "Internal server error",
10468
10835
  statusCode = 500,
@@ -10482,8 +10849,8 @@ var name66 = "GatewayResponseError";
10482
10849
  var marker76 = `vercel.ai.gateway.error.${name66}`;
10483
10850
  var symbol76 = Symbol.for(marker76);
10484
10851
  var _a76;
10485
- var _b73;
10486
- var GatewayResponseError2 = class extends (_b73 = GatewayError2, _a76 = symbol76, _b73) {
10852
+ var _b74;
10853
+ var GatewayResponseError2 = class extends (_b74 = GatewayError2, _a76 = symbol76, _b74) {
10487
10854
  constructor({
10488
10855
  message = "Invalid response from Gateway",
10489
10856
  statusCode = 502,
@@ -10582,7 +10949,7 @@ async function createGatewayErrorFromResponse2({
10582
10949
  });
10583
10950
  }
10584
10951
  }
10585
- var gatewayErrorResponseSchema2 = lazySchema(
10952
+ var gatewayErrorResponseSchema2 = lazySchema2(
10586
10953
  () => zodSchema3(
10587
10954
  z4.z.object({
10588
10955
  error: z4.z.object({
@@ -10595,12 +10962,25 @@ var gatewayErrorResponseSchema2 = lazySchema(
10595
10962
  })
10596
10963
  )
10597
10964
  );
10965
+ function extractApiCallResponse2(error) {
10966
+ if (error.data !== void 0) {
10967
+ return error.data;
10968
+ }
10969
+ if (error.responseBody != null) {
10970
+ try {
10971
+ return JSON.parse(error.responseBody);
10972
+ } catch (e) {
10973
+ return error.responseBody;
10974
+ }
10975
+ }
10976
+ return {};
10977
+ }
10598
10978
  var name76 = "GatewayTimeoutError";
10599
10979
  var marker86 = `vercel.ai.gateway.error.${name76}`;
10600
10980
  var symbol86 = Symbol.for(marker86);
10601
10981
  var _a86;
10602
- var _b83;
10603
- var GatewayTimeoutError = class _GatewayTimeoutError extends (_b83 = GatewayError2, _a86 = symbol86, _b83) {
10982
+ var _b84;
10983
+ var GatewayTimeoutError2 = class _GatewayTimeoutError2 extends (_b84 = GatewayError2, _a86 = symbol86, _b84) {
10604
10984
  constructor({
10605
10985
  message = "Request timed out",
10606
10986
  statusCode = 408,
@@ -10627,7 +11007,7 @@ var GatewayTimeoutError = class _GatewayTimeoutError extends (_b83 = GatewayErro
10627
11007
  const message = `Gateway request timed out: ${originalMessage}
10628
11008
 
10629
11009
  This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;
10630
- return new _GatewayTimeoutError({
11010
+ return new _GatewayTimeoutError2({
10631
11011
  message,
10632
11012
  statusCode,
10633
11013
  cause,
@@ -10635,7 +11015,7 @@ var GatewayTimeoutError = class _GatewayTimeoutError extends (_b83 = GatewayErro
10635
11015
  });
10636
11016
  }
10637
11017
  };
10638
- function isTimeoutError(error) {
11018
+ function isTimeoutError2(error) {
10639
11019
  if (!(error instanceof Error)) {
10640
11020
  return false;
10641
11021
  }
@@ -10655,15 +11035,15 @@ async function asGatewayError2(error, authMethod) {
10655
11035
  if (GatewayError2.isInstance(error)) {
10656
11036
  return error;
10657
11037
  }
10658
- if (isTimeoutError(error)) {
10659
- return GatewayTimeoutError.createTimeoutError({
11038
+ if (isTimeoutError2(error)) {
11039
+ return GatewayTimeoutError2.createTimeoutError({
10660
11040
  originalMessage: error instanceof Error ? error.message : "Unknown error",
10661
11041
  cause: error
10662
11042
  });
10663
11043
  }
10664
11044
  if (APICallError3.isInstance(error)) {
10665
- if (error.cause && isTimeoutError(error.cause)) {
10666
- return GatewayTimeoutError.createTimeoutError({
11045
+ if (error.cause && isTimeoutError2(error.cause)) {
11046
+ return GatewayTimeoutError2.createTimeoutError({
10667
11047
  originalMessage: error.message,
10668
11048
  cause: error
10669
11049
  });
@@ -10672,30 +11052,17 @@ async function asGatewayError2(error, authMethod) {
10672
11052
  response: extractApiCallResponse2(error),
10673
11053
  statusCode: (_a932 = error.statusCode) != null ? _a932 : 500,
10674
11054
  defaultMessage: "Gateway request failed",
10675
- cause: error,
10676
- authMethod
10677
- });
10678
- }
10679
- return await createGatewayErrorFromResponse2({
10680
- response: {},
10681
- statusCode: 500,
10682
- defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
10683
- cause: error,
10684
- authMethod
10685
- });
10686
- }
10687
- function extractApiCallResponse2(error) {
10688
- if (error.data !== void 0) {
10689
- return error.data;
10690
- }
10691
- if (error.responseBody != null) {
10692
- try {
10693
- return JSON.parse(error.responseBody);
10694
- } catch (e) {
10695
- return error.responseBody;
10696
- }
11055
+ cause: error,
11056
+ authMethod
11057
+ });
10697
11058
  }
10698
- return {};
11059
+ return await createGatewayErrorFromResponse2({
11060
+ response: {},
11061
+ statusCode: 500,
11062
+ defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
11063
+ cause: error,
11064
+ authMethod
11065
+ });
10699
11066
  }
10700
11067
  var GATEWAY_AUTH_METHOD_HEADER2 = "ai-gateway-auth-method";
10701
11068
  async function parseAuthMethod2(headers) {
@@ -10705,9 +11072,16 @@ async function parseAuthMethod2(headers) {
10705
11072
  });
10706
11073
  return result.success ? result.value : void 0;
10707
11074
  }
10708
- var gatewayAuthMethodSchema2 = lazySchema(
11075
+ var gatewayAuthMethodSchema2 = lazySchema2(
10709
11076
  () => zodSchema3(z4.z.union([z4.z.literal("api-key"), z4.z.literal("oidc")]))
10710
11077
  );
11078
+ var KNOWN_MODEL_TYPES2 = [
11079
+ "embedding",
11080
+ "image",
11081
+ "language",
11082
+ "reranking",
11083
+ "video"
11084
+ ];
10711
11085
  var GatewayFetchMetadata2 = class {
10712
11086
  constructor(config) {
10713
11087
  this.config = config;
@@ -10752,7 +11126,7 @@ var GatewayFetchMetadata2 = class {
10752
11126
  }
10753
11127
  }
10754
11128
  };
10755
- var gatewayAvailableModelsResponseSchema2 = lazySchema(
11129
+ var gatewayAvailableModelsResponseSchema2 = lazySchema2(
10756
11130
  () => zodSchema3(
10757
11131
  z4.z.object({
10758
11132
  models: z4.z.array(
@@ -10778,13 +11152,17 @@ var gatewayAvailableModelsResponseSchema2 = lazySchema(
10778
11152
  provider: z4.z.string(),
10779
11153
  modelId: z4.z.string()
10780
11154
  }),
10781
- modelType: z4.z.enum(["embedding", "image", "language", "video"]).nullish()
11155
+ modelType: z4.z.string().nullish()
10782
11156
  })
11157
+ ).transform(
11158
+ (models) => models.filter(
11159
+ (m) => m.modelType == null || KNOWN_MODEL_TYPES2.includes(m.modelType)
11160
+ )
10783
11161
  )
10784
11162
  })
10785
11163
  )
10786
11164
  );
10787
- var gatewayCreditsResponseSchema2 = lazySchema(
11165
+ var gatewayCreditsResponseSchema2 = lazySchema2(
10788
11166
  () => zodSchema3(
10789
11167
  z4.z.object({
10790
11168
  balance: z4.z.string(),
@@ -10795,6 +11173,187 @@ var gatewayCreditsResponseSchema2 = lazySchema(
10795
11173
  }))
10796
11174
  )
10797
11175
  );
11176
+ var GatewaySpendReport2 = class {
11177
+ constructor(config) {
11178
+ this.config = config;
11179
+ }
11180
+ async getSpendReport(params) {
11181
+ try {
11182
+ const baseUrl = new URL(this.config.baseURL);
11183
+ const searchParams = new URLSearchParams();
11184
+ searchParams.set("start_date", params.startDate);
11185
+ searchParams.set("end_date", params.endDate);
11186
+ if (params.groupBy) {
11187
+ searchParams.set("group_by", params.groupBy);
11188
+ }
11189
+ if (params.datePart) {
11190
+ searchParams.set("date_part", params.datePart);
11191
+ }
11192
+ if (params.userId) {
11193
+ searchParams.set("user_id", params.userId);
11194
+ }
11195
+ if (params.model) {
11196
+ searchParams.set("model", params.model);
11197
+ }
11198
+ if (params.provider) {
11199
+ searchParams.set("provider", params.provider);
11200
+ }
11201
+ if (params.credentialType) {
11202
+ searchParams.set("credential_type", params.credentialType);
11203
+ }
11204
+ if (params.tags && params.tags.length > 0) {
11205
+ searchParams.set("tags", params.tags.join(","));
11206
+ }
11207
+ const { value } = await getFromApi2({
11208
+ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
11209
+ headers: await resolve2(this.config.headers()),
11210
+ successfulResponseHandler: createJsonResponseHandler2(
11211
+ gatewaySpendReportResponseSchema2
11212
+ ),
11213
+ failedResponseHandler: createJsonErrorResponseHandler2({
11214
+ errorSchema: z4.z.any(),
11215
+ errorToMessage: (data) => data
11216
+ }),
11217
+ fetch: this.config.fetch
11218
+ });
11219
+ return value;
11220
+ } catch (error) {
11221
+ throw await asGatewayError2(error);
11222
+ }
11223
+ }
11224
+ };
11225
+ var gatewaySpendReportResponseSchema2 = lazySchema2(
11226
+ () => zodSchema3(
11227
+ z4.z.object({
11228
+ results: z4.z.array(
11229
+ z4.z.object({
11230
+ day: z4.z.string().optional(),
11231
+ hour: z4.z.string().optional(),
11232
+ user: z4.z.string().optional(),
11233
+ model: z4.z.string().optional(),
11234
+ tag: z4.z.string().optional(),
11235
+ provider: z4.z.string().optional(),
11236
+ credential_type: z4.z.enum(["byok", "system"]).optional(),
11237
+ total_cost: z4.z.number(),
11238
+ market_cost: z4.z.number().optional(),
11239
+ input_tokens: z4.z.number().optional(),
11240
+ output_tokens: z4.z.number().optional(),
11241
+ cached_input_tokens: z4.z.number().optional(),
11242
+ cache_creation_input_tokens: z4.z.number().optional(),
11243
+ reasoning_tokens: z4.z.number().optional(),
11244
+ request_count: z4.z.number().optional()
11245
+ }).transform(
11246
+ ({
11247
+ credential_type,
11248
+ total_cost,
11249
+ market_cost,
11250
+ input_tokens,
11251
+ output_tokens,
11252
+ cached_input_tokens,
11253
+ cache_creation_input_tokens,
11254
+ reasoning_tokens,
11255
+ request_count,
11256
+ ...rest
11257
+ }) => ({
11258
+ ...rest,
11259
+ ...credential_type !== void 0 ? { credentialType: credential_type } : {},
11260
+ totalCost: total_cost,
11261
+ ...market_cost !== void 0 ? { marketCost: market_cost } : {},
11262
+ ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
11263
+ ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
11264
+ ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
11265
+ ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
11266
+ ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
11267
+ ...request_count !== void 0 ? { requestCount: request_count } : {}
11268
+ })
11269
+ )
11270
+ )
11271
+ })
11272
+ )
11273
+ );
11274
+ var GatewayGenerationInfoFetcher2 = class {
11275
+ constructor(config) {
11276
+ this.config = config;
11277
+ }
11278
+ async getGenerationInfo(params) {
11279
+ try {
11280
+ const baseUrl = new URL(this.config.baseURL);
11281
+ const { value } = await getFromApi2({
11282
+ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
11283
+ headers: await resolve2(this.config.headers()),
11284
+ successfulResponseHandler: createJsonResponseHandler2(
11285
+ gatewayGenerationInfoResponseSchema2
11286
+ ),
11287
+ failedResponseHandler: createJsonErrorResponseHandler2({
11288
+ errorSchema: z4.z.any(),
11289
+ errorToMessage: (data) => data
11290
+ }),
11291
+ fetch: this.config.fetch
11292
+ });
11293
+ return value;
11294
+ } catch (error) {
11295
+ throw await asGatewayError2(error);
11296
+ }
11297
+ }
11298
+ };
11299
+ var gatewayGenerationInfoResponseSchema2 = lazySchema2(
11300
+ () => zodSchema3(
11301
+ z4.z.object({
11302
+ data: z4.z.object({
11303
+ id: z4.z.string(),
11304
+ total_cost: z4.z.number(),
11305
+ upstream_inference_cost: z4.z.number(),
11306
+ usage: z4.z.number(),
11307
+ created_at: z4.z.string(),
11308
+ model: z4.z.string(),
11309
+ is_byok: z4.z.boolean(),
11310
+ provider_name: z4.z.string(),
11311
+ streamed: z4.z.boolean(),
11312
+ finish_reason: z4.z.string(),
11313
+ latency: z4.z.number(),
11314
+ generation_time: z4.z.number(),
11315
+ native_tokens_prompt: z4.z.number(),
11316
+ native_tokens_completion: z4.z.number(),
11317
+ native_tokens_reasoning: z4.z.number(),
11318
+ native_tokens_cached: z4.z.number(),
11319
+ native_tokens_cache_creation: z4.z.number(),
11320
+ billable_web_search_calls: z4.z.number()
11321
+ }).transform(
11322
+ ({
11323
+ total_cost,
11324
+ upstream_inference_cost,
11325
+ created_at,
11326
+ is_byok,
11327
+ provider_name,
11328
+ finish_reason,
11329
+ generation_time,
11330
+ native_tokens_prompt,
11331
+ native_tokens_completion,
11332
+ native_tokens_reasoning,
11333
+ native_tokens_cached,
11334
+ native_tokens_cache_creation,
11335
+ billable_web_search_calls,
11336
+ ...rest
11337
+ }) => ({
11338
+ ...rest,
11339
+ totalCost: total_cost,
11340
+ upstreamInferenceCost: upstream_inference_cost,
11341
+ createdAt: created_at,
11342
+ isByok: is_byok,
11343
+ providerName: provider_name,
11344
+ finishReason: finish_reason,
11345
+ generationTime: generation_time,
11346
+ promptTokens: native_tokens_prompt,
11347
+ completionTokens: native_tokens_completion,
11348
+ reasoningTokens: native_tokens_reasoning,
11349
+ cachedTokens: native_tokens_cached,
11350
+ cacheCreationTokens: native_tokens_cache_creation,
11351
+ billableWebSearchCalls: billable_web_search_calls
11352
+ })
11353
+ )
11354
+ }).transform(({ data }) => data)
11355
+ )
11356
+ );
10798
11357
  var GatewayLanguageModel2 = class {
10799
11358
  constructor(modelId, config) {
10800
11359
  this.modelId = modelId;
@@ -11007,7 +11566,7 @@ var GatewayEmbeddingModel2 = class {
11007
11566
  };
11008
11567
  }
11009
11568
  };
11010
- var gatewayEmbeddingResponseSchema2 = lazySchema(
11569
+ var gatewayEmbeddingResponseSchema2 = lazySchema2(
11011
11570
  () => zodSchema3(
11012
11571
  z4.z.object({
11013
11572
  embeddings: z4.z.array(z4.z.array(z4.z.number())),
@@ -11038,7 +11597,7 @@ var GatewayImageModel2 = class {
11038
11597
  headers,
11039
11598
  abortSignal
11040
11599
  }) {
11041
- var _a932, _b92, _c, _d;
11600
+ var _a932, _b93, _c, _d;
11042
11601
  const resolvedHeaders = await resolve2(this.config.headers());
11043
11602
  try {
11044
11603
  const {
@@ -11086,7 +11645,7 @@ var GatewayImageModel2 = class {
11086
11645
  },
11087
11646
  ...responseBody.usage != null && {
11088
11647
  usage: {
11089
- inputTokens: (_b92 = responseBody.usage.inputTokens) != null ? _b92 : void 0,
11648
+ inputTokens: (_b93 = responseBody.usage.inputTokens) != null ? _b93 : void 0,
11090
11649
  outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,
11091
11650
  totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0
11092
11651
  }
@@ -11134,7 +11693,7 @@ var gatewayImageWarningSchema = z4.z.discriminatedUnion("type", [
11134
11693
  message: z4.z.string()
11135
11694
  })
11136
11695
  ]);
11137
- var gatewayImageUsageSchema = z4.z.object({
11696
+ var gatewayImageUsageSchema2 = z4.z.object({
11138
11697
  inputTokens: z4.z.number().nullish(),
11139
11698
  outputTokens: z4.z.number().nullish(),
11140
11699
  totalTokens: z4.z.number().nullish()
@@ -11144,7 +11703,7 @@ var gatewayImageResponseSchema2 = z4.z.object({
11144
11703
  // Always base64 strings over the wire
11145
11704
  warnings: z4.z.array(gatewayImageWarningSchema).optional(),
11146
11705
  providerMetadata: z4.z.record(z4.z.string(), providerMetadataEntrySchema2).optional(),
11147
- usage: gatewayImageUsageSchema.optional()
11706
+ usage: gatewayImageUsageSchema2.optional()
11148
11707
  });
11149
11708
  var GatewayVideoModel = class {
11150
11709
  constructor(modelId, config) {
@@ -11342,7 +11901,87 @@ var gatewayVideoEventSchema = z4.z.discriminatedUnion("type", [
11342
11901
  param: z4.z.unknown().nullable()
11343
11902
  })
11344
11903
  ]);
11345
- var parallelSearchInputSchema = lazySchema(
11904
+ var GatewayRerankingModel = class {
11905
+ constructor(modelId, config) {
11906
+ this.modelId = modelId;
11907
+ this.config = config;
11908
+ this.specificationVersion = "v3";
11909
+ }
11910
+ get provider() {
11911
+ return this.config.provider;
11912
+ }
11913
+ async doRerank({
11914
+ documents,
11915
+ query,
11916
+ topN,
11917
+ headers,
11918
+ abortSignal,
11919
+ providerOptions
11920
+ }) {
11921
+ const resolvedHeaders = await resolve2(this.config.headers());
11922
+ try {
11923
+ const {
11924
+ responseHeaders,
11925
+ value: responseBody,
11926
+ rawValue
11927
+ } = await postJsonToApi2({
11928
+ url: this.getUrl(),
11929
+ headers: combineHeaders2(
11930
+ resolvedHeaders,
11931
+ headers != null ? headers : {},
11932
+ this.getModelConfigHeaders(),
11933
+ await resolve2(this.config.o11yHeaders)
11934
+ ),
11935
+ body: {
11936
+ documents,
11937
+ query,
11938
+ ...topN != null ? { topN } : {},
11939
+ ...providerOptions ? { providerOptions } : {}
11940
+ },
11941
+ successfulResponseHandler: createJsonResponseHandler2(
11942
+ gatewayRerankingResponseSchema
11943
+ ),
11944
+ failedResponseHandler: createJsonErrorResponseHandler2({
11945
+ errorSchema: z4.z.any(),
11946
+ errorToMessage: (data) => data
11947
+ }),
11948
+ ...abortSignal && { abortSignal },
11949
+ fetch: this.config.fetch
11950
+ });
11951
+ return {
11952
+ ranking: responseBody.ranking,
11953
+ providerMetadata: responseBody.providerMetadata,
11954
+ response: { headers: responseHeaders, body: rawValue },
11955
+ warnings: []
11956
+ };
11957
+ } catch (error) {
11958
+ throw await asGatewayError2(error, await parseAuthMethod2(resolvedHeaders));
11959
+ }
11960
+ }
11961
+ getUrl() {
11962
+ return `${this.config.baseURL}/reranking-model`;
11963
+ }
11964
+ getModelConfigHeaders() {
11965
+ return {
11966
+ "ai-reranking-model-specification-version": "3",
11967
+ "ai-model-id": this.modelId
11968
+ };
11969
+ }
11970
+ };
11971
+ var gatewayRerankingResponseSchema = lazySchema2(
11972
+ () => zodSchema3(
11973
+ z4.z.object({
11974
+ ranking: z4.z.array(
11975
+ z4.z.object({
11976
+ index: z4.z.number(),
11977
+ relevanceScore: z4.z.number()
11978
+ })
11979
+ ),
11980
+ providerMetadata: z4.z.record(z4.z.string(), z4.z.record(z4.z.string(), z4.z.unknown())).optional()
11981
+ })
11982
+ )
11983
+ );
11984
+ var parallelSearchInputSchema2 = lazySchema2(
11346
11985
  () => zodSchema3(
11347
11986
  zod.z.object({
11348
11987
  objective: zod.z.string().describe(
@@ -11378,7 +12017,7 @@ var parallelSearchInputSchema = lazySchema(
11378
12017
  })
11379
12018
  )
11380
12019
  );
11381
- var parallelSearchOutputSchema = lazySchema(
12020
+ var parallelSearchOutputSchema2 = lazySchema2(
11382
12021
  () => zodSchema3(
11383
12022
  zod.z.union([
11384
12023
  // Success response
@@ -11410,13 +12049,13 @@ var parallelSearchOutputSchema = lazySchema(
11410
12049
  ])
11411
12050
  )
11412
12051
  );
11413
- var parallelSearchToolFactory = createProviderToolFactoryWithOutputSchema({
12052
+ var parallelSearchToolFactory2 = createProviderToolFactoryWithOutputSchema({
11414
12053
  id: "gateway.parallel_search",
11415
- inputSchema: parallelSearchInputSchema,
11416
- outputSchema: parallelSearchOutputSchema
12054
+ inputSchema: parallelSearchInputSchema2,
12055
+ outputSchema: parallelSearchOutputSchema2
11417
12056
  });
11418
- var parallelSearch = (config = {}) => parallelSearchToolFactory(config);
11419
- var perplexitySearchInputSchema = lazySchema(
12057
+ var parallelSearch2 = (config = {}) => parallelSearchToolFactory2(config);
12058
+ var perplexitySearchInputSchema2 = lazySchema2(
11420
12059
  () => zodSchema3(
11421
12060
  zod.z.object({
11422
12061
  query: zod.z.union([zod.z.string(), zod.z.array(zod.z.string())]).describe(
@@ -11458,7 +12097,7 @@ var perplexitySearchInputSchema = lazySchema(
11458
12097
  })
11459
12098
  )
11460
12099
  );
11461
- var perplexitySearchOutputSchema = lazySchema(
12100
+ var perplexitySearchOutputSchema2 = lazySchema2(
11462
12101
  () => zodSchema3(
11463
12102
  zod.z.union([
11464
12103
  // Success response
@@ -11489,13 +12128,13 @@ var perplexitySearchOutputSchema = lazySchema(
11489
12128
  ])
11490
12129
  )
11491
12130
  );
11492
- var perplexitySearchToolFactory = createProviderToolFactoryWithOutputSchema({
12131
+ var perplexitySearchToolFactory2 = createProviderToolFactoryWithOutputSchema({
11493
12132
  id: "gateway.perplexity_search",
11494
- inputSchema: perplexitySearchInputSchema,
11495
- outputSchema: perplexitySearchOutputSchema
12133
+ inputSchema: perplexitySearchInputSchema2,
12134
+ outputSchema: perplexitySearchOutputSchema2
11496
12135
  });
11497
- var perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);
11498
- var gatewayTools = {
12136
+ var perplexitySearch2 = (config = {}) => perplexitySearchToolFactory2(config);
12137
+ var gatewayTools2 = {
11499
12138
  /**
11500
12139
  * Search the web using Parallel AI's Search API for LLM-optimized excerpts.
11501
12140
  *
@@ -11504,7 +12143,7 @@ var gatewayTools = {
11504
12143
  * or complex queries. Supports different search types for depth vs
11505
12144
  * breadth tradeoffs.
11506
12145
  */
11507
- parallelSearch,
12146
+ parallelSearch: parallelSearch2,
11508
12147
  /**
11509
12148
  * Search the web using Perplexity's Search API for real-time information,
11510
12149
  * news, research papers, and articles.
@@ -11512,21 +12151,21 @@ var gatewayTools = {
11512
12151
  * Provides ranked search results with advanced filtering options including
11513
12152
  * domain, language, date range, and recency filters.
11514
12153
  */
11515
- perplexitySearch
12154
+ perplexitySearch: perplexitySearch2
11516
12155
  };
11517
12156
  async function getVercelRequestId2() {
11518
12157
  var _a932;
11519
- return (_a932 = (0, import_oidc3.getContext)().headers) == null ? void 0 : _a932["x-vercel-id"];
12158
+ return (_a932 = getContext2().headers) == null ? void 0 : _a932["x-vercel-id"];
11520
12159
  }
11521
- var VERSION5 = "3.0.66";
12160
+ var VERSION6 = "3.0.112";
11522
12161
  var AI_GATEWAY_PROTOCOL_VERSION2 = "0.0.1";
11523
12162
  function createGatewayProvider2(options = {}) {
11524
- var _a932, _b92;
12163
+ var _a932, _b93;
11525
12164
  let pendingMetadata = null;
11526
12165
  let metadataCache = null;
11527
12166
  const cacheRefreshMillis = (_a932 = options.metadataCacheRefreshMillis) != null ? _a932 : 1e3 * 60 * 5;
11528
12167
  let lastFetchTime = 0;
11529
- const baseURL = (_b92 = withoutTrailingSlash2(options.baseURL)) != null ? _b92 : "https://ai-gateway.vercel.sh/v3/ai";
12168
+ const baseURL = (_b93 = withoutTrailingSlash2(options.baseURL)) != null ? _b93 : "https://ai-gateway.vercel.sh/v3/ai";
11530
12169
  const getHeaders = async () => {
11531
12170
  try {
11532
12171
  const auth = await getGatewayAuthToken2(options);
@@ -11537,7 +12176,7 @@ function createGatewayProvider2(options = {}) {
11537
12176
  [GATEWAY_AUTH_METHOD_HEADER2]: auth.authMethod,
11538
12177
  ...options.headers
11539
12178
  },
11540
- `ai-sdk/gateway/${VERSION5}`
12179
+ `ai-sdk/gateway/${VERSION6}`
11541
12180
  );
11542
12181
  } catch (error) {
11543
12182
  throw GatewayAuthenticationError2.createContextualError({
@@ -11586,8 +12225,8 @@ function createGatewayProvider2(options = {}) {
11586
12225
  });
11587
12226
  };
11588
12227
  const getAvailableModels = async () => {
11589
- var _a1022, _b102, _c;
11590
- const now2 = (_c = (_b102 = (_a1022 = options._internal) == null ? void 0 : _a1022.currentDate) == null ? void 0 : _b102.call(_a1022).getTime()) != null ? _c : Date.now();
12228
+ var _a1022, _b103, _c;
12229
+ const now2 = (_c = (_b103 = (_a1022 = options._internal) == null ? void 0 : _a1022.currentDate) == null ? void 0 : _b103.call(_a1022).getTime()) != null ? _c : Date.now();
11591
12230
  if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) {
11592
12231
  lastFetchTime = now2;
11593
12232
  pendingMetadata = new GatewayFetchMetadata2({
@@ -11618,6 +12257,30 @@ function createGatewayProvider2(options = {}) {
11618
12257
  );
11619
12258
  });
11620
12259
  };
12260
+ const getSpendReport = async (params) => {
12261
+ return new GatewaySpendReport2({
12262
+ baseURL,
12263
+ headers: getHeaders,
12264
+ fetch: options.fetch
12265
+ }).getSpendReport(params).catch(async (error) => {
12266
+ throw await asGatewayError2(
12267
+ error,
12268
+ await parseAuthMethod2(await getHeaders())
12269
+ );
12270
+ });
12271
+ };
12272
+ const getGenerationInfo = async (params) => {
12273
+ return new GatewayGenerationInfoFetcher2({
12274
+ baseURL,
12275
+ headers: getHeaders,
12276
+ fetch: options.fetch
12277
+ }).getGenerationInfo(params).catch(async (error) => {
12278
+ throw await asGatewayError2(
12279
+ error,
12280
+ await parseAuthMethod2(await getHeaders())
12281
+ );
12282
+ });
12283
+ };
11621
12284
  const provider = function(modelId) {
11622
12285
  if (new.target) {
11623
12286
  throw new Error(
@@ -11629,6 +12292,8 @@ function createGatewayProvider2(options = {}) {
11629
12292
  provider.specificationVersion = "v3";
11630
12293
  provider.getAvailableModels = getAvailableModels;
11631
12294
  provider.getCredits = getCredits;
12295
+ provider.getSpendReport = getSpendReport;
12296
+ provider.getGenerationInfo = getGenerationInfo;
11632
12297
  provider.imageModel = (modelId) => {
11633
12298
  return new GatewayImageModel2(modelId, {
11634
12299
  provider: "gateway",
@@ -11659,11 +12324,22 @@ function createGatewayProvider2(options = {}) {
11659
12324
  o11yHeaders: createO11yHeaders()
11660
12325
  });
11661
12326
  };
12327
+ const createRerankingModel = (modelId) => {
12328
+ return new GatewayRerankingModel(modelId, {
12329
+ provider: "gateway",
12330
+ baseURL,
12331
+ headers: getHeaders,
12332
+ fetch: options.fetch,
12333
+ o11yHeaders: createO11yHeaders()
12334
+ });
12335
+ };
12336
+ provider.rerankingModel = createRerankingModel;
12337
+ provider.reranking = createRerankingModel;
11662
12338
  provider.chat = provider.languageModel;
11663
12339
  provider.embedding = provider.embeddingModel;
11664
12340
  provider.image = provider.imageModel;
11665
12341
  provider.video = provider.videoModel;
11666
- provider.tools = gatewayTools;
12342
+ provider.tools = gatewayTools2;
11667
12343
  return provider;
11668
12344
  }
11669
12345
  createGatewayProvider2();
@@ -11678,7 +12354,7 @@ async function getGatewayAuthToken2(options) {
11678
12354
  authMethod: "api-key"
11679
12355
  };
11680
12356
  }
11681
- const oidcToken = await (0, import_oidc22.getVercelOidcToken)();
12357
+ const oidcToken = await getVercelOidcToken2();
11682
12358
  return {
11683
12359
  token: oidcToken,
11684
12360
  authMethod: "oidc"
@@ -11777,12 +12453,12 @@ function registerGlobal3(type, instance, diag, allowOverride) {
11777
12453
  return true;
11778
12454
  }
11779
12455
  function getGlobal3(type) {
11780
- var _a21, _b92;
12456
+ var _a21, _b93;
11781
12457
  var globalVersion = (_a21 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _a21 === void 0 ? void 0 : _a21.version;
11782
12458
  if (!globalVersion || !isCompatible3(globalVersion)) {
11783
12459
  return;
11784
12460
  }
11785
- return (_b92 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _b92 === void 0 ? void 0 : _b92[type];
12461
+ return (_b93 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _b93 === void 0 ? void 0 : _b93[type];
11786
12462
  }
11787
12463
  function unregisterGlobal3(type, diag) {
11788
12464
  diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION23 + ".");
@@ -11947,7 +12623,7 @@ var DiagAPI3 = (
11947
12623
  }
11948
12624
  var self = this;
11949
12625
  var setLogger = function(logger, optionsOrLogLevel) {
11950
- var _a21, _b92, _c;
12626
+ var _a21, _b93, _c;
11951
12627
  if (optionsOrLogLevel === void 0) {
11952
12628
  optionsOrLogLevel = { logLevel: DiagLogLevel3.INFO };
11953
12629
  }
@@ -11962,7 +12638,7 @@ var DiagAPI3 = (
11962
12638
  };
11963
12639
  }
11964
12640
  var oldLogger = getGlobal3("diag");
11965
- var newLogger = createLogLevelDiagLogger3((_b92 = optionsOrLogLevel.logLevel) !== null && _b92 !== void 0 ? _b92 : DiagLogLevel3.INFO, logger);
12641
+ var newLogger = createLogLevelDiagLogger3((_b93 = optionsOrLogLevel.logLevel) !== null && _b93 !== void 0 ? _b93 : DiagLogLevel3.INFO, logger);
11966
12642
  if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
11967
12643
  var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
11968
12644
  oldLogger.warn("Current logger will be overwritten from " + stack);
@@ -12395,8 +13071,8 @@ var __export3 = (target, all) => {
12395
13071
  for (var name21 in all)
12396
13072
  __defProp4(target, name21, { get: all[name21], enumerable: true });
12397
13073
  };
12398
- var name822 = "AI_NoObjectGeneratedError";
12399
- var marker823 = `vercel.ai.error.${name822}`;
13074
+ var name823 = "AI_NoObjectGeneratedError";
13075
+ var marker823 = `vercel.ai.error.${name823}`;
12400
13076
  var symbol823 = Symbol.for(marker823);
12401
13077
  var _a823;
12402
13078
  var NoObjectGeneratedError3 = class extends AISDKError3 {
@@ -12408,7 +13084,7 @@ var NoObjectGeneratedError3 = class extends AISDKError3 {
12408
13084
  usage,
12409
13085
  finishReason
12410
13086
  }) {
12411
- super({ name: name822, message, cause });
13087
+ super({ name: name823, message, cause });
12412
13088
  this[_a823] = true;
12413
13089
  this.text = text22;
12414
13090
  this.response = response;
@@ -12641,8 +13317,8 @@ var dataContentSchema3 = z4.z.union([
12641
13317
  z4.z.custom(
12642
13318
  // Buffer might not be available in some environments such as CloudFlare:
12643
13319
  (value) => {
12644
- var _a21, _b92;
12645
- return (_b92 = (_a21 = globalThis.Buffer) == null ? void 0 : _a21.isBuffer(value)) != null ? _b92 : false;
13320
+ var _a21, _b93;
13321
+ return (_b93 = (_a21 = globalThis.Buffer) == null ? void 0 : _a21.isBuffer(value)) != null ? _b93 : false;
12646
13322
  },
12647
13323
  { message: "Must be a Buffer" }
12648
13324
  )
@@ -13489,10 +14165,18 @@ createIdGenerator3({
13489
14165
  prefix: "aitxt",
13490
14166
  size: 24
13491
14167
  });
14168
+ z4.z.record(
14169
+ z4.z.string(),
14170
+ jsonValueSchema3.optional()
14171
+ );
13492
14172
  createIdGenerator3({
13493
14173
  prefix: "aitxt",
13494
14174
  size: 24
13495
14175
  });
14176
+ z4.z.record(
14177
+ z4.z.string(),
14178
+ jsonValueSchema3.optional()
14179
+ );
13496
14180
  createIdGenerator3({ prefix: "aiobj", size: 24 });
13497
14181
  createIdGenerator3({ prefix: "aiobj", size: 24 });
13498
14182
  function asProviderV3(provider) {
@@ -13590,6 +14274,428 @@ function customProvider3({
13590
14274
  }
13591
14275
  };
13592
14276
  }
14277
+ var ExecutionProvider = /* @__PURE__ */ ((ExecutionProvider2) => {
14278
+ ExecutionProvider2["CPU"] = "cpu";
14279
+ ExecutionProvider2["CUDA"] = "cuda";
14280
+ ExecutionProvider2["WebGL"] = "webgl";
14281
+ ExecutionProvider2["WASM"] = "wasm";
14282
+ ExecutionProvider2["XNNPACK"] = "xnnpack";
14283
+ return ExecutionProvider2;
14284
+ })(ExecutionProvider || {});
14285
+ var EmbeddingModel = /* @__PURE__ */ ((EmbeddingModel2) => {
14286
+ EmbeddingModel2["AllMiniLML6V2"] = "fast-all-MiniLM-L6-v2";
14287
+ EmbeddingModel2["BGEBaseEN"] = "fast-bge-base-en";
14288
+ EmbeddingModel2["BGEBaseENV15"] = "fast-bge-base-en-v1.5";
14289
+ EmbeddingModel2["BGESmallEN"] = "fast-bge-small-en";
14290
+ EmbeddingModel2["BGESmallENV15"] = "fast-bge-small-en-v1.5";
14291
+ EmbeddingModel2["BGESmallZH"] = "fast-bge-small-zh-v1.5";
14292
+ EmbeddingModel2["MLE5Large"] = "fast-multilingual-e5-large";
14293
+ EmbeddingModel2["CUSTOM"] = "custom";
14294
+ return EmbeddingModel2;
14295
+ })(EmbeddingModel || {});
14296
+ var SparseEmbeddingModel = /* @__PURE__ */ ((SparseEmbeddingModel2) => {
14297
+ SparseEmbeddingModel2["SpladePPEnV1"] = "prithivida/Splade_PP_en_v1";
14298
+ SparseEmbeddingModel2["CUSTOM"] = "custom";
14299
+ return SparseEmbeddingModel2;
14300
+ })(SparseEmbeddingModel || {});
14301
+ function normalize(v) {
14302
+ const norm = Math.sqrt(v.reduce((acc, val) => acc + val * val, 0));
14303
+ const epsilon = 1e-12;
14304
+ return v.map((val) => val / Math.max(norm, epsilon));
14305
+ }
14306
+ function getEmbeddings(data, dimensions) {
14307
+ const [x2, _y, z5] = dimensions;
14308
+ return new Array(x2).fill(void 0).map((_, index) => {
14309
+ const startIndex = index * _y * z5;
14310
+ const endIndex = startIndex + z5;
14311
+ return data.slice(startIndex, endIndex);
14312
+ });
14313
+ }
14314
+ var Embedding = class {
14315
+ };
14316
+ var SparseEmbedding = class {
14317
+ };
14318
+ function isAddedTokenMap(token) {
14319
+ return typeof token === "object" && token !== null && "content" in token && "single_word" in token && "rstrip" in token && "lstrip" in token && "normalized" in token;
14320
+ }
14321
+ function loadTokenizerFromDir(modelDir, maxLength) {
14322
+ const tokenizerPath = path__default.default.join(modelDir.toString(), "tokenizer.json");
14323
+ if (!fs__default.default.existsSync(tokenizerPath)) {
14324
+ throw new Error(`Tokenizer file not found at ${tokenizerPath}`);
14325
+ }
14326
+ const configPath = path__default.default.join(modelDir.toString(), "config.json");
14327
+ if (!fs__default.default.existsSync(configPath)) {
14328
+ throw new Error(`Config file not found at ${configPath}`);
14329
+ }
14330
+ const config = JSON.parse(fs__default.default.readFileSync(configPath, "utf-8"));
14331
+ const tokenizerFilePath = path__default.default.join(modelDir.toString(), "tokenizer_config.json");
14332
+ if (!fs__default.default.existsSync(tokenizerFilePath)) {
14333
+ throw new Error(`Tokenizer config file not found at ${tokenizerFilePath}`);
14334
+ }
14335
+ const tokenizerConfig = JSON.parse(fs__default.default.readFileSync(tokenizerFilePath, "utf-8"));
14336
+ maxLength = Math.min(maxLength, tokenizerConfig["model_max_length"]);
14337
+ const tokensMapPath = path__default.default.join(modelDir.toString(), "special_tokens_map.json");
14338
+ if (!fs__default.default.existsSync(tokensMapPath)) {
14339
+ throw new Error(`Tokens map file not found at ${tokensMapPath}`);
14340
+ }
14341
+ const tokensMap = JSON.parse(fs__default.default.readFileSync(tokensMapPath, "utf-8"));
14342
+ const tokenizer = tokenizers.Tokenizer.fromFile(tokenizerPath);
14343
+ tokenizer.setTruncation(maxLength);
14344
+ tokenizer.setPadding({
14345
+ maxLength,
14346
+ padId: config["pad_token_id"],
14347
+ padToken: tokenizerConfig["pad_token"]
14348
+ });
14349
+ for (const token of Object.values(tokensMap)) {
14350
+ if (typeof token === "string") {
14351
+ tokenizer.addSpecialTokens([token]);
14352
+ } else if (isAddedTokenMap(token)) {
14353
+ const addedToken = new tokenizers.AddedToken(token["content"], true, {
14354
+ singleWord: token["single_word"],
14355
+ leftStrip: token["lstrip"],
14356
+ rightStrip: token["rstrip"],
14357
+ normalized: token["normalized"]
14358
+ });
14359
+ tokenizer.addAddedTokens([addedToken]);
14360
+ }
14361
+ }
14362
+ return tokenizer;
14363
+ }
14364
+ var FlagEmbedding = class _FlagEmbedding extends Embedding {
14365
+ constructor(tokenizer, session, model) {
14366
+ super();
14367
+ this.tokenizer = tokenizer;
14368
+ this.session = session;
14369
+ this.model = model;
14370
+ }
14371
+ static async init({
14372
+ model = "fast-bge-small-en-v1.5" /* BGESmallENV15 */,
14373
+ executionProviders = ["cpu" /* CPU */],
14374
+ maxLength = 512,
14375
+ cacheDir = "local_cache",
14376
+ showDownloadProgress = true,
14377
+ modelAbsoluteDirPath = "",
14378
+ modelName = ""
14379
+ } = {}) {
14380
+ if (model === "custom" /* CUSTOM */) {
14381
+ if (!modelAbsoluteDirPath) {
14382
+ throw new Error("For custom model, modelAbsoluteDirPath is required in FlagEmbedding.init");
14383
+ }
14384
+ if (!modelName) {
14385
+ throw new Error("For custom model, modelName is required in FlagEmbedding.init");
14386
+ }
14387
+ }
14388
+ const modelDir = model === "custom" /* CUSTOM */ ? modelAbsoluteDirPath : await _FlagEmbedding.retrieveModel(model, cacheDir, showDownloadProgress);
14389
+ const tokenizer = loadTokenizerFromDir(modelDir, maxLength);
14390
+ const defaultModelName = model === "fast-multilingual-e5-large" /* MLE5Large */ || model === "fast-all-MiniLM-L6-v2" /* AllMiniLML6V2 */ ? "model.onnx" : "model_optimized.onnx";
14391
+ const modelPath = path__default.default.join(modelDir.toString(), modelName || defaultModelName);
14392
+ if (!fs__default.default.existsSync(modelPath)) {
14393
+ throw new Error(`Model file not found at ${modelPath}`);
14394
+ }
14395
+ const session = await ort__namespace.InferenceSession.create(modelPath, {
14396
+ executionProviders,
14397
+ graphOptimizationLevel: "all"
14398
+ });
14399
+ return new _FlagEmbedding(tokenizer, session, model);
14400
+ }
14401
+ static async downloadFileFromGCS(outputFilePath, model, showDownloadProgress = true) {
14402
+ if (fs__default.default.existsSync(outputFilePath)) {
14403
+ return outputFilePath;
14404
+ }
14405
+ if (model === "fast-all-MiniLM-L6-v2" /* AllMiniLML6V2 */) {
14406
+ model = "sentence-transformers" + model.substring(model.indexOf("-"));
14407
+ }
14408
+ const url = `https://storage.googleapis.com/qdrant-fastembed/${model}.tar.gz`;
14409
+ const fileStream = fs__default.default.createWriteStream(outputFilePath);
14410
+ return new Promise((resolve3, reject) => {
14411
+ https__default.default.get(url, { headers: { "User-Agent": "Mozilla/5.0" } }, (response) => {
14412
+ const status = response.statusCode ?? 0;
14413
+ if (status < 200 || status >= 300) {
14414
+ response.resume();
14415
+ reject(new Error(`Failed to download ${model}: HTTP ${status}`));
14416
+ return;
14417
+ }
14418
+ const totalSizeInBytes = parseInt(response.headers["content-length"] || "0", 10);
14419
+ if (totalSizeInBytes === 0) {
14420
+ console.warn(`Warning: Content-length header is missing or zero in the response from ${url}.`);
14421
+ }
14422
+ if (showDownloadProgress) {
14423
+ const progressBar = new Progress__default.default(`Downloading ${model} [:bar] :percent :etas`, {
14424
+ complete: "=",
14425
+ width: 20,
14426
+ total: totalSizeInBytes
14427
+ });
14428
+ response.on("data", (chunk) => {
14429
+ progressBar.tick(chunk.length, { speed: "N/A" });
14430
+ });
14431
+ }
14432
+ response.on("error", (error) => {
14433
+ reject(error);
14434
+ });
14435
+ response.pipe(fileStream);
14436
+ fileStream.on("finish", () => {
14437
+ fileStream.close();
14438
+ resolve3(outputFilePath);
14439
+ });
14440
+ fileStream.on("error", (error) => {
14441
+ reject(error);
14442
+ });
14443
+ }).on("error", (error) => {
14444
+ fs__default.default.unlink(outputFilePath, () => {
14445
+ reject(error);
14446
+ });
14447
+ });
14448
+ });
14449
+ }
14450
+ static async decompressToCache(targzPath, cacheDir) {
14451
+ if (path__default.default.extname(targzPath.toString()) === ".gz") {
14452
+ await tar__namespace.x({
14453
+ file: targzPath.toString(),
14454
+ cwd: cacheDir.toString()
14455
+ });
14456
+ } else {
14457
+ throw new Error(`Unsupported file extension: ${targzPath}`);
14458
+ }
14459
+ }
14460
+ static async retrieveModel(model, cacheDir, showDownloadProgress = true) {
14461
+ if (!fs__default.default.existsSync(cacheDir)) {
14462
+ fs__default.default.mkdirSync(cacheDir, { mode: 493 });
14463
+ }
14464
+ const modelDir = path__default.default.join(cacheDir.toString(), model);
14465
+ if (fs__default.default.existsSync(modelDir)) {
14466
+ return modelDir;
14467
+ }
14468
+ const modelTarGz = path__default.default.join(cacheDir.toString(), `${model}.tar.gz`);
14469
+ await this.downloadFileFromGCS(modelTarGz, model, showDownloadProgress);
14470
+ await this.decompressToCache(modelTarGz, cacheDir);
14471
+ fs__default.default.unlinkSync(modelTarGz);
14472
+ return modelDir;
14473
+ }
14474
+ async *embed(textStrings, batchSize = 256) {
14475
+ for (let i = 0; i < textStrings.length; i += batchSize) {
14476
+ const batchTexts = textStrings.slice(i, i + batchSize);
14477
+ const encodedTexts = await Promise.all(batchTexts.map((textString) => this.tokenizer.encode(textString)));
14478
+ const idsArray = [];
14479
+ const maskArray = [];
14480
+ const typeIdsArray = [];
14481
+ encodedTexts.forEach((text4) => {
14482
+ const ids = text4.getIds().map(BigInt);
14483
+ const mask = text4.getAttentionMask().map(BigInt);
14484
+ const typeIds = text4.getTypeIds().map(BigInt);
14485
+ idsArray.push(ids);
14486
+ maskArray.push(mask);
14487
+ typeIdsArray.push(typeIds);
14488
+ });
14489
+ const maxLength = idsArray[0].length;
14490
+ const batchInputIds = new ort__namespace.Tensor("int64", idsArray.flat(), [
14491
+ batchTexts.length,
14492
+ maxLength
14493
+ ]);
14494
+ const batchAttentionMask = new ort__namespace.Tensor("int64", maskArray.flat(), [
14495
+ batchTexts.length,
14496
+ maxLength
14497
+ ]);
14498
+ const batchTokenTypeId = new ort__namespace.Tensor("int64", typeIdsArray.flat(), [
14499
+ batchTexts.length,
14500
+ maxLength
14501
+ ]);
14502
+ const inputs = {
14503
+ input_ids: batchInputIds,
14504
+ attention_mask: batchAttentionMask,
14505
+ token_type_ids: batchTokenTypeId
14506
+ };
14507
+ if (this.model === "fast-multilingual-e5-large" /* MLE5Large */) {
14508
+ delete inputs.token_type_ids;
14509
+ }
14510
+ const output = await this.session.run(inputs);
14511
+ const lastHiddenState = output.last_hidden_state;
14512
+ const embeddings = getEmbeddings(
14513
+ lastHiddenState.data,
14514
+ lastHiddenState.dims
14515
+ );
14516
+ yield embeddings.map(normalize);
14517
+ }
14518
+ }
14519
+ passageEmbed(texts, batchSize = 256) {
14520
+ texts = texts.map((text4) => `passage: ${text4}`);
14521
+ return this.embed(texts, batchSize);
14522
+ }
14523
+ async queryEmbed(query) {
14524
+ const result = await this.embed([`query: ${query}`]).next();
14525
+ return result.value[0];
14526
+ }
14527
+ listSupportedModels() {
14528
+ return [
14529
+ { model: "fast-bge-small-en" /* BGESmallEN */, dim: 384, description: "Fast English model" },
14530
+ { model: "fast-bge-small-en-v1.5" /* BGESmallENV15 */, dim: 384, description: "v1.5 release of the fast, default English model" },
14531
+ { model: "fast-bge-base-en" /* BGEBaseEN */, dim: 768, description: "Base English model" },
14532
+ { model: "fast-bge-base-en-v1.5" /* BGEBaseENV15 */, dim: 768, description: "v1.5 release of Base English model" },
14533
+ { model: "fast-bge-small-zh-v1.5" /* BGESmallZH */, dim: 512, description: "v1.5 release of the fast, Chinese model" },
14534
+ { model: "fast-all-MiniLM-L6-v2" /* AllMiniLML6V2 */, dim: 384, description: "Sentence Transformer model, MiniLM-L6-v2" },
14535
+ {
14536
+ model: "fast-multilingual-e5-large" /* MLE5Large */,
14537
+ dim: 1024,
14538
+ description: "Multilingual model, e5-large. Recommend using this model for non-English languages"
14539
+ }
14540
+ ];
14541
+ }
14542
+ };
14543
+ var SparseTextEmbedding = class _SparseTextEmbedding extends SparseEmbedding {
14544
+ constructor(tokenizer, session) {
14545
+ super();
14546
+ this.tokenizer = tokenizer;
14547
+ this.session = session;
14548
+ }
14549
+ static async init({
14550
+ model = "prithivida/Splade_PP_en_v1" /* SpladePPEnV1 */,
14551
+ executionProviders = ["cpu" /* CPU */],
14552
+ maxLength = 512,
14553
+ cacheDir = "local_cache",
14554
+ showDownloadProgress = true,
14555
+ modelAbsoluteDirPath = "",
14556
+ modelName = ""
14557
+ } = {}) {
14558
+ if (model === "custom" /* CUSTOM */) {
14559
+ if (!modelAbsoluteDirPath) {
14560
+ throw new Error("For custom model, modelAbsoluteDirPath is required in SparseTextEmbedding.init");
14561
+ }
14562
+ if (!modelName) {
14563
+ throw new Error("For custom model, modelName is required in SparseTextEmbedding.init");
14564
+ }
14565
+ }
14566
+ const modelDir = model === "custom" /* CUSTOM */ ? modelAbsoluteDirPath : await _SparseTextEmbedding.retrieveModel(model, cacheDir, showDownloadProgress);
14567
+ const { tokenizer } = this.loadTokenizer(modelDir, maxLength);
14568
+ const defaultModelName = "model.onnx";
14569
+ const modelPath = path__default.default.join(modelDir.toString(), "onnx", modelName || defaultModelName);
14570
+ if (!fs__default.default.existsSync(modelPath)) {
14571
+ throw new Error(`Model file not found at ${modelPath}`);
14572
+ }
14573
+ const session = await ort__namespace.InferenceSession.create(modelPath, {
14574
+ executionProviders,
14575
+ graphOptimizationLevel: "all"
14576
+ });
14577
+ return new _SparseTextEmbedding(tokenizer, session);
14578
+ }
14579
+ static loadTokenizer(modelDir, maxLength) {
14580
+ const tokenizer = loadTokenizerFromDir(modelDir, maxLength);
14581
+ return { tokenizer };
14582
+ }
14583
+ static async retrieveModel(model, cacheDir, _showDownloadProgress = true) {
14584
+ if (!fs__default.default.existsSync(cacheDir)) {
14585
+ fs__default.default.mkdirSync(cacheDir, { mode: 493 });
14586
+ }
14587
+ const modelDir = path__default.default.join(cacheDir.toString(), model.replace("/", "_"));
14588
+ if (fs__default.default.existsSync(modelDir)) {
14589
+ return modelDir;
14590
+ }
14591
+ fs__default.default.mkdirSync(modelDir, { mode: 493 });
14592
+ const filesToDownload = [
14593
+ "onnx/model.onnx",
14594
+ "tokenizer.json",
14595
+ "tokenizer_config.json",
14596
+ "config.json",
14597
+ "special_tokens_map.json"
14598
+ ];
14599
+ for (const fileName of filesToDownload) {
14600
+ const outputPath = path__default.default.join(modelDir, fileName);
14601
+ const outputDir = path__default.default.dirname(outputPath);
14602
+ if (!fs__default.default.existsSync(outputDir)) {
14603
+ fs__default.default.mkdirSync(outputDir, { recursive: true, mode: 493 });
14604
+ }
14605
+ const downloaded = await hub.downloadFileToCacheDir({
14606
+ repo: model,
14607
+ path: fileName
14608
+ });
14609
+ if (downloaded && typeof downloaded === "string") {
14610
+ fs__default.default.copyFileSync(downloaded, outputPath);
14611
+ }
14612
+ }
14613
+ return modelDir;
14614
+ }
14615
+ async *embed(textStrings, batchSize = 256) {
14616
+ for (let i = 0; i < textStrings.length; i += batchSize) {
14617
+ const batchTexts = textStrings.slice(i, i + batchSize);
14618
+ const encodedTexts = await Promise.all(batchTexts.map((textString) => this.tokenizer.encode(textString)));
14619
+ const idsArray = [];
14620
+ const maskArray = [];
14621
+ const typeIdsArray = [];
14622
+ encodedTexts.forEach((text4) => {
14623
+ const ids = text4.getIds().map(BigInt);
14624
+ const mask = text4.getAttentionMask();
14625
+ const typeIds = text4.getTypeIds().map(BigInt);
14626
+ idsArray.push(ids);
14627
+ maskArray.push(mask);
14628
+ typeIdsArray.push(typeIds);
14629
+ });
14630
+ const maxLength = idsArray[0].length;
14631
+ const batchInputIds = new ort__namespace.Tensor("int64", idsArray.flat(), [
14632
+ batchTexts.length,
14633
+ maxLength
14634
+ ]);
14635
+ const batchAttentionMask = new ort__namespace.Tensor("int64", maskArray.flat().map(BigInt), [
14636
+ batchTexts.length,
14637
+ maxLength
14638
+ ]);
14639
+ const batchTokenTypeId = new ort__namespace.Tensor("int64", typeIdsArray.flat(), [
14640
+ batchTexts.length,
14641
+ maxLength
14642
+ ]);
14643
+ const inputs = {
14644
+ input_ids: batchInputIds,
14645
+ input_mask: batchAttentionMask,
14646
+ segment_ids: batchTokenTypeId
14647
+ };
14648
+ const output = await this.session.run(inputs);
14649
+ const outputTensor = output.output;
14650
+ const logits = outputTensor.cpuData;
14651
+ const dims = outputTensor.dims;
14652
+ const [currentBatchSize, seqLen, currentVocabSize] = dims;
14653
+ const sparseVectors = [];
14654
+ for (let batchIdx = 0; batchIdx < currentBatchSize; batchIdx++) {
14655
+ const valuesArr = new Float32Array(currentVocabSize).fill(0);
14656
+ for (let seqIdx = 0; seqIdx < seqLen; seqIdx++) {
14657
+ const attentionValue = maskArray[batchIdx][seqIdx];
14658
+ if (attentionValue > 0) {
14659
+ for (let vocabIdx = 0; vocabIdx < currentVocabSize; vocabIdx++) {
14660
+ const logitIdx = batchIdx * seqLen * currentVocabSize + seqIdx * currentVocabSize + vocabIdx;
14661
+ const logitValue = logits[logitIdx];
14662
+ const reluValue = Math.max(0, logitValue);
14663
+ const logValue = Math.log(1 + reluValue);
14664
+ valuesArr[vocabIdx] = Math.max(valuesArr[vocabIdx], logValue);
14665
+ }
14666
+ }
14667
+ }
14668
+ const sparseVector = { values: [], indices: [] };
14669
+ for (let tokenId = 0; tokenId < currentVocabSize; tokenId++) {
14670
+ if (valuesArr[tokenId] > 0) {
14671
+ sparseVector.indices.push(tokenId);
14672
+ sparseVector.values.push(valuesArr[tokenId]);
14673
+ }
14674
+ }
14675
+ sparseVectors.push(sparseVector);
14676
+ }
14677
+ yield sparseVectors;
14678
+ }
14679
+ }
14680
+ passageEmbed(texts, batchSize = 256) {
14681
+ return this.embed(texts, batchSize);
14682
+ }
14683
+ async queryEmbed(query) {
14684
+ const result = await this.embed([query]).next();
14685
+ return result.value[0];
14686
+ }
14687
+ listSupportedModels() {
14688
+ return [
14689
+ {
14690
+ model: "prithivida/Splade_PP_en_v1" /* SpladePPEnV1 */,
14691
+ vocabSize: 30522,
14692
+ description: "SPLADE++ English model for sparse retrieval"
14693
+ }
14694
+ ];
14695
+ }
14696
+ };
14697
+
14698
+ // src/index.ts
13593
14699
  async function getModelCachePath() {
13594
14700
  const cachePath = path__default.default.join(os__default.default.homedir(), ".cache", "mastra", "fastembed-models");
13595
14701
  await fsp__default.default.mkdir(cachePath, { recursive: true });
@@ -13597,13 +14703,12 @@ async function getModelCachePath() {
13597
14703
  }
13598
14704
  async function warmup() {
13599
14705
  const cacheDir = await getModelCachePath();
13600
- const retrieve = fastembed$1.FlagEmbedding.retrieveModel.bind(fastembed$1.FlagEmbedding);
13601
- await retrieve(fastembed$1.EmbeddingModel.BGESmallENV15, cacheDir, false);
13602
- await retrieve(fastembed$1.EmbeddingModel.BGEBaseENV15, cacheDir, false);
14706
+ await FlagEmbedding.retrieveModel("fast-bge-small-en-v1.5" /* BGESmallENV15 */, cacheDir, false);
14707
+ await FlagEmbedding.retrieveModel("fast-bge-base-en-v1.5" /* BGEBaseENV15 */, cacheDir, false);
13603
14708
  }
13604
14709
  async function generateEmbeddings(values, modelType) {
13605
- const model = await fastembed$1.FlagEmbedding.init({
13606
- model: fastembed$1.EmbeddingModel[modelType],
14710
+ const model = await FlagEmbedding.init({
14711
+ model: EmbeddingModel[modelType],
13607
14712
  cacheDir: await getModelCachePath()
13608
14713
  });
13609
14714
  const embeddings = model.embed(values);
@@ -13699,6 +14804,11 @@ var fastembed = Object.assign(fastEmbedProviderV3.embeddingModel(`bge-small-en-v
13699
14804
  baseLegacy: fastEmbedLegacyProvider.textEmbeddingModel(`bge-base-en-v1.5`)
13700
14805
  });
13701
14806
 
14807
+ exports.EmbeddingModel = EmbeddingModel;
14808
+ exports.ExecutionProvider = ExecutionProvider;
14809
+ exports.FlagEmbedding = FlagEmbedding;
14810
+ exports.SparseEmbeddingModel = SparseEmbeddingModel;
14811
+ exports.SparseTextEmbedding = SparseTextEmbedding;
13702
14812
  exports.fastembed = fastembed;
13703
14813
  exports.warmup = warmup;
13704
14814
  //# sourceMappingURL=index.cjs.map