@mastra/ai-sdk 1.4.1 → 1.4.2-alpha.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 (49) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/_types/@internal_ai-sdk-v5/dist/index.d.ts +425 -1757
  3. package/dist/_types/@internal_ai-v6/dist/index.d.ts +311 -1772
  4. package/dist/helpers.d.ts.map +1 -1
  5. package/dist/index.cjs +895 -440
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.js +895 -440
  8. package/dist/index.js.map +1 -1
  9. package/dist/ui.cjs +1 -0
  10. package/dist/ui.cjs.map +1 -1
  11. package/dist/ui.js +1 -0
  12. package/dist/ui.js.map +1 -1
  13. package/package.json +14 -14
  14. package/dist/chunk-3YJ25IUJ.js +0 -79
  15. package/dist/chunk-3YJ25IUJ.js.map +0 -1
  16. package/dist/chunk-DGUM43GV.js +0 -10
  17. package/dist/chunk-DGUM43GV.js.map +0 -1
  18. package/dist/chunk-HDI4ZP7N.js +0 -79
  19. package/dist/chunk-HDI4ZP7N.js.map +0 -1
  20. package/dist/chunk-HMOX24BQ.js +0 -439
  21. package/dist/chunk-HMOX24BQ.js.map +0 -1
  22. package/dist/chunk-IV3RKEE4.js +0 -439
  23. package/dist/chunk-IV3RKEE4.js.map +0 -1
  24. package/dist/chunk-JEQ2X3Z6.cjs +0 -12
  25. package/dist/chunk-JEQ2X3Z6.cjs.map +0 -1
  26. package/dist/chunk-PEZAMDZJ.cjs +0 -84
  27. package/dist/chunk-PEZAMDZJ.cjs.map +0 -1
  28. package/dist/chunk-VJW66KXQ.cjs +0 -441
  29. package/dist/chunk-VJW66KXQ.cjs.map +0 -1
  30. package/dist/chunk-WFARZCDO.cjs +0 -84
  31. package/dist/chunk-WFARZCDO.cjs.map +0 -1
  32. package/dist/chunk-X72VW7EY.cjs +0 -441
  33. package/dist/chunk-X72VW7EY.cjs.map +0 -1
  34. package/dist/token-APYSY3BW-CBIBV5F2.js +0 -61
  35. package/dist/token-APYSY3BW-CBIBV5F2.js.map +0 -1
  36. package/dist/token-APYSY3BW-INR55PKP.js +0 -61
  37. package/dist/token-APYSY3BW-INR55PKP.js.map +0 -1
  38. package/dist/token-APYSY3BW-M2K6HVOG.cjs +0 -63
  39. package/dist/token-APYSY3BW-M2K6HVOG.cjs.map +0 -1
  40. package/dist/token-APYSY3BW-Y5VD4L7Z.cjs +0 -63
  41. package/dist/token-APYSY3BW-Y5VD4L7Z.cjs.map +0 -1
  42. package/dist/token-util-RMHT2CPJ-3LCBPXJ6.cjs +0 -10
  43. package/dist/token-util-RMHT2CPJ-3LCBPXJ6.cjs.map +0 -1
  44. package/dist/token-util-RMHT2CPJ-4YTBAZ23.cjs +0 -10
  45. package/dist/token-util-RMHT2CPJ-4YTBAZ23.cjs.map +0 -1
  46. package/dist/token-util-RMHT2CPJ-HCMQIDTV.js +0 -8
  47. package/dist/token-util-RMHT2CPJ-HCMQIDTV.js.map +0 -1
  48. package/dist/token-util-RMHT2CPJ-IOKQM5O3.js +0 -8
  49. package/dist/token-util-RMHT2CPJ-IOKQM5O3.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- var chunkWFARZCDO_cjs = require('./chunk-WFARZCDO.cjs');
4
- var chunkPEZAMDZJ_cjs = require('./chunk-PEZAMDZJ.cjs');
5
3
  var z4 = require('zod/v4');
6
4
  var v3 = require('zod/v3');
7
5
  var zod = require('zod');
@@ -32,6 +30,7 @@ function _interopNamespace(e) {
32
30
 
33
31
  var z4__namespace = /*#__PURE__*/_interopNamespace(z4);
34
32
 
33
+ // ../../packages/_vendored/ai_v5/dist/chunk-UDIOFQR2.js
35
34
  var marker = "vercel.ai.error";
36
35
  var symbol = Symbol.for(marker);
37
36
  var _a;
@@ -210,6 +209,9 @@ var ParseError = class extends Error {
210
209
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
211
210
  }
212
211
  };
212
+ var LF = 10;
213
+ var CR = 13;
214
+ var SPACE = 32;
213
215
  function noop(_arg) {
214
216
  }
215
217
  function createParser(callbacks) {
@@ -217,39 +219,109 @@ function createParser(callbacks) {
217
219
  throw new TypeError(
218
220
  "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
219
221
  );
220
- const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
221
- let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
222
- function feed(newChunk) {
223
- const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
224
- for (const line of complete)
225
- parseLine(line);
226
- incompleteLine = incomplete, isFirstChunk = false;
227
- }
228
- function parseLine(line) {
229
- if (line === "") {
222
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];
223
+ let isFirstChunk = true, id, data = "", dataLines = 0, eventType;
224
+ function feed(chunk) {
225
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
226
+ const trailing2 = processLines(chunk);
227
+ trailing2 !== "" && pendingFragments.push(trailing2);
228
+ return;
229
+ }
230
+ if (chunk.indexOf(`
231
+ `) === -1 && chunk.indexOf("\r") === -1) {
232
+ pendingFragments.push(chunk);
233
+ return;
234
+ }
235
+ pendingFragments.push(chunk);
236
+ const input = pendingFragments.join("");
237
+ pendingFragments.length = 0;
238
+ const trailing = processLines(input);
239
+ trailing !== "" && pendingFragments.push(trailing);
240
+ }
241
+ function processLines(chunk) {
242
+ let searchIndex = 0;
243
+ if (chunk.indexOf("\r") === -1) {
244
+ let lfIndex = chunk.indexOf(`
245
+ `, searchIndex);
246
+ for (; lfIndex !== -1; ) {
247
+ if (searchIndex === lfIndex) {
248
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
249
+ `, searchIndex);
250
+ continue;
251
+ }
252
+ const firstCharCode = chunk.charCodeAt(searchIndex);
253
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
254
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
255
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
256
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
257
+ `, searchIndex);
258
+ continue;
259
+ }
260
+ data = dataLines === 0 ? value : `${data}
261
+ ${value}`, dataLines++;
262
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
263
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
264
+ lfIndex
265
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
266
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
267
+ `, searchIndex);
268
+ }
269
+ return chunk.slice(searchIndex);
270
+ }
271
+ for (; searchIndex < chunk.length; ) {
272
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
273
+ `, searchIndex);
274
+ let lineEnd = -1;
275
+ 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)
276
+ break;
277
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
278
+ }
279
+ return chunk.slice(searchIndex);
280
+ }
281
+ function parseLine(chunk, start, end) {
282
+ if (start === end) {
230
283
  dispatchEvent();
231
284
  return;
232
285
  }
233
- if (line.startsWith(":")) {
234
- onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
286
+ const firstCharCode = chunk.charCodeAt(start);
287
+ if (isDataPrefix(chunk, start, firstCharCode)) {
288
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
289
+ data = dataLines === 0 ? value2 : `${data}
290
+ ${value2}`, dataLines++;
291
+ return;
292
+ }
293
+ if (isEventPrefix(chunk, start, firstCharCode)) {
294
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
295
+ return;
296
+ }
297
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
298
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
299
+ id = value2.includes("\0") ? void 0 : value2;
300
+ return;
301
+ }
302
+ if (firstCharCode === 58) {
303
+ if (onComment) {
304
+ const line2 = chunk.slice(start, end);
305
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
306
+ }
235
307
  return;
236
308
  }
237
- const fieldSeparatorIndex = line.indexOf(":");
238
- if (fieldSeparatorIndex !== -1) {
239
- const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
240
- processField(field, value, line);
309
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
310
+ if (fieldSeparatorIndex === -1) {
311
+ processField(line, "", line);
241
312
  return;
242
313
  }
243
- processField(line, "", line);
314
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
315
+ processField(field, value, line);
244
316
  }
245
317
  function processField(field, value, line) {
246
318
  switch (field) {
247
319
  case "event":
248
- eventType = value;
320
+ eventType = value || void 0;
249
321
  break;
250
322
  case "data":
251
- data = `${data}${value}
252
- `;
323
+ data = dataLines === 0 ? value : `${data}
324
+ ${value}`, dataLines++;
253
325
  break;
254
326
  case "id":
255
327
  id = value.includes("\0") ? void 0 : value;
@@ -274,37 +346,26 @@ function createParser(callbacks) {
274
346
  }
275
347
  }
276
348
  function dispatchEvent() {
277
- data.length > 0 && onEvent({
349
+ dataLines > 0 && onEvent({
278
350
  id,
279
- event: eventType || void 0,
280
- // If the data buffer's last character is a U+000A LINE FEED (LF) character,
281
- // then remove the last character from the data buffer.
282
- data: data.endsWith(`
283
- `) ? data.slice(0, -1) : data
284
- }), id = void 0, data = "", eventType = "";
351
+ event: eventType,
352
+ data
353
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
285
354
  }
286
355
  function reset(options = {}) {
287
- incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
356
+ if (options.consume && pendingFragments.length > 0) {
357
+ const incompleteLine = pendingFragments.join("");
358
+ parseLine(incompleteLine, 0, incompleteLine.length);
359
+ }
360
+ isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0;
288
361
  }
289
362
  return { feed, reset };
290
363
  }
291
- function splitLines(chunk) {
292
- const lines = [];
293
- let incompleteLine = "", searchIndex = 0;
294
- for (; searchIndex < chunk.length; ) {
295
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
296
- `, searchIndex);
297
- let lineEnd = -1;
298
- 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) {
299
- incompleteLine = chunk.slice(searchIndex);
300
- break;
301
- } else {
302
- const line = chunk.slice(searchIndex, lineEnd);
303
- lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
304
- ` && searchIndex++;
305
- }
306
- }
307
- return [lines, incompleteLine];
364
+ function isDataPrefix(chunk, i, firstCharCode) {
365
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
366
+ }
367
+ function isEventPrefix(chunk, i, firstCharCode) {
368
+ 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;
308
369
  }
309
370
  var EventSourceParserStream = class extends TransformStream {
310
371
  constructor({ onError, onRetry, onComment } = {}) {
@@ -452,7 +513,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
452
513
  );
453
514
  return Object.fromEntries(normalizedHeaders.entries());
454
515
  }
455
- var VERSION = "3.0.22";
516
+ var VERSION = "3.0.25";
456
517
  var getOriginalFetch = () => globalThis.fetch;
457
518
  var getFromApi = async ({
458
519
  url,
@@ -921,6 +982,33 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
921
982
  rawValue: parsedResult.rawValue
922
983
  };
923
984
  };
985
+ var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
986
+ function lazySchema(createSchema) {
987
+ let schema;
988
+ return () => {
989
+ if (schema == null) {
990
+ schema = createSchema();
991
+ }
992
+ return schema;
993
+ };
994
+ }
995
+ function jsonSchema(jsonSchema22, {
996
+ validate
997
+ } = {}) {
998
+ return {
999
+ [schemaSymbol]: true,
1000
+ _type: void 0,
1001
+ // should never be used directly
1002
+ [validatorSymbol]: true,
1003
+ get jsonSchema() {
1004
+ if (typeof jsonSchema22 === "function") {
1005
+ jsonSchema22 = jsonSchema22();
1006
+ }
1007
+ return jsonSchema22;
1008
+ },
1009
+ validate
1010
+ };
1011
+ }
924
1012
  function addAdditionalPropertiesToJsonSchema(jsonSchema22) {
925
1013
  if (jsonSchema22.type === "object") {
926
1014
  jsonSchema22.additionalProperties = false;
@@ -946,13 +1034,6 @@ function addAdditionalPropertiesToJsonSchema(jsonSchema22) {
946
1034
  }
947
1035
  return jsonSchema22;
948
1036
  }
949
- var getRelativePath = (pathA, pathB) => {
950
- let i = 0;
951
- for (; i < pathA.length && i < pathB.length; i++) {
952
- if (pathA[i] !== pathB[i]) break;
953
- }
954
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
955
- };
956
1037
  var ignoreOverride = /* @__PURE__ */ Symbol(
957
1038
  "Let zodToJsonSchema decide on which parser to use"
958
1039
  );
@@ -1896,6 +1977,13 @@ var selectParser = (def, typeName, refs) => {
1896
1977
  return /* @__PURE__ */ ((_) => void 0)();
1897
1978
  }
1898
1979
  };
1980
+ var getRelativePath = (pathA, pathB) => {
1981
+ let i = 0;
1982
+ for (; i < pathA.length && i < pathB.length; i++) {
1983
+ if (pathA[i] !== pathB[i]) break;
1984
+ }
1985
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1986
+ };
1899
1987
  function parseDef(def, refs, forceResolution = false) {
1900
1988
  var _a224;
1901
1989
  const seenItem = refs.seen.get(def);
@@ -2075,33 +2163,6 @@ function zodSchema(zodSchema22, options) {
2075
2163
  return zod3Schema(zodSchema22);
2076
2164
  }
2077
2165
  }
2078
- var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
2079
- function lazySchema(createSchema) {
2080
- let schema;
2081
- return () => {
2082
- if (schema == null) {
2083
- schema = createSchema();
2084
- }
2085
- return schema;
2086
- };
2087
- }
2088
- function jsonSchema(jsonSchema22, {
2089
- validate
2090
- } = {}) {
2091
- return {
2092
- [schemaSymbol]: true,
2093
- _type: void 0,
2094
- // should never be used directly
2095
- [validatorSymbol]: true,
2096
- get jsonSchema() {
2097
- if (typeof jsonSchema22 === "function") {
2098
- jsonSchema22 = jsonSchema22();
2099
- }
2100
- return jsonSchema22;
2101
- },
2102
- validate
2103
- };
2104
- }
2105
2166
  function isSchema(value) {
2106
2167
  return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2107
2168
  }
@@ -2114,138 +2175,17 @@ function asSchema(schema) {
2114
2175
  function withoutTrailingSlash(url) {
2115
2176
  return url == null ? void 0 : url.replace(/\/$/, "");
2116
2177
  }
2117
- var require_get_context = chunkWFARZCDO_cjs.__commonJS({
2118
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-context.js"(exports$1, module) {
2119
- var __defProp22 = Object.defineProperty;
2120
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2121
- var __getOwnPropNames = Object.getOwnPropertyNames;
2122
- var __hasOwnProp = Object.prototype.hasOwnProperty;
2123
- var __export22 = (target, all) => {
2124
- for (var name163 in all)
2125
- __defProp22(target, name163, { get: all[name163], enumerable: true });
2126
- };
2127
- var __copyProps = (to, from, except, desc) => {
2128
- if (from && typeof from === "object" || typeof from === "function") {
2129
- for (let key of __getOwnPropNames(from))
2130
- if (!__hasOwnProp.call(to, key) && key !== except)
2131
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2132
- }
2133
- return to;
2134
- };
2135
- var __toCommonJS = (mod) => __copyProps(__defProp22({}, "__esModule", { value: true }), mod);
2136
- var get_context_exports = {};
2137
- __export22(get_context_exports, {
2138
- SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
2139
- getContext: () => getContext3
2140
- });
2141
- module.exports = __toCommonJS(get_context_exports);
2142
- var SYMBOL_FOR_REQ_CONTEXT = /* @__PURE__ */ Symbol.for("@vercel/request-context");
2143
- function getContext3() {
2144
- const fromSymbol = globalThis;
2145
- return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
2146
- }
2147
- }
2148
- });
2149
- var require_get_vercel_oidc_token = chunkWFARZCDO_cjs.__commonJS({
2150
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports$1, module) {
2151
- var __defProp22 = Object.defineProperty;
2152
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2153
- var __getOwnPropNames = Object.getOwnPropertyNames;
2154
- var __hasOwnProp = Object.prototype.hasOwnProperty;
2155
- var __export22 = (target, all) => {
2156
- for (var name163 in all)
2157
- __defProp22(target, name163, { get: all[name163], enumerable: true });
2158
- };
2159
- var __copyProps = (to, from, except, desc) => {
2160
- if (from && typeof from === "object" || typeof from === "function") {
2161
- for (let key of __getOwnPropNames(from))
2162
- if (!__hasOwnProp.call(to, key) && key !== except)
2163
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2164
- }
2165
- return to;
2166
- };
2167
- var __toCommonJS = (mod) => __copyProps(__defProp22({}, "__esModule", { value: true }), mod);
2168
- var get_vercel_oidc_token_exports = {};
2169
- __export22(get_vercel_oidc_token_exports, {
2170
- getVercelOidcToken: () => getVercelOidcToken3,
2171
- getVercelOidcTokenSync: () => getVercelOidcTokenSync2
2172
- });
2173
- module.exports = __toCommonJS(get_vercel_oidc_token_exports);
2174
- var import_get_context = require_get_context();
2175
- var import_token_error = chunkWFARZCDO_cjs.require_token_error();
2176
- async function getVercelOidcToken3() {
2177
- let token = "";
2178
- let err;
2179
- try {
2180
- token = getVercelOidcTokenSync2();
2181
- } catch (error) {
2182
- err = error;
2183
- }
2184
- try {
2185
- const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
2186
- await import('./token-util-RMHT2CPJ-4YTBAZ23.cjs'),
2187
- await import('./token-APYSY3BW-Y5VD4L7Z.cjs')
2188
- ]);
2189
- if (!token || isExpired(getTokenPayload(token))) {
2190
- await refreshToken();
2191
- token = getVercelOidcTokenSync2();
2192
- }
2193
- } catch (error) {
2194
- let message = err instanceof Error ? err.message : "";
2195
- if (error instanceof Error) {
2196
- message = `${message}
2197
- ${error.message}`;
2198
- }
2199
- if (message) {
2200
- throw new import_token_error.VercelOidcTokenError(message);
2201
- }
2202
- throw error;
2203
- }
2204
- return token;
2205
- }
2206
- function getVercelOidcTokenSync2() {
2207
- const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
2208
- if (!token) {
2209
- throw new Error(
2210
- `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
2211
- );
2212
- }
2213
- return token;
2214
- }
2215
- }
2216
- });
2217
- var require_dist = chunkWFARZCDO_cjs.__commonJS({
2218
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/index.js"(exports$1, module) {
2219
- var __defProp22 = Object.defineProperty;
2220
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2221
- var __getOwnPropNames = Object.getOwnPropertyNames;
2222
- var __hasOwnProp = Object.prototype.hasOwnProperty;
2223
- var __export22 = (target, all) => {
2224
- for (var name163 in all)
2225
- __defProp22(target, name163, { get: all[name163], enumerable: true });
2226
- };
2227
- var __copyProps = (to, from, except, desc) => {
2228
- if (from && typeof from === "object" || typeof from === "function") {
2229
- for (let key of __getOwnPropNames(from))
2230
- if (!__hasOwnProp.call(to, key) && key !== except)
2231
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2232
- }
2233
- return to;
2234
- };
2235
- var __toCommonJS = (mod) => __copyProps(__defProp22({}, "__esModule", { value: true }), mod);
2236
- var src_exports = {};
2237
- __export22(src_exports, {
2238
- getContext: () => import_get_context.getContext,
2239
- getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
2240
- getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
2241
- });
2242
- module.exports = __toCommonJS(src_exports);
2243
- var import_get_vercel_oidc_token = require_get_vercel_oidc_token();
2244
- var import_get_context = require_get_context();
2178
+ function getContext() {
2179
+ return {
2180
+ headers: {}
2181
+ };
2182
+ }
2183
+ async function getVercelOidcToken() {
2184
+ if (process.env.VERCEL_OIDC_TOKEN) {
2185
+ return process.env.VERCEL_OIDC_TOKEN ?? "";
2245
2186
  }
2246
- });
2247
- var import_oidc = chunkWFARZCDO_cjs.__toESM(require_dist(), 1);
2248
- var import_oidc2 = chunkWFARZCDO_cjs.__toESM(require_dist(), 1);
2187
+ throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
2188
+ }
2249
2189
  var marker16 = "vercel.ai.gateway.error";
2250
2190
  var symbol16 = Symbol.for(marker16);
2251
2191
  var _a16;
@@ -2510,6 +2450,19 @@ var gatewayErrorResponseSchema = lazyValidator(
2510
2450
  })
2511
2451
  )
2512
2452
  );
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
+ }
2513
2466
  var name72 = "GatewayTimeoutError";
2514
2467
  var marker82 = `vercel.ai.gateway.error.${name72}`;
2515
2468
  var symbol82 = Symbol.for(marker82);
@@ -2596,19 +2549,6 @@ async function asGatewayError(error, authMethod) {
2596
2549
  authMethod
2597
2550
  });
2598
2551
  }
2599
- function extractApiCallResponse(error) {
2600
- if (error.data !== void 0) {
2601
- return error.data;
2602
- }
2603
- if (error.responseBody != null) {
2604
- try {
2605
- return JSON.parse(error.responseBody);
2606
- } catch (e) {
2607
- return error.responseBody;
2608
- }
2609
- }
2610
- return {};
2611
- }
2612
2552
  var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
2613
2553
  async function parseAuthMethod(headers) {
2614
2554
  const result = await safeValidateTypes({
@@ -2620,6 +2560,7 @@ async function parseAuthMethod(headers) {
2620
2560
  var gatewayAuthMethodSchema = lazyValidator(
2621
2561
  () => zodSchema(z4.z.union([z4.z.literal("api-key"), z4.z.literal("oidc")]))
2622
2562
  );
2563
+ var KNOWN_MODEL_TYPES = ["embedding", "image", "language"];
2623
2564
  var GatewayFetchMetadata = class {
2624
2565
  constructor(config) {
2625
2566
  this.config = config;
@@ -2690,8 +2631,12 @@ var gatewayAvailableModelsResponseSchema = lazyValidator(
2690
2631
  provider: z4.z.string(),
2691
2632
  modelId: z4.z.string()
2692
2633
  }),
2693
- modelType: z4.z.enum(["language", "embedding", "image"]).nullish()
2634
+ modelType: z4.z.string().nullish()
2694
2635
  })
2636
+ ).transform(
2637
+ (models) => models.filter(
2638
+ (m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType)
2639
+ )
2695
2640
  )
2696
2641
  })
2697
2642
  )
@@ -2707,6 +2652,187 @@ var gatewayCreditsResponseSchema = lazyValidator(
2707
2652
  }))
2708
2653
  )
2709
2654
  );
2655
+ var GatewaySpendReport = class {
2656
+ constructor(config) {
2657
+ this.config = config;
2658
+ }
2659
+ async getSpendReport(params) {
2660
+ try {
2661
+ const baseUrl = new URL(this.config.baseURL);
2662
+ const searchParams = new URLSearchParams();
2663
+ searchParams.set("start_date", params.startDate);
2664
+ searchParams.set("end_date", params.endDate);
2665
+ if (params.groupBy) {
2666
+ searchParams.set("group_by", params.groupBy);
2667
+ }
2668
+ if (params.datePart) {
2669
+ searchParams.set("date_part", params.datePart);
2670
+ }
2671
+ if (params.userId) {
2672
+ searchParams.set("user_id", params.userId);
2673
+ }
2674
+ if (params.model) {
2675
+ searchParams.set("model", params.model);
2676
+ }
2677
+ if (params.provider) {
2678
+ searchParams.set("provider", params.provider);
2679
+ }
2680
+ if (params.credentialType) {
2681
+ searchParams.set("credential_type", params.credentialType);
2682
+ }
2683
+ if (params.tags && params.tags.length > 0) {
2684
+ searchParams.set("tags", params.tags.join(","));
2685
+ }
2686
+ const { value } = await getFromApi({
2687
+ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
2688
+ headers: await resolve(this.config.headers()),
2689
+ successfulResponseHandler: createJsonResponseHandler(
2690
+ gatewaySpendReportResponseSchema
2691
+ ),
2692
+ failedResponseHandler: createJsonErrorResponseHandler({
2693
+ errorSchema: z4.z.any(),
2694
+ errorToMessage: (data) => data
2695
+ }),
2696
+ fetch: this.config.fetch
2697
+ });
2698
+ return value;
2699
+ } catch (error) {
2700
+ throw await asGatewayError(error);
2701
+ }
2702
+ }
2703
+ };
2704
+ var gatewaySpendReportResponseSchema = lazySchema(
2705
+ () => zodSchema(
2706
+ z4.z.object({
2707
+ results: z4.z.array(
2708
+ z4.z.object({
2709
+ day: z4.z.string().optional(),
2710
+ hour: z4.z.string().optional(),
2711
+ user: z4.z.string().optional(),
2712
+ model: z4.z.string().optional(),
2713
+ tag: z4.z.string().optional(),
2714
+ provider: z4.z.string().optional(),
2715
+ credential_type: z4.z.enum(["byok", "system"]).optional(),
2716
+ total_cost: z4.z.number(),
2717
+ market_cost: z4.z.number().optional(),
2718
+ input_tokens: z4.z.number().optional(),
2719
+ output_tokens: z4.z.number().optional(),
2720
+ cached_input_tokens: z4.z.number().optional(),
2721
+ cache_creation_input_tokens: z4.z.number().optional(),
2722
+ reasoning_tokens: z4.z.number().optional(),
2723
+ request_count: z4.z.number().optional()
2724
+ }).transform(
2725
+ ({
2726
+ credential_type,
2727
+ total_cost,
2728
+ market_cost,
2729
+ input_tokens,
2730
+ output_tokens,
2731
+ cached_input_tokens,
2732
+ cache_creation_input_tokens,
2733
+ reasoning_tokens,
2734
+ request_count,
2735
+ ...rest
2736
+ }) => ({
2737
+ ...rest,
2738
+ ...credential_type !== void 0 ? { credentialType: credential_type } : {},
2739
+ totalCost: total_cost,
2740
+ ...market_cost !== void 0 ? { marketCost: market_cost } : {},
2741
+ ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
2742
+ ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
2743
+ ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
2744
+ ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
2745
+ ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
2746
+ ...request_count !== void 0 ? { requestCount: request_count } : {}
2747
+ })
2748
+ )
2749
+ )
2750
+ })
2751
+ )
2752
+ );
2753
+ var GatewayGenerationInfoFetcher = class {
2754
+ constructor(config) {
2755
+ this.config = config;
2756
+ }
2757
+ async getGenerationInfo(params) {
2758
+ try {
2759
+ const baseUrl = new URL(this.config.baseURL);
2760
+ const { value } = await getFromApi({
2761
+ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
2762
+ headers: await resolve(this.config.headers()),
2763
+ successfulResponseHandler: createJsonResponseHandler(
2764
+ gatewayGenerationInfoResponseSchema
2765
+ ),
2766
+ failedResponseHandler: createJsonErrorResponseHandler({
2767
+ errorSchema: z4.z.any(),
2768
+ errorToMessage: (data) => data
2769
+ }),
2770
+ fetch: this.config.fetch
2771
+ });
2772
+ return value;
2773
+ } catch (error) {
2774
+ throw await asGatewayError(error);
2775
+ }
2776
+ }
2777
+ };
2778
+ var gatewayGenerationInfoResponseSchema = lazySchema(
2779
+ () => zodSchema(
2780
+ z4.z.object({
2781
+ data: z4.z.object({
2782
+ id: z4.z.string(),
2783
+ total_cost: z4.z.number(),
2784
+ upstream_inference_cost: z4.z.number(),
2785
+ usage: z4.z.number(),
2786
+ created_at: z4.z.string(),
2787
+ model: z4.z.string(),
2788
+ is_byok: z4.z.boolean(),
2789
+ provider_name: z4.z.string(),
2790
+ streamed: z4.z.boolean(),
2791
+ finish_reason: z4.z.string(),
2792
+ latency: z4.z.number(),
2793
+ generation_time: z4.z.number(),
2794
+ native_tokens_prompt: z4.z.number(),
2795
+ native_tokens_completion: z4.z.number(),
2796
+ native_tokens_reasoning: z4.z.number(),
2797
+ native_tokens_cached: z4.z.number(),
2798
+ native_tokens_cache_creation: z4.z.number(),
2799
+ billable_web_search_calls: z4.z.number()
2800
+ }).transform(
2801
+ ({
2802
+ total_cost,
2803
+ upstream_inference_cost,
2804
+ created_at,
2805
+ is_byok,
2806
+ provider_name,
2807
+ finish_reason,
2808
+ generation_time,
2809
+ native_tokens_prompt,
2810
+ native_tokens_completion,
2811
+ native_tokens_reasoning,
2812
+ native_tokens_cached,
2813
+ native_tokens_cache_creation,
2814
+ billable_web_search_calls,
2815
+ ...rest
2816
+ }) => ({
2817
+ ...rest,
2818
+ totalCost: total_cost,
2819
+ upstreamInferenceCost: upstream_inference_cost,
2820
+ createdAt: created_at,
2821
+ isByok: is_byok,
2822
+ providerName: provider_name,
2823
+ finishReason: finish_reason,
2824
+ generationTime: generation_time,
2825
+ promptTokens: native_tokens_prompt,
2826
+ completionTokens: native_tokens_completion,
2827
+ reasoningTokens: native_tokens_reasoning,
2828
+ cachedTokens: native_tokens_cached,
2829
+ cacheCreationTokens: native_tokens_cache_creation,
2830
+ billableWebSearchCalls: billable_web_search_calls
2831
+ })
2832
+ )
2833
+ }).transform(({ data }) => data)
2834
+ )
2835
+ );
2710
2836
  var GatewayLanguageModel = class {
2711
2837
  constructor(modelId, config) {
2712
2838
  this.modelId = modelId;
@@ -3207,9 +3333,9 @@ var gatewayTools = {
3207
3333
  };
3208
3334
  async function getVercelRequestId() {
3209
3335
  var _a932;
3210
- return (_a932 = (0, import_oidc.getContext)().headers) == null ? void 0 : _a932["x-vercel-id"];
3336
+ return (_a932 = getContext().headers) == null ? void 0 : _a932["x-vercel-id"];
3211
3337
  }
3212
- var VERSION2 = "2.0.59";
3338
+ var VERSION2 = "2.0.86";
3213
3339
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
3214
3340
  function createGatewayProvider(options = {}) {
3215
3341
  var _a932, _b93;
@@ -3307,6 +3433,30 @@ function createGatewayProvider(options = {}) {
3307
3433
  );
3308
3434
  });
3309
3435
  };
3436
+ const getSpendReport = async (params) => {
3437
+ return new GatewaySpendReport({
3438
+ baseURL,
3439
+ headers: getHeaders,
3440
+ fetch: options.fetch
3441
+ }).getSpendReport(params).catch(async (error) => {
3442
+ throw await asGatewayError(
3443
+ error,
3444
+ await parseAuthMethod(await getHeaders())
3445
+ );
3446
+ });
3447
+ };
3448
+ const getGenerationInfo = async (params) => {
3449
+ return new GatewayGenerationInfoFetcher({
3450
+ baseURL,
3451
+ headers: getHeaders,
3452
+ fetch: options.fetch
3453
+ }).getGenerationInfo(params).catch(async (error) => {
3454
+ throw await asGatewayError(
3455
+ error,
3456
+ await parseAuthMethod(await getHeaders())
3457
+ );
3458
+ });
3459
+ };
3310
3460
  const provider = function(modelId) {
3311
3461
  if (new.target) {
3312
3462
  throw new Error(
@@ -3317,6 +3467,8 @@ function createGatewayProvider(options = {}) {
3317
3467
  };
3318
3468
  provider.getAvailableModels = getAvailableModels;
3319
3469
  provider.getCredits = getCredits;
3470
+ provider.getSpendReport = getSpendReport;
3471
+ provider.getGenerationInfo = getGenerationInfo;
3320
3472
  provider.imageModel = (modelId) => {
3321
3473
  return new GatewayImageModel(modelId, {
3322
3474
  provider: "gateway",
@@ -3352,7 +3504,7 @@ async function getGatewayAuthToken(options) {
3352
3504
  };
3353
3505
  }
3354
3506
  try {
3355
- const oidcToken = await (0, import_oidc2.getVercelOidcToken)();
3507
+ const oidcToken = await getVercelOidcToken();
3356
3508
  return {
3357
3509
  token: oidcToken,
3358
3510
  authMethod: "oidc"
@@ -4309,6 +4461,9 @@ function mergeObjects(base, overrides) {
4309
4461
  }
4310
4462
  const result = { ...base };
4311
4463
  for (const key in overrides) {
4464
+ if (key === "__proto__" || key === "constructor" || key === "prototype") {
4465
+ continue;
4466
+ }
4312
4467
  if (Object.prototype.hasOwnProperty.call(overrides, key)) {
4313
4468
  const overridesValue = overrides[key];
4314
4469
  if (overridesValue === void 0)
@@ -5620,6 +5775,9 @@ var ParseError2 = class extends Error {
5620
5775
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
5621
5776
  }
5622
5777
  };
5778
+ var LF2 = 10;
5779
+ var CR2 = 13;
5780
+ var SPACE2 = 32;
5623
5781
  function noop2(_arg) {
5624
5782
  }
5625
5783
  function createParser2(callbacks) {
@@ -5627,39 +5785,109 @@ function createParser2(callbacks) {
5627
5785
  throw new TypeError(
5628
5786
  "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
5629
5787
  );
5630
- const { onEvent = noop2, onError = noop2, onRetry = noop2, onComment } = callbacks;
5631
- let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
5632
- function feed(newChunk) {
5633
- const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines2(`${incompleteLine}${chunk}`);
5634
- for (const line of complete)
5635
- parseLine(line);
5636
- incompleteLine = incomplete, isFirstChunk = false;
5637
- }
5638
- function parseLine(line) {
5639
- if (line === "") {
5788
+ const { onEvent = noop2, onError = noop2, onRetry = noop2, onComment } = callbacks, pendingFragments = [];
5789
+ let isFirstChunk = true, id, data = "", dataLines = 0, eventType;
5790
+ function feed(chunk) {
5791
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
5792
+ const trailing2 = processLines(chunk);
5793
+ trailing2 !== "" && pendingFragments.push(trailing2);
5794
+ return;
5795
+ }
5796
+ if (chunk.indexOf(`
5797
+ `) === -1 && chunk.indexOf("\r") === -1) {
5798
+ pendingFragments.push(chunk);
5799
+ return;
5800
+ }
5801
+ pendingFragments.push(chunk);
5802
+ const input = pendingFragments.join("");
5803
+ pendingFragments.length = 0;
5804
+ const trailing = processLines(input);
5805
+ trailing !== "" && pendingFragments.push(trailing);
5806
+ }
5807
+ function processLines(chunk) {
5808
+ let searchIndex = 0;
5809
+ if (chunk.indexOf("\r") === -1) {
5810
+ let lfIndex = chunk.indexOf(`
5811
+ `, searchIndex);
5812
+ for (; lfIndex !== -1; ) {
5813
+ if (searchIndex === lfIndex) {
5814
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
5815
+ `, searchIndex);
5816
+ continue;
5817
+ }
5818
+ const firstCharCode = chunk.charCodeAt(searchIndex);
5819
+ if (isDataPrefix2(chunk, searchIndex, firstCharCode)) {
5820
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE2 ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
5821
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF2) {
5822
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
5823
+ `, searchIndex);
5824
+ continue;
5825
+ }
5826
+ data = dataLines === 0 ? value : `${data}
5827
+ ${value}`, dataLines++;
5828
+ } else isEventPrefix2(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
5829
+ chunk.charCodeAt(searchIndex + 6) === SPACE2 ? searchIndex + 7 : searchIndex + 6,
5830
+ lfIndex
5831
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
5832
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
5833
+ `, searchIndex);
5834
+ }
5835
+ return chunk.slice(searchIndex);
5836
+ }
5837
+ for (; searchIndex < chunk.length; ) {
5838
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
5839
+ `, searchIndex);
5840
+ let lineEnd = -1;
5841
+ 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)
5842
+ break;
5843
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR2 && chunk.charCodeAt(searchIndex) === LF2 && searchIndex++;
5844
+ }
5845
+ return chunk.slice(searchIndex);
5846
+ }
5847
+ function parseLine(chunk, start, end) {
5848
+ if (start === end) {
5640
5849
  dispatchEvent();
5641
5850
  return;
5642
5851
  }
5643
- if (line.startsWith(":")) {
5644
- onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
5852
+ const firstCharCode = chunk.charCodeAt(start);
5853
+ if (isDataPrefix2(chunk, start, firstCharCode)) {
5854
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE2 ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
5855
+ data = dataLines === 0 ? value2 : `${data}
5856
+ ${value2}`, dataLines++;
5857
+ return;
5858
+ }
5859
+ if (isEventPrefix2(chunk, start, firstCharCode)) {
5860
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE2 ? start + 7 : start + 6, end) || void 0;
5861
+ return;
5862
+ }
5863
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
5864
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE2 ? start + 4 : start + 3, end);
5865
+ id = value2.includes("\0") ? void 0 : value2;
5866
+ return;
5867
+ }
5868
+ if (firstCharCode === 58) {
5869
+ if (onComment) {
5870
+ const line2 = chunk.slice(start, end);
5871
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE2 ? 2 : 1));
5872
+ }
5645
5873
  return;
5646
5874
  }
5647
- const fieldSeparatorIndex = line.indexOf(":");
5648
- if (fieldSeparatorIndex !== -1) {
5649
- const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
5650
- processField(field, value, line);
5875
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
5876
+ if (fieldSeparatorIndex === -1) {
5877
+ processField(line, "", line);
5651
5878
  return;
5652
5879
  }
5653
- processField(line, "", line);
5880
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE2 ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
5881
+ processField(field, value, line);
5654
5882
  }
5655
5883
  function processField(field, value, line) {
5656
5884
  switch (field) {
5657
5885
  case "event":
5658
- eventType = value;
5886
+ eventType = value || void 0;
5659
5887
  break;
5660
5888
  case "data":
5661
- data = `${data}${value}
5662
- `;
5889
+ data = dataLines === 0 ? value : `${data}
5890
+ ${value}`, dataLines++;
5663
5891
  break;
5664
5892
  case "id":
5665
5893
  id = value.includes("\0") ? void 0 : value;
@@ -5684,37 +5912,26 @@ function createParser2(callbacks) {
5684
5912
  }
5685
5913
  }
5686
5914
  function dispatchEvent() {
5687
- data.length > 0 && onEvent({
5915
+ dataLines > 0 && onEvent({
5688
5916
  id,
5689
- event: eventType || void 0,
5690
- // If the data buffer's last character is a U+000A LINE FEED (LF) character,
5691
- // then remove the last character from the data buffer.
5692
- data: data.endsWith(`
5693
- `) ? data.slice(0, -1) : data
5694
- }), id = void 0, data = "", eventType = "";
5917
+ event: eventType,
5918
+ data
5919
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
5695
5920
  }
5696
5921
  function reset(options = {}) {
5697
- incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
5922
+ if (options.consume && pendingFragments.length > 0) {
5923
+ const incompleteLine = pendingFragments.join("");
5924
+ parseLine(incompleteLine, 0, incompleteLine.length);
5925
+ }
5926
+ isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0;
5698
5927
  }
5699
5928
  return { feed, reset };
5700
5929
  }
5701
- function splitLines2(chunk) {
5702
- const lines = [];
5703
- let incompleteLine = "", searchIndex = 0;
5704
- for (; searchIndex < chunk.length; ) {
5705
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
5706
- `, searchIndex);
5707
- let lineEnd = -1;
5708
- 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) {
5709
- incompleteLine = chunk.slice(searchIndex);
5710
- break;
5711
- } else {
5712
- const line = chunk.slice(searchIndex, lineEnd);
5713
- lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
5714
- ` && searchIndex++;
5715
- }
5716
- }
5717
- return [lines, incompleteLine];
5930
+ function isDataPrefix2(chunk, i, firstCharCode) {
5931
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
5932
+ }
5933
+ function isEventPrefix2(chunk, i, firstCharCode) {
5934
+ 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;
5718
5935
  }
5719
5936
  var EventSourceParserStream2 = class extends TransformStream {
5720
5937
  constructor({ onError, onRetry, onComment } = {}) {
@@ -5898,7 +6115,7 @@ function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
5898
6115
  );
5899
6116
  return Object.fromEntries(normalizedHeaders.entries());
5900
6117
  }
5901
- var VERSION4 = "4.0.19";
6118
+ var VERSION4 = "4.0.26";
5902
6119
  var getOriginalFetch3 = () => globalThis.fetch;
5903
6120
  var getFromApi2 = async ({
5904
6121
  url,
@@ -7558,138 +7775,17 @@ var createJsonResponseHandler2 = (responseSchema) => async ({ response, url, req
7558
7775
  function withoutTrailingSlash2(url) {
7559
7776
  return url == null ? void 0 : url.replace(/\/$/, "");
7560
7777
  }
7561
- var require_get_context2 = chunkPEZAMDZJ_cjs.__commonJS({
7562
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-context.js"(exports$1, module) {
7563
- var __defProp22 = Object.defineProperty;
7564
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7565
- var __getOwnPropNames = Object.getOwnPropertyNames;
7566
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7567
- var __export22 = (target, all) => {
7568
- for (var name21 in all)
7569
- __defProp22(target, name21, { get: all[name21], enumerable: true });
7570
- };
7571
- var __copyProps = (to, from, except, desc) => {
7572
- if (from && typeof from === "object" || typeof from === "function") {
7573
- for (let key of __getOwnPropNames(from))
7574
- if (!__hasOwnProp.call(to, key) && key !== except)
7575
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
7576
- }
7577
- return to;
7578
- };
7579
- var __toCommonJS = (mod) => __copyProps(__defProp22({}, "__esModule", { value: true }), mod);
7580
- var get_context_exports = {};
7581
- __export22(get_context_exports, {
7582
- SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
7583
- getContext: () => getContext3
7584
- });
7585
- module.exports = __toCommonJS(get_context_exports);
7586
- var SYMBOL_FOR_REQ_CONTEXT = /* @__PURE__ */ Symbol.for("@vercel/request-context");
7587
- function getContext3() {
7588
- const fromSymbol = globalThis;
7589
- return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
7590
- }
7591
- }
7592
- });
7593
- var require_get_vercel_oidc_token2 = chunkPEZAMDZJ_cjs.__commonJS({
7594
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports$1, module) {
7595
- var __defProp22 = Object.defineProperty;
7596
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7597
- var __getOwnPropNames = Object.getOwnPropertyNames;
7598
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7599
- var __export22 = (target, all) => {
7600
- for (var name21 in all)
7601
- __defProp22(target, name21, { get: all[name21], enumerable: true });
7602
- };
7603
- var __copyProps = (to, from, except, desc) => {
7604
- if (from && typeof from === "object" || typeof from === "function") {
7605
- for (let key of __getOwnPropNames(from))
7606
- if (!__hasOwnProp.call(to, key) && key !== except)
7607
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
7608
- }
7609
- return to;
7610
- };
7611
- var __toCommonJS = (mod) => __copyProps(__defProp22({}, "__esModule", { value: true }), mod);
7612
- var get_vercel_oidc_token_exports = {};
7613
- __export22(get_vercel_oidc_token_exports, {
7614
- getVercelOidcToken: () => getVercelOidcToken3,
7615
- getVercelOidcTokenSync: () => getVercelOidcTokenSync2
7616
- });
7617
- module.exports = __toCommonJS(get_vercel_oidc_token_exports);
7618
- var import_get_context = require_get_context2();
7619
- var import_token_error = chunkPEZAMDZJ_cjs.require_token_error();
7620
- async function getVercelOidcToken3() {
7621
- let token = "";
7622
- let err;
7623
- try {
7624
- token = getVercelOidcTokenSync2();
7625
- } catch (error) {
7626
- err = error;
7627
- }
7628
- try {
7629
- const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
7630
- await import('./token-util-RMHT2CPJ-3LCBPXJ6.cjs'),
7631
- await import('./token-APYSY3BW-M2K6HVOG.cjs')
7632
- ]);
7633
- if (!token || isExpired(getTokenPayload(token))) {
7634
- await refreshToken();
7635
- token = getVercelOidcTokenSync2();
7636
- }
7637
- } catch (error) {
7638
- let message = err instanceof Error ? err.message : "";
7639
- if (error instanceof Error) {
7640
- message = `${message}
7641
- ${error.message}`;
7642
- }
7643
- if (message) {
7644
- throw new import_token_error.VercelOidcTokenError(message);
7645
- }
7646
- throw error;
7647
- }
7648
- return token;
7649
- }
7650
- function getVercelOidcTokenSync2() {
7651
- const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
7652
- if (!token) {
7653
- throw new Error(
7654
- `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
7655
- );
7656
- }
7657
- return token;
7658
- }
7659
- }
7660
- });
7661
- var require_dist2 = chunkPEZAMDZJ_cjs.__commonJS({
7662
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/index.js"(exports$1, module) {
7663
- var __defProp22 = Object.defineProperty;
7664
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7665
- var __getOwnPropNames = Object.getOwnPropertyNames;
7666
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7667
- var __export22 = (target, all) => {
7668
- for (var name21 in all)
7669
- __defProp22(target, name21, { get: all[name21], enumerable: true });
7670
- };
7671
- var __copyProps = (to, from, except, desc) => {
7672
- if (from && typeof from === "object" || typeof from === "function") {
7673
- for (let key of __getOwnPropNames(from))
7674
- if (!__hasOwnProp.call(to, key) && key !== except)
7675
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
7676
- }
7677
- return to;
7678
- };
7679
- var __toCommonJS = (mod) => __copyProps(__defProp22({}, "__esModule", { value: true }), mod);
7680
- var src_exports = {};
7681
- __export22(src_exports, {
7682
- getContext: () => import_get_context.getContext,
7683
- getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
7684
- getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
7685
- });
7686
- module.exports = __toCommonJS(src_exports);
7687
- var import_get_vercel_oidc_token = require_get_vercel_oidc_token2();
7688
- var import_get_context = require_get_context2();
7778
+ function getContext2() {
7779
+ return {
7780
+ headers: {}
7781
+ };
7782
+ }
7783
+ async function getVercelOidcToken2() {
7784
+ if (process.env.VERCEL_OIDC_TOKEN) {
7785
+ return process.env.VERCEL_OIDC_TOKEN ?? "";
7689
7786
  }
7690
- });
7691
- var import_oidc3 = chunkPEZAMDZJ_cjs.__toESM(require_dist2(), 1);
7692
- var import_oidc22 = chunkPEZAMDZJ_cjs.__toESM(require_dist2(), 1);
7787
+ throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
7788
+ }
7693
7789
  var marker18 = "vercel.ai.gateway.error";
7694
7790
  var symbol18 = Symbol.for(marker18);
7695
7791
  var _a18;
@@ -7991,6 +8087,19 @@ var gatewayErrorResponseSchema2 = lazySchema2(
7991
8087
  })
7992
8088
  )
7993
8089
  );
8090
+ function extractApiCallResponse2(error) {
8091
+ if (error.data !== void 0) {
8092
+ return error.data;
8093
+ }
8094
+ if (error.responseBody != null) {
8095
+ try {
8096
+ return JSON.parse(error.responseBody);
8097
+ } catch (e) {
8098
+ return error.responseBody;
8099
+ }
8100
+ }
8101
+ return {};
8102
+ }
7994
8103
  var name74 = "GatewayTimeoutError";
7995
8104
  var marker84 = `vercel.ai.gateway.error.${name74}`;
7996
8105
  var symbol84 = Symbol.for(marker84);
@@ -8080,19 +8189,6 @@ async function asGatewayError2(error, authMethod) {
8080
8189
  authMethod
8081
8190
  });
8082
8191
  }
8083
- function extractApiCallResponse2(error) {
8084
- if (error.data !== void 0) {
8085
- return error.data;
8086
- }
8087
- if (error.responseBody != null) {
8088
- try {
8089
- return JSON.parse(error.responseBody);
8090
- } catch (e) {
8091
- return error.responseBody;
8092
- }
8093
- }
8094
- return {};
8095
- }
8096
8192
  var GATEWAY_AUTH_METHOD_HEADER2 = "ai-gateway-auth-method";
8097
8193
  async function parseAuthMethod2(headers) {
8098
8194
  const result = await safeValidateTypes2({
@@ -8104,6 +8200,13 @@ async function parseAuthMethod2(headers) {
8104
8200
  var gatewayAuthMethodSchema2 = lazySchema2(
8105
8201
  () => zodSchema2(z4.z.union([z4.z.literal("api-key"), z4.z.literal("oidc")]))
8106
8202
  );
8203
+ var KNOWN_MODEL_TYPES2 = [
8204
+ "embedding",
8205
+ "image",
8206
+ "language",
8207
+ "reranking",
8208
+ "video"
8209
+ ];
8107
8210
  var GatewayFetchMetadata2 = class {
8108
8211
  constructor(config) {
8109
8212
  this.config = config;
@@ -8174,8 +8277,12 @@ var gatewayAvailableModelsResponseSchema2 = lazySchema2(
8174
8277
  provider: z4.z.string(),
8175
8278
  modelId: z4.z.string()
8176
8279
  }),
8177
- modelType: z4.z.enum(["embedding", "image", "language", "video"]).nullish()
8280
+ modelType: z4.z.string().nullish()
8178
8281
  })
8282
+ ).transform(
8283
+ (models) => models.filter(
8284
+ (m) => m.modelType == null || KNOWN_MODEL_TYPES2.includes(m.modelType)
8285
+ )
8179
8286
  )
8180
8287
  })
8181
8288
  )
@@ -8191,6 +8298,187 @@ var gatewayCreditsResponseSchema2 = lazySchema2(
8191
8298
  }))
8192
8299
  )
8193
8300
  );
8301
+ var GatewaySpendReport2 = class {
8302
+ constructor(config) {
8303
+ this.config = config;
8304
+ }
8305
+ async getSpendReport(params) {
8306
+ try {
8307
+ const baseUrl = new URL(this.config.baseURL);
8308
+ const searchParams = new URLSearchParams();
8309
+ searchParams.set("start_date", params.startDate);
8310
+ searchParams.set("end_date", params.endDate);
8311
+ if (params.groupBy) {
8312
+ searchParams.set("group_by", params.groupBy);
8313
+ }
8314
+ if (params.datePart) {
8315
+ searchParams.set("date_part", params.datePart);
8316
+ }
8317
+ if (params.userId) {
8318
+ searchParams.set("user_id", params.userId);
8319
+ }
8320
+ if (params.model) {
8321
+ searchParams.set("model", params.model);
8322
+ }
8323
+ if (params.provider) {
8324
+ searchParams.set("provider", params.provider);
8325
+ }
8326
+ if (params.credentialType) {
8327
+ searchParams.set("credential_type", params.credentialType);
8328
+ }
8329
+ if (params.tags && params.tags.length > 0) {
8330
+ searchParams.set("tags", params.tags.join(","));
8331
+ }
8332
+ const { value } = await getFromApi2({
8333
+ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
8334
+ headers: await resolve2(this.config.headers()),
8335
+ successfulResponseHandler: createJsonResponseHandler2(
8336
+ gatewaySpendReportResponseSchema2
8337
+ ),
8338
+ failedResponseHandler: createJsonErrorResponseHandler2({
8339
+ errorSchema: z4.z.any(),
8340
+ errorToMessage: (data) => data
8341
+ }),
8342
+ fetch: this.config.fetch
8343
+ });
8344
+ return value;
8345
+ } catch (error) {
8346
+ throw await asGatewayError2(error);
8347
+ }
8348
+ }
8349
+ };
8350
+ var gatewaySpendReportResponseSchema2 = lazySchema2(
8351
+ () => zodSchema2(
8352
+ z4.z.object({
8353
+ results: z4.z.array(
8354
+ z4.z.object({
8355
+ day: z4.z.string().optional(),
8356
+ hour: z4.z.string().optional(),
8357
+ user: z4.z.string().optional(),
8358
+ model: z4.z.string().optional(),
8359
+ tag: z4.z.string().optional(),
8360
+ provider: z4.z.string().optional(),
8361
+ credential_type: z4.z.enum(["byok", "system"]).optional(),
8362
+ total_cost: z4.z.number(),
8363
+ market_cost: z4.z.number().optional(),
8364
+ input_tokens: z4.z.number().optional(),
8365
+ output_tokens: z4.z.number().optional(),
8366
+ cached_input_tokens: z4.z.number().optional(),
8367
+ cache_creation_input_tokens: z4.z.number().optional(),
8368
+ reasoning_tokens: z4.z.number().optional(),
8369
+ request_count: z4.z.number().optional()
8370
+ }).transform(
8371
+ ({
8372
+ credential_type,
8373
+ total_cost,
8374
+ market_cost,
8375
+ input_tokens,
8376
+ output_tokens,
8377
+ cached_input_tokens,
8378
+ cache_creation_input_tokens,
8379
+ reasoning_tokens,
8380
+ request_count,
8381
+ ...rest
8382
+ }) => ({
8383
+ ...rest,
8384
+ ...credential_type !== void 0 ? { credentialType: credential_type } : {},
8385
+ totalCost: total_cost,
8386
+ ...market_cost !== void 0 ? { marketCost: market_cost } : {},
8387
+ ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
8388
+ ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
8389
+ ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
8390
+ ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
8391
+ ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
8392
+ ...request_count !== void 0 ? { requestCount: request_count } : {}
8393
+ })
8394
+ )
8395
+ )
8396
+ })
8397
+ )
8398
+ );
8399
+ var GatewayGenerationInfoFetcher2 = class {
8400
+ constructor(config) {
8401
+ this.config = config;
8402
+ }
8403
+ async getGenerationInfo(params) {
8404
+ try {
8405
+ const baseUrl = new URL(this.config.baseURL);
8406
+ const { value } = await getFromApi2({
8407
+ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
8408
+ headers: await resolve2(this.config.headers()),
8409
+ successfulResponseHandler: createJsonResponseHandler2(
8410
+ gatewayGenerationInfoResponseSchema2
8411
+ ),
8412
+ failedResponseHandler: createJsonErrorResponseHandler2({
8413
+ errorSchema: z4.z.any(),
8414
+ errorToMessage: (data) => data
8415
+ }),
8416
+ fetch: this.config.fetch
8417
+ });
8418
+ return value;
8419
+ } catch (error) {
8420
+ throw await asGatewayError2(error);
8421
+ }
8422
+ }
8423
+ };
8424
+ var gatewayGenerationInfoResponseSchema2 = lazySchema2(
8425
+ () => zodSchema2(
8426
+ z4.z.object({
8427
+ data: z4.z.object({
8428
+ id: z4.z.string(),
8429
+ total_cost: z4.z.number(),
8430
+ upstream_inference_cost: z4.z.number(),
8431
+ usage: z4.z.number(),
8432
+ created_at: z4.z.string(),
8433
+ model: z4.z.string(),
8434
+ is_byok: z4.z.boolean(),
8435
+ provider_name: z4.z.string(),
8436
+ streamed: z4.z.boolean(),
8437
+ finish_reason: z4.z.string(),
8438
+ latency: z4.z.number(),
8439
+ generation_time: z4.z.number(),
8440
+ native_tokens_prompt: z4.z.number(),
8441
+ native_tokens_completion: z4.z.number(),
8442
+ native_tokens_reasoning: z4.z.number(),
8443
+ native_tokens_cached: z4.z.number(),
8444
+ native_tokens_cache_creation: z4.z.number(),
8445
+ billable_web_search_calls: z4.z.number()
8446
+ }).transform(
8447
+ ({
8448
+ total_cost,
8449
+ upstream_inference_cost,
8450
+ created_at,
8451
+ is_byok,
8452
+ provider_name,
8453
+ finish_reason,
8454
+ generation_time,
8455
+ native_tokens_prompt,
8456
+ native_tokens_completion,
8457
+ native_tokens_reasoning,
8458
+ native_tokens_cached,
8459
+ native_tokens_cache_creation,
8460
+ billable_web_search_calls,
8461
+ ...rest
8462
+ }) => ({
8463
+ ...rest,
8464
+ totalCost: total_cost,
8465
+ upstreamInferenceCost: upstream_inference_cost,
8466
+ createdAt: created_at,
8467
+ isByok: is_byok,
8468
+ providerName: provider_name,
8469
+ finishReason: finish_reason,
8470
+ generationTime: generation_time,
8471
+ promptTokens: native_tokens_prompt,
8472
+ completionTokens: native_tokens_completion,
8473
+ reasoningTokens: native_tokens_reasoning,
8474
+ cachedTokens: native_tokens_cached,
8475
+ cacheCreationTokens: native_tokens_cache_creation,
8476
+ billableWebSearchCalls: billable_web_search_calls
8477
+ })
8478
+ )
8479
+ }).transform(({ data }) => data)
8480
+ )
8481
+ );
8194
8482
  var GatewayLanguageModel2 = class {
8195
8483
  constructor(modelId, config) {
8196
8484
  this.modelId = modelId;
@@ -8738,6 +9026,86 @@ var gatewayVideoEventSchema = z4.z.discriminatedUnion("type", [
8738
9026
  param: z4.z.unknown().nullable()
8739
9027
  })
8740
9028
  ]);
9029
+ var GatewayRerankingModel = class {
9030
+ constructor(modelId, config) {
9031
+ this.modelId = modelId;
9032
+ this.config = config;
9033
+ this.specificationVersion = "v3";
9034
+ }
9035
+ get provider() {
9036
+ return this.config.provider;
9037
+ }
9038
+ async doRerank({
9039
+ documents,
9040
+ query,
9041
+ topN,
9042
+ headers,
9043
+ abortSignal,
9044
+ providerOptions
9045
+ }) {
9046
+ const resolvedHeaders = await resolve2(this.config.headers());
9047
+ try {
9048
+ const {
9049
+ responseHeaders,
9050
+ value: responseBody,
9051
+ rawValue
9052
+ } = await postJsonToApi2({
9053
+ url: this.getUrl(),
9054
+ headers: combineHeaders2(
9055
+ resolvedHeaders,
9056
+ headers != null ? headers : {},
9057
+ this.getModelConfigHeaders(),
9058
+ await resolve2(this.config.o11yHeaders)
9059
+ ),
9060
+ body: {
9061
+ documents,
9062
+ query,
9063
+ ...topN != null ? { topN } : {},
9064
+ ...providerOptions ? { providerOptions } : {}
9065
+ },
9066
+ successfulResponseHandler: createJsonResponseHandler2(
9067
+ gatewayRerankingResponseSchema
9068
+ ),
9069
+ failedResponseHandler: createJsonErrorResponseHandler2({
9070
+ errorSchema: z4.z.any(),
9071
+ errorToMessage: (data) => data
9072
+ }),
9073
+ ...abortSignal && { abortSignal },
9074
+ fetch: this.config.fetch
9075
+ });
9076
+ return {
9077
+ ranking: responseBody.ranking,
9078
+ providerMetadata: responseBody.providerMetadata,
9079
+ response: { headers: responseHeaders, body: rawValue },
9080
+ warnings: []
9081
+ };
9082
+ } catch (error) {
9083
+ throw await asGatewayError2(error, await parseAuthMethod2(resolvedHeaders));
9084
+ }
9085
+ }
9086
+ getUrl() {
9087
+ return `${this.config.baseURL}/reranking-model`;
9088
+ }
9089
+ getModelConfigHeaders() {
9090
+ return {
9091
+ "ai-reranking-model-specification-version": "3",
9092
+ "ai-model-id": this.modelId
9093
+ };
9094
+ }
9095
+ };
9096
+ var gatewayRerankingResponseSchema = lazySchema2(
9097
+ () => zodSchema2(
9098
+ z4.z.object({
9099
+ ranking: z4.z.array(
9100
+ z4.z.object({
9101
+ index: z4.z.number(),
9102
+ relevanceScore: z4.z.number()
9103
+ })
9104
+ ),
9105
+ providerMetadata: z4.z.record(z4.z.string(), z4.z.record(z4.z.string(), z4.z.unknown())).optional()
9106
+ })
9107
+ )
9108
+ );
8741
9109
  var parallelSearchInputSchema2 = lazySchema2(
8742
9110
  () => zodSchema2(
8743
9111
  zod.z.object({
@@ -8912,9 +9280,9 @@ var gatewayTools2 = {
8912
9280
  };
8913
9281
  async function getVercelRequestId2() {
8914
9282
  var _a932;
8915
- return (_a932 = (0, import_oidc3.getContext)().headers) == null ? void 0 : _a932["x-vercel-id"];
9283
+ return (_a932 = getContext2().headers) == null ? void 0 : _a932["x-vercel-id"];
8916
9284
  }
8917
- var VERSION5 = "3.0.66";
9285
+ var VERSION5 = "3.0.110";
8918
9286
  var AI_GATEWAY_PROTOCOL_VERSION2 = "0.0.1";
8919
9287
  function createGatewayProvider2(options = {}) {
8920
9288
  var _a932, _b93;
@@ -9014,6 +9382,30 @@ function createGatewayProvider2(options = {}) {
9014
9382
  );
9015
9383
  });
9016
9384
  };
9385
+ const getSpendReport = async (params) => {
9386
+ return new GatewaySpendReport2({
9387
+ baseURL,
9388
+ headers: getHeaders,
9389
+ fetch: options.fetch
9390
+ }).getSpendReport(params).catch(async (error) => {
9391
+ throw await asGatewayError2(
9392
+ error,
9393
+ await parseAuthMethod2(await getHeaders())
9394
+ );
9395
+ });
9396
+ };
9397
+ const getGenerationInfo = async (params) => {
9398
+ return new GatewayGenerationInfoFetcher2({
9399
+ baseURL,
9400
+ headers: getHeaders,
9401
+ fetch: options.fetch
9402
+ }).getGenerationInfo(params).catch(async (error) => {
9403
+ throw await asGatewayError2(
9404
+ error,
9405
+ await parseAuthMethod2(await getHeaders())
9406
+ );
9407
+ });
9408
+ };
9017
9409
  const provider = function(modelId) {
9018
9410
  if (new.target) {
9019
9411
  throw new Error(
@@ -9025,6 +9417,8 @@ function createGatewayProvider2(options = {}) {
9025
9417
  provider.specificationVersion = "v3";
9026
9418
  provider.getAvailableModels = getAvailableModels;
9027
9419
  provider.getCredits = getCredits;
9420
+ provider.getSpendReport = getSpendReport;
9421
+ provider.getGenerationInfo = getGenerationInfo;
9028
9422
  provider.imageModel = (modelId) => {
9029
9423
  return new GatewayImageModel2(modelId, {
9030
9424
  provider: "gateway",
@@ -9055,6 +9449,17 @@ function createGatewayProvider2(options = {}) {
9055
9449
  o11yHeaders: createO11yHeaders()
9056
9450
  });
9057
9451
  };
9452
+ const createRerankingModel = (modelId) => {
9453
+ return new GatewayRerankingModel(modelId, {
9454
+ provider: "gateway",
9455
+ baseURL,
9456
+ headers: getHeaders,
9457
+ fetch: options.fetch,
9458
+ o11yHeaders: createO11yHeaders()
9459
+ });
9460
+ };
9461
+ provider.rerankingModel = createRerankingModel;
9462
+ provider.reranking = createRerankingModel;
9058
9463
  provider.chat = provider.languageModel;
9059
9464
  provider.embedding = provider.embeddingModel;
9060
9465
  provider.image = provider.imageModel;
@@ -9074,7 +9479,7 @@ async function getGatewayAuthToken2(options) {
9074
9479
  authMethod: "api-key"
9075
9480
  };
9076
9481
  }
9077
- const oidcToken = await (0, import_oidc22.getVercelOidcToken)();
9482
+ const oidcToken = await getVercelOidcToken2();
9078
9483
  return {
9079
9484
  token: oidcToken,
9080
9485
  authMethod: "oidc"
@@ -10054,6 +10459,9 @@ function mergeObjects2(base, overrides) {
10054
10459
  }
10055
10460
  const result = { ...base };
10056
10461
  for (const key in overrides) {
10462
+ if (key === "__proto__" || key === "constructor" || key === "prototype") {
10463
+ continue;
10464
+ }
10057
10465
  if (Object.prototype.hasOwnProperty.call(overrides, key)) {
10058
10466
  const overridesValue = overrides[key];
10059
10467
  if (overridesValue === void 0)
@@ -10852,8 +11260,14 @@ function processUIMessageStream2({
10852
11260
  anyPart.title = options.title;
10853
11261
  }
10854
11262
  anyPart.providerExecuted = (_a2222 = anyOptions.providerExecuted) != null ? _a2222 : part.providerExecuted;
10855
- if (anyOptions.providerMetadata != null) {
10856
- part.callProviderMetadata = anyOptions.providerMetadata;
11263
+ const providerMetadata = anyOptions.providerMetadata;
11264
+ if (providerMetadata != null) {
11265
+ if (options.state === "output-available" || options.state === "output-error") {
11266
+ const resultPart = part;
11267
+ resultPart.resultProviderMetadata = providerMetadata;
11268
+ } else {
11269
+ part.callProviderMetadata = providerMetadata;
11270
+ }
10857
11271
  }
10858
11272
  } else {
10859
11273
  state.message.parts.push({
@@ -10867,7 +11281,8 @@ function processUIMessageStream2({
10867
11281
  errorText: anyOptions.errorText,
10868
11282
  providerExecuted: anyOptions.providerExecuted,
10869
11283
  preliminary: anyOptions.preliminary,
10870
- ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
11284
+ ...anyOptions.providerMetadata != null && (options.state === "output-available" || options.state === "output-error") ? { resultProviderMetadata: anyOptions.providerMetadata } : {},
11285
+ ...anyOptions.providerMetadata != null && !(options.state === "output-available" || options.state === "output-error") ? { callProviderMetadata: anyOptions.providerMetadata } : {}
10871
11286
  });
10872
11287
  }
10873
11288
  }
@@ -10890,8 +11305,14 @@ function processUIMessageStream2({
10890
11305
  anyPart.title = options.title;
10891
11306
  }
10892
11307
  anyPart.providerExecuted = (_b222 = anyOptions.providerExecuted) != null ? _b222 : part.providerExecuted;
10893
- if (anyOptions.providerMetadata != null) {
10894
- part.callProviderMetadata = anyOptions.providerMetadata;
11308
+ const providerMetadata = anyOptions.providerMetadata;
11309
+ if (providerMetadata != null) {
11310
+ if (options.state === "output-available" || options.state === "output-error") {
11311
+ const resultPart = part;
11312
+ resultPart.resultProviderMetadata = providerMetadata;
11313
+ } else {
11314
+ part.callProviderMetadata = providerMetadata;
11315
+ }
10895
11316
  }
10896
11317
  } else {
10897
11318
  state.message.parts.push({
@@ -10905,7 +11326,8 @@ function processUIMessageStream2({
10905
11326
  preliminary: anyOptions.preliminary,
10906
11327
  providerExecuted: anyOptions.providerExecuted,
10907
11328
  title: options.title,
10908
- ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
11329
+ ...anyOptions.providerMetadata != null && (options.state === "output-available" || options.state === "output-error") ? { resultProviderMetadata: anyOptions.providerMetadata } : {},
11330
+ ...anyOptions.providerMetadata != null && !(options.state === "output-available" || options.state === "output-error") ? { callProviderMetadata: anyOptions.providerMetadata } : {}
10909
11331
  });
10910
11332
  }
10911
11333
  }
@@ -11189,6 +11611,7 @@ function processUIMessageStream2({
11189
11611
  output: chunk.output,
11190
11612
  preliminary: chunk.preliminary,
11191
11613
  providerExecuted: chunk.providerExecuted,
11614
+ providerMetadata: chunk.providerMetadata,
11192
11615
  title: toolInvocation.title
11193
11616
  });
11194
11617
  } else {
@@ -11200,6 +11623,7 @@ function processUIMessageStream2({
11200
11623
  output: chunk.output,
11201
11624
  providerExecuted: chunk.providerExecuted,
11202
11625
  preliminary: chunk.preliminary,
11626
+ providerMetadata: chunk.providerMetadata,
11203
11627
  title: toolInvocation.title
11204
11628
  });
11205
11629
  }
@@ -11216,6 +11640,7 @@ function processUIMessageStream2({
11216
11640
  input: toolInvocation.input,
11217
11641
  errorText: chunk.errorText,
11218
11642
  providerExecuted: chunk.providerExecuted,
11643
+ providerMetadata: chunk.providerMetadata,
11219
11644
  title: toolInvocation.title
11220
11645
  });
11221
11646
  } else {
@@ -11227,6 +11652,7 @@ function processUIMessageStream2({
11227
11652
  rawInput: toolInvocation.rawInput,
11228
11653
  errorText: chunk.errorText,
11229
11654
  providerExecuted: chunk.providerExecuted,
11655
+ providerMetadata: chunk.providerMetadata,
11230
11656
  title: toolInvocation.title
11231
11657
  });
11232
11658
  }
@@ -11623,6 +12049,25 @@ function toAISDKFinishReason(reason) {
11623
12049
  }
11624
12050
  return reason;
11625
12051
  }
12052
+ function normalizeToolPayloadState(state) {
12053
+ if (!state || typeof state !== "object") {
12054
+ return void 0;
12055
+ }
12056
+ const payloadState = state;
12057
+ if (Object.prototype.hasOwnProperty.call(payloadState, "projected") && !Object.prototype.hasOwnProperty.call(payloadState, "transformed")) {
12058
+ const { projected, ...rest } = payloadState;
12059
+ return { ...rest, transformed: projected };
12060
+ }
12061
+ return payloadState;
12062
+ }
12063
+ function getTransformedToolPayload(metadata, target, phase) {
12064
+ const mastraMetadata = metadata?.mastra;
12065
+ const state = mastraMetadata?.toolPayloadTransform?.[target]?.[phase] ?? mastraMetadata?.toolPayloadProjection?.[target]?.[phase];
12066
+ return normalizeToolPayloadState(state);
12067
+ }
12068
+ function hasTransformedToolPayload(transform) {
12069
+ return Boolean(transform && Object.prototype.hasOwnProperty.call(transform, "transformed"));
12070
+ }
11626
12071
  function convertMastraChunkToAISDKBase({
11627
12072
  chunk,
11628
12073
  mode = "stream",
@@ -11631,6 +12076,12 @@ function convertMastraChunkToAISDKBase({
11631
12076
  normalizeFinishReason,
11632
12077
  includeRawFinishReason = false
11633
12078
  }) {
12079
+ const displayInputTransform = getTransformedToolPayload(chunk.metadata, "display", "input-available");
12080
+ const displayInputDeltaTransform = getTransformedToolPayload(chunk.metadata, "display", "input-delta");
12081
+ const displayOutputTransform = getTransformedToolPayload(chunk.metadata, "display", "output-available");
12082
+ const displayErrorTransform = getTransformedToolPayload(chunk.metadata, "display", "error");
12083
+ const displayApprovalTransform = getTransformedToolPayload(chunk.metadata, "display", "approval");
12084
+ const displaySuspendTransform = getTransformedToolPayload(chunk.metadata, "display", "suspend");
11634
12085
  switch (chunk.type) {
11635
12086
  case "start":
11636
12087
  return {
@@ -11736,7 +12187,7 @@ function convertMastraChunkToAISDKBase({
11736
12187
  providerMetadata: chunk.payload.providerMetadata,
11737
12188
  providerExecuted: chunk.payload.providerExecuted,
11738
12189
  toolName: chunk.payload.toolName,
11739
- input: chunk.payload.args
12190
+ input: hasTransformedToolPayload(displayInputTransform) ? displayInputTransform.transformed : chunk.payload.args
11740
12191
  };
11741
12192
  case "tool-call-approval":
11742
12193
  return {
@@ -11747,7 +12198,7 @@ function convertMastraChunkToAISDKBase({
11747
12198
  runId: chunk.runId,
11748
12199
  toolCallId: chunk.payload.toolCallId,
11749
12200
  toolName: chunk.payload.toolName,
11750
- args: chunk.payload.args,
12201
+ args: hasTransformedToolPayload(displayApprovalTransform) ? displayApprovalTransform.transformed : chunk.payload.args,
11751
12202
  resumeSchema: chunk.payload.resumeSchema
11752
12203
  }
11753
12204
  };
@@ -11760,7 +12211,7 @@ function convertMastraChunkToAISDKBase({
11760
12211
  runId: chunk.runId,
11761
12212
  toolCallId: chunk.payload.toolCallId,
11762
12213
  toolName: chunk.payload.toolName,
11763
- suspendPayload: chunk.payload.suspendPayload,
12214
+ suspendPayload: hasTransformedToolPayload(displaySuspendTransform) ? displaySuspendTransform.transformed : chunk.payload.suspendPayload,
11764
12215
  resumeSchema: chunk.payload.resumeSchema
11765
12216
  }
11766
12217
  };
@@ -11780,10 +12231,13 @@ function convertMastraChunkToAISDKBase({
11780
12231
  providerMetadata: chunk.payload.providerMetadata
11781
12232
  };
11782
12233
  case "tool-call-delta":
12234
+ if (displayInputDeltaTransform?.suppress) {
12235
+ return;
12236
+ }
11783
12237
  return {
11784
12238
  type: "tool-input-delta",
11785
12239
  id: chunk.payload.toolCallId,
11786
- delta: chunk.payload.argsTextDelta,
12240
+ delta: displayInputDeltaTransform?.transformed ?? chunk.payload.argsTextDelta,
11787
12241
  providerMetadata: chunk.payload.providerMetadata
11788
12242
  };
11789
12243
  case "step-finish": {
@@ -11824,18 +12278,18 @@ function convertMastraChunkToAISDKBase({
11824
12278
  case "tool-result":
11825
12279
  return {
11826
12280
  type: "tool-result",
11827
- input: chunk.payload.args,
12281
+ input: hasTransformedToolPayload(displayInputTransform) ? displayInputTransform.transformed : chunk.payload.args,
11828
12282
  toolCallId: chunk.payload.toolCallId,
11829
12283
  providerExecuted: chunk.payload.providerExecuted,
11830
12284
  toolName: chunk.payload.toolName,
11831
- output: chunk.payload.result
12285
+ output: hasTransformedToolPayload(displayOutputTransform) ? displayOutputTransform.transformed : chunk.payload.result
11832
12286
  // providerMetadata: chunk.payload.providerMetadata, // AI v5 types don't show this?
11833
12287
  };
11834
12288
  case "tool-error":
11835
12289
  return {
11836
12290
  type: "tool-error",
11837
- error: chunk.payload.error,
11838
- input: chunk.payload.args,
12291
+ error: hasTransformedToolPayload(displayErrorTransform) ? displayErrorTransform.transformed : chunk.payload.error,
12292
+ input: hasTransformedToolPayload(displayInputTransform) ? displayInputTransform.transformed : chunk.payload.args,
11839
12293
  toolCallId: chunk.payload.toolCallId,
11840
12294
  providerExecuted: chunk.payload.providerExecuted,
11841
12295
  toolName: chunk.payload.toolName
@@ -11937,7 +12391,7 @@ function normalizeV6Usage(usage) {
11937
12391
  inputTokenDetails: {
11938
12392
  noCacheTokens: usage?.inputTokens,
11939
12393
  cacheReadTokens: usage?.cachedInputTokens,
11940
- cacheWriteTokens: void 0
12394
+ cacheWriteTokens: usage?.cacheCreationInputTokens
11941
12395
  },
11942
12396
  outputTokens: usage?.outputTokens,
11943
12397
  outputTokenDetails: {
@@ -11954,6 +12408,7 @@ function convertMastraChunkToAISDKv6({
11954
12408
  mode = "stream"
11955
12409
  }) {
11956
12410
  if (chunk.type === "tool-call-approval") {
12411
+ const displayTransform = getTransformedToolPayload(chunk.metadata, "display", "approval");
11957
12412
  return [
11958
12413
  {
11959
12414
  type: "tool-approval-request",
@@ -11968,7 +12423,7 @@ function convertMastraChunkToAISDKv6({
11968
12423
  runId: chunk.runId,
11969
12424
  toolCallId: chunk.payload.toolCallId,
11970
12425
  toolName: chunk.payload.toolName,
11971
- args: chunk.payload.args,
12426
+ args: hasTransformedToolPayload(displayTransform) ? displayTransform.transformed : chunk.payload.args,
11972
12427
  resumeSchema: chunk.payload.resumeSchema
11973
12428
  }
11974
12429
  }