@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.js CHANGED
@@ -1,5 +1,3 @@
1
- import { __commonJS, require_token_error, __toESM } from './chunk-BSDWQEU3.js';
2
- import { __commonJS as __commonJS$1, require_token_error as require_token_error$1, __toESM as __toESM$1 } from './chunk-RC6RZVYE.js';
3
1
  import fsp from 'fs/promises';
4
2
  import os from 'os';
5
3
  import path from 'path';
@@ -7,12 +5,20 @@ import * as z4 from 'zod/v4';
7
5
  import { z } from 'zod/v4';
8
6
  import { ZodFirstPartyTypeKind } from 'zod/v3';
9
7
  import { z as z$1 } from 'zod';
10
- import { FlagEmbedding, EmbeddingModel } from 'fastembed';
8
+ import { Tokenizer, AddedToken } from '@anush008/tokenizers';
9
+ import fs from 'fs';
10
+ import https from 'https';
11
+ import * as ort from 'onnxruntime-node';
12
+ import Progress from 'progress';
13
+ import * as tar from 'tar';
14
+ import { downloadFileToCacheDir } from '@huggingface/hub';
11
15
 
16
+ // src/index.ts
12
17
  var marker = "vercel.ai.error";
13
18
  var symbol = Symbol.for(marker);
14
19
  var _a;
15
- var _AISDKError = class _AISDKError2 extends Error {
20
+ var _b;
21
+ var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
16
22
  /**
17
23
  * Creates an AI SDK Error.
18
24
  *
@@ -22,13 +28,13 @@ var _AISDKError = class _AISDKError2 extends Error {
22
28
  * @param {unknown} [params.cause] - The underlying cause of the error.
23
29
  */
24
30
  constructor({
25
- name: name146,
31
+ name: name1422,
26
32
  message,
27
33
  cause
28
34
  }) {
29
35
  super(message);
30
36
  this[_a] = true;
31
- this.name = name146;
37
+ this.name = name1422;
32
38
  this.cause = cause;
33
39
  }
34
40
  /**
@@ -37,20 +43,19 @@ var _AISDKError = class _AISDKError2 extends Error {
37
43
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
38
44
  */
39
45
  static isInstance(error) {
40
- return _AISDKError2.hasMarker(error, marker);
46
+ return _AISDKError.hasMarker(error, marker);
41
47
  }
42
- static hasMarker(error, marker156) {
43
- const markerSymbol = Symbol.for(marker156);
48
+ static hasMarker(error, marker1522) {
49
+ const markerSymbol = Symbol.for(marker1522);
44
50
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
45
51
  }
46
52
  };
47
- _a = symbol;
48
- var AISDKError = _AISDKError;
49
53
  var name = "AI_APICallError";
50
54
  var marker2 = `vercel.ai.error.${name}`;
51
55
  var symbol2 = Symbol.for(marker2);
52
56
  var _a2;
53
- var APICallError = class extends AISDKError {
57
+ var _b2;
58
+ var APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {
54
59
  constructor({
55
60
  message,
56
61
  url,
@@ -80,12 +85,12 @@ var APICallError = class extends AISDKError {
80
85
  return AISDKError.hasMarker(error, marker2);
81
86
  }
82
87
  };
83
- _a2 = symbol2;
84
88
  var name2 = "AI_EmptyResponseBodyError";
85
89
  var marker3 = `vercel.ai.error.${name2}`;
86
90
  var symbol3 = Symbol.for(marker3);
87
91
  var _a3;
88
- var EmptyResponseBodyError = class extends AISDKError {
92
+ var _b3;
93
+ var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {
89
94
  // used in isInstance
90
95
  constructor({ message = "Empty response body" } = {}) {
91
96
  super({ name: name2, message });
@@ -95,7 +100,6 @@ var EmptyResponseBodyError = class extends AISDKError {
95
100
  return AISDKError.hasMarker(error, marker3);
96
101
  }
97
102
  };
98
- _a3 = symbol3;
99
103
  function getErrorMessage(error) {
100
104
  if (error == null) {
101
105
  return "unknown error";
@@ -112,7 +116,8 @@ var name3 = "AI_InvalidArgumentError";
112
116
  var marker4 = `vercel.ai.error.${name3}`;
113
117
  var symbol4 = Symbol.for(marker4);
114
118
  var _a4;
115
- var InvalidArgumentError = class extends AISDKError {
119
+ var _b4;
120
+ var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {
116
121
  constructor({
117
122
  message,
118
123
  cause,
@@ -126,12 +131,12 @@ var InvalidArgumentError = class extends AISDKError {
126
131
  return AISDKError.hasMarker(error, marker4);
127
132
  }
128
133
  };
129
- _a4 = symbol4;
130
134
  var name6 = "AI_JSONParseError";
131
135
  var marker7 = `vercel.ai.error.${name6}`;
132
136
  var symbol7 = Symbol.for(marker7);
133
137
  var _a7;
134
- var JSONParseError = class extends AISDKError {
138
+ var _b7;
139
+ var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {
135
140
  constructor({ text: text4, cause }) {
136
141
  super({
137
142
  name: name6,
@@ -146,12 +151,12 @@ Error message: ${getErrorMessage(cause)}`,
146
151
  return AISDKError.hasMarker(error, marker7);
147
152
  }
148
153
  };
149
- _a7 = symbol7;
150
154
  var name10 = "AI_NoSuchModelError";
151
155
  var marker11 = `vercel.ai.error.${name10}`;
152
156
  var symbol11 = Symbol.for(marker11);
153
157
  var _a11;
154
- var NoSuchModelError = class extends AISDKError {
158
+ var _b11;
159
+ var NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {
155
160
  constructor({
156
161
  errorName = name10,
157
162
  modelId,
@@ -167,12 +172,12 @@ var NoSuchModelError = class extends AISDKError {
167
172
  return AISDKError.hasMarker(error, marker11);
168
173
  }
169
174
  };
170
- _a11 = symbol11;
171
175
  var name12 = "AI_TypeValidationError";
172
176
  var marker13 = `vercel.ai.error.${name12}`;
173
177
  var symbol13 = Symbol.for(marker13);
174
178
  var _a13;
175
- var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
179
+ var _b13;
180
+ var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
176
181
  constructor({ value, cause }) {
177
182
  super({
178
183
  name: name12,
@@ -200,11 +205,9 @@ Error message: ${getErrorMessage(cause)}`,
200
205
  value,
201
206
  cause
202
207
  }) {
203
- return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
208
+ return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
204
209
  }
205
210
  };
206
- _a13 = symbol13;
207
- var TypeValidationError = _TypeValidationError;
208
211
  var ParseError = class extends Error {
209
212
  constructor(message, options) {
210
213
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
@@ -395,14 +398,14 @@ function handleFetchError({
395
398
  return error;
396
399
  }
397
400
  function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
398
- var _a156, _b17, _c;
401
+ var _a224, _b222, _c;
399
402
  if (globalThisAny.window) {
400
403
  return `runtime/browser`;
401
404
  }
402
- if ((_a156 = globalThisAny.navigator) == null ? void 0 : _a156.userAgent) {
405
+ if ((_a224 = globalThisAny.navigator) == null ? void 0 : _a224.userAgent) {
403
406
  return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
404
407
  }
405
- if ((_c = (_b17 = globalThisAny.process) == null ? void 0 : _b17.versions) == null ? void 0 : _c.node) {
408
+ if ((_c = (_b222 = globalThisAny.process) == null ? void 0 : _b222.versions) == null ? void 0 : _c.node) {
406
409
  return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
407
410
  }
408
411
  if (globalThisAny.EdgeRuntime) {
@@ -440,7 +443,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
440
443
  );
441
444
  return Object.fromEntries(normalizedHeaders.entries());
442
445
  }
443
- var VERSION = "3.0.17";
446
+ var VERSION = "3.0.25";
444
447
  var getOriginalFetch = () => globalThis.fetch;
445
448
  var getFromApi = async ({
446
449
  url,
@@ -525,8 +528,8 @@ function loadOptionalSetting({
525
528
  }
526
529
  return settingValue;
527
530
  }
528
- var suspectProtoRx = /"__proto__"\s*:/;
529
- var suspectConstructorRx = /"constructor"\s*:/;
531
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
532
+ 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*:/;
530
533
  function _parse(text4) {
531
534
  const obj = JSON.parse(text4);
532
535
  if (obj === null || typeof obj !== "object") {
@@ -546,7 +549,7 @@ function filter(obj) {
546
549
  if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
547
550
  throw new SyntaxError("Object contains forbidden prototype property");
548
551
  }
549
- if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
552
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
550
553
  throw new SyntaxError("Object contains forbidden prototype property");
551
554
  }
552
555
  for (const key in node) {
@@ -782,6 +785,36 @@ var postToApi = async ({
782
785
  throw handleFetchError({ error, url, requestBodyValues: body.values });
783
786
  }
784
787
  };
788
+ function tool(tool22) {
789
+ return tool22;
790
+ }
791
+ function createProviderDefinedToolFactoryWithOutputSchema({
792
+ id,
793
+ name: name224,
794
+ inputSchema,
795
+ outputSchema: outputSchema3
796
+ }) {
797
+ return ({
798
+ execute,
799
+ toModelOutput,
800
+ onInputStart,
801
+ onInputDelta,
802
+ onInputAvailable,
803
+ ...args
804
+ }) => tool({
805
+ type: "provider-defined",
806
+ id,
807
+ name: name224,
808
+ args,
809
+ inputSchema,
810
+ outputSchema: outputSchema3,
811
+ execute,
812
+ toModelOutput,
813
+ onInputStart,
814
+ onInputDelta,
815
+ onInputAvailable
816
+ });
817
+ }
785
818
  async function resolve(value) {
786
819
  if (typeof value === "function") {
787
820
  value = value();
@@ -879,13 +912,58 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
879
912
  rawValue: parsedResult.rawValue
880
913
  };
881
914
  };
882
- var getRelativePath = (pathA, pathB) => {
883
- let i = 0;
884
- for (; i < pathA.length && i < pathB.length; i++) {
885
- if (pathA[i] !== pathB[i]) break;
915
+ var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
916
+ function lazySchema(createSchema) {
917
+ let schema;
918
+ return () => {
919
+ if (schema == null) {
920
+ schema = createSchema();
921
+ }
922
+ return schema;
923
+ };
924
+ }
925
+ function jsonSchema(jsonSchema22, {
926
+ validate
927
+ } = {}) {
928
+ return {
929
+ [schemaSymbol]: true,
930
+ _type: void 0,
931
+ // should never be used directly
932
+ [validatorSymbol]: true,
933
+ get jsonSchema() {
934
+ if (typeof jsonSchema22 === "function") {
935
+ jsonSchema22 = jsonSchema22();
936
+ }
937
+ return jsonSchema22;
938
+ },
939
+ validate
940
+ };
941
+ }
942
+ function addAdditionalPropertiesToJsonSchema(jsonSchema22) {
943
+ if (jsonSchema22.type === "object") {
944
+ jsonSchema22.additionalProperties = false;
945
+ const properties = jsonSchema22.properties;
946
+ if (properties != null) {
947
+ for (const property in properties) {
948
+ properties[property] = addAdditionalPropertiesToJsonSchema(
949
+ properties[property]
950
+ );
951
+ }
952
+ }
886
953
  }
887
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
888
- };
954
+ if (jsonSchema22.type === "array" && jsonSchema22.items != null) {
955
+ if (Array.isArray(jsonSchema22.items)) {
956
+ jsonSchema22.items = jsonSchema22.items.map(
957
+ (item) => addAdditionalPropertiesToJsonSchema(item)
958
+ );
959
+ } else {
960
+ jsonSchema22.items = addAdditionalPropertiesToJsonSchema(
961
+ jsonSchema22.items
962
+ );
963
+ }
964
+ }
965
+ return jsonSchema22;
966
+ }
889
967
  var ignoreOverride = /* @__PURE__ */ Symbol(
890
968
  "Let zodToJsonSchema decide on which parser to use"
891
969
  );
@@ -921,11 +999,11 @@ function parseAnyDef() {
921
999
  return {};
922
1000
  }
923
1001
  function parseArrayDef(def, refs) {
924
- var _a156, _b17, _c;
1002
+ var _a224, _b222, _c;
925
1003
  const res = {
926
1004
  type: "array"
927
1005
  };
928
- if (((_a156 = def.type) == null ? void 0 : _a156._def) && ((_c = (_b17 = def.type) == null ? void 0 : _b17._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
1006
+ if (((_a224 = def.type) == null ? void 0 : _a224._def) && ((_c = (_b222 = def.type) == null ? void 0 : _b222._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
929
1007
  res.items = parseDef(def.type._def, {
930
1008
  ...refs,
931
1009
  currentPath: [...refs.currentPath, "items"]
@@ -1050,7 +1128,7 @@ function parseIntersectionDef(def, refs) {
1050
1128
  ...refs,
1051
1129
  currentPath: [...refs.currentPath, "allOf", "1"]
1052
1130
  })
1053
- ].filter((x) => !!x);
1131
+ ].filter((x2) => !!x2);
1054
1132
  const mergedAllOf = [];
1055
1133
  allOf.forEach((schema) => {
1056
1134
  if (isJsonSchema7AllOfType(schema)) {
@@ -1284,8 +1362,8 @@ function escapeNonAlphaNumeric(source) {
1284
1362
  return result;
1285
1363
  }
1286
1364
  function addFormat(schema, value, message, refs) {
1287
- var _a156;
1288
- if (schema.format || ((_a156 = schema.anyOf) == null ? void 0 : _a156.some((x) => x.format))) {
1365
+ var _a224;
1366
+ if (schema.format || ((_a224 = schema.anyOf) == null ? void 0 : _a224.some((x2) => x2.format))) {
1289
1367
  if (!schema.anyOf) {
1290
1368
  schema.anyOf = [];
1291
1369
  }
@@ -1304,8 +1382,8 @@ function addFormat(schema, value, message, refs) {
1304
1382
  }
1305
1383
  }
1306
1384
  function addPattern(schema, regex, message, refs) {
1307
- var _a156;
1308
- if (schema.pattern || ((_a156 = schema.allOf) == null ? void 0 : _a156.some((x) => x.pattern))) {
1385
+ var _a224;
1386
+ if (schema.pattern || ((_a224 = schema.allOf) == null ? void 0 : _a224.some((x2) => x2.pattern))) {
1309
1387
  if (!schema.allOf) {
1310
1388
  schema.allOf = [];
1311
1389
  }
@@ -1324,7 +1402,7 @@ function addPattern(schema, regex, message, refs) {
1324
1402
  }
1325
1403
  }
1326
1404
  function stringifyRegExpWithFlags(regex, refs) {
1327
- var _a156;
1405
+ var _a224;
1328
1406
  if (!refs.applyRegexFlags || !regex.flags) {
1329
1407
  return regex.source;
1330
1408
  }
@@ -1354,7 +1432,7 @@ function stringifyRegExpWithFlags(regex, refs) {
1354
1432
  pattern += source[i];
1355
1433
  pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1356
1434
  inCharRange = false;
1357
- } else if (source[i + 1] === "-" && ((_a156 = source[i + 2]) == null ? void 0 : _a156.match(/[a-z]/))) {
1435
+ } else if (source[i + 1] === "-" && ((_a224 = source[i + 2]) == null ? void 0 : _a224.match(/[a-z]/))) {
1358
1436
  pattern += source[i];
1359
1437
  inCharRange = true;
1360
1438
  } else {
@@ -1396,15 +1474,15 @@ function stringifyRegExpWithFlags(regex, refs) {
1396
1474
  return pattern;
1397
1475
  }
1398
1476
  function parseRecordDef(def, refs) {
1399
- var _a156, _b17, _c, _d, _e, _f;
1477
+ var _a224, _b222, _c, _d, _e, _f;
1400
1478
  const schema = {
1401
1479
  type: "object",
1402
- additionalProperties: (_a156 = parseDef(def.valueType._def, {
1480
+ additionalProperties: (_a224 = parseDef(def.valueType._def, {
1403
1481
  ...refs,
1404
1482
  currentPath: [...refs.currentPath, "additionalProperties"]
1405
- })) != null ? _a156 : refs.allowedAdditionalProperties
1483
+ })) != null ? _a224 : refs.allowedAdditionalProperties
1406
1484
  };
1407
- if (((_b17 = def.keyType) == null ? void 0 : _b17._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1485
+ if (((_b222 = def.keyType) == null ? void 0 : _b222._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1408
1486
  const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1409
1487
  return {
1410
1488
  ...schema,
@@ -1484,19 +1562,19 @@ var primitiveMappings = {
1484
1562
  function parseUnionDef(def, refs) {
1485
1563
  const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1486
1564
  if (options.every(
1487
- (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1565
+ (x2) => x2._def.typeName in primitiveMappings && (!x2._def.checks || !x2._def.checks.length)
1488
1566
  )) {
1489
- const types = options.reduce((types2, x) => {
1490
- const type = primitiveMappings[x._def.typeName];
1567
+ const types = options.reduce((types2, x2) => {
1568
+ const type = primitiveMappings[x2._def.typeName];
1491
1569
  return type && !types2.includes(type) ? [...types2, type] : types2;
1492
1570
  }, []);
1493
1571
  return {
1494
1572
  type: types.length > 1 ? types : types[0]
1495
1573
  };
1496
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1574
+ } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
1497
1575
  const types = options.reduce(
1498
- (acc, x) => {
1499
- const type = typeof x._def.value;
1576
+ (acc, x2) => {
1577
+ const type = typeof x2._def.value;
1500
1578
  switch (type) {
1501
1579
  case "string":
1502
1580
  case "number":
@@ -1505,7 +1583,7 @@ function parseUnionDef(def, refs) {
1505
1583
  case "bigint":
1506
1584
  return [...acc, "integer"];
1507
1585
  case "object":
1508
- if (x._def.value === null) return [...acc, "null"];
1586
+ if (x2._def.value === null) return [...acc, "null"];
1509
1587
  case "symbol":
1510
1588
  case "undefined":
1511
1589
  case "function":
@@ -1516,24 +1594,24 @@ function parseUnionDef(def, refs) {
1516
1594
  []
1517
1595
  );
1518
1596
  if (types.length === options.length) {
1519
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1597
+ const uniqueTypes = types.filter((x2, i, a) => a.indexOf(x2) === i);
1520
1598
  return {
1521
1599
  type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1522
1600
  enum: options.reduce(
1523
- (acc, x) => {
1524
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1601
+ (acc, x2) => {
1602
+ return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
1525
1603
  },
1526
1604
  []
1527
1605
  )
1528
1606
  };
1529
1607
  }
1530
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1608
+ } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
1531
1609
  return {
1532
1610
  type: "string",
1533
1611
  enum: options.reduce(
1534
- (acc, x) => [
1612
+ (acc, x2) => [
1535
1613
  ...acc,
1536
- ...x._def.values.filter((x2) => !acc.includes(x2))
1614
+ ...x2._def.values.filter((x22) => !acc.includes(x22))
1537
1615
  ],
1538
1616
  []
1539
1617
  )
@@ -1543,12 +1621,12 @@ function parseUnionDef(def, refs) {
1543
1621
  }
1544
1622
  var asAnyOf = (def, refs) => {
1545
1623
  const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1546
- (x, i) => parseDef(x._def, {
1624
+ (x2, i) => parseDef(x2._def, {
1547
1625
  ...refs,
1548
1626
  currentPath: [...refs.currentPath, "anyOf", `${i}`]
1549
1627
  })
1550
1628
  ).filter(
1551
- (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1629
+ (x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0)
1552
1630
  );
1553
1631
  return anyOf.length ? { anyOf } : void 0;
1554
1632
  };
@@ -1659,8 +1737,8 @@ function safeIsOptional(schema) {
1659
1737
  }
1660
1738
  }
1661
1739
  var parseOptionalDef = (def, refs) => {
1662
- var _a156;
1663
- if (refs.currentPath.toString() === ((_a156 = refs.propertyPath) == null ? void 0 : _a156.toString())) {
1740
+ var _a224;
1741
+ if (refs.currentPath.toString() === ((_a224 = refs.propertyPath) == null ? void 0 : _a224.toString())) {
1664
1742
  return parseDef(def.innerType._def, refs);
1665
1743
  }
1666
1744
  const innerSchema = parseDef(def.innerType._def, {
@@ -1684,7 +1762,7 @@ var parsePipelineDef = (def, refs) => {
1684
1762
  currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1685
1763
  });
1686
1764
  return {
1687
- allOf: [a, b].filter((x) => x !== void 0)
1765
+ allOf: [a, b].filter((x2) => x2 !== void 0)
1688
1766
  };
1689
1767
  };
1690
1768
  function parsePromiseDef(def, refs) {
@@ -1714,12 +1792,12 @@ function parseTupleDef(def, refs) {
1714
1792
  type: "array",
1715
1793
  minItems: def.items.length,
1716
1794
  items: def.items.map(
1717
- (x, i) => parseDef(x._def, {
1795
+ (x2, i) => parseDef(x2._def, {
1718
1796
  ...refs,
1719
1797
  currentPath: [...refs.currentPath, "items", `${i}`]
1720
1798
  })
1721
1799
  ).reduce(
1722
- (acc, x) => x === void 0 ? acc : [...acc, x],
1800
+ (acc, x2) => x2 === void 0 ? acc : [...acc, x2],
1723
1801
  []
1724
1802
  ),
1725
1803
  additionalItems: parseDef(def.rest._def, {
@@ -1733,12 +1811,12 @@ function parseTupleDef(def, refs) {
1733
1811
  minItems: def.items.length,
1734
1812
  maxItems: def.items.length,
1735
1813
  items: def.items.map(
1736
- (x, i) => parseDef(x._def, {
1814
+ (x2, i) => parseDef(x2._def, {
1737
1815
  ...refs,
1738
1816
  currentPath: [...refs.currentPath, "items", `${i}`]
1739
1817
  })
1740
1818
  ).reduce(
1741
- (acc, x) => x === void 0 ? acc : [...acc, x],
1819
+ (acc, x2) => x2 === void 0 ? acc : [...acc, x2],
1742
1820
  []
1743
1821
  )
1744
1822
  };
@@ -1829,11 +1907,18 @@ var selectParser = (def, typeName, refs) => {
1829
1907
  return /* @__PURE__ */ ((_) => void 0)();
1830
1908
  }
1831
1909
  };
1910
+ var getRelativePath = (pathA, pathB) => {
1911
+ let i = 0;
1912
+ for (; i < pathA.length && i < pathB.length; i++) {
1913
+ if (pathA[i] !== pathB[i]) break;
1914
+ }
1915
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1916
+ };
1832
1917
  function parseDef(def, refs, forceResolution = false) {
1833
- var _a156;
1918
+ var _a224;
1834
1919
  const seenItem = refs.seen.get(def);
1835
1920
  if (refs.override) {
1836
- const overrideResult = (_a156 = refs.override) == null ? void 0 : _a156.call(
1921
+ const overrideResult = (_a224 = refs.override) == null ? void 0 : _a224.call(
1837
1922
  refs,
1838
1923
  def,
1839
1924
  refs,
@@ -1899,11 +1984,11 @@ var getRefs = (options) => {
1899
1984
  currentPath,
1900
1985
  propertyPath: void 0,
1901
1986
  seen: new Map(
1902
- Object.entries(_options.definitions).map(([name146, def]) => [
1987
+ Object.entries(_options.definitions).map(([name224, def]) => [
1903
1988
  def._def,
1904
1989
  {
1905
1990
  def: def._def,
1906
- path: [..._options.basePath, _options.definitionPath, name146],
1991
+ path: [..._options.basePath, _options.definitionPath, name224],
1907
1992
  // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1908
1993
  jsonSchema: void 0
1909
1994
  }
@@ -1912,50 +1997,50 @@ var getRefs = (options) => {
1912
1997
  };
1913
1998
  };
1914
1999
  var zodToJsonSchema = (schema, options) => {
1915
- var _a156;
2000
+ var _a224;
1916
2001
  const refs = getRefs(options);
1917
2002
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1918
- (acc, [name224, schema2]) => {
1919
- var _a224;
2003
+ (acc, [name324, schema2]) => {
2004
+ var _a324;
1920
2005
  return {
1921
2006
  ...acc,
1922
- [name224]: (_a224 = parseDef(
2007
+ [name324]: (_a324 = parseDef(
1923
2008
  schema2._def,
1924
2009
  {
1925
2010
  ...refs,
1926
- currentPath: [...refs.basePath, refs.definitionPath, name224]
2011
+ currentPath: [...refs.basePath, refs.definitionPath, name324]
1927
2012
  },
1928
2013
  true
1929
- )) != null ? _a224 : parseAnyDef()
2014
+ )) != null ? _a324 : parseAnyDef()
1930
2015
  };
1931
2016
  },
1932
2017
  {}
1933
2018
  ) : void 0;
1934
- const name146 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1935
- const main = (_a156 = parseDef(
2019
+ const name224 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
2020
+ const main = (_a224 = parseDef(
1936
2021
  schema._def,
1937
- name146 === void 0 ? refs : {
2022
+ name224 === void 0 ? refs : {
1938
2023
  ...refs,
1939
- currentPath: [...refs.basePath, refs.definitionPath, name146]
2024
+ currentPath: [...refs.basePath, refs.definitionPath, name224]
1940
2025
  },
1941
2026
  false
1942
- )) != null ? _a156 : parseAnyDef();
2027
+ )) != null ? _a224 : parseAnyDef();
1943
2028
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1944
2029
  if (title !== void 0) {
1945
2030
  main.title = title;
1946
2031
  }
1947
- const combined = name146 === void 0 ? definitions ? {
2032
+ const combined = name224 === void 0 ? definitions ? {
1948
2033
  ...main,
1949
2034
  [refs.definitionPath]: definitions
1950
2035
  } : main : {
1951
2036
  $ref: [
1952
2037
  ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1953
2038
  refs.definitionPath,
1954
- name146
2039
+ name224
1955
2040
  ].join("/"),
1956
2041
  [refs.definitionPath]: {
1957
2042
  ...definitions,
1958
- [name146]: main
2043
+ [name224]: main
1959
2044
  }
1960
2045
  };
1961
2046
  combined.$schema = "http://json-schema.org/draft-07/schema#";
@@ -1963,8 +2048,8 @@ var zodToJsonSchema = (schema, options) => {
1963
2048
  };
1964
2049
  var zod_to_json_schema_default = zodToJsonSchema;
1965
2050
  function zod3Schema(zodSchema22, options) {
1966
- var _a156;
1967
- const useReferences = (_a156 = void 0 ) != null ? _a156 : false;
2051
+ var _a224;
2052
+ const useReferences = (_a224 = void 0 ) != null ? _a224 : false;
1968
2053
  return jsonSchema(
1969
2054
  // defer json schema creation to avoid unnecessary computation when only validation is needed
1970
2055
  () => zod_to_json_schema_default(zodSchema22, {
@@ -1979,15 +2064,17 @@ function zod3Schema(zodSchema22, options) {
1979
2064
  );
1980
2065
  }
1981
2066
  function zod4Schema(zodSchema22, options) {
1982
- var _a156;
1983
- const useReferences = (_a156 = void 0 ) != null ? _a156 : false;
2067
+ var _a224;
2068
+ const useReferences = (_a224 = void 0 ) != null ? _a224 : false;
1984
2069
  return jsonSchema(
1985
2070
  // defer json schema creation to avoid unnecessary computation when only validation is needed
1986
- () => z4.toJSONSchema(zodSchema22, {
1987
- target: "draft-7",
1988
- io: "output",
1989
- reused: useReferences ? "ref" : "inline"
1990
- }),
2071
+ () => addAdditionalPropertiesToJsonSchema(
2072
+ z4.toJSONSchema(zodSchema22, {
2073
+ target: "draft-7",
2074
+ io: "input",
2075
+ reused: useReferences ? "ref" : "inline"
2076
+ })
2077
+ ),
1991
2078
  {
1992
2079
  validate: async (value) => {
1993
2080
  const result = await z4.safeParseAsync(zodSchema22, value);
@@ -2006,24 +2093,6 @@ function zodSchema(zodSchema22, options) {
2006
2093
  return zod3Schema(zodSchema22);
2007
2094
  }
2008
2095
  }
2009
- var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
2010
- function jsonSchema(jsonSchema22, {
2011
- validate
2012
- } = {}) {
2013
- return {
2014
- [schemaSymbol]: true,
2015
- _type: void 0,
2016
- // should never be used directly
2017
- [validatorSymbol]: true,
2018
- get jsonSchema() {
2019
- if (typeof jsonSchema22 === "function") {
2020
- jsonSchema22 = jsonSchema22();
2021
- }
2022
- return jsonSchema22;
2023
- },
2024
- validate
2025
- };
2026
- }
2027
2096
  function isSchema(value) {
2028
2097
  return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2029
2098
  }
@@ -2036,146 +2105,29 @@ function asSchema(schema) {
2036
2105
  function withoutTrailingSlash(url) {
2037
2106
  return url == null ? void 0 : url.replace(/\/$/, "");
2038
2107
  }
2039
- var require_get_context = __commonJS({
2040
- "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-context.js"(exports$1, module) {
2041
- var __defProp22 = Object.defineProperty;
2042
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
2043
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
2044
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2045
- var __export22 = (target, all) => {
2046
- for (var name164 in all)
2047
- __defProp22(target, name164, { get: all[name164], enumerable: true });
2048
- };
2049
- var __copyProps2 = (to, from, except, desc) => {
2050
- if (from && typeof from === "object" || typeof from === "function") {
2051
- for (let key of __getOwnPropNames2(from))
2052
- if (!__hasOwnProp2.call(to, key) && key !== except)
2053
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
2054
- }
2055
- return to;
2056
- };
2057
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
2058
- var get_context_exports = {};
2059
- __export22(get_context_exports, {
2060
- SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
2061
- getContext: () => getContext3
2062
- });
2063
- module.exports = __toCommonJS(get_context_exports);
2064
- var SYMBOL_FOR_REQ_CONTEXT = /* @__PURE__ */ Symbol.for("@vercel/request-context");
2065
- function getContext3() {
2066
- const fromSymbol = globalThis;
2067
- return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
2068
- }
2069
- }
2070
- });
2071
- var require_get_vercel_oidc_token = __commonJS({
2072
- "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports$1, module) {
2073
- var __defProp22 = Object.defineProperty;
2074
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
2075
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
2076
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2077
- var __export22 = (target, all) => {
2078
- for (var name164 in all)
2079
- __defProp22(target, name164, { get: all[name164], enumerable: true });
2080
- };
2081
- var __copyProps2 = (to, from, except, desc) => {
2082
- if (from && typeof from === "object" || typeof from === "function") {
2083
- for (let key of __getOwnPropNames2(from))
2084
- if (!__hasOwnProp2.call(to, key) && key !== except)
2085
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
2086
- }
2087
- return to;
2088
- };
2089
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
2090
- var get_vercel_oidc_token_exports = {};
2091
- __export22(get_vercel_oidc_token_exports, {
2092
- getVercelOidcToken: () => getVercelOidcToken3,
2093
- getVercelOidcTokenSync: () => getVercelOidcTokenSync2
2094
- });
2095
- module.exports = __toCommonJS(get_vercel_oidc_token_exports);
2096
- var import_get_context = require_get_context();
2097
- var import_token_error = require_token_error();
2098
- async function getVercelOidcToken3() {
2099
- let token = "";
2100
- let err;
2101
- try {
2102
- token = getVercelOidcTokenSync2();
2103
- } catch (error) {
2104
- err = error;
2105
- }
2106
- try {
2107
- const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
2108
- await import('./token-util-NEHG7TUY-XQP3QSPX.js'),
2109
- await import('./token-6GSAFR2W-ABXTQD64.js')
2110
- ]);
2111
- if (!token || isExpired(getTokenPayload(token))) {
2112
- await refreshToken();
2113
- token = getVercelOidcTokenSync2();
2114
- }
2115
- } catch (error) {
2116
- if (err?.message && error instanceof Error) {
2117
- error.message = `${err.message}
2118
- ${error.message}`;
2119
- }
2120
- throw new import_token_error.VercelOidcTokenError(`Failed to refresh OIDC token`, error);
2121
- }
2122
- return token;
2123
- }
2124
- function getVercelOidcTokenSync2() {
2125
- const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
2126
- if (!token) {
2127
- throw new Error(
2128
- `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
2129
- );
2130
- }
2131
- return token;
2132
- }
2133
- }
2134
- });
2135
- var require_dist = __commonJS({
2136
- "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/index.js"(exports$1, module) {
2137
- var __defProp22 = Object.defineProperty;
2138
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
2139
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
2140
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2141
- var __export22 = (target, all) => {
2142
- for (var name164 in all)
2143
- __defProp22(target, name164, { get: all[name164], enumerable: true });
2144
- };
2145
- var __copyProps2 = (to, from, except, desc) => {
2146
- if (from && typeof from === "object" || typeof from === "function") {
2147
- for (let key of __getOwnPropNames2(from))
2148
- if (!__hasOwnProp2.call(to, key) && key !== except)
2149
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
2150
- }
2151
- return to;
2152
- };
2153
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
2154
- var src_exports = {};
2155
- __export22(src_exports, {
2156
- getContext: () => import_get_context.getContext,
2157
- getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
2158
- getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
2159
- });
2160
- module.exports = __toCommonJS(src_exports);
2161
- var import_get_vercel_oidc_token = require_get_vercel_oidc_token();
2162
- var import_get_context = require_get_context();
2108
+ function getContext() {
2109
+ return {
2110
+ headers: {}
2111
+ };
2112
+ }
2113
+ async function getVercelOidcToken() {
2114
+ if (process.env.VERCEL_OIDC_TOKEN) {
2115
+ return process.env.VERCEL_OIDC_TOKEN ?? "";
2163
2116
  }
2164
- });
2165
- var import_oidc = __toESM(require_dist(), 1);
2166
- var import_oidc2 = __toESM(require_dist(), 1);
2167
- var marker15 = "vercel.ai.gateway.error";
2168
- var symbol15 = Symbol.for(marker15);
2169
- var _a15;
2170
- var _b;
2171
- var GatewayError = class _GatewayError extends (_b = Error, _a15 = symbol15, _b) {
2117
+ throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
2118
+ }
2119
+ var marker16 = "vercel.ai.gateway.error";
2120
+ var symbol16 = Symbol.for(marker16);
2121
+ var _a16;
2122
+ var _b16;
2123
+ var GatewayError = class _GatewayError extends (_b16 = Error, _a16 = symbol16, _b16) {
2172
2124
  constructor({
2173
2125
  message,
2174
2126
  statusCode = 500,
2175
2127
  cause
2176
2128
  }) {
2177
2129
  super(message);
2178
- this[_a15] = true;
2130
+ this[_a16] = true;
2179
2131
  this.statusCode = statusCode;
2180
2132
  this.cause = cause;
2181
2133
  }
@@ -2188,15 +2140,15 @@ var GatewayError = class _GatewayError extends (_b = Error, _a15 = symbol15, _b)
2188
2140
  return _GatewayError.hasMarker(error);
2189
2141
  }
2190
2142
  static hasMarker(error) {
2191
- return typeof error === "object" && error !== null && symbol15 in error && error[symbol15] === true;
2143
+ return typeof error === "object" && error !== null && symbol16 in error && error[symbol16] === true;
2192
2144
  }
2193
2145
  };
2194
- var name14 = "GatewayAuthenticationError";
2195
- var marker22 = `vercel.ai.gateway.error.${name14}`;
2146
+ var name15 = "GatewayAuthenticationError";
2147
+ var marker22 = `vercel.ai.gateway.error.${name15}`;
2196
2148
  var symbol22 = Symbol.for(marker22);
2197
2149
  var _a22;
2198
- var _b2;
2199
- var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a22 = symbol22, _b2) {
2150
+ var _b22;
2151
+ var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b22 = GatewayError, _a22 = symbol22, _b22) {
2200
2152
  constructor({
2201
2153
  message = "Authentication failed",
2202
2154
  statusCode = 401,
@@ -2204,7 +2156,7 @@ var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2
2204
2156
  } = {}) {
2205
2157
  super({ message, statusCode, cause });
2206
2158
  this[_a22] = true;
2207
- this.name = name14;
2159
+ this.name = name15;
2208
2160
  this.type = "authentication_error";
2209
2161
  }
2210
2162
  static isInstance(error) {
@@ -2254,8 +2206,8 @@ var name22 = "GatewayInvalidRequestError";
2254
2206
  var marker32 = `vercel.ai.gateway.error.${name22}`;
2255
2207
  var symbol32 = Symbol.for(marker32);
2256
2208
  var _a32;
2257
- var _b3;
2258
- var GatewayInvalidRequestError = class extends (_b3 = GatewayError, _a32 = symbol32, _b3) {
2209
+ var _b32;
2210
+ var GatewayInvalidRequestError = class extends (_b32 = GatewayError, _a32 = symbol32, _b32) {
2259
2211
  constructor({
2260
2212
  message = "Invalid request",
2261
2213
  statusCode = 400,
@@ -2274,8 +2226,8 @@ var name32 = "GatewayRateLimitError";
2274
2226
  var marker42 = `vercel.ai.gateway.error.${name32}`;
2275
2227
  var symbol42 = Symbol.for(marker42);
2276
2228
  var _a42;
2277
- var _b4;
2278
- var GatewayRateLimitError = class extends (_b4 = GatewayError, _a42 = symbol42, _b4) {
2229
+ var _b42;
2230
+ var GatewayRateLimitError = class extends (_b42 = GatewayError, _a42 = symbol42, _b42) {
2279
2231
  constructor({
2280
2232
  message = "Rate limit exceeded",
2281
2233
  statusCode = 429,
@@ -2301,8 +2253,8 @@ var modelNotFoundParamSchema = lazyValidator(
2301
2253
  )
2302
2254
  );
2303
2255
  var _a52;
2304
- var _b5;
2305
- var GatewayModelNotFoundError = class extends (_b5 = GatewayError, _a52 = symbol52, _b5) {
2256
+ var _b52;
2257
+ var GatewayModelNotFoundError = class extends (_b52 = GatewayError, _a52 = symbol52, _b52) {
2306
2258
  constructor({
2307
2259
  message = "Model not found",
2308
2260
  statusCode = 404,
@@ -2323,8 +2275,8 @@ var name52 = "GatewayInternalServerError";
2323
2275
  var marker62 = `vercel.ai.gateway.error.${name52}`;
2324
2276
  var symbol62 = Symbol.for(marker62);
2325
2277
  var _a62;
2326
- var _b6;
2327
- var GatewayInternalServerError = class extends (_b6 = GatewayError, _a62 = symbol62, _b6) {
2278
+ var _b62;
2279
+ var GatewayInternalServerError = class extends (_b62 = GatewayError, _a62 = symbol62, _b62) {
2328
2280
  constructor({
2329
2281
  message = "Internal server error",
2330
2282
  statusCode = 500,
@@ -2343,8 +2295,8 @@ var name62 = "GatewayResponseError";
2343
2295
  var marker72 = `vercel.ai.gateway.error.${name62}`;
2344
2296
  var symbol72 = Symbol.for(marker72);
2345
2297
  var _a72;
2346
- var _b7;
2347
- var GatewayResponseError = class extends (_b7 = GatewayError, _a72 = symbol72, _b7) {
2298
+ var _b72;
2299
+ var GatewayResponseError = class extends (_b72 = GatewayError, _a72 = symbol72, _b72) {
2348
2300
  constructor({
2349
2301
  message = "Invalid response from Gateway",
2350
2302
  statusCode = 502,
@@ -2428,21 +2380,98 @@ var gatewayErrorResponseSchema = lazyValidator(
2428
2380
  })
2429
2381
  )
2430
2382
  );
2431
- function asGatewayError(error, authMethod) {
2432
- var _a832;
2383
+ function extractApiCallResponse(error) {
2384
+ if (error.data !== void 0) {
2385
+ return error.data;
2386
+ }
2387
+ if (error.responseBody != null) {
2388
+ try {
2389
+ return JSON.parse(error.responseBody);
2390
+ } catch (e) {
2391
+ return error.responseBody;
2392
+ }
2393
+ }
2394
+ return {};
2395
+ }
2396
+ var name72 = "GatewayTimeoutError";
2397
+ var marker82 = `vercel.ai.gateway.error.${name72}`;
2398
+ var symbol82 = Symbol.for(marker82);
2399
+ var _a82;
2400
+ var _b82;
2401
+ var GatewayTimeoutError = class _GatewayTimeoutError extends (_b82 = GatewayError, _a82 = symbol82, _b82) {
2402
+ constructor({
2403
+ message = "Request timed out",
2404
+ statusCode = 408,
2405
+ cause
2406
+ } = {}) {
2407
+ super({ message, statusCode, cause });
2408
+ this[_a82] = true;
2409
+ this.name = name72;
2410
+ this.type = "timeout_error";
2411
+ }
2412
+ static isInstance(error) {
2413
+ return GatewayError.hasMarker(error) && symbol82 in error;
2414
+ }
2415
+ /**
2416
+ * Creates a helpful timeout error message with troubleshooting guidance
2417
+ */
2418
+ static createTimeoutError({
2419
+ originalMessage,
2420
+ statusCode = 408,
2421
+ cause
2422
+ }) {
2423
+ const message = `Gateway request timed out: ${originalMessage}
2424
+
2425
+ 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`;
2426
+ return new _GatewayTimeoutError({
2427
+ message,
2428
+ statusCode,
2429
+ cause
2430
+ });
2431
+ }
2432
+ };
2433
+ function isTimeoutError(error) {
2434
+ if (!(error instanceof Error)) {
2435
+ return false;
2436
+ }
2437
+ const errorCode = error.code;
2438
+ if (typeof errorCode === "string") {
2439
+ const undiciTimeoutCodes = [
2440
+ "UND_ERR_HEADERS_TIMEOUT",
2441
+ "UND_ERR_BODY_TIMEOUT",
2442
+ "UND_ERR_CONNECT_TIMEOUT"
2443
+ ];
2444
+ return undiciTimeoutCodes.includes(errorCode);
2445
+ }
2446
+ return false;
2447
+ }
2448
+ async function asGatewayError(error, authMethod) {
2449
+ var _a932;
2433
2450
  if (GatewayError.isInstance(error)) {
2434
2451
  return error;
2435
2452
  }
2453
+ if (isTimeoutError(error)) {
2454
+ return GatewayTimeoutError.createTimeoutError({
2455
+ originalMessage: error instanceof Error ? error.message : "Unknown error",
2456
+ cause: error
2457
+ });
2458
+ }
2436
2459
  if (APICallError.isInstance(error)) {
2437
- return createGatewayErrorFromResponse({
2460
+ if (error.cause && isTimeoutError(error.cause)) {
2461
+ return GatewayTimeoutError.createTimeoutError({
2462
+ originalMessage: error.message,
2463
+ cause: error
2464
+ });
2465
+ }
2466
+ return await createGatewayErrorFromResponse({
2438
2467
  response: extractApiCallResponse(error),
2439
- statusCode: (_a832 = error.statusCode) != null ? _a832 : 500,
2468
+ statusCode: (_a932 = error.statusCode) != null ? _a932 : 500,
2440
2469
  defaultMessage: "Gateway request failed",
2441
2470
  cause: error,
2442
2471
  authMethod
2443
2472
  });
2444
2473
  }
2445
- return createGatewayErrorFromResponse({
2474
+ return await createGatewayErrorFromResponse({
2446
2475
  response: {},
2447
2476
  statusCode: 500,
2448
2477
  defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
@@ -2450,19 +2479,6 @@ function asGatewayError(error, authMethod) {
2450
2479
  authMethod
2451
2480
  });
2452
2481
  }
2453
- function extractApiCallResponse(error) {
2454
- if (error.data !== void 0) {
2455
- return error.data;
2456
- }
2457
- if (error.responseBody != null) {
2458
- try {
2459
- return JSON.parse(error.responseBody);
2460
- } catch (e) {
2461
- return error.responseBody;
2462
- }
2463
- }
2464
- return {};
2465
- }
2466
2482
  var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
2467
2483
  async function parseAuthMethod(headers) {
2468
2484
  const result = await safeValidateTypes({
@@ -2474,6 +2490,7 @@ async function parseAuthMethod(headers) {
2474
2490
  var gatewayAuthMethodSchema = lazyValidator(
2475
2491
  () => zodSchema(z.union([z.literal("api-key"), z.literal("oidc")]))
2476
2492
  );
2493
+ var KNOWN_MODEL_TYPES = ["embedding", "image", "language"];
2477
2494
  var GatewayFetchMetadata = class {
2478
2495
  constructor(config) {
2479
2496
  this.config = config;
@@ -2544,8 +2561,12 @@ var gatewayAvailableModelsResponseSchema = lazyValidator(
2544
2561
  provider: z.string(),
2545
2562
  modelId: z.string()
2546
2563
  }),
2547
- modelType: z.enum(["language", "embedding", "image"]).nullish()
2564
+ modelType: z.string().nullish()
2548
2565
  })
2566
+ ).transform(
2567
+ (models) => models.filter(
2568
+ (m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType)
2569
+ )
2549
2570
  )
2550
2571
  })
2551
2572
  )
@@ -2561,6 +2582,187 @@ var gatewayCreditsResponseSchema = lazyValidator(
2561
2582
  }))
2562
2583
  )
2563
2584
  );
2585
+ var GatewaySpendReport = class {
2586
+ constructor(config) {
2587
+ this.config = config;
2588
+ }
2589
+ async getSpendReport(params) {
2590
+ try {
2591
+ const baseUrl = new URL(this.config.baseURL);
2592
+ const searchParams = new URLSearchParams();
2593
+ searchParams.set("start_date", params.startDate);
2594
+ searchParams.set("end_date", params.endDate);
2595
+ if (params.groupBy) {
2596
+ searchParams.set("group_by", params.groupBy);
2597
+ }
2598
+ if (params.datePart) {
2599
+ searchParams.set("date_part", params.datePart);
2600
+ }
2601
+ if (params.userId) {
2602
+ searchParams.set("user_id", params.userId);
2603
+ }
2604
+ if (params.model) {
2605
+ searchParams.set("model", params.model);
2606
+ }
2607
+ if (params.provider) {
2608
+ searchParams.set("provider", params.provider);
2609
+ }
2610
+ if (params.credentialType) {
2611
+ searchParams.set("credential_type", params.credentialType);
2612
+ }
2613
+ if (params.tags && params.tags.length > 0) {
2614
+ searchParams.set("tags", params.tags.join(","));
2615
+ }
2616
+ const { value } = await getFromApi({
2617
+ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
2618
+ headers: await resolve(this.config.headers()),
2619
+ successfulResponseHandler: createJsonResponseHandler(
2620
+ gatewaySpendReportResponseSchema
2621
+ ),
2622
+ failedResponseHandler: createJsonErrorResponseHandler({
2623
+ errorSchema: z.any(),
2624
+ errorToMessage: (data) => data
2625
+ }),
2626
+ fetch: this.config.fetch
2627
+ });
2628
+ return value;
2629
+ } catch (error) {
2630
+ throw await asGatewayError(error);
2631
+ }
2632
+ }
2633
+ };
2634
+ var gatewaySpendReportResponseSchema = lazySchema(
2635
+ () => zodSchema(
2636
+ z.object({
2637
+ results: z.array(
2638
+ z.object({
2639
+ day: z.string().optional(),
2640
+ hour: z.string().optional(),
2641
+ user: z.string().optional(),
2642
+ model: z.string().optional(),
2643
+ tag: z.string().optional(),
2644
+ provider: z.string().optional(),
2645
+ credential_type: z.enum(["byok", "system"]).optional(),
2646
+ total_cost: z.number(),
2647
+ market_cost: z.number().optional(),
2648
+ input_tokens: z.number().optional(),
2649
+ output_tokens: z.number().optional(),
2650
+ cached_input_tokens: z.number().optional(),
2651
+ cache_creation_input_tokens: z.number().optional(),
2652
+ reasoning_tokens: z.number().optional(),
2653
+ request_count: z.number().optional()
2654
+ }).transform(
2655
+ ({
2656
+ credential_type,
2657
+ total_cost,
2658
+ market_cost,
2659
+ input_tokens,
2660
+ output_tokens,
2661
+ cached_input_tokens,
2662
+ cache_creation_input_tokens,
2663
+ reasoning_tokens,
2664
+ request_count,
2665
+ ...rest
2666
+ }) => ({
2667
+ ...rest,
2668
+ ...credential_type !== void 0 ? { credentialType: credential_type } : {},
2669
+ totalCost: total_cost,
2670
+ ...market_cost !== void 0 ? { marketCost: market_cost } : {},
2671
+ ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
2672
+ ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
2673
+ ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
2674
+ ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
2675
+ ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
2676
+ ...request_count !== void 0 ? { requestCount: request_count } : {}
2677
+ })
2678
+ )
2679
+ )
2680
+ })
2681
+ )
2682
+ );
2683
+ var GatewayGenerationInfoFetcher = class {
2684
+ constructor(config) {
2685
+ this.config = config;
2686
+ }
2687
+ async getGenerationInfo(params) {
2688
+ try {
2689
+ const baseUrl = new URL(this.config.baseURL);
2690
+ const { value } = await getFromApi({
2691
+ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
2692
+ headers: await resolve(this.config.headers()),
2693
+ successfulResponseHandler: createJsonResponseHandler(
2694
+ gatewayGenerationInfoResponseSchema
2695
+ ),
2696
+ failedResponseHandler: createJsonErrorResponseHandler({
2697
+ errorSchema: z.any(),
2698
+ errorToMessage: (data) => data
2699
+ }),
2700
+ fetch: this.config.fetch
2701
+ });
2702
+ return value;
2703
+ } catch (error) {
2704
+ throw await asGatewayError(error);
2705
+ }
2706
+ }
2707
+ };
2708
+ var gatewayGenerationInfoResponseSchema = lazySchema(
2709
+ () => zodSchema(
2710
+ z.object({
2711
+ data: z.object({
2712
+ id: z.string(),
2713
+ total_cost: z.number(),
2714
+ upstream_inference_cost: z.number(),
2715
+ usage: z.number(),
2716
+ created_at: z.string(),
2717
+ model: z.string(),
2718
+ is_byok: z.boolean(),
2719
+ provider_name: z.string(),
2720
+ streamed: z.boolean(),
2721
+ finish_reason: z.string(),
2722
+ latency: z.number(),
2723
+ generation_time: z.number(),
2724
+ native_tokens_prompt: z.number(),
2725
+ native_tokens_completion: z.number(),
2726
+ native_tokens_reasoning: z.number(),
2727
+ native_tokens_cached: z.number(),
2728
+ native_tokens_cache_creation: z.number(),
2729
+ billable_web_search_calls: z.number()
2730
+ }).transform(
2731
+ ({
2732
+ total_cost,
2733
+ upstream_inference_cost,
2734
+ created_at,
2735
+ is_byok,
2736
+ provider_name,
2737
+ finish_reason,
2738
+ generation_time,
2739
+ native_tokens_prompt,
2740
+ native_tokens_completion,
2741
+ native_tokens_reasoning,
2742
+ native_tokens_cached,
2743
+ native_tokens_cache_creation,
2744
+ billable_web_search_calls,
2745
+ ...rest
2746
+ }) => ({
2747
+ ...rest,
2748
+ totalCost: total_cost,
2749
+ upstreamInferenceCost: upstream_inference_cost,
2750
+ createdAt: created_at,
2751
+ isByok: is_byok,
2752
+ providerName: provider_name,
2753
+ finishReason: finish_reason,
2754
+ generationTime: generation_time,
2755
+ promptTokens: native_tokens_prompt,
2756
+ completionTokens: native_tokens_completion,
2757
+ reasoningTokens: native_tokens_reasoning,
2758
+ cachedTokens: native_tokens_cached,
2759
+ cacheCreationTokens: native_tokens_cache_creation,
2760
+ billableWebSearchCalls: billable_web_search_calls
2761
+ })
2762
+ )
2763
+ }).transform(({ data }) => data)
2764
+ )
2765
+ );
2564
2766
  var GatewayLanguageModel = class {
2565
2767
  constructor(modelId, config) {
2566
2768
  this.modelId = modelId;
@@ -2723,7 +2925,7 @@ var GatewayEmbeddingModel = class {
2723
2925
  abortSignal,
2724
2926
  providerOptions
2725
2927
  }) {
2726
- var _a832;
2928
+ var _a932;
2727
2929
  const resolvedHeaders = await resolve(this.config.headers());
2728
2930
  try {
2729
2931
  const {
@@ -2754,7 +2956,7 @@ var GatewayEmbeddingModel = class {
2754
2956
  });
2755
2957
  return {
2756
2958
  embeddings: responseBody.embeddings,
2757
- usage: (_a832 = responseBody.usage) != null ? _a832 : void 0,
2959
+ usage: (_a932 = responseBody.usage) != null ? _a932 : void 0,
2758
2960
  providerMetadata: responseBody.providerMetadata,
2759
2961
  response: { headers: responseHeaders, body: rawValue }
2760
2962
  };
@@ -2801,7 +3003,7 @@ var GatewayImageModel = class {
2801
3003
  headers,
2802
3004
  abortSignal
2803
3005
  }) {
2804
- var _a832;
3006
+ var _a932, _b93, _c, _d;
2805
3007
  const resolvedHeaders = await resolve(this.config.headers());
2806
3008
  try {
2807
3009
  const {
@@ -2836,16 +3038,23 @@ var GatewayImageModel = class {
2836
3038
  return {
2837
3039
  images: responseBody.images,
2838
3040
  // Always base64 strings from server
2839
- warnings: (_a832 = responseBody.warnings) != null ? _a832 : [],
3041
+ warnings: (_a932 = responseBody.warnings) != null ? _a932 : [],
2840
3042
  providerMetadata: responseBody.providerMetadata,
2841
3043
  response: {
2842
3044
  timestamp: /* @__PURE__ */ new Date(),
2843
3045
  modelId: this.modelId,
2844
3046
  headers: responseHeaders
3047
+ },
3048
+ ...responseBody.usage != null && {
3049
+ usage: {
3050
+ inputTokens: (_b93 = responseBody.usage.inputTokens) != null ? _b93 : void 0,
3051
+ outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,
3052
+ totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0
3053
+ }
2845
3054
  }
2846
3055
  };
2847
3056
  } catch (error) {
2848
- throw asGatewayError(error, await parseAuthMethod(resolvedHeaders));
3057
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
2849
3058
  }
2850
3059
  }
2851
3060
  getUrl() {
@@ -2861,6 +3070,11 @@ var GatewayImageModel = class {
2861
3070
  var providerMetadataEntrySchema = z.object({
2862
3071
  images: z.array(z.unknown()).optional()
2863
3072
  }).catchall(z.unknown());
3073
+ var gatewayImageUsageSchema = z.object({
3074
+ inputTokens: z.number().nullish(),
3075
+ outputTokens: z.number().nullish(),
3076
+ totalTokens: z.number().nullish()
3077
+ });
2864
3078
  var gatewayImageResponseSchema = z.object({
2865
3079
  images: z.array(z.string()),
2866
3080
  // Always base64 strings over the wire
@@ -2869,22 +3083,197 @@ var gatewayImageResponseSchema = z.object({
2869
3083
  type: z.literal("other"),
2870
3084
  message: z.string()
2871
3085
  })
2872
- ).optional(),
2873
- providerMetadata: z.record(z.string(), providerMetadataEntrySchema).optional()
3086
+ ).optional(),
3087
+ providerMetadata: z.record(z.string(), providerMetadataEntrySchema).optional(),
3088
+ usage: gatewayImageUsageSchema.optional()
3089
+ });
3090
+ var parallelSearchInputSchema = lazySchema(
3091
+ () => zodSchema(
3092
+ z$1.object({
3093
+ objective: z$1.string().describe(
3094
+ "Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."
3095
+ ),
3096
+ search_queries: z$1.array(z$1.string()).optional().describe(
3097
+ "Optional search queries to supplement the objective. Maximum 200 characters per query."
3098
+ ),
3099
+ mode: z$1.enum(["one-shot", "agentic"]).optional().describe(
3100
+ 'Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'
3101
+ ),
3102
+ max_results: z$1.number().optional().describe(
3103
+ "Maximum number of results to return (1-20). Defaults to 10 if not specified."
3104
+ ),
3105
+ source_policy: z$1.object({
3106
+ include_domains: z$1.array(z$1.string()).optional().describe("List of domains to include in search results."),
3107
+ exclude_domains: z$1.array(z$1.string()).optional().describe("List of domains to exclude from search results."),
3108
+ after_date: z$1.string().optional().describe(
3109
+ "Only include results published after this date (ISO 8601 format)."
3110
+ )
3111
+ }).optional().describe(
3112
+ "Source policy for controlling which domains to include/exclude and freshness."
3113
+ ),
3114
+ excerpts: z$1.object({
3115
+ max_chars_per_result: z$1.number().optional().describe("Maximum characters per result."),
3116
+ max_chars_total: z$1.number().optional().describe("Maximum total characters across all results.")
3117
+ }).optional().describe("Excerpt configuration for controlling result length."),
3118
+ fetch_policy: z$1.object({
3119
+ max_age_seconds: z$1.number().optional().describe(
3120
+ "Maximum age in seconds for cached content. Set to 0 to always fetch fresh content."
3121
+ )
3122
+ }).optional().describe("Fetch policy for controlling content freshness.")
3123
+ })
3124
+ )
3125
+ );
3126
+ var parallelSearchOutputSchema = lazySchema(
3127
+ () => zodSchema(
3128
+ z$1.union([
3129
+ // Success response
3130
+ z$1.object({
3131
+ searchId: z$1.string(),
3132
+ results: z$1.array(
3133
+ z$1.object({
3134
+ url: z$1.string(),
3135
+ title: z$1.string(),
3136
+ excerpt: z$1.string(),
3137
+ publishDate: z$1.string().nullable().optional(),
3138
+ relevanceScore: z$1.number().optional()
3139
+ })
3140
+ )
3141
+ }),
3142
+ // Error response
3143
+ z$1.object({
3144
+ error: z$1.enum([
3145
+ "api_error",
3146
+ "rate_limit",
3147
+ "timeout",
3148
+ "invalid_input",
3149
+ "configuration_error",
3150
+ "unknown"
3151
+ ]),
3152
+ statusCode: z$1.number().optional(),
3153
+ message: z$1.string()
3154
+ })
3155
+ ])
3156
+ )
3157
+ );
3158
+ var parallelSearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
3159
+ id: "gateway.parallel_search",
3160
+ name: "parallel_search",
3161
+ inputSchema: parallelSearchInputSchema,
3162
+ outputSchema: parallelSearchOutputSchema
3163
+ });
3164
+ var parallelSearch = (config = {}) => parallelSearchToolFactory(config);
3165
+ var perplexitySearchInputSchema = lazySchema(
3166
+ () => zodSchema(
3167
+ z$1.object({
3168
+ query: z$1.union([z$1.string(), z$1.array(z$1.string())]).describe(
3169
+ "Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."
3170
+ ),
3171
+ max_results: z$1.number().optional().describe(
3172
+ "Maximum number of search results to return (1-20, default: 10)"
3173
+ ),
3174
+ max_tokens_per_page: z$1.number().optional().describe(
3175
+ "Maximum number of tokens to extract per search result page (256-2048, default: 2048)"
3176
+ ),
3177
+ max_tokens: z$1.number().optional().describe(
3178
+ "Maximum total tokens across all search results (default: 25000, max: 1000000)"
3179
+ ),
3180
+ country: z$1.string().optional().describe(
3181
+ "Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"
3182
+ ),
3183
+ search_domain_filter: z$1.array(z$1.string()).optional().describe(
3184
+ "List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"
3185
+ ),
3186
+ search_language_filter: z$1.array(z$1.string()).optional().describe(
3187
+ "List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"
3188
+ ),
3189
+ search_after_date: z$1.string().optional().describe(
3190
+ "Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."
3191
+ ),
3192
+ search_before_date: z$1.string().optional().describe(
3193
+ "Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."
3194
+ ),
3195
+ last_updated_after_filter: z$1.string().optional().describe(
3196
+ "Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."
3197
+ ),
3198
+ last_updated_before_filter: z$1.string().optional().describe(
3199
+ "Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."
3200
+ ),
3201
+ search_recency_filter: z$1.enum(["day", "week", "month", "year"]).optional().describe(
3202
+ "Filter results by relative time period. Cannot be used with search_after_date or search_before_date."
3203
+ )
3204
+ })
3205
+ )
3206
+ );
3207
+ var perplexitySearchOutputSchema = lazySchema(
3208
+ () => zodSchema(
3209
+ z$1.union([
3210
+ // Success response
3211
+ z$1.object({
3212
+ results: z$1.array(
3213
+ z$1.object({
3214
+ title: z$1.string(),
3215
+ url: z$1.string(),
3216
+ snippet: z$1.string(),
3217
+ date: z$1.string().optional(),
3218
+ lastUpdated: z$1.string().optional()
3219
+ })
3220
+ ),
3221
+ id: z$1.string()
3222
+ }),
3223
+ // Error response
3224
+ z$1.object({
3225
+ error: z$1.enum([
3226
+ "api_error",
3227
+ "rate_limit",
3228
+ "timeout",
3229
+ "invalid_input",
3230
+ "unknown"
3231
+ ]),
3232
+ statusCode: z$1.number().optional(),
3233
+ message: z$1.string()
3234
+ })
3235
+ ])
3236
+ )
3237
+ );
3238
+ var perplexitySearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
3239
+ id: "gateway.perplexity_search",
3240
+ name: "perplexity_search",
3241
+ inputSchema: perplexitySearchInputSchema,
3242
+ outputSchema: perplexitySearchOutputSchema
2874
3243
  });
3244
+ var perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);
3245
+ var gatewayTools = {
3246
+ /**
3247
+ * Search the web using Parallel AI's Search API for LLM-optimized excerpts.
3248
+ *
3249
+ * Takes a natural language objective and returns relevant excerpts,
3250
+ * replacing multiple keyword searches with a single call for broad
3251
+ * or complex queries. Supports different search types for depth vs
3252
+ * breadth tradeoffs.
3253
+ */
3254
+ parallelSearch,
3255
+ /**
3256
+ * Search the web using Perplexity's Search API for real-time information,
3257
+ * news, research papers, and articles.
3258
+ *
3259
+ * Provides ranked search results with advanced filtering options including
3260
+ * domain, language, date range, and recency filters.
3261
+ */
3262
+ perplexitySearch
3263
+ };
2875
3264
  async function getVercelRequestId() {
2876
- var _a832;
2877
- return (_a832 = (0, import_oidc.getContext)().headers) == null ? void 0 : _a832["x-vercel-id"];
3265
+ var _a932;
3266
+ return (_a932 = getContext().headers) == null ? void 0 : _a932["x-vercel-id"];
2878
3267
  }
2879
- var VERSION2 = "2.0.15";
3268
+ var VERSION2 = "2.0.88";
2880
3269
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
2881
3270
  function createGatewayProvider(options = {}) {
2882
- var _a832, _b84;
3271
+ var _a932, _b93;
2883
3272
  let pendingMetadata = null;
2884
3273
  let metadataCache = null;
2885
- const cacheRefreshMillis = (_a832 = options.metadataCacheRefreshMillis) != null ? _a832 : 1e3 * 60 * 5;
3274
+ const cacheRefreshMillis = (_a932 = options.metadataCacheRefreshMillis) != null ? _a932 : 1e3 * 60 * 5;
2886
3275
  let lastFetchTime = 0;
2887
- const baseURL = (_b84 = withoutTrailingSlash(options.baseURL)) != null ? _b84 : "https://ai-gateway.vercel.sh/v1/ai";
3276
+ const baseURL = (_b93 = withoutTrailingSlash(options.baseURL)) != null ? _b93 : "https://ai-gateway.vercel.sh/v1/ai";
2888
3277
  const getHeaders = async () => {
2889
3278
  const auth = await getGatewayAuthToken(options);
2890
3279
  if (auth) {
@@ -2917,13 +3306,18 @@ function createGatewayProvider(options = {}) {
2917
3306
  settingValue: void 0,
2918
3307
  environmentVariableName: "VERCEL_REGION"
2919
3308
  });
3309
+ const projectId = loadOptionalSetting({
3310
+ settingValue: void 0,
3311
+ environmentVariableName: "VERCEL_PROJECT_ID"
3312
+ });
2920
3313
  return async () => {
2921
3314
  const requestId = await getVercelRequestId();
2922
3315
  return {
2923
3316
  ...deploymentId && { "ai-o11y-deployment-id": deploymentId },
2924
3317
  ...environment && { "ai-o11y-environment": environment },
2925
3318
  ...region && { "ai-o11y-region": region },
2926
- ...requestId && { "ai-o11y-request-id": requestId }
3319
+ ...requestId && { "ai-o11y-request-id": requestId },
3320
+ ...projectId && { "ai-o11y-project-id": projectId }
2927
3321
  };
2928
3322
  };
2929
3323
  };
@@ -2937,8 +3331,8 @@ function createGatewayProvider(options = {}) {
2937
3331
  });
2938
3332
  };
2939
3333
  const getAvailableModels = async () => {
2940
- var _a923, _b92, _c;
2941
- const now2 = (_c = (_b92 = (_a923 = options._internal) == null ? void 0 : _a923.currentDate) == null ? void 0 : _b92.call(_a923).getTime()) != null ? _c : Date.now();
3334
+ var _a1022, _b103, _c;
3335
+ const now2 = (_c = (_b103 = (_a1022 = options._internal) == null ? void 0 : _a1022.currentDate) == null ? void 0 : _b103.call(_a1022).getTime()) != null ? _c : Date.now();
2942
3336
  if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) {
2943
3337
  lastFetchTime = now2;
2944
3338
  pendingMetadata = new GatewayFetchMetadata({
@@ -2969,6 +3363,30 @@ function createGatewayProvider(options = {}) {
2969
3363
  );
2970
3364
  });
2971
3365
  };
3366
+ const getSpendReport = async (params) => {
3367
+ return new GatewaySpendReport({
3368
+ baseURL,
3369
+ headers: getHeaders,
3370
+ fetch: options.fetch
3371
+ }).getSpendReport(params).catch(async (error) => {
3372
+ throw await asGatewayError(
3373
+ error,
3374
+ await parseAuthMethod(await getHeaders())
3375
+ );
3376
+ });
3377
+ };
3378
+ const getGenerationInfo = async (params) => {
3379
+ return new GatewayGenerationInfoFetcher({
3380
+ baseURL,
3381
+ headers: getHeaders,
3382
+ fetch: options.fetch
3383
+ }).getGenerationInfo(params).catch(async (error) => {
3384
+ throw await asGatewayError(
3385
+ error,
3386
+ await parseAuthMethod(await getHeaders())
3387
+ );
3388
+ });
3389
+ };
2972
3390
  const provider = function(modelId) {
2973
3391
  if (new.target) {
2974
3392
  throw new Error(
@@ -2979,6 +3397,8 @@ function createGatewayProvider(options = {}) {
2979
3397
  };
2980
3398
  provider.getAvailableModels = getAvailableModels;
2981
3399
  provider.getCredits = getCredits;
3400
+ provider.getSpendReport = getSpendReport;
3401
+ provider.getGenerationInfo = getGenerationInfo;
2982
3402
  provider.imageModel = (modelId) => {
2983
3403
  return new GatewayImageModel(modelId, {
2984
3404
  provider: "gateway",
@@ -2998,6 +3418,7 @@ function createGatewayProvider(options = {}) {
2998
3418
  o11yHeaders: createO11yHeaders()
2999
3419
  });
3000
3420
  };
3421
+ provider.tools = gatewayTools;
3001
3422
  return provider;
3002
3423
  }
3003
3424
  createGatewayProvider();
@@ -3013,7 +3434,7 @@ async function getGatewayAuthToken(options) {
3013
3434
  };
3014
3435
  }
3015
3436
  try {
3016
- const oidcToken = await (0, import_oidc2.getVercelOidcToken)();
3437
+ const oidcToken = await getVercelOidcToken();
3017
3438
  return {
3018
3439
  token: oidcToken,
3019
3440
  authMethod: "oidc"
@@ -3115,12 +3536,12 @@ function registerGlobal(type, instance, diag, allowOverride) {
3115
3536
  return true;
3116
3537
  }
3117
3538
  function getGlobal(type) {
3118
- var _a164, _b84;
3539
+ var _a164, _b93;
3119
3540
  var globalVersion = (_a164 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a164 === void 0 ? void 0 : _a164.version;
3120
3541
  if (!globalVersion || !isCompatible(globalVersion)) {
3121
3542
  return;
3122
3543
  }
3123
- return (_b84 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b84 === void 0 ? void 0 : _b84[type];
3544
+ return (_b93 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b93 === void 0 ? void 0 : _b93[type];
3124
3545
  }
3125
3546
  function unregisterGlobal(type, diag) {
3126
3547
  diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION22 + ".");
@@ -3285,7 +3706,7 @@ var DiagAPI = (
3285
3706
  }
3286
3707
  var self = this;
3287
3708
  var setLogger = function(logger, optionsOrLogLevel) {
3288
- var _a164, _b84, _c;
3709
+ var _a164, _b93, _c;
3289
3710
  if (optionsOrLogLevel === void 0) {
3290
3711
  optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
3291
3712
  }
@@ -3300,7 +3721,7 @@ var DiagAPI = (
3300
3721
  };
3301
3722
  }
3302
3723
  var oldLogger = getGlobal("diag");
3303
- var newLogger = createLogLevelDiagLogger((_b84 = optionsOrLogLevel.logLevel) !== null && _b84 !== void 0 ? _b84 : DiagLogLevel.INFO, logger);
3724
+ var newLogger = createLogLevelDiagLogger((_b93 = optionsOrLogLevel.logLevel) !== null && _b93 !== void 0 ? _b93 : DiagLogLevel.INFO, logger);
3304
3725
  if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
3305
3726
  var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
3306
3727
  oldLogger.warn("Current logger will be overwritten from " + stack);
@@ -3764,8 +4185,8 @@ var dataContentSchema = z.union([
3764
4185
  z.custom(
3765
4186
  // Buffer might not be available in some environments such as CloudFlare:
3766
4187
  (value) => {
3767
- var _a164, _b84;
3768
- return (_b84 = (_a164 = globalThis.Buffer) == null ? void 0 : _a164.isBuffer(value)) != null ? _b84 : false;
4188
+ var _a164, _b93;
4189
+ return (_b93 = (_a164 = globalThis.Buffer) == null ? void 0 : _a164.isBuffer(value)) != null ? _b93 : false;
3769
4190
  },
3770
4191
  { message: "Must be a Buffer" }
3771
4192
  )
@@ -4375,7 +4796,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4375
4796
  var __getOwnPropNames = Object.getOwnPropertyNames;
4376
4797
  var __getProtoOf = Object.getPrototypeOf;
4377
4798
  var __hasOwnProp = Object.prototype.hasOwnProperty;
4378
- var __commonJS3 = (cb, mod) => function __require2() {
4799
+ var __commonJS = (cb, mod) => function __require2() {
4379
4800
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
4380
4801
  };
4381
4802
  var __copyProps = (to, from, except, desc) => {
@@ -4386,7 +4807,7 @@ var __copyProps = (to, from, except, desc) => {
4386
4807
  }
4387
4808
  return to;
4388
4809
  };
4389
- var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
4810
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
4390
4811
  // If the importer is in node compatibility mode or this is not an ESM
4391
4812
  // file that has been converted to a CommonJS file using a Babel-
4392
4813
  // compatible transform (i.e. "__esModule" has not been set), then set
@@ -4394,8 +4815,8 @@ var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create(__g
4394
4815
  __defProp2(target, "default", { value: mod, enumerable: true }),
4395
4816
  mod
4396
4817
  ));
4397
- var require_secure_json_parse = __commonJS3({
4398
- "../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports$1, module) {
4818
+ var require_secure_json_parse = __commonJS({
4819
+ "../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports, module) {
4399
4820
  var hasBuffer = typeof Buffer !== "undefined";
4400
4821
  var suspectProtoRx3 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
4401
4822
  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*:/;
@@ -4495,10 +4916,10 @@ var require_secure_json_parse = __commonJS3({
4495
4916
  module.exports.scan = filter3;
4496
4917
  }
4497
4918
  });
4498
- var marker16 = "vercel.ai.error";
4499
- var symbol16 = Symbol.for(marker16);
4500
- var _a16;
4501
- var _AISDKError3 = class _AISDKError22 extends Error {
4919
+ var marker17 = "vercel.ai.error";
4920
+ var symbol17 = Symbol.for(marker17);
4921
+ var _a17;
4922
+ var _AISDKError2 = class _AISDKError22 extends Error {
4502
4923
  /**
4503
4924
  * Creates an AI SDK Error.
4504
4925
  *
@@ -4513,7 +4934,7 @@ var _AISDKError3 = class _AISDKError22 extends Error {
4513
4934
  cause
4514
4935
  }) {
4515
4936
  super(message);
4516
- this[_a16] = true;
4937
+ this[_a17] = true;
4517
4938
  this.name = name146;
4518
4939
  this.cause = cause;
4519
4940
  }
@@ -4523,15 +4944,15 @@ var _AISDKError3 = class _AISDKError22 extends Error {
4523
4944
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
4524
4945
  */
4525
4946
  static isInstance(error) {
4526
- return _AISDKError22.hasMarker(error, marker16);
4947
+ return _AISDKError22.hasMarker(error, marker17);
4527
4948
  }
4528
4949
  static hasMarker(error, marker156) {
4529
4950
  const markerSymbol = Symbol.for(marker156);
4530
4951
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
4531
4952
  }
4532
4953
  };
4533
- _a16 = symbol16;
4534
- var AISDKError2 = _AISDKError3;
4954
+ _a17 = symbol17;
4955
+ var AISDKError2 = _AISDKError2;
4535
4956
  function getErrorMessage3(error) {
4536
4957
  if (error == null) {
4537
4958
  return "unknown error";
@@ -4608,7 +5029,7 @@ var name123 = "AI_TypeValidationError";
4608
5029
  var marker133 = `vercel.ai.error.${name123}`;
4609
5030
  var symbol133 = Symbol.for(marker133);
4610
5031
  var _a133;
4611
- var _TypeValidationError3 = class _TypeValidationError22 extends AISDKError2 {
5032
+ var _TypeValidationError2 = class _TypeValidationError22 extends AISDKError2 {
4612
5033
  constructor({ value, cause }) {
4613
5034
  super({
4614
5035
  name: name123,
@@ -4640,7 +5061,7 @@ Error message: ${getErrorMessage3(cause)}`,
4640
5061
  }
4641
5062
  };
4642
5063
  _a133 = symbol133;
4643
- var TypeValidationError2 = _TypeValidationError3;
5064
+ var TypeValidationError2 = _TypeValidationError2;
4644
5065
  var customAlphabet = (alphabet, defaultSize = 21) => {
4645
5066
  return (size = defaultSize) => {
4646
5067
  let id = "";
@@ -4651,7 +5072,7 @@ var customAlphabet = (alphabet, defaultSize = 21) => {
4651
5072
  return id;
4652
5073
  };
4653
5074
  };
4654
- var import_secure_json_parse = __toESM3(require_secure_json_parse());
5075
+ var import_secure_json_parse = __toESM(require_secure_json_parse());
4655
5076
  function convertAsyncIteratorToReadableStream(iterator) {
4656
5077
  return new ReadableStream({
4657
5078
  /**
@@ -5007,7 +5428,7 @@ function parseIntersectionDef2(def, refs) {
5007
5428
  ...refs,
5008
5429
  currentPath: [...refs.currentPath, "allOf", "1"]
5009
5430
  })
5010
- ].filter((x) => !!x);
5431
+ ].filter((x2) => !!x2);
5011
5432
  let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
5012
5433
  const mergedAllOf = [];
5013
5434
  allOf.forEach((schema) => {
@@ -5236,7 +5657,7 @@ function escapeNonAlphaNumeric2(source) {
5236
5657
  return result;
5237
5658
  }
5238
5659
  function addFormat2(schema, value, message, refs) {
5239
- if (schema.format || schema.anyOf?.some((x) => x.format)) {
5660
+ if (schema.format || schema.anyOf?.some((x2) => x2.format)) {
5240
5661
  if (!schema.anyOf) {
5241
5662
  schema.anyOf = [];
5242
5663
  }
@@ -5264,7 +5685,7 @@ function addFormat2(schema, value, message, refs) {
5264
5685
  }
5265
5686
  }
5266
5687
  function addPattern2(schema, regex, message, refs) {
5267
- if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
5688
+ if (schema.pattern || schema.allOf?.some((x2) => x2.pattern)) {
5268
5689
  if (!schema.allOf) {
5269
5690
  schema.allOf = [];
5270
5691
  }
@@ -5472,17 +5893,17 @@ function parseUnionDef2(def, refs) {
5472
5893
  if (refs.target === "openApi3")
5473
5894
  return asAnyOf2(def, refs);
5474
5895
  const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
5475
- if (options.every((x) => x._def.typeName in primitiveMappings2 && (!x._def.checks || !x._def.checks.length))) {
5476
- const types = options.reduce((types2, x) => {
5477
- const type = primitiveMappings2[x._def.typeName];
5896
+ if (options.every((x2) => x2._def.typeName in primitiveMappings2 && (!x2._def.checks || !x2._def.checks.length))) {
5897
+ const types = options.reduce((types2, x2) => {
5898
+ const type = primitiveMappings2[x2._def.typeName];
5478
5899
  return type && !types2.includes(type) ? [...types2, type] : types2;
5479
5900
  }, []);
5480
5901
  return {
5481
5902
  type: types.length > 1 ? types : types[0]
5482
5903
  };
5483
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
5484
- const types = options.reduce((acc, x) => {
5485
- const type = typeof x._def.value;
5904
+ } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
5905
+ const types = options.reduce((acc, x2) => {
5906
+ const type = typeof x2._def.value;
5486
5907
  switch (type) {
5487
5908
  case "string":
5488
5909
  case "number":
@@ -5491,7 +5912,7 @@ function parseUnionDef2(def, refs) {
5491
5912
  case "bigint":
5492
5913
  return [...acc, "integer"];
5493
5914
  case "object":
5494
- if (x._def.value === null)
5915
+ if (x2._def.value === null)
5495
5916
  return [...acc, "null"];
5496
5917
  case "symbol":
5497
5918
  case "undefined":
@@ -5501,30 +5922,30 @@ function parseUnionDef2(def, refs) {
5501
5922
  }
5502
5923
  }, []);
5503
5924
  if (types.length === options.length) {
5504
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
5925
+ const uniqueTypes = types.filter((x2, i, a) => a.indexOf(x2) === i);
5505
5926
  return {
5506
5927
  type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
5507
- enum: options.reduce((acc, x) => {
5508
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
5928
+ enum: options.reduce((acc, x2) => {
5929
+ return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
5509
5930
  }, [])
5510
5931
  };
5511
5932
  }
5512
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
5933
+ } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
5513
5934
  return {
5514
5935
  type: "string",
5515
- enum: options.reduce((acc, x) => [
5936
+ enum: options.reduce((acc, x2) => [
5516
5937
  ...acc,
5517
- ...x._def.values.filter((x2) => !acc.includes(x2))
5938
+ ...x2._def.values.filter((x22) => !acc.includes(x22))
5518
5939
  ], [])
5519
5940
  };
5520
5941
  }
5521
5942
  return asAnyOf2(def, refs);
5522
5943
  }
5523
5944
  var asAnyOf2 = (def, refs) => {
5524
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef2(x._def, {
5945
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i) => parseDef2(x2._def, {
5525
5946
  ...refs,
5526
5947
  currentPath: [...refs.currentPath, "anyOf", `${i}`]
5527
- })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
5948
+ })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0));
5528
5949
  return anyOf.length ? { anyOf } : void 0;
5529
5950
  };
5530
5951
  function parseNullableDef2(def, refs) {
@@ -5704,7 +6125,7 @@ var parsePipelineDef2 = (def, refs) => {
5704
6125
  currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
5705
6126
  });
5706
6127
  return {
5707
- allOf: [a, b].filter((x) => x !== void 0)
6128
+ allOf: [a, b].filter((x2) => x2 !== void 0)
5708
6129
  };
5709
6130
  };
5710
6131
  function parsePromiseDef2(def, refs) {
@@ -5733,10 +6154,10 @@ function parseTupleDef2(def, refs) {
5733
6154
  return {
5734
6155
  type: "array",
5735
6156
  minItems: def.items.length,
5736
- items: def.items.map((x, i) => parseDef2(x._def, {
6157
+ items: def.items.map((x2, i) => parseDef2(x2._def, {
5737
6158
  ...refs,
5738
6159
  currentPath: [...refs.currentPath, "items", `${i}`]
5739
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
6160
+ })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []),
5740
6161
  additionalItems: parseDef2(def.rest._def, {
5741
6162
  ...refs,
5742
6163
  currentPath: [...refs.currentPath, "additionalItems"]
@@ -5747,10 +6168,10 @@ function parseTupleDef2(def, refs) {
5747
6168
  type: "array",
5748
6169
  minItems: def.items.length,
5749
6170
  maxItems: def.items.length,
5750
- items: def.items.map((x, i) => parseDef2(x._def, {
6171
+ items: def.items.map((x2, i) => parseDef2(x2._def, {
5751
6172
  ...refs,
5752
6173
  currentPath: [...refs.currentPath, "items", `${i}`]
5753
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
6174
+ })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], [])
5754
6175
  };
5755
6176
  }
5756
6177
  }
@@ -6584,7 +7005,7 @@ function asSchema2(schema) {
6584
7005
  return isSchema2(schema) ? schema : zodSchema2(schema);
6585
7006
  }
6586
7007
  var _globalThis2 = typeof globalThis === "object" ? globalThis : global;
6587
- var VERSION3 = "1.9.0";
7008
+ var VERSION4 = "1.9.0";
6588
7009
  var re2 = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
6589
7010
  function _makeCompatibilityCheck2(ownVersion) {
6590
7011
  var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
@@ -6649,8 +7070,8 @@ function _makeCompatibilityCheck2(ownVersion) {
6649
7070
  return _reject(globalVersion);
6650
7071
  };
6651
7072
  }
6652
- var isCompatible2 = _makeCompatibilityCheck2(VERSION3);
6653
- var major2 = VERSION3.split(".")[0];
7073
+ var isCompatible2 = _makeCompatibilityCheck2(VERSION4);
7074
+ var major2 = VERSION4.split(".")[0];
6654
7075
  var GLOBAL_OPENTELEMETRY_API_KEY2 = /* @__PURE__ */ Symbol.for("opentelemetry.js.api." + major2);
6655
7076
  var _global2 = _globalThis2;
6656
7077
  function registerGlobal2(type, instance, diag, allowOverride) {
@@ -6659,32 +7080,32 @@ function registerGlobal2(type, instance, diag, allowOverride) {
6659
7080
  allowOverride = false;
6660
7081
  }
6661
7082
  var api = _global2[GLOBAL_OPENTELEMETRY_API_KEY2] = (_a173 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) !== null && _a173 !== void 0 ? _a173 : {
6662
- version: VERSION3
7083
+ version: VERSION4
6663
7084
  };
6664
7085
  if (!allowOverride && api[type]) {
6665
7086
  var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
6666
7087
  diag.error(err.stack || err.message);
6667
7088
  return false;
6668
7089
  }
6669
- if (api.version !== VERSION3) {
6670
- var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION3);
7090
+ if (api.version !== VERSION4) {
7091
+ var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION4);
6671
7092
  diag.error(err.stack || err.message);
6672
7093
  return false;
6673
7094
  }
6674
7095
  api[type] = instance;
6675
- diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION3 + ".");
7096
+ diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION4 + ".");
6676
7097
  return true;
6677
7098
  }
6678
7099
  function getGlobal2(type) {
6679
- var _a173, _b17;
7100
+ var _a173, _b19;
6680
7101
  var globalVersion = (_a173 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) === null || _a173 === void 0 ? void 0 : _a173.version;
6681
7102
  if (!globalVersion || !isCompatible2(globalVersion)) {
6682
7103
  return;
6683
7104
  }
6684
- return (_b17 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) === null || _b17 === void 0 ? void 0 : _b17[type];
7105
+ return (_b19 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) === null || _b19 === void 0 ? void 0 : _b19[type];
6685
7106
  }
6686
7107
  function unregisterGlobal2(type, diag) {
6687
- diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION3 + ".");
7108
+ diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION4 + ".");
6688
7109
  var api = _global2[GLOBAL_OPENTELEMETRY_API_KEY2];
6689
7110
  if (api) {
6690
7111
  delete api[type];
@@ -6846,7 +7267,7 @@ var DiagAPI2 = (
6846
7267
  }
6847
7268
  var self = this;
6848
7269
  var setLogger = function(logger, optionsOrLogLevel) {
6849
- var _a173, _b17, _c;
7270
+ var _a173, _b19, _c;
6850
7271
  if (optionsOrLogLevel === void 0) {
6851
7272
  optionsOrLogLevel = { logLevel: DiagLogLevel2.INFO };
6852
7273
  }
@@ -6861,7 +7282,7 @@ var DiagAPI2 = (
6861
7282
  };
6862
7283
  }
6863
7284
  var oldLogger = getGlobal2("diag");
6864
- var newLogger = createLogLevelDiagLogger2((_b17 = optionsOrLogLevel.logLevel) !== null && _b17 !== void 0 ? _b17 : DiagLogLevel2.INFO, logger);
7285
+ var newLogger = createLogLevelDiagLogger2((_b19 = optionsOrLogLevel.logLevel) !== null && _b19 !== void 0 ? _b19 : DiagLogLevel2.INFO, logger);
6865
7286
  if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
6866
7287
  var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
6867
7288
  oldLogger.warn("Current logger will be overwritten from " + stack);
@@ -7338,8 +7759,8 @@ var dataContentSchema2 = z$1.union([
7338
7759
  z$1.custom(
7339
7760
  // Buffer might not be available in some environments such as CloudFlare:
7340
7761
  (value) => {
7341
- var _a173, _b17;
7342
- return (_b17 = (_a173 = globalThis.Buffer) == null ? void 0 : _a173.isBuffer(value)) != null ? _b17 : false;
7762
+ var _a173, _b19;
7763
+ return (_b19 = (_a173 = globalThis.Buffer) == null ? void 0 : _a173.isBuffer(value)) != null ? _b19 : false;
7343
7764
  },
7344
7765
  { message: "Must be a Buffer" }
7345
7766
  )
@@ -7984,11 +8405,11 @@ function trimStartOfStream() {
7984
8405
  return text22;
7985
8406
  };
7986
8407
  }
7987
- var marker18 = "vercel.ai.error";
7988
- var symbol18 = Symbol.for(marker18);
7989
- var _a18;
7990
- var _b8;
7991
- var AISDKError3 = class _AISDKError4 extends (_b8 = Error, _a18 = symbol18, _b8) {
8408
+ var marker19 = "vercel.ai.error";
8409
+ var symbol19 = Symbol.for(marker19);
8410
+ var _a19;
8411
+ var _b17;
8412
+ var AISDKError3 = class _AISDKError3 extends (_b17 = Error, _a19 = symbol19, _b17) {
7992
8413
  /**
7993
8414
  * Creates an AI SDK Error.
7994
8415
  *
@@ -8003,7 +8424,7 @@ var AISDKError3 = class _AISDKError4 extends (_b8 = Error, _a18 = symbol18, _b8)
8003
8424
  cause
8004
8425
  }) {
8005
8426
  super(message);
8006
- this[_a18] = true;
8427
+ this[_a19] = true;
8007
8428
  this.name = name1422;
8008
8429
  this.cause = cause;
8009
8430
  }
@@ -8013,7 +8434,7 @@ var AISDKError3 = class _AISDKError4 extends (_b8 = Error, _a18 = symbol18, _b8)
8013
8434
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
8014
8435
  */
8015
8436
  static isInstance(error) {
8016
- return _AISDKError4.hasMarker(error, marker18);
8437
+ return _AISDKError3.hasMarker(error, marker19);
8017
8438
  }
8018
8439
  static hasMarker(error, marker1522) {
8019
8440
  const markerSymbol = Symbol.for(marker1522);
@@ -8024,8 +8445,8 @@ var name18 = "AI_APICallError";
8024
8445
  var marker25 = `vercel.ai.error.${name18}`;
8025
8446
  var symbol25 = Symbol.for(marker25);
8026
8447
  var _a25;
8027
- var _b22;
8028
- var APICallError3 = class extends (_b22 = AISDKError3, _a25 = symbol25, _b22) {
8448
+ var _b23;
8449
+ var APICallError3 = class extends (_b23 = AISDKError3, _a25 = symbol25, _b23) {
8029
8450
  constructor({
8030
8451
  message,
8031
8452
  url,
@@ -8059,8 +8480,8 @@ var name25 = "AI_EmptyResponseBodyError";
8059
8480
  var marker35 = `vercel.ai.error.${name25}`;
8060
8481
  var symbol35 = Symbol.for(marker35);
8061
8482
  var _a35;
8062
- var _b32;
8063
- var EmptyResponseBodyError2 = class extends (_b32 = AISDKError3, _a35 = symbol35, _b32) {
8483
+ var _b33;
8484
+ var EmptyResponseBodyError2 = class extends (_b33 = AISDKError3, _a35 = symbol35, _b33) {
8064
8485
  // used in isInstance
8065
8486
  constructor({ message = "Empty response body" } = {}) {
8066
8487
  super({ name: name25, message });
@@ -8086,8 +8507,8 @@ var name35 = "AI_InvalidArgumentError";
8086
8507
  var marker45 = `vercel.ai.error.${name35}`;
8087
8508
  var symbol45 = Symbol.for(marker45);
8088
8509
  var _a45;
8089
- var _b42;
8090
- var InvalidArgumentError3 = class extends (_b42 = AISDKError3, _a45 = symbol45, _b42) {
8510
+ var _b43;
8511
+ var InvalidArgumentError3 = class extends (_b43 = AISDKError3, _a45 = symbol45, _b43) {
8091
8512
  constructor({
8092
8513
  message,
8093
8514
  cause,
@@ -8105,8 +8526,8 @@ var name65 = "AI_JSONParseError";
8105
8526
  var marker75 = `vercel.ai.error.${name65}`;
8106
8527
  var symbol75 = Symbol.for(marker75);
8107
8528
  var _a75;
8108
- var _b72;
8109
- var JSONParseError3 = class extends (_b72 = AISDKError3, _a75 = symbol75, _b72) {
8529
+ var _b73;
8530
+ var JSONParseError3 = class extends (_b73 = AISDKError3, _a75 = symbol75, _b73) {
8110
8531
  constructor({ text: text4, cause }) {
8111
8532
  super({
8112
8533
  name: name65,
@@ -8125,8 +8546,8 @@ var name105 = "AI_NoSuchModelError";
8125
8546
  var marker115 = `vercel.ai.error.${name105}`;
8126
8547
  var symbol115 = Symbol.for(marker115);
8127
8548
  var _a115;
8128
- var _b11;
8129
- var NoSuchModelError3 = class extends (_b11 = AISDKError3, _a115 = symbol115, _b11) {
8549
+ var _b112;
8550
+ var NoSuchModelError3 = class extends (_b112 = AISDKError3, _a115 = symbol115, _b112) {
8130
8551
  constructor({
8131
8552
  errorName = name105,
8132
8553
  modelId,
@@ -8146,8 +8567,8 @@ var name125 = "AI_TypeValidationError";
8146
8567
  var marker135 = `vercel.ai.error.${name125}`;
8147
8568
  var symbol135 = Symbol.for(marker135);
8148
8569
  var _a135;
8149
- var _b13;
8150
- var TypeValidationError3 = class _TypeValidationError4 extends (_b13 = AISDKError3, _a135 = symbol135, _b13) {
8570
+ var _b132;
8571
+ var TypeValidationError3 = class _TypeValidationError3 extends (_b132 = AISDKError3, _a135 = symbol135, _b132) {
8151
8572
  constructor({
8152
8573
  value,
8153
8574
  cause,
@@ -8198,11 +8619,11 @@ Error message: ${getErrorMessage4(cause)}`,
8198
8619
  cause,
8199
8620
  context: context2
8200
8621
  }) {
8201
- var _a1522, _b152, _c;
8202
- 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)) {
8622
+ var _a1522, _b1522, _c;
8623
+ 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)) {
8203
8624
  return cause;
8204
8625
  }
8205
- return new _TypeValidationError4({ value, cause, context: context2 });
8626
+ return new _TypeValidationError3({ value, cause, context: context2 });
8206
8627
  }
8207
8628
  };
8208
8629
  var ParseError2 = class extends Error {
@@ -8210,6 +8631,9 @@ var ParseError2 = class extends Error {
8210
8631
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
8211
8632
  }
8212
8633
  };
8634
+ var LF = 10;
8635
+ var CR = 13;
8636
+ var SPACE = 32;
8213
8637
  function noop2(_arg) {
8214
8638
  }
8215
8639
  function createParser2(callbacks) {
@@ -8217,39 +8641,109 @@ function createParser2(callbacks) {
8217
8641
  throw new TypeError(
8218
8642
  "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
8219
8643
  );
8220
- const { onEvent = noop2, onError = noop2, onRetry = noop2, onComment } = callbacks;
8221
- let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
8222
- function feed(newChunk) {
8223
- const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines2(`${incompleteLine}${chunk}`);
8224
- for (const line of complete)
8225
- parseLine(line);
8226
- incompleteLine = incomplete, isFirstChunk = false;
8644
+ const { onEvent = noop2, onError = noop2, onRetry = noop2, onComment } = callbacks, pendingFragments = [];
8645
+ let isFirstChunk = true, id, data = "", dataLines = 0, eventType;
8646
+ function feed(chunk) {
8647
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
8648
+ const trailing2 = processLines(chunk);
8649
+ trailing2 !== "" && pendingFragments.push(trailing2);
8650
+ return;
8651
+ }
8652
+ if (chunk.indexOf(`
8653
+ `) === -1 && chunk.indexOf("\r") === -1) {
8654
+ pendingFragments.push(chunk);
8655
+ return;
8656
+ }
8657
+ pendingFragments.push(chunk);
8658
+ const input = pendingFragments.join("");
8659
+ pendingFragments.length = 0;
8660
+ const trailing = processLines(input);
8661
+ trailing !== "" && pendingFragments.push(trailing);
8227
8662
  }
8228
- function parseLine(line) {
8229
- if (line === "") {
8663
+ function processLines(chunk) {
8664
+ let searchIndex = 0;
8665
+ if (chunk.indexOf("\r") === -1) {
8666
+ let lfIndex = chunk.indexOf(`
8667
+ `, searchIndex);
8668
+ for (; lfIndex !== -1; ) {
8669
+ if (searchIndex === lfIndex) {
8670
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
8671
+ `, searchIndex);
8672
+ continue;
8673
+ }
8674
+ const firstCharCode = chunk.charCodeAt(searchIndex);
8675
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
8676
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
8677
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
8678
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
8679
+ `, searchIndex);
8680
+ continue;
8681
+ }
8682
+ data = dataLines === 0 ? value : `${data}
8683
+ ${value}`, dataLines++;
8684
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
8685
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
8686
+ lfIndex
8687
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
8688
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
8689
+ `, searchIndex);
8690
+ }
8691
+ return chunk.slice(searchIndex);
8692
+ }
8693
+ for (; searchIndex < chunk.length; ) {
8694
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
8695
+ `, searchIndex);
8696
+ let lineEnd = -1;
8697
+ 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)
8698
+ break;
8699
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
8700
+ }
8701
+ return chunk.slice(searchIndex);
8702
+ }
8703
+ function parseLine(chunk, start, end) {
8704
+ if (start === end) {
8230
8705
  dispatchEvent();
8231
8706
  return;
8232
8707
  }
8233
- if (line.startsWith(":")) {
8234
- onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
8708
+ const firstCharCode = chunk.charCodeAt(start);
8709
+ if (isDataPrefix(chunk, start, firstCharCode)) {
8710
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
8711
+ data = dataLines === 0 ? value2 : `${data}
8712
+ ${value2}`, dataLines++;
8235
8713
  return;
8236
8714
  }
8237
- const fieldSeparatorIndex = line.indexOf(":");
8238
- if (fieldSeparatorIndex !== -1) {
8239
- const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
8240
- processField(field, value, line);
8715
+ if (isEventPrefix(chunk, start, firstCharCode)) {
8716
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
8241
8717
  return;
8242
8718
  }
8243
- processField(line, "", line);
8719
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
8720
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
8721
+ id = value2.includes("\0") ? void 0 : value2;
8722
+ return;
8723
+ }
8724
+ if (firstCharCode === 58) {
8725
+ if (onComment) {
8726
+ const line2 = chunk.slice(start, end);
8727
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
8728
+ }
8729
+ return;
8730
+ }
8731
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
8732
+ if (fieldSeparatorIndex === -1) {
8733
+ processField(line, "", line);
8734
+ return;
8735
+ }
8736
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
8737
+ processField(field, value, line);
8244
8738
  }
8245
8739
  function processField(field, value, line) {
8246
8740
  switch (field) {
8247
8741
  case "event":
8248
- eventType = value;
8742
+ eventType = value || void 0;
8249
8743
  break;
8250
8744
  case "data":
8251
- data = `${data}${value}
8252
- `;
8745
+ data = dataLines === 0 ? value : `${data}
8746
+ ${value}`, dataLines++;
8253
8747
  break;
8254
8748
  case "id":
8255
8749
  id = value.includes("\0") ? void 0 : value;
@@ -8274,37 +8768,26 @@ function createParser2(callbacks) {
8274
8768
  }
8275
8769
  }
8276
8770
  function dispatchEvent() {
8277
- data.length > 0 && onEvent({
8771
+ dataLines > 0 && onEvent({
8278
8772
  id,
8279
- event: eventType || void 0,
8280
- // If the data buffer's last character is a U+000A LINE FEED (LF) character,
8281
- // then remove the last character from the data buffer.
8282
- data: data.endsWith(`
8283
- `) ? data.slice(0, -1) : data
8284
- }), id = void 0, data = "", eventType = "";
8773
+ event: eventType,
8774
+ data
8775
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
8285
8776
  }
8286
8777
  function reset(options = {}) {
8287
- incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
8778
+ if (options.consume && pendingFragments.length > 0) {
8779
+ const incompleteLine = pendingFragments.join("");
8780
+ parseLine(incompleteLine, 0, incompleteLine.length);
8781
+ }
8782
+ isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0;
8288
8783
  }
8289
8784
  return { feed, reset };
8290
8785
  }
8291
- function splitLines2(chunk) {
8292
- const lines = [];
8293
- let incompleteLine = "", searchIndex = 0;
8294
- for (; searchIndex < chunk.length; ) {
8295
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
8296
- `, searchIndex);
8297
- let lineEnd = -1;
8298
- 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) {
8299
- incompleteLine = chunk.slice(searchIndex);
8300
- break;
8301
- } else {
8302
- const line = chunk.slice(searchIndex, lineEnd);
8303
- lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
8304
- ` && searchIndex++;
8305
- }
8306
- }
8307
- return [lines, incompleteLine];
8786
+ function isDataPrefix(chunk, i, firstCharCode) {
8787
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
8788
+ }
8789
+ function isEventPrefix(chunk, i, firstCharCode) {
8790
+ 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;
8308
8791
  }
8309
8792
  var EventSourceParserStream2 = class extends TransformStream {
8310
8793
  constructor({ onError, onRetry, onComment } = {}) {
@@ -8476,7 +8959,7 @@ function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
8476
8959
  );
8477
8960
  return Object.fromEntries(normalizedHeaders.entries());
8478
8961
  }
8479
- var VERSION4 = "4.0.19";
8962
+ var VERSION5 = "4.0.27";
8480
8963
  var getOriginalFetch3 = () => globalThis.fetch;
8481
8964
  var getFromApi2 = async ({
8482
8965
  url,
@@ -8491,7 +8974,7 @@ var getFromApi2 = async ({
8491
8974
  method: "GET",
8492
8975
  headers: withUserAgentSuffix2(
8493
8976
  headers,
8494
- `ai-sdk/provider-utils/${VERSION4}`,
8977
+ `ai-sdk/provider-utils/${VERSION5}`,
8495
8978
  getRuntimeEnvironmentUserAgent2()
8496
8979
  ),
8497
8980
  signal: abortSignal
@@ -8608,7 +9091,7 @@ function secureJsonParse2(text4) {
8608
9091
  Error.stackTraceLimit = stackTraceLimit;
8609
9092
  }
8610
9093
  }
8611
- function addAdditionalPropertiesToJsonSchema(jsonSchema22) {
9094
+ function addAdditionalPropertiesToJsonSchema2(jsonSchema22) {
8612
9095
  if (jsonSchema22.type === "object" || Array.isArray(jsonSchema22.type) && jsonSchema22.type.includes("object")) {
8613
9096
  jsonSchema22.additionalProperties = false;
8614
9097
  const { properties } = jsonSchema22;
@@ -8640,7 +9123,7 @@ function addAdditionalPropertiesToJsonSchema(jsonSchema22) {
8640
9123
  }
8641
9124
  function visit(def) {
8642
9125
  if (typeof def === "boolean") return def;
8643
- return addAdditionalPropertiesToJsonSchema(def);
9126
+ return addAdditionalPropertiesToJsonSchema2(def);
8644
9127
  }
8645
9128
  var ignoreOverride3 = /* @__PURE__ */ Symbol(
8646
9129
  "Let zodToJsonSchema decide on which parser to use"
@@ -8806,7 +9289,7 @@ function parseIntersectionDef3(def, refs) {
8806
9289
  ...refs,
8807
9290
  currentPath: [...refs.currentPath, "allOf", "1"]
8808
9291
  })
8809
- ].filter((x) => !!x);
9292
+ ].filter((x2) => !!x2);
8810
9293
  const mergedAllOf = [];
8811
9294
  allOf.forEach((schema) => {
8812
9295
  if (isJsonSchema7AllOfType3(schema)) {
@@ -9041,7 +9524,7 @@ function escapeNonAlphaNumeric3(source) {
9041
9524
  }
9042
9525
  function addFormat3(schema, value, message, refs) {
9043
9526
  var _a224;
9044
- if (schema.format || ((_a224 = schema.anyOf) == null ? void 0 : _a224.some((x) => x.format))) {
9527
+ if (schema.format || ((_a224 = schema.anyOf) == null ? void 0 : _a224.some((x2) => x2.format))) {
9045
9528
  if (!schema.anyOf) {
9046
9529
  schema.anyOf = [];
9047
9530
  }
@@ -9061,7 +9544,7 @@ function addFormat3(schema, value, message, refs) {
9061
9544
  }
9062
9545
  function addPattern3(schema, regex, message, refs) {
9063
9546
  var _a224;
9064
- if (schema.pattern || ((_a224 = schema.allOf) == null ? void 0 : _a224.some((x) => x.pattern))) {
9547
+ if (schema.pattern || ((_a224 = schema.allOf) == null ? void 0 : _a224.some((x2) => x2.pattern))) {
9065
9548
  if (!schema.allOf) {
9066
9549
  schema.allOf = [];
9067
9550
  }
@@ -9240,19 +9723,19 @@ var primitiveMappings3 = {
9240
9723
  function parseUnionDef3(def, refs) {
9241
9724
  const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
9242
9725
  if (options.every(
9243
- (x) => x._def.typeName in primitiveMappings3 && (!x._def.checks || !x._def.checks.length)
9726
+ (x2) => x2._def.typeName in primitiveMappings3 && (!x2._def.checks || !x2._def.checks.length)
9244
9727
  )) {
9245
- const types = options.reduce((types2, x) => {
9246
- const type = primitiveMappings3[x._def.typeName];
9728
+ const types = options.reduce((types2, x2) => {
9729
+ const type = primitiveMappings3[x2._def.typeName];
9247
9730
  return type && !types2.includes(type) ? [...types2, type] : types2;
9248
9731
  }, []);
9249
9732
  return {
9250
9733
  type: types.length > 1 ? types : types[0]
9251
9734
  };
9252
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
9735
+ } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
9253
9736
  const types = options.reduce(
9254
- (acc, x) => {
9255
- const type = typeof x._def.value;
9737
+ (acc, x2) => {
9738
+ const type = typeof x2._def.value;
9256
9739
  switch (type) {
9257
9740
  case "string":
9258
9741
  case "number":
@@ -9261,7 +9744,7 @@ function parseUnionDef3(def, refs) {
9261
9744
  case "bigint":
9262
9745
  return [...acc, "integer"];
9263
9746
  case "object":
9264
- if (x._def.value === null) return [...acc, "null"];
9747
+ if (x2._def.value === null) return [...acc, "null"];
9265
9748
  case "symbol":
9266
9749
  case "undefined":
9267
9750
  case "function":
@@ -9272,24 +9755,24 @@ function parseUnionDef3(def, refs) {
9272
9755
  []
9273
9756
  );
9274
9757
  if (types.length === options.length) {
9275
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
9758
+ const uniqueTypes = types.filter((x2, i, a) => a.indexOf(x2) === i);
9276
9759
  return {
9277
9760
  type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
9278
9761
  enum: options.reduce(
9279
- (acc, x) => {
9280
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
9762
+ (acc, x2) => {
9763
+ return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
9281
9764
  },
9282
9765
  []
9283
9766
  )
9284
9767
  };
9285
9768
  }
9286
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
9769
+ } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
9287
9770
  return {
9288
9771
  type: "string",
9289
9772
  enum: options.reduce(
9290
- (acc, x) => [
9773
+ (acc, x2) => [
9291
9774
  ...acc,
9292
- ...x._def.values.filter((x2) => !acc.includes(x2))
9775
+ ...x2._def.values.filter((x22) => !acc.includes(x22))
9293
9776
  ],
9294
9777
  []
9295
9778
  )
@@ -9299,12 +9782,12 @@ function parseUnionDef3(def, refs) {
9299
9782
  }
9300
9783
  var asAnyOf3 = (def, refs) => {
9301
9784
  const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
9302
- (x, i) => parseDef3(x._def, {
9785
+ (x2, i) => parseDef3(x2._def, {
9303
9786
  ...refs,
9304
9787
  currentPath: [...refs.currentPath, "anyOf", `${i}`]
9305
9788
  })
9306
9789
  ).filter(
9307
- (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
9790
+ (x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0)
9308
9791
  );
9309
9792
  return anyOf.length ? { anyOf } : void 0;
9310
9793
  };
@@ -9440,7 +9923,7 @@ var parsePipelineDef3 = (def, refs) => {
9440
9923
  currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
9441
9924
  });
9442
9925
  return {
9443
- allOf: [a, b].filter((x) => x !== void 0)
9926
+ allOf: [a, b].filter((x2) => x2 !== void 0)
9444
9927
  };
9445
9928
  };
9446
9929
  function parsePromiseDef3(def, refs) {
@@ -9470,12 +9953,12 @@ function parseTupleDef3(def, refs) {
9470
9953
  type: "array",
9471
9954
  minItems: def.items.length,
9472
9955
  items: def.items.map(
9473
- (x, i) => parseDef3(x._def, {
9956
+ (x2, i) => parseDef3(x2._def, {
9474
9957
  ...refs,
9475
9958
  currentPath: [...refs.currentPath, "items", `${i}`]
9476
9959
  })
9477
9960
  ).reduce(
9478
- (acc, x) => x === void 0 ? acc : [...acc, x],
9961
+ (acc, x2) => x2 === void 0 ? acc : [...acc, x2],
9479
9962
  []
9480
9963
  ),
9481
9964
  additionalItems: parseDef3(def.rest._def, {
@@ -9489,12 +9972,12 @@ function parseTupleDef3(def, refs) {
9489
9972
  minItems: def.items.length,
9490
9973
  maxItems: def.items.length,
9491
9974
  items: def.items.map(
9492
- (x, i) => parseDef3(x._def, {
9975
+ (x2, i) => parseDef3(x2._def, {
9493
9976
  ...refs,
9494
9977
  currentPath: [...refs.currentPath, "items", `${i}`]
9495
9978
  })
9496
9979
  ).reduce(
9497
- (acc, x) => x === void 0 ? acc : [...acc, x],
9980
+ (acc, x2) => x2 === void 0 ? acc : [...acc, x2],
9498
9981
  []
9499
9982
  )
9500
9983
  };
@@ -9725,7 +10208,7 @@ var zod3ToJsonSchema = (schema, options) => {
9725
10208
  return combined;
9726
10209
  };
9727
10210
  var schemaSymbol3 = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
9728
- function lazySchema(createSchema) {
10211
+ function lazySchema2(createSchema) {
9729
10212
  let schema;
9730
10213
  return () => {
9731
10214
  if (schema == null) {
@@ -9758,7 +10241,7 @@ function asSchema3(schema) {
9758
10241
  }
9759
10242
  function standardSchema(standardSchema2) {
9760
10243
  return jsonSchema3(
9761
- () => addAdditionalPropertiesToJsonSchema(
10244
+ () => addAdditionalPropertiesToJsonSchema2(
9762
10245
  standardSchema2["~standard"].jsonSchema.input({
9763
10246
  target: "draft-07"
9764
10247
  })
@@ -9798,7 +10281,7 @@ function zod4Schema2(zodSchema22, options) {
9798
10281
  const useReferences = (_a224 = void 0 ) != null ? _a224 : false;
9799
10282
  return jsonSchema3(
9800
10283
  // defer json schema creation to avoid unnecessary computation when only validation is needed
9801
- () => addAdditionalPropertiesToJsonSchema(
10284
+ () => addAdditionalPropertiesToJsonSchema2(
9802
10285
  z4.toJSONSchema(zodSchema22, {
9803
10286
  target: "draft-7",
9804
10287
  io: "input",
@@ -9949,7 +10432,7 @@ var postToApi2 = async ({
9949
10432
  method: "POST",
9950
10433
  headers: withUserAgentSuffix2(
9951
10434
  headers,
9952
- `ai-sdk/provider-utils/${VERSION4}`,
10435
+ `ai-sdk/provider-utils/${VERSION5}`,
9953
10436
  getRuntimeEnvironmentUserAgent2()
9954
10437
  ),
9955
10438
  body: body.content,
@@ -10004,8 +10487,8 @@ var postToApi2 = async ({
10004
10487
  throw handleFetchError2({ error, url, requestBodyValues: body.values });
10005
10488
  }
10006
10489
  };
10007
- function tool(tool2) {
10008
- return tool2;
10490
+ function tool2(tool22) {
10491
+ return tool22;
10009
10492
  }
10010
10493
  function createProviderToolFactoryWithOutputSchema({
10011
10494
  id,
@@ -10021,7 +10504,7 @@ function createProviderToolFactoryWithOutputSchema({
10021
10504
  onInputDelta,
10022
10505
  onInputAvailable,
10023
10506
  ...args
10024
- }) => tool({
10507
+ }) => tool2({
10025
10508
  type: "provider",
10026
10509
  id,
10027
10510
  args,
@@ -10136,143 +10619,22 @@ var createJsonResponseHandler2 = (responseSchema) => async ({ response, url, req
10136
10619
  function withoutTrailingSlash2(url) {
10137
10620
  return url == null ? void 0 : url.replace(/\/$/, "");
10138
10621
  }
10139
- var require_get_context2 = __commonJS$1({
10140
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-context.js"(exports$1, module) {
10141
- var __defProp22 = Object.defineProperty;
10142
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
10143
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
10144
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
10145
- var __export22 = (target, all) => {
10146
- for (var name21 in all)
10147
- __defProp22(target, name21, { get: all[name21], enumerable: true });
10148
- };
10149
- var __copyProps2 = (to, from, except, desc) => {
10150
- if (from && typeof from === "object" || typeof from === "function") {
10151
- for (let key of __getOwnPropNames2(from))
10152
- if (!__hasOwnProp2.call(to, key) && key !== except)
10153
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
10154
- }
10155
- return to;
10156
- };
10157
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
10158
- var get_context_exports = {};
10159
- __export22(get_context_exports, {
10160
- SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
10161
- getContext: () => getContext3
10162
- });
10163
- module.exports = __toCommonJS(get_context_exports);
10164
- var SYMBOL_FOR_REQ_CONTEXT = /* @__PURE__ */ Symbol.for("@vercel/request-context");
10165
- function getContext3() {
10166
- const fromSymbol = globalThis;
10167
- return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
10168
- }
10169
- }
10170
- });
10171
- var require_get_vercel_oidc_token2 = __commonJS$1({
10172
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports$1, module) {
10173
- var __defProp22 = Object.defineProperty;
10174
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
10175
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
10176
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
10177
- var __export22 = (target, all) => {
10178
- for (var name21 in all)
10179
- __defProp22(target, name21, { get: all[name21], enumerable: true });
10180
- };
10181
- var __copyProps2 = (to, from, except, desc) => {
10182
- if (from && typeof from === "object" || typeof from === "function") {
10183
- for (let key of __getOwnPropNames2(from))
10184
- if (!__hasOwnProp2.call(to, key) && key !== except)
10185
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
10186
- }
10187
- return to;
10188
- };
10189
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
10190
- var get_vercel_oidc_token_exports = {};
10191
- __export22(get_vercel_oidc_token_exports, {
10192
- getVercelOidcToken: () => getVercelOidcToken3,
10193
- getVercelOidcTokenSync: () => getVercelOidcTokenSync2
10194
- });
10195
- module.exports = __toCommonJS(get_vercel_oidc_token_exports);
10196
- var import_get_context = require_get_context2();
10197
- var import_token_error = require_token_error$1();
10198
- async function getVercelOidcToken3() {
10199
- let token = "";
10200
- let err;
10201
- try {
10202
- token = getVercelOidcTokenSync2();
10203
- } catch (error) {
10204
- err = error;
10205
- }
10206
- try {
10207
- const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
10208
- await import('./token-util-RMHT2CPJ-RJEA3FAN.js'),
10209
- await import('./token-APYSY3BW-2DN6RAUY.js')
10210
- ]);
10211
- if (!token || isExpired(getTokenPayload(token))) {
10212
- await refreshToken();
10213
- token = getVercelOidcTokenSync2();
10214
- }
10215
- } catch (error) {
10216
- let message = err instanceof Error ? err.message : "";
10217
- if (error instanceof Error) {
10218
- message = `${message}
10219
- ${error.message}`;
10220
- }
10221
- if (message) {
10222
- throw new import_token_error.VercelOidcTokenError(message);
10223
- }
10224
- throw error;
10225
- }
10226
- return token;
10227
- }
10228
- function getVercelOidcTokenSync2() {
10229
- const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
10230
- if (!token) {
10231
- throw new Error(
10232
- `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
10233
- );
10234
- }
10235
- return token;
10236
- }
10237
- }
10238
- });
10239
- var require_dist2 = __commonJS$1({
10240
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/index.js"(exports$1, module) {
10241
- var __defProp22 = Object.defineProperty;
10242
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
10243
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
10244
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
10245
- var __export22 = (target, all) => {
10246
- for (var name21 in all)
10247
- __defProp22(target, name21, { get: all[name21], enumerable: true });
10248
- };
10249
- var __copyProps2 = (to, from, except, desc) => {
10250
- if (from && typeof from === "object" || typeof from === "function") {
10251
- for (let key of __getOwnPropNames2(from))
10252
- if (!__hasOwnProp2.call(to, key) && key !== except)
10253
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
10254
- }
10255
- return to;
10256
- };
10257
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
10258
- var src_exports = {};
10259
- __export22(src_exports, {
10260
- getContext: () => import_get_context.getContext,
10261
- getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
10262
- getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
10263
- });
10264
- module.exports = __toCommonJS(src_exports);
10265
- var import_get_vercel_oidc_token = require_get_vercel_oidc_token2();
10266
- var import_get_context = require_get_context2();
10622
+ function getContext2() {
10623
+ return {
10624
+ headers: {}
10625
+ };
10626
+ }
10627
+ async function getVercelOidcToken2() {
10628
+ if (process.env.VERCEL_OIDC_TOKEN) {
10629
+ return process.env.VERCEL_OIDC_TOKEN ?? "";
10267
10630
  }
10268
- });
10269
- var import_oidc3 = __toESM$1(require_dist2(), 1);
10270
- var import_oidc22 = __toESM$1(require_dist2(), 1);
10271
- var marker19 = "vercel.ai.gateway.error";
10272
- var symbol19 = Symbol.for(marker19);
10273
- var _a19;
10274
- var _b16;
10275
- var GatewayError2 = class _GatewayError2 extends (_b16 = Error, _a19 = symbol19, _b16) {
10631
+ throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
10632
+ }
10633
+ var marker20 = "vercel.ai.gateway.error";
10634
+ var symbol20 = Symbol.for(marker20);
10635
+ var _a20;
10636
+ var _b18;
10637
+ var GatewayError2 = class _GatewayError2 extends (_b18 = Error, _a20 = symbol20, _b18) {
10276
10638
  constructor({
10277
10639
  message,
10278
10640
  statusCode = 500,
@@ -10280,7 +10642,7 @@ var GatewayError2 = class _GatewayError2 extends (_b16 = Error, _a19 = symbol19,
10280
10642
  generationId
10281
10643
  }) {
10282
10644
  super(generationId ? `${message} [${generationId}]` : message);
10283
- this[_a19] = true;
10645
+ this[_a20] = true;
10284
10646
  this.statusCode = statusCode;
10285
10647
  this.cause = cause;
10286
10648
  this.generationId = generationId;
@@ -10294,15 +10656,15 @@ var GatewayError2 = class _GatewayError2 extends (_b16 = Error, _a19 = symbol19,
10294
10656
  return _GatewayError2.hasMarker(error);
10295
10657
  }
10296
10658
  static hasMarker(error) {
10297
- return typeof error === "object" && error !== null && symbol19 in error && error[symbol19] === true;
10659
+ return typeof error === "object" && error !== null && symbol20 in error && error[symbol20] === true;
10298
10660
  }
10299
10661
  };
10300
10662
  var name19 = "GatewayAuthenticationError";
10301
10663
  var marker26 = `vercel.ai.gateway.error.${name19}`;
10302
10664
  var symbol26 = Symbol.for(marker26);
10303
10665
  var _a26;
10304
- var _b23;
10305
- var GatewayAuthenticationError2 = class _GatewayAuthenticationError2 extends (_b23 = GatewayError2, _a26 = symbol26, _b23) {
10666
+ var _b24;
10667
+ var GatewayAuthenticationError2 = class _GatewayAuthenticationError2 extends (_b24 = GatewayError2, _a26 = symbol26, _b24) {
10306
10668
  constructor({
10307
10669
  message = "Authentication failed",
10308
10670
  statusCode = 401,
@@ -10363,8 +10725,8 @@ var name26 = "GatewayInvalidRequestError";
10363
10725
  var marker36 = `vercel.ai.gateway.error.${name26}`;
10364
10726
  var symbol36 = Symbol.for(marker36);
10365
10727
  var _a36;
10366
- var _b33;
10367
- var GatewayInvalidRequestError2 = class extends (_b33 = GatewayError2, _a36 = symbol36, _b33) {
10728
+ var _b34;
10729
+ var GatewayInvalidRequestError2 = class extends (_b34 = GatewayError2, _a36 = symbol36, _b34) {
10368
10730
  constructor({
10369
10731
  message = "Invalid request",
10370
10732
  statusCode = 400,
@@ -10384,8 +10746,8 @@ var name36 = "GatewayRateLimitError";
10384
10746
  var marker46 = `vercel.ai.gateway.error.${name36}`;
10385
10747
  var symbol46 = Symbol.for(marker46);
10386
10748
  var _a46;
10387
- var _b43;
10388
- var GatewayRateLimitError2 = class extends (_b43 = GatewayError2, _a46 = symbol46, _b43) {
10749
+ var _b44;
10750
+ var GatewayRateLimitError2 = class extends (_b44 = GatewayError2, _a46 = symbol46, _b44) {
10389
10751
  constructor({
10390
10752
  message = "Rate limit exceeded",
10391
10753
  statusCode = 429,
@@ -10404,7 +10766,7 @@ var GatewayRateLimitError2 = class extends (_b43 = GatewayError2, _a46 = symbol4
10404
10766
  var name46 = "GatewayModelNotFoundError";
10405
10767
  var marker56 = `vercel.ai.gateway.error.${name46}`;
10406
10768
  var symbol56 = Symbol.for(marker56);
10407
- var modelNotFoundParamSchema2 = lazySchema(
10769
+ var modelNotFoundParamSchema2 = lazySchema2(
10408
10770
  () => zodSchema3(
10409
10771
  z.object({
10410
10772
  modelId: z.string()
@@ -10412,8 +10774,8 @@ var modelNotFoundParamSchema2 = lazySchema(
10412
10774
  )
10413
10775
  );
10414
10776
  var _a56;
10415
- var _b53;
10416
- var GatewayModelNotFoundError2 = class extends (_b53 = GatewayError2, _a56 = symbol56, _b53) {
10777
+ var _b54;
10778
+ var GatewayModelNotFoundError2 = class extends (_b54 = GatewayError2, _a56 = symbol56, _b54) {
10417
10779
  constructor({
10418
10780
  message = "Model not found",
10419
10781
  statusCode = 404,
@@ -10435,8 +10797,8 @@ var name56 = "GatewayInternalServerError";
10435
10797
  var marker66 = `vercel.ai.gateway.error.${name56}`;
10436
10798
  var symbol66 = Symbol.for(marker66);
10437
10799
  var _a66;
10438
- var _b63;
10439
- var GatewayInternalServerError2 = class extends (_b63 = GatewayError2, _a66 = symbol66, _b63) {
10800
+ var _b64;
10801
+ var GatewayInternalServerError2 = class extends (_b64 = GatewayError2, _a66 = symbol66, _b64) {
10440
10802
  constructor({
10441
10803
  message = "Internal server error",
10442
10804
  statusCode = 500,
@@ -10456,8 +10818,8 @@ var name66 = "GatewayResponseError";
10456
10818
  var marker76 = `vercel.ai.gateway.error.${name66}`;
10457
10819
  var symbol76 = Symbol.for(marker76);
10458
10820
  var _a76;
10459
- var _b73;
10460
- var GatewayResponseError2 = class extends (_b73 = GatewayError2, _a76 = symbol76, _b73) {
10821
+ var _b74;
10822
+ var GatewayResponseError2 = class extends (_b74 = GatewayError2, _a76 = symbol76, _b74) {
10461
10823
  constructor({
10462
10824
  message = "Invalid response from Gateway",
10463
10825
  statusCode = 502,
@@ -10556,7 +10918,7 @@ async function createGatewayErrorFromResponse2({
10556
10918
  });
10557
10919
  }
10558
10920
  }
10559
- var gatewayErrorResponseSchema2 = lazySchema(
10921
+ var gatewayErrorResponseSchema2 = lazySchema2(
10560
10922
  () => zodSchema3(
10561
10923
  z.object({
10562
10924
  error: z.object({
@@ -10569,12 +10931,25 @@ var gatewayErrorResponseSchema2 = lazySchema(
10569
10931
  })
10570
10932
  )
10571
10933
  );
10934
+ function extractApiCallResponse2(error) {
10935
+ if (error.data !== void 0) {
10936
+ return error.data;
10937
+ }
10938
+ if (error.responseBody != null) {
10939
+ try {
10940
+ return JSON.parse(error.responseBody);
10941
+ } catch (e) {
10942
+ return error.responseBody;
10943
+ }
10944
+ }
10945
+ return {};
10946
+ }
10572
10947
  var name76 = "GatewayTimeoutError";
10573
10948
  var marker86 = `vercel.ai.gateway.error.${name76}`;
10574
10949
  var symbol86 = Symbol.for(marker86);
10575
10950
  var _a86;
10576
- var _b83;
10577
- var GatewayTimeoutError = class _GatewayTimeoutError extends (_b83 = GatewayError2, _a86 = symbol86, _b83) {
10951
+ var _b84;
10952
+ var GatewayTimeoutError2 = class _GatewayTimeoutError2 extends (_b84 = GatewayError2, _a86 = symbol86, _b84) {
10578
10953
  constructor({
10579
10954
  message = "Request timed out",
10580
10955
  statusCode = 408,
@@ -10601,7 +10976,7 @@ var GatewayTimeoutError = class _GatewayTimeoutError extends (_b83 = GatewayErro
10601
10976
  const message = `Gateway request timed out: ${originalMessage}
10602
10977
 
10603
10978
  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`;
10604
- return new _GatewayTimeoutError({
10979
+ return new _GatewayTimeoutError2({
10605
10980
  message,
10606
10981
  statusCode,
10607
10982
  cause,
@@ -10609,7 +10984,7 @@ var GatewayTimeoutError = class _GatewayTimeoutError extends (_b83 = GatewayErro
10609
10984
  });
10610
10985
  }
10611
10986
  };
10612
- function isTimeoutError(error) {
10987
+ function isTimeoutError2(error) {
10613
10988
  if (!(error instanceof Error)) {
10614
10989
  return false;
10615
10990
  }
@@ -10629,15 +11004,15 @@ async function asGatewayError2(error, authMethod) {
10629
11004
  if (GatewayError2.isInstance(error)) {
10630
11005
  return error;
10631
11006
  }
10632
- if (isTimeoutError(error)) {
10633
- return GatewayTimeoutError.createTimeoutError({
11007
+ if (isTimeoutError2(error)) {
11008
+ return GatewayTimeoutError2.createTimeoutError({
10634
11009
  originalMessage: error instanceof Error ? error.message : "Unknown error",
10635
11010
  cause: error
10636
11011
  });
10637
11012
  }
10638
11013
  if (APICallError3.isInstance(error)) {
10639
- if (error.cause && isTimeoutError(error.cause)) {
10640
- return GatewayTimeoutError.createTimeoutError({
11014
+ if (error.cause && isTimeoutError2(error.cause)) {
11015
+ return GatewayTimeoutError2.createTimeoutError({
10641
11016
  originalMessage: error.message,
10642
11017
  cause: error
10643
11018
  });
@@ -10646,30 +11021,17 @@ async function asGatewayError2(error, authMethod) {
10646
11021
  response: extractApiCallResponse2(error),
10647
11022
  statusCode: (_a932 = error.statusCode) != null ? _a932 : 500,
10648
11023
  defaultMessage: "Gateway request failed",
10649
- cause: error,
10650
- authMethod
10651
- });
10652
- }
10653
- return await createGatewayErrorFromResponse2({
10654
- response: {},
10655
- statusCode: 500,
10656
- defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
10657
- cause: error,
10658
- authMethod
10659
- });
10660
- }
10661
- function extractApiCallResponse2(error) {
10662
- if (error.data !== void 0) {
10663
- return error.data;
10664
- }
10665
- if (error.responseBody != null) {
10666
- try {
10667
- return JSON.parse(error.responseBody);
10668
- } catch (e) {
10669
- return error.responseBody;
10670
- }
11024
+ cause: error,
11025
+ authMethod
11026
+ });
10671
11027
  }
10672
- return {};
11028
+ return await createGatewayErrorFromResponse2({
11029
+ response: {},
11030
+ statusCode: 500,
11031
+ defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
11032
+ cause: error,
11033
+ authMethod
11034
+ });
10673
11035
  }
10674
11036
  var GATEWAY_AUTH_METHOD_HEADER2 = "ai-gateway-auth-method";
10675
11037
  async function parseAuthMethod2(headers) {
@@ -10679,9 +11041,16 @@ async function parseAuthMethod2(headers) {
10679
11041
  });
10680
11042
  return result.success ? result.value : void 0;
10681
11043
  }
10682
- var gatewayAuthMethodSchema2 = lazySchema(
11044
+ var gatewayAuthMethodSchema2 = lazySchema2(
10683
11045
  () => zodSchema3(z.union([z.literal("api-key"), z.literal("oidc")]))
10684
11046
  );
11047
+ var KNOWN_MODEL_TYPES2 = [
11048
+ "embedding",
11049
+ "image",
11050
+ "language",
11051
+ "reranking",
11052
+ "video"
11053
+ ];
10685
11054
  var GatewayFetchMetadata2 = class {
10686
11055
  constructor(config) {
10687
11056
  this.config = config;
@@ -10726,7 +11095,7 @@ var GatewayFetchMetadata2 = class {
10726
11095
  }
10727
11096
  }
10728
11097
  };
10729
- var gatewayAvailableModelsResponseSchema2 = lazySchema(
11098
+ var gatewayAvailableModelsResponseSchema2 = lazySchema2(
10730
11099
  () => zodSchema3(
10731
11100
  z.object({
10732
11101
  models: z.array(
@@ -10752,13 +11121,17 @@ var gatewayAvailableModelsResponseSchema2 = lazySchema(
10752
11121
  provider: z.string(),
10753
11122
  modelId: z.string()
10754
11123
  }),
10755
- modelType: z.enum(["embedding", "image", "language", "video"]).nullish()
11124
+ modelType: z.string().nullish()
10756
11125
  })
11126
+ ).transform(
11127
+ (models) => models.filter(
11128
+ (m) => m.modelType == null || KNOWN_MODEL_TYPES2.includes(m.modelType)
11129
+ )
10757
11130
  )
10758
11131
  })
10759
11132
  )
10760
11133
  );
10761
- var gatewayCreditsResponseSchema2 = lazySchema(
11134
+ var gatewayCreditsResponseSchema2 = lazySchema2(
10762
11135
  () => zodSchema3(
10763
11136
  z.object({
10764
11137
  balance: z.string(),
@@ -10769,6 +11142,187 @@ var gatewayCreditsResponseSchema2 = lazySchema(
10769
11142
  }))
10770
11143
  )
10771
11144
  );
11145
+ var GatewaySpendReport2 = class {
11146
+ constructor(config) {
11147
+ this.config = config;
11148
+ }
11149
+ async getSpendReport(params) {
11150
+ try {
11151
+ const baseUrl = new URL(this.config.baseURL);
11152
+ const searchParams = new URLSearchParams();
11153
+ searchParams.set("start_date", params.startDate);
11154
+ searchParams.set("end_date", params.endDate);
11155
+ if (params.groupBy) {
11156
+ searchParams.set("group_by", params.groupBy);
11157
+ }
11158
+ if (params.datePart) {
11159
+ searchParams.set("date_part", params.datePart);
11160
+ }
11161
+ if (params.userId) {
11162
+ searchParams.set("user_id", params.userId);
11163
+ }
11164
+ if (params.model) {
11165
+ searchParams.set("model", params.model);
11166
+ }
11167
+ if (params.provider) {
11168
+ searchParams.set("provider", params.provider);
11169
+ }
11170
+ if (params.credentialType) {
11171
+ searchParams.set("credential_type", params.credentialType);
11172
+ }
11173
+ if (params.tags && params.tags.length > 0) {
11174
+ searchParams.set("tags", params.tags.join(","));
11175
+ }
11176
+ const { value } = await getFromApi2({
11177
+ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
11178
+ headers: await resolve2(this.config.headers()),
11179
+ successfulResponseHandler: createJsonResponseHandler2(
11180
+ gatewaySpendReportResponseSchema2
11181
+ ),
11182
+ failedResponseHandler: createJsonErrorResponseHandler2({
11183
+ errorSchema: z.any(),
11184
+ errorToMessage: (data) => data
11185
+ }),
11186
+ fetch: this.config.fetch
11187
+ });
11188
+ return value;
11189
+ } catch (error) {
11190
+ throw await asGatewayError2(error);
11191
+ }
11192
+ }
11193
+ };
11194
+ var gatewaySpendReportResponseSchema2 = lazySchema2(
11195
+ () => zodSchema3(
11196
+ z.object({
11197
+ results: z.array(
11198
+ z.object({
11199
+ day: z.string().optional(),
11200
+ hour: z.string().optional(),
11201
+ user: z.string().optional(),
11202
+ model: z.string().optional(),
11203
+ tag: z.string().optional(),
11204
+ provider: z.string().optional(),
11205
+ credential_type: z.enum(["byok", "system"]).optional(),
11206
+ total_cost: z.number(),
11207
+ market_cost: z.number().optional(),
11208
+ input_tokens: z.number().optional(),
11209
+ output_tokens: z.number().optional(),
11210
+ cached_input_tokens: z.number().optional(),
11211
+ cache_creation_input_tokens: z.number().optional(),
11212
+ reasoning_tokens: z.number().optional(),
11213
+ request_count: z.number().optional()
11214
+ }).transform(
11215
+ ({
11216
+ credential_type,
11217
+ total_cost,
11218
+ market_cost,
11219
+ input_tokens,
11220
+ output_tokens,
11221
+ cached_input_tokens,
11222
+ cache_creation_input_tokens,
11223
+ reasoning_tokens,
11224
+ request_count,
11225
+ ...rest
11226
+ }) => ({
11227
+ ...rest,
11228
+ ...credential_type !== void 0 ? { credentialType: credential_type } : {},
11229
+ totalCost: total_cost,
11230
+ ...market_cost !== void 0 ? { marketCost: market_cost } : {},
11231
+ ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
11232
+ ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
11233
+ ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
11234
+ ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
11235
+ ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
11236
+ ...request_count !== void 0 ? { requestCount: request_count } : {}
11237
+ })
11238
+ )
11239
+ )
11240
+ })
11241
+ )
11242
+ );
11243
+ var GatewayGenerationInfoFetcher2 = class {
11244
+ constructor(config) {
11245
+ this.config = config;
11246
+ }
11247
+ async getGenerationInfo(params) {
11248
+ try {
11249
+ const baseUrl = new URL(this.config.baseURL);
11250
+ const { value } = await getFromApi2({
11251
+ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
11252
+ headers: await resolve2(this.config.headers()),
11253
+ successfulResponseHandler: createJsonResponseHandler2(
11254
+ gatewayGenerationInfoResponseSchema2
11255
+ ),
11256
+ failedResponseHandler: createJsonErrorResponseHandler2({
11257
+ errorSchema: z.any(),
11258
+ errorToMessage: (data) => data
11259
+ }),
11260
+ fetch: this.config.fetch
11261
+ });
11262
+ return value;
11263
+ } catch (error) {
11264
+ throw await asGatewayError2(error);
11265
+ }
11266
+ }
11267
+ };
11268
+ var gatewayGenerationInfoResponseSchema2 = lazySchema2(
11269
+ () => zodSchema3(
11270
+ z.object({
11271
+ data: z.object({
11272
+ id: z.string(),
11273
+ total_cost: z.number(),
11274
+ upstream_inference_cost: z.number(),
11275
+ usage: z.number(),
11276
+ created_at: z.string(),
11277
+ model: z.string(),
11278
+ is_byok: z.boolean(),
11279
+ provider_name: z.string(),
11280
+ streamed: z.boolean(),
11281
+ finish_reason: z.string(),
11282
+ latency: z.number(),
11283
+ generation_time: z.number(),
11284
+ native_tokens_prompt: z.number(),
11285
+ native_tokens_completion: z.number(),
11286
+ native_tokens_reasoning: z.number(),
11287
+ native_tokens_cached: z.number(),
11288
+ native_tokens_cache_creation: z.number(),
11289
+ billable_web_search_calls: z.number()
11290
+ }).transform(
11291
+ ({
11292
+ total_cost,
11293
+ upstream_inference_cost,
11294
+ created_at,
11295
+ is_byok,
11296
+ provider_name,
11297
+ finish_reason,
11298
+ generation_time,
11299
+ native_tokens_prompt,
11300
+ native_tokens_completion,
11301
+ native_tokens_reasoning,
11302
+ native_tokens_cached,
11303
+ native_tokens_cache_creation,
11304
+ billable_web_search_calls,
11305
+ ...rest
11306
+ }) => ({
11307
+ ...rest,
11308
+ totalCost: total_cost,
11309
+ upstreamInferenceCost: upstream_inference_cost,
11310
+ createdAt: created_at,
11311
+ isByok: is_byok,
11312
+ providerName: provider_name,
11313
+ finishReason: finish_reason,
11314
+ generationTime: generation_time,
11315
+ promptTokens: native_tokens_prompt,
11316
+ completionTokens: native_tokens_completion,
11317
+ reasoningTokens: native_tokens_reasoning,
11318
+ cachedTokens: native_tokens_cached,
11319
+ cacheCreationTokens: native_tokens_cache_creation,
11320
+ billableWebSearchCalls: billable_web_search_calls
11321
+ })
11322
+ )
11323
+ }).transform(({ data }) => data)
11324
+ )
11325
+ );
10772
11326
  var GatewayLanguageModel2 = class {
10773
11327
  constructor(modelId, config) {
10774
11328
  this.modelId = modelId;
@@ -10981,7 +11535,7 @@ var GatewayEmbeddingModel2 = class {
10981
11535
  };
10982
11536
  }
10983
11537
  };
10984
- var gatewayEmbeddingResponseSchema2 = lazySchema(
11538
+ var gatewayEmbeddingResponseSchema2 = lazySchema2(
10985
11539
  () => zodSchema3(
10986
11540
  z.object({
10987
11541
  embeddings: z.array(z.array(z.number())),
@@ -11012,7 +11566,7 @@ var GatewayImageModel2 = class {
11012
11566
  headers,
11013
11567
  abortSignal
11014
11568
  }) {
11015
- var _a932, _b92, _c, _d;
11569
+ var _a932, _b93, _c, _d;
11016
11570
  const resolvedHeaders = await resolve2(this.config.headers());
11017
11571
  try {
11018
11572
  const {
@@ -11060,7 +11614,7 @@ var GatewayImageModel2 = class {
11060
11614
  },
11061
11615
  ...responseBody.usage != null && {
11062
11616
  usage: {
11063
- inputTokens: (_b92 = responseBody.usage.inputTokens) != null ? _b92 : void 0,
11617
+ inputTokens: (_b93 = responseBody.usage.inputTokens) != null ? _b93 : void 0,
11064
11618
  outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,
11065
11619
  totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0
11066
11620
  }
@@ -11108,7 +11662,7 @@ var gatewayImageWarningSchema = z.discriminatedUnion("type", [
11108
11662
  message: z.string()
11109
11663
  })
11110
11664
  ]);
11111
- var gatewayImageUsageSchema = z.object({
11665
+ var gatewayImageUsageSchema2 = z.object({
11112
11666
  inputTokens: z.number().nullish(),
11113
11667
  outputTokens: z.number().nullish(),
11114
11668
  totalTokens: z.number().nullish()
@@ -11118,7 +11672,7 @@ var gatewayImageResponseSchema2 = z.object({
11118
11672
  // Always base64 strings over the wire
11119
11673
  warnings: z.array(gatewayImageWarningSchema).optional(),
11120
11674
  providerMetadata: z.record(z.string(), providerMetadataEntrySchema2).optional(),
11121
- usage: gatewayImageUsageSchema.optional()
11675
+ usage: gatewayImageUsageSchema2.optional()
11122
11676
  });
11123
11677
  var GatewayVideoModel = class {
11124
11678
  constructor(modelId, config) {
@@ -11316,7 +11870,87 @@ var gatewayVideoEventSchema = z.discriminatedUnion("type", [
11316
11870
  param: z.unknown().nullable()
11317
11871
  })
11318
11872
  ]);
11319
- var parallelSearchInputSchema = lazySchema(
11873
+ var GatewayRerankingModel = class {
11874
+ constructor(modelId, config) {
11875
+ this.modelId = modelId;
11876
+ this.config = config;
11877
+ this.specificationVersion = "v3";
11878
+ }
11879
+ get provider() {
11880
+ return this.config.provider;
11881
+ }
11882
+ async doRerank({
11883
+ documents,
11884
+ query,
11885
+ topN,
11886
+ headers,
11887
+ abortSignal,
11888
+ providerOptions
11889
+ }) {
11890
+ const resolvedHeaders = await resolve2(this.config.headers());
11891
+ try {
11892
+ const {
11893
+ responseHeaders,
11894
+ value: responseBody,
11895
+ rawValue
11896
+ } = await postJsonToApi2({
11897
+ url: this.getUrl(),
11898
+ headers: combineHeaders2(
11899
+ resolvedHeaders,
11900
+ headers != null ? headers : {},
11901
+ this.getModelConfigHeaders(),
11902
+ await resolve2(this.config.o11yHeaders)
11903
+ ),
11904
+ body: {
11905
+ documents,
11906
+ query,
11907
+ ...topN != null ? { topN } : {},
11908
+ ...providerOptions ? { providerOptions } : {}
11909
+ },
11910
+ successfulResponseHandler: createJsonResponseHandler2(
11911
+ gatewayRerankingResponseSchema
11912
+ ),
11913
+ failedResponseHandler: createJsonErrorResponseHandler2({
11914
+ errorSchema: z.any(),
11915
+ errorToMessage: (data) => data
11916
+ }),
11917
+ ...abortSignal && { abortSignal },
11918
+ fetch: this.config.fetch
11919
+ });
11920
+ return {
11921
+ ranking: responseBody.ranking,
11922
+ providerMetadata: responseBody.providerMetadata,
11923
+ response: { headers: responseHeaders, body: rawValue },
11924
+ warnings: []
11925
+ };
11926
+ } catch (error) {
11927
+ throw await asGatewayError2(error, await parseAuthMethod2(resolvedHeaders));
11928
+ }
11929
+ }
11930
+ getUrl() {
11931
+ return `${this.config.baseURL}/reranking-model`;
11932
+ }
11933
+ getModelConfigHeaders() {
11934
+ return {
11935
+ "ai-reranking-model-specification-version": "3",
11936
+ "ai-model-id": this.modelId
11937
+ };
11938
+ }
11939
+ };
11940
+ var gatewayRerankingResponseSchema = lazySchema2(
11941
+ () => zodSchema3(
11942
+ z.object({
11943
+ ranking: z.array(
11944
+ z.object({
11945
+ index: z.number(),
11946
+ relevanceScore: z.number()
11947
+ })
11948
+ ),
11949
+ providerMetadata: z.record(z.string(), z.record(z.string(), z.unknown())).optional()
11950
+ })
11951
+ )
11952
+ );
11953
+ var parallelSearchInputSchema2 = lazySchema2(
11320
11954
  () => zodSchema3(
11321
11955
  z$1.object({
11322
11956
  objective: z$1.string().describe(
@@ -11352,7 +11986,7 @@ var parallelSearchInputSchema = lazySchema(
11352
11986
  })
11353
11987
  )
11354
11988
  );
11355
- var parallelSearchOutputSchema = lazySchema(
11989
+ var parallelSearchOutputSchema2 = lazySchema2(
11356
11990
  () => zodSchema3(
11357
11991
  z$1.union([
11358
11992
  // Success response
@@ -11384,13 +12018,13 @@ var parallelSearchOutputSchema = lazySchema(
11384
12018
  ])
11385
12019
  )
11386
12020
  );
11387
- var parallelSearchToolFactory = createProviderToolFactoryWithOutputSchema({
12021
+ var parallelSearchToolFactory2 = createProviderToolFactoryWithOutputSchema({
11388
12022
  id: "gateway.parallel_search",
11389
- inputSchema: parallelSearchInputSchema,
11390
- outputSchema: parallelSearchOutputSchema
12023
+ inputSchema: parallelSearchInputSchema2,
12024
+ outputSchema: parallelSearchOutputSchema2
11391
12025
  });
11392
- var parallelSearch = (config = {}) => parallelSearchToolFactory(config);
11393
- var perplexitySearchInputSchema = lazySchema(
12026
+ var parallelSearch2 = (config = {}) => parallelSearchToolFactory2(config);
12027
+ var perplexitySearchInputSchema2 = lazySchema2(
11394
12028
  () => zodSchema3(
11395
12029
  z$1.object({
11396
12030
  query: z$1.union([z$1.string(), z$1.array(z$1.string())]).describe(
@@ -11432,7 +12066,7 @@ var perplexitySearchInputSchema = lazySchema(
11432
12066
  })
11433
12067
  )
11434
12068
  );
11435
- var perplexitySearchOutputSchema = lazySchema(
12069
+ var perplexitySearchOutputSchema2 = lazySchema2(
11436
12070
  () => zodSchema3(
11437
12071
  z$1.union([
11438
12072
  // Success response
@@ -11463,13 +12097,13 @@ var perplexitySearchOutputSchema = lazySchema(
11463
12097
  ])
11464
12098
  )
11465
12099
  );
11466
- var perplexitySearchToolFactory = createProviderToolFactoryWithOutputSchema({
12100
+ var perplexitySearchToolFactory2 = createProviderToolFactoryWithOutputSchema({
11467
12101
  id: "gateway.perplexity_search",
11468
- inputSchema: perplexitySearchInputSchema,
11469
- outputSchema: perplexitySearchOutputSchema
12102
+ inputSchema: perplexitySearchInputSchema2,
12103
+ outputSchema: perplexitySearchOutputSchema2
11470
12104
  });
11471
- var perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);
11472
- var gatewayTools = {
12105
+ var perplexitySearch2 = (config = {}) => perplexitySearchToolFactory2(config);
12106
+ var gatewayTools2 = {
11473
12107
  /**
11474
12108
  * Search the web using Parallel AI's Search API for LLM-optimized excerpts.
11475
12109
  *
@@ -11478,7 +12112,7 @@ var gatewayTools = {
11478
12112
  * or complex queries. Supports different search types for depth vs
11479
12113
  * breadth tradeoffs.
11480
12114
  */
11481
- parallelSearch,
12115
+ parallelSearch: parallelSearch2,
11482
12116
  /**
11483
12117
  * Search the web using Perplexity's Search API for real-time information,
11484
12118
  * news, research papers, and articles.
@@ -11486,21 +12120,21 @@ var gatewayTools = {
11486
12120
  * Provides ranked search results with advanced filtering options including
11487
12121
  * domain, language, date range, and recency filters.
11488
12122
  */
11489
- perplexitySearch
12123
+ perplexitySearch: perplexitySearch2
11490
12124
  };
11491
12125
  async function getVercelRequestId2() {
11492
12126
  var _a932;
11493
- return (_a932 = (0, import_oidc3.getContext)().headers) == null ? void 0 : _a932["x-vercel-id"];
12127
+ return (_a932 = getContext2().headers) == null ? void 0 : _a932["x-vercel-id"];
11494
12128
  }
11495
- var VERSION5 = "3.0.66";
12129
+ var VERSION6 = "3.0.112";
11496
12130
  var AI_GATEWAY_PROTOCOL_VERSION2 = "0.0.1";
11497
12131
  function createGatewayProvider2(options = {}) {
11498
- var _a932, _b92;
12132
+ var _a932, _b93;
11499
12133
  let pendingMetadata = null;
11500
12134
  let metadataCache = null;
11501
12135
  const cacheRefreshMillis = (_a932 = options.metadataCacheRefreshMillis) != null ? _a932 : 1e3 * 60 * 5;
11502
12136
  let lastFetchTime = 0;
11503
- const baseURL = (_b92 = withoutTrailingSlash2(options.baseURL)) != null ? _b92 : "https://ai-gateway.vercel.sh/v3/ai";
12137
+ const baseURL = (_b93 = withoutTrailingSlash2(options.baseURL)) != null ? _b93 : "https://ai-gateway.vercel.sh/v3/ai";
11504
12138
  const getHeaders = async () => {
11505
12139
  try {
11506
12140
  const auth = await getGatewayAuthToken2(options);
@@ -11511,7 +12145,7 @@ function createGatewayProvider2(options = {}) {
11511
12145
  [GATEWAY_AUTH_METHOD_HEADER2]: auth.authMethod,
11512
12146
  ...options.headers
11513
12147
  },
11514
- `ai-sdk/gateway/${VERSION5}`
12148
+ `ai-sdk/gateway/${VERSION6}`
11515
12149
  );
11516
12150
  } catch (error) {
11517
12151
  throw GatewayAuthenticationError2.createContextualError({
@@ -11560,8 +12194,8 @@ function createGatewayProvider2(options = {}) {
11560
12194
  });
11561
12195
  };
11562
12196
  const getAvailableModels = async () => {
11563
- var _a1022, _b102, _c;
11564
- const now2 = (_c = (_b102 = (_a1022 = options._internal) == null ? void 0 : _a1022.currentDate) == null ? void 0 : _b102.call(_a1022).getTime()) != null ? _c : Date.now();
12197
+ var _a1022, _b103, _c;
12198
+ const now2 = (_c = (_b103 = (_a1022 = options._internal) == null ? void 0 : _a1022.currentDate) == null ? void 0 : _b103.call(_a1022).getTime()) != null ? _c : Date.now();
11565
12199
  if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) {
11566
12200
  lastFetchTime = now2;
11567
12201
  pendingMetadata = new GatewayFetchMetadata2({
@@ -11592,6 +12226,30 @@ function createGatewayProvider2(options = {}) {
11592
12226
  );
11593
12227
  });
11594
12228
  };
12229
+ const getSpendReport = async (params) => {
12230
+ return new GatewaySpendReport2({
12231
+ baseURL,
12232
+ headers: getHeaders,
12233
+ fetch: options.fetch
12234
+ }).getSpendReport(params).catch(async (error) => {
12235
+ throw await asGatewayError2(
12236
+ error,
12237
+ await parseAuthMethod2(await getHeaders())
12238
+ );
12239
+ });
12240
+ };
12241
+ const getGenerationInfo = async (params) => {
12242
+ return new GatewayGenerationInfoFetcher2({
12243
+ baseURL,
12244
+ headers: getHeaders,
12245
+ fetch: options.fetch
12246
+ }).getGenerationInfo(params).catch(async (error) => {
12247
+ throw await asGatewayError2(
12248
+ error,
12249
+ await parseAuthMethod2(await getHeaders())
12250
+ );
12251
+ });
12252
+ };
11595
12253
  const provider = function(modelId) {
11596
12254
  if (new.target) {
11597
12255
  throw new Error(
@@ -11603,6 +12261,8 @@ function createGatewayProvider2(options = {}) {
11603
12261
  provider.specificationVersion = "v3";
11604
12262
  provider.getAvailableModels = getAvailableModels;
11605
12263
  provider.getCredits = getCredits;
12264
+ provider.getSpendReport = getSpendReport;
12265
+ provider.getGenerationInfo = getGenerationInfo;
11606
12266
  provider.imageModel = (modelId) => {
11607
12267
  return new GatewayImageModel2(modelId, {
11608
12268
  provider: "gateway",
@@ -11633,11 +12293,22 @@ function createGatewayProvider2(options = {}) {
11633
12293
  o11yHeaders: createO11yHeaders()
11634
12294
  });
11635
12295
  };
12296
+ const createRerankingModel = (modelId) => {
12297
+ return new GatewayRerankingModel(modelId, {
12298
+ provider: "gateway",
12299
+ baseURL,
12300
+ headers: getHeaders,
12301
+ fetch: options.fetch,
12302
+ o11yHeaders: createO11yHeaders()
12303
+ });
12304
+ };
12305
+ provider.rerankingModel = createRerankingModel;
12306
+ provider.reranking = createRerankingModel;
11636
12307
  provider.chat = provider.languageModel;
11637
12308
  provider.embedding = provider.embeddingModel;
11638
12309
  provider.image = provider.imageModel;
11639
12310
  provider.video = provider.videoModel;
11640
- provider.tools = gatewayTools;
12311
+ provider.tools = gatewayTools2;
11641
12312
  return provider;
11642
12313
  }
11643
12314
  createGatewayProvider2();
@@ -11652,7 +12323,7 @@ async function getGatewayAuthToken2(options) {
11652
12323
  authMethod: "api-key"
11653
12324
  };
11654
12325
  }
11655
- const oidcToken = await (0, import_oidc22.getVercelOidcToken)();
12326
+ const oidcToken = await getVercelOidcToken2();
11656
12327
  return {
11657
12328
  token: oidcToken,
11658
12329
  authMethod: "oidc"
@@ -11751,12 +12422,12 @@ function registerGlobal3(type, instance, diag, allowOverride) {
11751
12422
  return true;
11752
12423
  }
11753
12424
  function getGlobal3(type) {
11754
- var _a21, _b92;
12425
+ var _a21, _b93;
11755
12426
  var globalVersion = (_a21 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _a21 === void 0 ? void 0 : _a21.version;
11756
12427
  if (!globalVersion || !isCompatible3(globalVersion)) {
11757
12428
  return;
11758
12429
  }
11759
- return (_b92 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _b92 === void 0 ? void 0 : _b92[type];
12430
+ return (_b93 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _b93 === void 0 ? void 0 : _b93[type];
11760
12431
  }
11761
12432
  function unregisterGlobal3(type, diag) {
11762
12433
  diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION23 + ".");
@@ -11921,7 +12592,7 @@ var DiagAPI3 = (
11921
12592
  }
11922
12593
  var self = this;
11923
12594
  var setLogger = function(logger, optionsOrLogLevel) {
11924
- var _a21, _b92, _c;
12595
+ var _a21, _b93, _c;
11925
12596
  if (optionsOrLogLevel === void 0) {
11926
12597
  optionsOrLogLevel = { logLevel: DiagLogLevel3.INFO };
11927
12598
  }
@@ -11936,7 +12607,7 @@ var DiagAPI3 = (
11936
12607
  };
11937
12608
  }
11938
12609
  var oldLogger = getGlobal3("diag");
11939
- var newLogger = createLogLevelDiagLogger3((_b92 = optionsOrLogLevel.logLevel) !== null && _b92 !== void 0 ? _b92 : DiagLogLevel3.INFO, logger);
12610
+ var newLogger = createLogLevelDiagLogger3((_b93 = optionsOrLogLevel.logLevel) !== null && _b93 !== void 0 ? _b93 : DiagLogLevel3.INFO, logger);
11940
12611
  if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
11941
12612
  var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
11942
12613
  oldLogger.warn("Current logger will be overwritten from " + stack);
@@ -12369,8 +13040,8 @@ var __export3 = (target, all) => {
12369
13040
  for (var name21 in all)
12370
13041
  __defProp4(target, name21, { get: all[name21], enumerable: true });
12371
13042
  };
12372
- var name822 = "AI_NoObjectGeneratedError";
12373
- var marker823 = `vercel.ai.error.${name822}`;
13043
+ var name823 = "AI_NoObjectGeneratedError";
13044
+ var marker823 = `vercel.ai.error.${name823}`;
12374
13045
  var symbol823 = Symbol.for(marker823);
12375
13046
  var _a823;
12376
13047
  var NoObjectGeneratedError3 = class extends AISDKError3 {
@@ -12382,7 +13053,7 @@ var NoObjectGeneratedError3 = class extends AISDKError3 {
12382
13053
  usage,
12383
13054
  finishReason
12384
13055
  }) {
12385
- super({ name: name822, message, cause });
13056
+ super({ name: name823, message, cause });
12386
13057
  this[_a823] = true;
12387
13058
  this.text = text22;
12388
13059
  this.response = response;
@@ -12615,8 +13286,8 @@ var dataContentSchema3 = z.union([
12615
13286
  z.custom(
12616
13287
  // Buffer might not be available in some environments such as CloudFlare:
12617
13288
  (value) => {
12618
- var _a21, _b92;
12619
- return (_b92 = (_a21 = globalThis.Buffer) == null ? void 0 : _a21.isBuffer(value)) != null ? _b92 : false;
13289
+ var _a21, _b93;
13290
+ return (_b93 = (_a21 = globalThis.Buffer) == null ? void 0 : _a21.isBuffer(value)) != null ? _b93 : false;
12620
13291
  },
12621
13292
  { message: "Must be a Buffer" }
12622
13293
  )
@@ -13463,10 +14134,18 @@ createIdGenerator3({
13463
14134
  prefix: "aitxt",
13464
14135
  size: 24
13465
14136
  });
14137
+ z.record(
14138
+ z.string(),
14139
+ jsonValueSchema3.optional()
14140
+ );
13466
14141
  createIdGenerator3({
13467
14142
  prefix: "aitxt",
13468
14143
  size: 24
13469
14144
  });
14145
+ z.record(
14146
+ z.string(),
14147
+ jsonValueSchema3.optional()
14148
+ );
13470
14149
  createIdGenerator3({ prefix: "aiobj", size: 24 });
13471
14150
  createIdGenerator3({ prefix: "aiobj", size: 24 });
13472
14151
  function asProviderV3(provider) {
@@ -13564,6 +14243,428 @@ function customProvider3({
13564
14243
  }
13565
14244
  };
13566
14245
  }
14246
+ var ExecutionProvider = /* @__PURE__ */ ((ExecutionProvider2) => {
14247
+ ExecutionProvider2["CPU"] = "cpu";
14248
+ ExecutionProvider2["CUDA"] = "cuda";
14249
+ ExecutionProvider2["WebGL"] = "webgl";
14250
+ ExecutionProvider2["WASM"] = "wasm";
14251
+ ExecutionProvider2["XNNPACK"] = "xnnpack";
14252
+ return ExecutionProvider2;
14253
+ })(ExecutionProvider || {});
14254
+ var EmbeddingModel = /* @__PURE__ */ ((EmbeddingModel2) => {
14255
+ EmbeddingModel2["AllMiniLML6V2"] = "fast-all-MiniLM-L6-v2";
14256
+ EmbeddingModel2["BGEBaseEN"] = "fast-bge-base-en";
14257
+ EmbeddingModel2["BGEBaseENV15"] = "fast-bge-base-en-v1.5";
14258
+ EmbeddingModel2["BGESmallEN"] = "fast-bge-small-en";
14259
+ EmbeddingModel2["BGESmallENV15"] = "fast-bge-small-en-v1.5";
14260
+ EmbeddingModel2["BGESmallZH"] = "fast-bge-small-zh-v1.5";
14261
+ EmbeddingModel2["MLE5Large"] = "fast-multilingual-e5-large";
14262
+ EmbeddingModel2["CUSTOM"] = "custom";
14263
+ return EmbeddingModel2;
14264
+ })(EmbeddingModel || {});
14265
+ var SparseEmbeddingModel = /* @__PURE__ */ ((SparseEmbeddingModel2) => {
14266
+ SparseEmbeddingModel2["SpladePPEnV1"] = "prithivida/Splade_PP_en_v1";
14267
+ SparseEmbeddingModel2["CUSTOM"] = "custom";
14268
+ return SparseEmbeddingModel2;
14269
+ })(SparseEmbeddingModel || {});
14270
+ function normalize(v) {
14271
+ const norm = Math.sqrt(v.reduce((acc, val) => acc + val * val, 0));
14272
+ const epsilon = 1e-12;
14273
+ return v.map((val) => val / Math.max(norm, epsilon));
14274
+ }
14275
+ function getEmbeddings(data, dimensions) {
14276
+ const [x2, _y, z5] = dimensions;
14277
+ return new Array(x2).fill(void 0).map((_, index) => {
14278
+ const startIndex = index * _y * z5;
14279
+ const endIndex = startIndex + z5;
14280
+ return data.slice(startIndex, endIndex);
14281
+ });
14282
+ }
14283
+ var Embedding = class {
14284
+ };
14285
+ var SparseEmbedding = class {
14286
+ };
14287
+ function isAddedTokenMap(token) {
14288
+ return typeof token === "object" && token !== null && "content" in token && "single_word" in token && "rstrip" in token && "lstrip" in token && "normalized" in token;
14289
+ }
14290
+ function loadTokenizerFromDir(modelDir, maxLength) {
14291
+ const tokenizerPath = path.join(modelDir.toString(), "tokenizer.json");
14292
+ if (!fs.existsSync(tokenizerPath)) {
14293
+ throw new Error(`Tokenizer file not found at ${tokenizerPath}`);
14294
+ }
14295
+ const configPath = path.join(modelDir.toString(), "config.json");
14296
+ if (!fs.existsSync(configPath)) {
14297
+ throw new Error(`Config file not found at ${configPath}`);
14298
+ }
14299
+ const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
14300
+ const tokenizerFilePath = path.join(modelDir.toString(), "tokenizer_config.json");
14301
+ if (!fs.existsSync(tokenizerFilePath)) {
14302
+ throw new Error(`Tokenizer config file not found at ${tokenizerFilePath}`);
14303
+ }
14304
+ const tokenizerConfig = JSON.parse(fs.readFileSync(tokenizerFilePath, "utf-8"));
14305
+ maxLength = Math.min(maxLength, tokenizerConfig["model_max_length"]);
14306
+ const tokensMapPath = path.join(modelDir.toString(), "special_tokens_map.json");
14307
+ if (!fs.existsSync(tokensMapPath)) {
14308
+ throw new Error(`Tokens map file not found at ${tokensMapPath}`);
14309
+ }
14310
+ const tokensMap = JSON.parse(fs.readFileSync(tokensMapPath, "utf-8"));
14311
+ const tokenizer = Tokenizer.fromFile(tokenizerPath);
14312
+ tokenizer.setTruncation(maxLength);
14313
+ tokenizer.setPadding({
14314
+ maxLength,
14315
+ padId: config["pad_token_id"],
14316
+ padToken: tokenizerConfig["pad_token"]
14317
+ });
14318
+ for (const token of Object.values(tokensMap)) {
14319
+ if (typeof token === "string") {
14320
+ tokenizer.addSpecialTokens([token]);
14321
+ } else if (isAddedTokenMap(token)) {
14322
+ const addedToken = new AddedToken(token["content"], true, {
14323
+ singleWord: token["single_word"],
14324
+ leftStrip: token["lstrip"],
14325
+ rightStrip: token["rstrip"],
14326
+ normalized: token["normalized"]
14327
+ });
14328
+ tokenizer.addAddedTokens([addedToken]);
14329
+ }
14330
+ }
14331
+ return tokenizer;
14332
+ }
14333
+ var FlagEmbedding = class _FlagEmbedding extends Embedding {
14334
+ constructor(tokenizer, session, model) {
14335
+ super();
14336
+ this.tokenizer = tokenizer;
14337
+ this.session = session;
14338
+ this.model = model;
14339
+ }
14340
+ static async init({
14341
+ model = "fast-bge-small-en-v1.5" /* BGESmallENV15 */,
14342
+ executionProviders = ["cpu" /* CPU */],
14343
+ maxLength = 512,
14344
+ cacheDir = "local_cache",
14345
+ showDownloadProgress = true,
14346
+ modelAbsoluteDirPath = "",
14347
+ modelName = ""
14348
+ } = {}) {
14349
+ if (model === "custom" /* CUSTOM */) {
14350
+ if (!modelAbsoluteDirPath) {
14351
+ throw new Error("For custom model, modelAbsoluteDirPath is required in FlagEmbedding.init");
14352
+ }
14353
+ if (!modelName) {
14354
+ throw new Error("For custom model, modelName is required in FlagEmbedding.init");
14355
+ }
14356
+ }
14357
+ const modelDir = model === "custom" /* CUSTOM */ ? modelAbsoluteDirPath : await _FlagEmbedding.retrieveModel(model, cacheDir, showDownloadProgress);
14358
+ const tokenizer = loadTokenizerFromDir(modelDir, maxLength);
14359
+ const defaultModelName = model === "fast-multilingual-e5-large" /* MLE5Large */ || model === "fast-all-MiniLM-L6-v2" /* AllMiniLML6V2 */ ? "model.onnx" : "model_optimized.onnx";
14360
+ const modelPath = path.join(modelDir.toString(), modelName || defaultModelName);
14361
+ if (!fs.existsSync(modelPath)) {
14362
+ throw new Error(`Model file not found at ${modelPath}`);
14363
+ }
14364
+ const session = await ort.InferenceSession.create(modelPath, {
14365
+ executionProviders,
14366
+ graphOptimizationLevel: "all"
14367
+ });
14368
+ return new _FlagEmbedding(tokenizer, session, model);
14369
+ }
14370
+ static async downloadFileFromGCS(outputFilePath, model, showDownloadProgress = true) {
14371
+ if (fs.existsSync(outputFilePath)) {
14372
+ return outputFilePath;
14373
+ }
14374
+ if (model === "fast-all-MiniLM-L6-v2" /* AllMiniLML6V2 */) {
14375
+ model = "sentence-transformers" + model.substring(model.indexOf("-"));
14376
+ }
14377
+ const url = `https://storage.googleapis.com/qdrant-fastembed/${model}.tar.gz`;
14378
+ const fileStream = fs.createWriteStream(outputFilePath);
14379
+ return new Promise((resolve3, reject) => {
14380
+ https.get(url, { headers: { "User-Agent": "Mozilla/5.0" } }, (response) => {
14381
+ const status = response.statusCode ?? 0;
14382
+ if (status < 200 || status >= 300) {
14383
+ response.resume();
14384
+ reject(new Error(`Failed to download ${model}: HTTP ${status}`));
14385
+ return;
14386
+ }
14387
+ const totalSizeInBytes = parseInt(response.headers["content-length"] || "0", 10);
14388
+ if (totalSizeInBytes === 0) {
14389
+ console.warn(`Warning: Content-length header is missing or zero in the response from ${url}.`);
14390
+ }
14391
+ if (showDownloadProgress) {
14392
+ const progressBar = new Progress(`Downloading ${model} [:bar] :percent :etas`, {
14393
+ complete: "=",
14394
+ width: 20,
14395
+ total: totalSizeInBytes
14396
+ });
14397
+ response.on("data", (chunk) => {
14398
+ progressBar.tick(chunk.length, { speed: "N/A" });
14399
+ });
14400
+ }
14401
+ response.on("error", (error) => {
14402
+ reject(error);
14403
+ });
14404
+ response.pipe(fileStream);
14405
+ fileStream.on("finish", () => {
14406
+ fileStream.close();
14407
+ resolve3(outputFilePath);
14408
+ });
14409
+ fileStream.on("error", (error) => {
14410
+ reject(error);
14411
+ });
14412
+ }).on("error", (error) => {
14413
+ fs.unlink(outputFilePath, () => {
14414
+ reject(error);
14415
+ });
14416
+ });
14417
+ });
14418
+ }
14419
+ static async decompressToCache(targzPath, cacheDir) {
14420
+ if (path.extname(targzPath.toString()) === ".gz") {
14421
+ await tar.x({
14422
+ file: targzPath.toString(),
14423
+ cwd: cacheDir.toString()
14424
+ });
14425
+ } else {
14426
+ throw new Error(`Unsupported file extension: ${targzPath}`);
14427
+ }
14428
+ }
14429
+ static async retrieveModel(model, cacheDir, showDownloadProgress = true) {
14430
+ if (!fs.existsSync(cacheDir)) {
14431
+ fs.mkdirSync(cacheDir, { mode: 493 });
14432
+ }
14433
+ const modelDir = path.join(cacheDir.toString(), model);
14434
+ if (fs.existsSync(modelDir)) {
14435
+ return modelDir;
14436
+ }
14437
+ const modelTarGz = path.join(cacheDir.toString(), `${model}.tar.gz`);
14438
+ await this.downloadFileFromGCS(modelTarGz, model, showDownloadProgress);
14439
+ await this.decompressToCache(modelTarGz, cacheDir);
14440
+ fs.unlinkSync(modelTarGz);
14441
+ return modelDir;
14442
+ }
14443
+ async *embed(textStrings, batchSize = 256) {
14444
+ for (let i = 0; i < textStrings.length; i += batchSize) {
14445
+ const batchTexts = textStrings.slice(i, i + batchSize);
14446
+ const encodedTexts = await Promise.all(batchTexts.map((textString) => this.tokenizer.encode(textString)));
14447
+ const idsArray = [];
14448
+ const maskArray = [];
14449
+ const typeIdsArray = [];
14450
+ encodedTexts.forEach((text4) => {
14451
+ const ids = text4.getIds().map(BigInt);
14452
+ const mask = text4.getAttentionMask().map(BigInt);
14453
+ const typeIds = text4.getTypeIds().map(BigInt);
14454
+ idsArray.push(ids);
14455
+ maskArray.push(mask);
14456
+ typeIdsArray.push(typeIds);
14457
+ });
14458
+ const maxLength = idsArray[0].length;
14459
+ const batchInputIds = new ort.Tensor("int64", idsArray.flat(), [
14460
+ batchTexts.length,
14461
+ maxLength
14462
+ ]);
14463
+ const batchAttentionMask = new ort.Tensor("int64", maskArray.flat(), [
14464
+ batchTexts.length,
14465
+ maxLength
14466
+ ]);
14467
+ const batchTokenTypeId = new ort.Tensor("int64", typeIdsArray.flat(), [
14468
+ batchTexts.length,
14469
+ maxLength
14470
+ ]);
14471
+ const inputs = {
14472
+ input_ids: batchInputIds,
14473
+ attention_mask: batchAttentionMask,
14474
+ token_type_ids: batchTokenTypeId
14475
+ };
14476
+ if (this.model === "fast-multilingual-e5-large" /* MLE5Large */) {
14477
+ delete inputs.token_type_ids;
14478
+ }
14479
+ const output = await this.session.run(inputs);
14480
+ const lastHiddenState = output.last_hidden_state;
14481
+ const embeddings = getEmbeddings(
14482
+ lastHiddenState.data,
14483
+ lastHiddenState.dims
14484
+ );
14485
+ yield embeddings.map(normalize);
14486
+ }
14487
+ }
14488
+ passageEmbed(texts, batchSize = 256) {
14489
+ texts = texts.map((text4) => `passage: ${text4}`);
14490
+ return this.embed(texts, batchSize);
14491
+ }
14492
+ async queryEmbed(query) {
14493
+ const result = await this.embed([`query: ${query}`]).next();
14494
+ return result.value[0];
14495
+ }
14496
+ listSupportedModels() {
14497
+ return [
14498
+ { model: "fast-bge-small-en" /* BGESmallEN */, dim: 384, description: "Fast English model" },
14499
+ { model: "fast-bge-small-en-v1.5" /* BGESmallENV15 */, dim: 384, description: "v1.5 release of the fast, default English model" },
14500
+ { model: "fast-bge-base-en" /* BGEBaseEN */, dim: 768, description: "Base English model" },
14501
+ { model: "fast-bge-base-en-v1.5" /* BGEBaseENV15 */, dim: 768, description: "v1.5 release of Base English model" },
14502
+ { model: "fast-bge-small-zh-v1.5" /* BGESmallZH */, dim: 512, description: "v1.5 release of the fast, Chinese model" },
14503
+ { model: "fast-all-MiniLM-L6-v2" /* AllMiniLML6V2 */, dim: 384, description: "Sentence Transformer model, MiniLM-L6-v2" },
14504
+ {
14505
+ model: "fast-multilingual-e5-large" /* MLE5Large */,
14506
+ dim: 1024,
14507
+ description: "Multilingual model, e5-large. Recommend using this model for non-English languages"
14508
+ }
14509
+ ];
14510
+ }
14511
+ };
14512
+ var SparseTextEmbedding = class _SparseTextEmbedding extends SparseEmbedding {
14513
+ constructor(tokenizer, session) {
14514
+ super();
14515
+ this.tokenizer = tokenizer;
14516
+ this.session = session;
14517
+ }
14518
+ static async init({
14519
+ model = "prithivida/Splade_PP_en_v1" /* SpladePPEnV1 */,
14520
+ executionProviders = ["cpu" /* CPU */],
14521
+ maxLength = 512,
14522
+ cacheDir = "local_cache",
14523
+ showDownloadProgress = true,
14524
+ modelAbsoluteDirPath = "",
14525
+ modelName = ""
14526
+ } = {}) {
14527
+ if (model === "custom" /* CUSTOM */) {
14528
+ if (!modelAbsoluteDirPath) {
14529
+ throw new Error("For custom model, modelAbsoluteDirPath is required in SparseTextEmbedding.init");
14530
+ }
14531
+ if (!modelName) {
14532
+ throw new Error("For custom model, modelName is required in SparseTextEmbedding.init");
14533
+ }
14534
+ }
14535
+ const modelDir = model === "custom" /* CUSTOM */ ? modelAbsoluteDirPath : await _SparseTextEmbedding.retrieveModel(model, cacheDir, showDownloadProgress);
14536
+ const { tokenizer } = this.loadTokenizer(modelDir, maxLength);
14537
+ const defaultModelName = "model.onnx";
14538
+ const modelPath = path.join(modelDir.toString(), "onnx", modelName || defaultModelName);
14539
+ if (!fs.existsSync(modelPath)) {
14540
+ throw new Error(`Model file not found at ${modelPath}`);
14541
+ }
14542
+ const session = await ort.InferenceSession.create(modelPath, {
14543
+ executionProviders,
14544
+ graphOptimizationLevel: "all"
14545
+ });
14546
+ return new _SparseTextEmbedding(tokenizer, session);
14547
+ }
14548
+ static loadTokenizer(modelDir, maxLength) {
14549
+ const tokenizer = loadTokenizerFromDir(modelDir, maxLength);
14550
+ return { tokenizer };
14551
+ }
14552
+ static async retrieveModel(model, cacheDir, _showDownloadProgress = true) {
14553
+ if (!fs.existsSync(cacheDir)) {
14554
+ fs.mkdirSync(cacheDir, { mode: 493 });
14555
+ }
14556
+ const modelDir = path.join(cacheDir.toString(), model.replace("/", "_"));
14557
+ if (fs.existsSync(modelDir)) {
14558
+ return modelDir;
14559
+ }
14560
+ fs.mkdirSync(modelDir, { mode: 493 });
14561
+ const filesToDownload = [
14562
+ "onnx/model.onnx",
14563
+ "tokenizer.json",
14564
+ "tokenizer_config.json",
14565
+ "config.json",
14566
+ "special_tokens_map.json"
14567
+ ];
14568
+ for (const fileName of filesToDownload) {
14569
+ const outputPath = path.join(modelDir, fileName);
14570
+ const outputDir = path.dirname(outputPath);
14571
+ if (!fs.existsSync(outputDir)) {
14572
+ fs.mkdirSync(outputDir, { recursive: true, mode: 493 });
14573
+ }
14574
+ const downloaded = await downloadFileToCacheDir({
14575
+ repo: model,
14576
+ path: fileName
14577
+ });
14578
+ if (downloaded && typeof downloaded === "string") {
14579
+ fs.copyFileSync(downloaded, outputPath);
14580
+ }
14581
+ }
14582
+ return modelDir;
14583
+ }
14584
+ async *embed(textStrings, batchSize = 256) {
14585
+ for (let i = 0; i < textStrings.length; i += batchSize) {
14586
+ const batchTexts = textStrings.slice(i, i + batchSize);
14587
+ const encodedTexts = await Promise.all(batchTexts.map((textString) => this.tokenizer.encode(textString)));
14588
+ const idsArray = [];
14589
+ const maskArray = [];
14590
+ const typeIdsArray = [];
14591
+ encodedTexts.forEach((text4) => {
14592
+ const ids = text4.getIds().map(BigInt);
14593
+ const mask = text4.getAttentionMask();
14594
+ const typeIds = text4.getTypeIds().map(BigInt);
14595
+ idsArray.push(ids);
14596
+ maskArray.push(mask);
14597
+ typeIdsArray.push(typeIds);
14598
+ });
14599
+ const maxLength = idsArray[0].length;
14600
+ const batchInputIds = new ort.Tensor("int64", idsArray.flat(), [
14601
+ batchTexts.length,
14602
+ maxLength
14603
+ ]);
14604
+ const batchAttentionMask = new ort.Tensor("int64", maskArray.flat().map(BigInt), [
14605
+ batchTexts.length,
14606
+ maxLength
14607
+ ]);
14608
+ const batchTokenTypeId = new ort.Tensor("int64", typeIdsArray.flat(), [
14609
+ batchTexts.length,
14610
+ maxLength
14611
+ ]);
14612
+ const inputs = {
14613
+ input_ids: batchInputIds,
14614
+ input_mask: batchAttentionMask,
14615
+ segment_ids: batchTokenTypeId
14616
+ };
14617
+ const output = await this.session.run(inputs);
14618
+ const outputTensor = output.output;
14619
+ const logits = outputTensor.cpuData;
14620
+ const dims = outputTensor.dims;
14621
+ const [currentBatchSize, seqLen, currentVocabSize] = dims;
14622
+ const sparseVectors = [];
14623
+ for (let batchIdx = 0; batchIdx < currentBatchSize; batchIdx++) {
14624
+ const valuesArr = new Float32Array(currentVocabSize).fill(0);
14625
+ for (let seqIdx = 0; seqIdx < seqLen; seqIdx++) {
14626
+ const attentionValue = maskArray[batchIdx][seqIdx];
14627
+ if (attentionValue > 0) {
14628
+ for (let vocabIdx = 0; vocabIdx < currentVocabSize; vocabIdx++) {
14629
+ const logitIdx = batchIdx * seqLen * currentVocabSize + seqIdx * currentVocabSize + vocabIdx;
14630
+ const logitValue = logits[logitIdx];
14631
+ const reluValue = Math.max(0, logitValue);
14632
+ const logValue = Math.log(1 + reluValue);
14633
+ valuesArr[vocabIdx] = Math.max(valuesArr[vocabIdx], logValue);
14634
+ }
14635
+ }
14636
+ }
14637
+ const sparseVector = { values: [], indices: [] };
14638
+ for (let tokenId = 0; tokenId < currentVocabSize; tokenId++) {
14639
+ if (valuesArr[tokenId] > 0) {
14640
+ sparseVector.indices.push(tokenId);
14641
+ sparseVector.values.push(valuesArr[tokenId]);
14642
+ }
14643
+ }
14644
+ sparseVectors.push(sparseVector);
14645
+ }
14646
+ yield sparseVectors;
14647
+ }
14648
+ }
14649
+ passageEmbed(texts, batchSize = 256) {
14650
+ return this.embed(texts, batchSize);
14651
+ }
14652
+ async queryEmbed(query) {
14653
+ const result = await this.embed([query]).next();
14654
+ return result.value[0];
14655
+ }
14656
+ listSupportedModels() {
14657
+ return [
14658
+ {
14659
+ model: "prithivida/Splade_PP_en_v1" /* SpladePPEnV1 */,
14660
+ vocabSize: 30522,
14661
+ description: "SPLADE++ English model for sparse retrieval"
14662
+ }
14663
+ ];
14664
+ }
14665
+ };
14666
+
14667
+ // src/index.ts
13567
14668
  async function getModelCachePath() {
13568
14669
  const cachePath = path.join(os.homedir(), ".cache", "mastra", "fastembed-models");
13569
14670
  await fsp.mkdir(cachePath, { recursive: true });
@@ -13571,9 +14672,8 @@ async function getModelCachePath() {
13571
14672
  }
13572
14673
  async function warmup() {
13573
14674
  const cacheDir = await getModelCachePath();
13574
- const retrieve = FlagEmbedding.retrieveModel.bind(FlagEmbedding);
13575
- await retrieve(EmbeddingModel.BGESmallENV15, cacheDir, false);
13576
- await retrieve(EmbeddingModel.BGEBaseENV15, cacheDir, false);
14675
+ await FlagEmbedding.retrieveModel("fast-bge-small-en-v1.5" /* BGESmallENV15 */, cacheDir, false);
14676
+ await FlagEmbedding.retrieveModel("fast-bge-base-en-v1.5" /* BGEBaseENV15 */, cacheDir, false);
13577
14677
  }
13578
14678
  async function generateEmbeddings(values, modelType) {
13579
14679
  const model = await FlagEmbedding.init({
@@ -13673,6 +14773,6 @@ var fastembed = Object.assign(fastEmbedProviderV3.embeddingModel(`bge-small-en-v
13673
14773
  baseLegacy: fastEmbedLegacyProvider.textEmbeddingModel(`bge-base-en-v1.5`)
13674
14774
  });
13675
14775
 
13676
- export { fastembed, warmup };
14776
+ export { EmbeddingModel, ExecutionProvider, FlagEmbedding, SparseEmbeddingModel, SparseTextEmbedding, fastembed, warmup };
13677
14777
  //# sourceMappingURL=index.js.map
13678
14778
  //# sourceMappingURL=index.js.map