@mastra/memory 1.23.0-alpha.3 → 1.23.0-alpha.4

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.
@@ -275,10 +275,10 @@ var BUILT_IN_EXTRACTOR_SLUGS = [...BUILT_IN_SLUGS];
275
275
  function isBuiltInExtractorSlug(slug) {
276
276
  return BUILT_IN_SLUGS.has(slug);
277
277
  }
278
- function slugifyExtractorName(name21) {
278
+ function slugifyExtractorName(name28) {
279
279
  let normalized = "";
280
280
  let previousWasSeparator = false;
281
- for (const char of name21.trim().toLowerCase()) {
281
+ for (const char of name28.trim().toLowerCase()) {
282
282
  const code = char.charCodeAt(0);
283
283
  const isLetter = code >= 97 && code <= 122;
284
284
  const isNumber = code >= 48 && code <= 57;
@@ -297,9 +297,9 @@ function slugifyExtractorName(name21) {
297
297
  }
298
298
  return normalized.endsWith("-") ? normalized.slice(0, -1) : normalized;
299
299
  }
300
- function assertValidSlug(slug, name21) {
300
+ function assertValidSlug(slug, name28) {
301
301
  if (!slug) {
302
- throw new Error(`Extractor name "${name21}" must produce a non-empty slug.`);
302
+ throw new Error(`Extractor name "${name28}" must produce a non-empty slug.`);
303
303
  }
304
304
  const first = slug.charCodeAt(0);
305
305
  const last = slug.charCodeAt(slug.length - 1);
@@ -310,7 +310,7 @@ function assertValidSlug(slug, name21) {
310
310
  return code >= 97 && code <= 122 || code >= 48 && code <= 57 || char === "-";
311
311
  });
312
312
  if (!startsWithLetter || !endsWithLetterOrNumber || !hasOnlySlugCharacters) {
313
- throw new Error(`Extractor name "${name21}" produced invalid slug "${slug}".`);
313
+ throw new Error(`Extractor name "${name28}" produced invalid slug "${slug}".`);
314
314
  }
315
315
  }
316
316
  var Extractor = class _Extractor {
@@ -327,20 +327,20 @@ var Extractor = class _Extractor {
327
327
  instructionsConfig;
328
328
  schemaConfig;
329
329
  constructor(config, internal = false) {
330
- const name21 = config.name.trim();
330
+ const name28 = config.name.trim();
331
331
  const instructions = typeof config.instructions === "string" ? config.instructions.trim() : void 0;
332
- const slug = slugifyExtractorName(name21);
333
- if (!name21) {
332
+ const slug = slugifyExtractorName(name28);
333
+ if (!name28) {
334
334
  throw new Error("Extractor name is required.");
335
335
  }
336
336
  if (instructions !== void 0 && !instructions) {
337
- throw new Error(`Extractor "${name21}" must include instructions.`);
337
+ throw new Error(`Extractor "${name28}" must include instructions.`);
338
338
  }
339
- assertValidSlug(slug, name21);
339
+ assertValidSlug(slug, name28);
340
340
  if (!internal && RESERVED_XML_TAGS.has(slug)) {
341
341
  throw new Error(`Extractor slug "${slug}" is reserved by Observational Memory.`);
342
342
  }
343
- this.name = name21;
343
+ this.name = name28;
344
344
  this.slug = slug;
345
345
  this.instructionsConfig = config.instructions;
346
346
  this.schemaConfig = config.schema;
@@ -1697,13 +1697,13 @@ var ObservationStrategy = class _ObservationStrategy {
1697
1697
  generateCycleId() {
1698
1698
  return crypto.randomUUID();
1699
1699
  }
1700
- async streamMarker(marker21) {
1700
+ async streamMarker(marker28) {
1701
1701
  if (this.opts.writer) {
1702
- await this.opts.writer.custom({ ...marker21, transient: true }).catch(() => {
1702
+ await this.opts.writer.custom({ ...marker28, transient: true }).catch(() => {
1703
1703
  });
1704
1704
  }
1705
- const markerThreadId = marker21.data?.threadId ?? this.opts.threadId;
1706
- await this.persistMarkerToStorage(marker21, markerThreadId, this.opts.resourceId);
1705
+ const markerThreadId = marker28.data?.threadId ?? this.opts.threadId;
1706
+ await this.persistMarkerToStorage(marker28, markerThreadId, this.opts.resourceId);
1707
1707
  }
1708
1708
  getObservationMarkerConfig() {
1709
1709
  return {
@@ -1841,7 +1841,7 @@ ${threadClose}`;
1841
1841
  * Fetches messages directly from the DB so it works even when
1842
1842
  * no MessageList is available (e.g. async buffering ops).
1843
1843
  */
1844
- async persistMarkerToStorage(marker21, threadId, resourceId) {
1844
+ async persistMarkerToStorage(marker28, threadId, resourceId) {
1845
1845
  try {
1846
1846
  const result = await this.storage.listMessages({
1847
1847
  threadId,
@@ -1851,10 +1851,10 @@ ${threadClose}`;
1851
1851
  const messages = result?.messages ?? [];
1852
1852
  for (const msg of messages) {
1853
1853
  if (msg?.role === "assistant" && msg.content?.parts && Array.isArray(msg.content.parts)) {
1854
- const markerData = marker21.data;
1855
- const alreadyPresent = markerData?.cycleId && msg.content.parts.some((p) => p?.type === marker21.type && p?.data?.cycleId === markerData.cycleId);
1854
+ const markerData = marker28.data;
1855
+ const alreadyPresent = markerData?.cycleId && msg.content.parts.some((p) => p?.type === marker28.type && p?.data?.cycleId === markerData.cycleId);
1856
1856
  if (!alreadyPresent) {
1857
- msg.content.parts.push(marker21);
1857
+ msg.content.parts.push(marker28);
1858
1858
  }
1859
1859
  await this.messageHistory.persistMessages({
1860
1860
  messages: [msg],
@@ -1872,16 +1872,16 @@ ${threadClose}`;
1872
1872
  * Persist a marker part on the last assistant message in a MessageList
1873
1873
  * AND save the updated message to the DB.
1874
1874
  */
1875
- async persistMarkerToMessage(marker21, messageList, threadId, resourceId) {
1875
+ async persistMarkerToMessage(marker28, messageList, threadId, resourceId) {
1876
1876
  if (!messageList) return;
1877
1877
  const allMsgs = messageList.get.all.db();
1878
1878
  for (let i = allMsgs.length - 1; i >= 0; i--) {
1879
1879
  const msg = allMsgs[i];
1880
1880
  if (msg?.role === "assistant" && msg.content?.parts && Array.isArray(msg.content.parts)) {
1881
- const markerData = marker21.data;
1882
- const alreadyPresent = markerData?.cycleId && msg.content.parts.some((p) => p?.type === marker21.type && p?.data?.cycleId === markerData.cycleId);
1881
+ const markerData = marker28.data;
1882
+ const alreadyPresent = markerData?.cycleId && msg.content.parts.some((p) => p?.type === marker28.type && p?.data?.cycleId === markerData.cycleId);
1883
1883
  if (!alreadyPresent) {
1884
- msg.content.parts.push(marker21);
1884
+ msg.content.parts.push(marker28);
1885
1885
  }
1886
1886
  try {
1887
1887
  await this.messageHistory.persistMessages({
@@ -2275,13 +2275,13 @@ var AsyncBufferObservationStrategy = class extends ObservationStrategy {
2275
2275
  metadata: newMetadata
2276
2276
  });
2277
2277
  if (shouldUpdateThreadTitle) {
2278
- const marker21 = createThreadUpdateMarker({
2278
+ const marker28 = createThreadUpdateMarker({
2279
2279
  cycleId: this.cycleId,
2280
2280
  threadId,
2281
2281
  oldTitle,
2282
2282
  newTitle
2283
2283
  });
2284
- await this.streamMarker(marker21);
2284
+ await this.streamMarker(marker28);
2285
2285
  }
2286
2286
  }
2287
2287
  }
@@ -2665,8 +2665,8 @@ var ResourceScopedObservationStrategy = class extends ObservationStrategy {
2665
2665
  }
2666
2666
  }
2667
2667
  }
2668
- for (const marker21 of threadUpdateMarkers) {
2669
- await this.streamMarker(marker21);
2668
+ for (const marker28 of threadUpdateMarkers) {
2669
+ await this.streamMarker(marker28);
2670
2670
  }
2671
2671
  await this.storage.updateActiveObservations({
2672
2672
  id: record.id,
@@ -4860,7 +4860,7 @@ async function withRetry(fn, opts) {
4860
4860
  }
4861
4861
  }
4862
4862
 
4863
- // ../_vendored/ai_v4/dist/chunk-QGLOM3VL.js
4863
+ // ../_vendored/ai_v4/dist/chunk-SJKFJOR6.js
4864
4864
  var __create = Object.create;
4865
4865
  var __defProp = Object.defineProperty;
4866
4866
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -7368,15 +7368,15 @@ var DiagAPI = (
7368
7368
  return logger[funcName].apply(logger, __spreadArray2([], __read2(args), false));
7369
7369
  };
7370
7370
  }
7371
- var self = this;
7371
+ var self2 = this;
7372
7372
  var setLogger = function(logger, optionsOrLogLevel) {
7373
7373
  var _a173, _b19, _c;
7374
7374
  if (optionsOrLogLevel === void 0) {
7375
7375
  optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
7376
7376
  }
7377
- if (logger === self) {
7377
+ if (logger === self2) {
7378
7378
  var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
7379
- self.error((_a173 = err.stack) !== null && _a173 !== void 0 ? _a173 : err.message);
7379
+ self2.error((_a173 = err.stack) !== null && _a173 !== void 0 ? _a173 : err.message);
7380
7380
  return false;
7381
7381
  }
7382
7382
  if (typeof optionsOrLogLevel === "number") {
@@ -7391,20 +7391,20 @@ var DiagAPI = (
7391
7391
  oldLogger.warn("Current logger will be overwritten from " + stack);
7392
7392
  newLogger.warn("Current logger will overwrite one already registered from " + stack);
7393
7393
  }
7394
- return registerGlobal("diag", newLogger, self, true);
7394
+ return registerGlobal("diag", newLogger, self2, true);
7395
7395
  };
7396
- self.setLogger = setLogger;
7397
- self.disable = function() {
7398
- unregisterGlobal(API_NAME, self);
7396
+ self2.setLogger = setLogger;
7397
+ self2.disable = function() {
7398
+ unregisterGlobal(API_NAME, self2);
7399
7399
  };
7400
- self.createComponentLogger = function(options) {
7400
+ self2.createComponentLogger = function(options) {
7401
7401
  return new DiagComponentLogger(options);
7402
7402
  };
7403
- self.verbose = _logProxy("verbose");
7404
- self.debug = _logProxy("debug");
7405
- self.info = _logProxy("info");
7406
- self.warn = _logProxy("warn");
7407
- self.error = _logProxy("error");
7403
+ self2.verbose = _logProxy("verbose");
7404
+ self2.debug = _logProxy("debug");
7405
+ self2.info = _logProxy("info");
7406
+ self2.warn = _logProxy("warn");
7407
+ self2.error = _logProxy("error");
7408
7408
  }
7409
7409
  DiagAPI22.instance = function() {
7410
7410
  if (!this._instance) {
@@ -7422,18 +7422,18 @@ var BaseContext = (
7422
7422
  /** @class */
7423
7423
  /* @__PURE__ */ (function() {
7424
7424
  function BaseContext22(parentContext) {
7425
- var self = this;
7426
- self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
7427
- self.getValue = function(key) {
7428
- return self._currentContext.get(key);
7425
+ var self2 = this;
7426
+ self2._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
7427
+ self2.getValue = function(key) {
7428
+ return self2._currentContext.get(key);
7429
7429
  };
7430
- self.setValue = function(key, value) {
7431
- var context2 = new BaseContext22(self._currentContext);
7430
+ self2.setValue = function(key, value) {
7431
+ var context2 = new BaseContext22(self2._currentContext);
7432
7432
  context2._currentContext.set(key, value);
7433
7433
  return context2;
7434
7434
  };
7435
- self.deleteValue = function(key) {
7436
- var context2 = new BaseContext22(self._currentContext);
7435
+ self2.deleteValue = function(key) {
7436
+ var context2 = new BaseContext22(self2._currentContext);
7437
7437
  context2._currentContext.delete(key);
7438
7438
  return context2;
7439
7439
  };
@@ -9354,6 +9354,90 @@ function createAbortError() {
9354
9354
  function extractResponseHeaders(response) {
9355
9355
  return Object.fromEntries([...response.headers]);
9356
9356
  }
9357
+ var name142 = "AI_DownloadError";
9358
+ var marker152 = `vercel.ai.error.${name142}`;
9359
+ var symbol152 = Symbol.for(marker152);
9360
+ var _a152;
9361
+ var _b15;
9362
+ var DownloadError = class extends (_b15 = AISDKError2, _a152 = symbol152, _b15) {
9363
+ constructor({
9364
+ url,
9365
+ statusCode,
9366
+ statusText,
9367
+ cause,
9368
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
9369
+ }) {
9370
+ super({ name: name142, message, cause });
9371
+ this[_a152] = true;
9372
+ this.url = url;
9373
+ this.statusCode = statusCode;
9374
+ this.statusText = statusText;
9375
+ }
9376
+ static isInstance(error) {
9377
+ return AISDKError2.hasMarker(error, marker152);
9378
+ }
9379
+ };
9380
+ async function cancelResponseBody(response) {
9381
+ var _a223;
9382
+ try {
9383
+ await ((_a223 = response.body) == null ? void 0 : _a223.cancel());
9384
+ } catch (e) {
9385
+ }
9386
+ }
9387
+ var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
9388
+ async function readResponseWithSizeLimit({
9389
+ response,
9390
+ url,
9391
+ maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE
9392
+ }) {
9393
+ const contentLength = response.headers.get("content-length");
9394
+ if (contentLength != null) {
9395
+ const length = parseInt(contentLength, 10);
9396
+ if (!isNaN(length) && length > maxBytes) {
9397
+ await cancelResponseBody(response);
9398
+ throw new DownloadError({
9399
+ url,
9400
+ message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`
9401
+ });
9402
+ }
9403
+ }
9404
+ const body = response.body;
9405
+ if (body == null) {
9406
+ return new Uint8Array(0);
9407
+ }
9408
+ const reader = body.getReader();
9409
+ const chunks = [];
9410
+ let totalBytes = 0;
9411
+ try {
9412
+ while (true) {
9413
+ const { done, value } = await reader.read();
9414
+ if (done) {
9415
+ break;
9416
+ }
9417
+ totalBytes += value.length;
9418
+ if (totalBytes > maxBytes) {
9419
+ throw new DownloadError({
9420
+ url,
9421
+ message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`
9422
+ });
9423
+ }
9424
+ chunks.push(value);
9425
+ }
9426
+ } finally {
9427
+ try {
9428
+ await reader.cancel();
9429
+ } finally {
9430
+ reader.releaseLock();
9431
+ }
9432
+ }
9433
+ const result = new Uint8Array(totalBytes);
9434
+ let offset = 0;
9435
+ for (const chunk of chunks) {
9436
+ result.set(chunk, offset);
9437
+ offset += chunk.length;
9438
+ }
9439
+ return result;
9440
+ }
9357
9441
  var createIdGenerator2 = ({
9358
9442
  prefix,
9359
9443
  size = 16,
@@ -9421,11 +9505,11 @@ function handleFetchError({
9421
9505
  return error;
9422
9506
  }
9423
9507
  function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
9424
- var _a224, _b222, _c;
9508
+ var _a223, _b222, _c;
9425
9509
  if (globalThisAny.window) {
9426
9510
  return `runtime/browser`;
9427
9511
  }
9428
- if ((_a224 = globalThisAny.navigator) == null ? void 0 : _a224.userAgent) {
9512
+ if ((_a223 = globalThisAny.navigator) == null ? void 0 : _a223.userAgent) {
9429
9513
  return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
9430
9514
  }
9431
9515
  if ((_c = (_b222 = globalThisAny.process) == null ? void 0 : _b222.versions) == null ? void 0 : _c.node) {
@@ -9466,7 +9550,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
9466
9550
  );
9467
9551
  return Object.fromEntries(normalizedHeaders.entries());
9468
9552
  }
9469
- var VERSION2 = "3.0.25";
9553
+ var VERSION2 = "3.0.28";
9470
9554
  var getOriginalFetch = () => globalThis.fetch;
9471
9555
  var getFromApi = async ({
9472
9556
  url,
@@ -9813,7 +9897,7 @@ function tool(tool22) {
9813
9897
  }
9814
9898
  function createProviderDefinedToolFactoryWithOutputSchema({
9815
9899
  id,
9816
- name: name224,
9900
+ name: name223,
9817
9901
  inputSchema,
9818
9902
  outputSchema: outputSchema3
9819
9903
  }) {
@@ -9827,7 +9911,7 @@ function createProviderDefinedToolFactoryWithOutputSchema({
9827
9911
  }) => tool({
9828
9912
  type: "provider-defined",
9829
9913
  id,
9830
- name: name224,
9914
+ name: name223,
9831
9915
  args,
9832
9916
  inputSchema,
9833
9917
  outputSchema: outputSchema3,
@@ -9844,12 +9928,24 @@ async function resolve(value) {
9844
9928
  }
9845
9929
  return Promise.resolve(value);
9846
9930
  }
9931
+ var textDecoder = new TextDecoder();
9932
+ async function readResponseBodyAsText({
9933
+ response,
9934
+ url
9935
+ }) {
9936
+ return textDecoder.decode(
9937
+ await readResponseWithSizeLimit({
9938
+ response,
9939
+ url
9940
+ })
9941
+ );
9942
+ }
9847
9943
  var createJsonErrorResponseHandler = ({
9848
9944
  errorSchema,
9849
9945
  errorToMessage,
9850
9946
  isRetryable
9851
9947
  }) => async ({ response, url, requestBodyValues }) => {
9852
- const responseBody = await response.text();
9948
+ const responseBody = await readResponseBodyAsText({ response, url });
9853
9949
  const responseHeaders = extractResponseHeaders(response);
9854
9950
  if (responseBody.trim() === "") {
9855
9951
  return {
@@ -9912,7 +10008,7 @@ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) =>
9912
10008
  };
9913
10009
  };
9914
10010
  var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
9915
- const responseBody = await response.text();
10011
+ const responseBody = await readResponseBodyAsText({ response, url });
9916
10012
  const parsedResult = await safeParseJSON2({
9917
10013
  text: responseBody,
9918
10014
  schema: responseSchema
@@ -10022,11 +10118,11 @@ function parseAnyDef2() {
10022
10118
  return {};
10023
10119
  }
10024
10120
  function parseArrayDef2(def, refs) {
10025
- var _a224, _b222, _c;
10121
+ var _a223, _b222, _c;
10026
10122
  const res = {
10027
10123
  type: "array"
10028
10124
  };
10029
- 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) {
10125
+ if (((_a223 = def.type) == null ? void 0 : _a223._def) && ((_c = (_b222 = def.type) == null ? void 0 : _b222._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
10030
10126
  res.items = parseDef2(def.type._def, {
10031
10127
  ...refs,
10032
10128
  currentPath: [...refs.currentPath, "items"]
@@ -10385,8 +10481,8 @@ function escapeNonAlphaNumeric2(source) {
10385
10481
  return result;
10386
10482
  }
10387
10483
  function addFormat2(schema, value, message, refs) {
10388
- var _a224;
10389
- if (schema.format || ((_a224 = schema.anyOf) == null ? void 0 : _a224.some((x) => x.format))) {
10484
+ var _a223;
10485
+ if (schema.format || ((_a223 = schema.anyOf) == null ? void 0 : _a223.some((x) => x.format))) {
10390
10486
  if (!schema.anyOf) {
10391
10487
  schema.anyOf = [];
10392
10488
  }
@@ -10405,8 +10501,8 @@ function addFormat2(schema, value, message, refs) {
10405
10501
  }
10406
10502
  }
10407
10503
  function addPattern2(schema, regex, message, refs) {
10408
- var _a224;
10409
- if (schema.pattern || ((_a224 = schema.allOf) == null ? void 0 : _a224.some((x) => x.pattern))) {
10504
+ var _a223;
10505
+ if (schema.pattern || ((_a223 = schema.allOf) == null ? void 0 : _a223.some((x) => x.pattern))) {
10410
10506
  if (!schema.allOf) {
10411
10507
  schema.allOf = [];
10412
10508
  }
@@ -10425,7 +10521,7 @@ function addPattern2(schema, regex, message, refs) {
10425
10521
  }
10426
10522
  }
10427
10523
  function stringifyRegExpWithFlags2(regex, refs) {
10428
- var _a224;
10524
+ var _a223;
10429
10525
  if (!refs.applyRegexFlags || !regex.flags) {
10430
10526
  return regex.source;
10431
10527
  }
@@ -10455,7 +10551,7 @@ function stringifyRegExpWithFlags2(regex, refs) {
10455
10551
  pattern += source[i];
10456
10552
  pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
10457
10553
  inCharRange = false;
10458
- } else if (source[i + 1] === "-" && ((_a224 = source[i + 2]) == null ? void 0 : _a224.match(/[a-z]/))) {
10554
+ } else if (source[i + 1] === "-" && ((_a223 = source[i + 2]) == null ? void 0 : _a223.match(/[a-z]/))) {
10459
10555
  pattern += source[i];
10460
10556
  inCharRange = true;
10461
10557
  } else {
@@ -10497,13 +10593,13 @@ function stringifyRegExpWithFlags2(regex, refs) {
10497
10593
  return pattern;
10498
10594
  }
10499
10595
  function parseRecordDef2(def, refs) {
10500
- var _a224, _b222, _c, _d, _e, _f;
10596
+ var _a223, _b222, _c, _d, _e, _f;
10501
10597
  const schema = {
10502
10598
  type: "object",
10503
- additionalProperties: (_a224 = parseDef2(def.valueType._def, {
10599
+ additionalProperties: (_a223 = parseDef2(def.valueType._def, {
10504
10600
  ...refs,
10505
10601
  currentPath: [...refs.currentPath, "additionalProperties"]
10506
- })) != null ? _a224 : refs.allowedAdditionalProperties
10602
+ })) != null ? _a223 : refs.allowedAdditionalProperties
10507
10603
  };
10508
10604
  if (((_b222 = def.keyType) == null ? void 0 : _b222._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
10509
10605
  const { type, ...keyType } = parseStringDef2(def.keyType._def, refs);
@@ -10760,8 +10856,8 @@ function safeIsOptional2(schema) {
10760
10856
  }
10761
10857
  }
10762
10858
  var parseOptionalDef2 = (def, refs) => {
10763
- var _a224;
10764
- if (refs.currentPath.toString() === ((_a224 = refs.propertyPath) == null ? void 0 : _a224.toString())) {
10859
+ var _a223;
10860
+ if (refs.currentPath.toString() === ((_a223 = refs.propertyPath) == null ? void 0 : _a223.toString())) {
10765
10861
  return parseDef2(def.innerType._def, refs);
10766
10862
  }
10767
10863
  const innerSchema = parseDef2(def.innerType._def, {
@@ -10938,10 +11034,10 @@ var getRelativePath2 = (pathA, pathB) => {
10938
11034
  return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
10939
11035
  };
10940
11036
  function parseDef2(def, refs, forceResolution = false) {
10941
- var _a224;
11037
+ var _a223;
10942
11038
  const seenItem = refs.seen.get(def);
10943
11039
  if (refs.override) {
10944
- const overrideResult = (_a224 = refs.override) == null ? void 0 : _a224.call(
11040
+ const overrideResult = (_a223 = refs.override) == null ? void 0 : _a223.call(
10945
11041
  refs,
10946
11042
  def,
10947
11043
  refs,
@@ -11007,11 +11103,11 @@ var getRefs2 = (options) => {
11007
11103
  currentPath,
11008
11104
  propertyPath: void 0,
11009
11105
  seen: new Map(
11010
- Object.entries(_options.definitions).map(([name224, def]) => [
11106
+ Object.entries(_options.definitions).map(([name223, def]) => [
11011
11107
  def._def,
11012
11108
  {
11013
11109
  def: def._def,
11014
- path: [..._options.basePath, _options.definitionPath, name224],
11110
+ path: [..._options.basePath, _options.definitionPath, name223],
11015
11111
  // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
11016
11112
  jsonSchema: void 0
11017
11113
  }
@@ -11020,50 +11116,50 @@ var getRefs2 = (options) => {
11020
11116
  };
11021
11117
  };
11022
11118
  var zodToJsonSchema2 = (schema, options) => {
11023
- var _a224;
11119
+ var _a223;
11024
11120
  const refs = getRefs2(options);
11025
11121
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
11026
- (acc, [name324, schema2]) => {
11027
- var _a324;
11122
+ (acc, [name323, schema2]) => {
11123
+ var _a323;
11028
11124
  return {
11029
11125
  ...acc,
11030
- [name324]: (_a324 = parseDef2(
11126
+ [name323]: (_a323 = parseDef2(
11031
11127
  schema2._def,
11032
11128
  {
11033
11129
  ...refs,
11034
- currentPath: [...refs.basePath, refs.definitionPath, name324]
11130
+ currentPath: [...refs.basePath, refs.definitionPath, name323]
11035
11131
  },
11036
11132
  true
11037
- )) != null ? _a324 : parseAnyDef2()
11133
+ )) != null ? _a323 : parseAnyDef2()
11038
11134
  };
11039
11135
  },
11040
11136
  {}
11041
11137
  ) : void 0;
11042
- const name224 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
11043
- const main = (_a224 = parseDef2(
11138
+ const name223 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
11139
+ const main = (_a223 = parseDef2(
11044
11140
  schema._def,
11045
- name224 === void 0 ? refs : {
11141
+ name223 === void 0 ? refs : {
11046
11142
  ...refs,
11047
- currentPath: [...refs.basePath, refs.definitionPath, name224]
11143
+ currentPath: [...refs.basePath, refs.definitionPath, name223]
11048
11144
  },
11049
11145
  false
11050
- )) != null ? _a224 : parseAnyDef2();
11146
+ )) != null ? _a223 : parseAnyDef2();
11051
11147
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
11052
11148
  if (title !== void 0) {
11053
11149
  main.title = title;
11054
11150
  }
11055
- const combined = name224 === void 0 ? definitions ? {
11151
+ const combined = name223 === void 0 ? definitions ? {
11056
11152
  ...main,
11057
11153
  [refs.definitionPath]: definitions
11058
11154
  } : main : {
11059
11155
  $ref: [
11060
11156
  ...refs.$refStrategy === "relative" ? [] : refs.basePath,
11061
11157
  refs.definitionPath,
11062
- name224
11158
+ name223
11063
11159
  ].join("/"),
11064
11160
  [refs.definitionPath]: {
11065
11161
  ...definitions,
11066
- [name224]: main
11162
+ [name223]: main
11067
11163
  }
11068
11164
  };
11069
11165
  combined.$schema = "http://json-schema.org/draft-07/schema#";
@@ -11071,8 +11167,8 @@ var zodToJsonSchema2 = (schema, options) => {
11071
11167
  };
11072
11168
  var zod_to_json_schema_default = zodToJsonSchema2;
11073
11169
  function zod3Schema(zodSchema22, options) {
11074
- var _a224;
11075
- const useReferences = (_a224 = void 0 ) != null ? _a224 : false;
11170
+ var _a223;
11171
+ const useReferences = (_a223 = void 0 ) != null ? _a223 : false;
11076
11172
  return jsonSchema2(
11077
11173
  // defer json schema creation to avoid unnecessary computation when only validation is needed
11078
11174
  () => zod_to_json_schema_default(zodSchema22, {
@@ -11087,8 +11183,8 @@ function zod3Schema(zodSchema22, options) {
11087
11183
  );
11088
11184
  }
11089
11185
  function zod4Schema(zodSchema22, options) {
11090
- var _a224;
11091
- const useReferences = (_a224 = void 0 ) != null ? _a224 : false;
11186
+ var _a223;
11187
+ const useReferences = (_a223 = void 0 ) != null ? _a223 : false;
11092
11188
  return jsonSchema2(
11093
11189
  // defer json schema creation to avoid unnecessary computation when only validation is needed
11094
11190
  () => addAdditionalPropertiesToJsonSchema(
@@ -11225,101 +11321,121 @@ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the toke
11225
11321
  });
11226
11322
  }
11227
11323
  };
11228
- var name24 = "GatewayInvalidRequestError";
11324
+ var name24 = "GatewayForbiddenError";
11229
11325
  var marker34 = `vercel.ai.gateway.error.${name24}`;
11230
11326
  var symbol34 = Symbol.for(marker34);
11231
11327
  var _a34;
11232
11328
  var _b32;
11233
- var GatewayInvalidRequestError = class extends (_b32 = GatewayError, _a34 = symbol34, _b32) {
11329
+ var GatewayForbiddenError = class extends (_b32 = GatewayError, _a34 = symbol34, _b32) {
11234
11330
  constructor({
11235
- message = "Invalid request",
11236
- statusCode = 400,
11331
+ message = "Forbidden",
11332
+ statusCode = 403,
11237
11333
  cause
11238
11334
  } = {}) {
11239
11335
  super({ message, statusCode, cause });
11240
11336
  this[_a34] = true;
11241
11337
  this.name = name24;
11242
- this.type = "invalid_request_error";
11338
+ this.type = "forbidden";
11243
11339
  }
11244
11340
  static isInstance(error) {
11245
11341
  return GatewayError.hasMarker(error) && symbol34 in error;
11246
11342
  }
11247
11343
  };
11248
- var name34 = "GatewayRateLimitError";
11344
+ var name34 = "GatewayInvalidRequestError";
11249
11345
  var marker44 = `vercel.ai.gateway.error.${name34}`;
11250
11346
  var symbol44 = Symbol.for(marker44);
11251
11347
  var _a44;
11252
11348
  var _b42;
11253
- var GatewayRateLimitError = class extends (_b42 = GatewayError, _a44 = symbol44, _b42) {
11349
+ var GatewayInvalidRequestError = class extends (_b42 = GatewayError, _a44 = symbol44, _b42) {
11254
11350
  constructor({
11255
- message = "Rate limit exceeded",
11256
- statusCode = 429,
11351
+ message = "Invalid request",
11352
+ statusCode = 400,
11257
11353
  cause
11258
11354
  } = {}) {
11259
11355
  super({ message, statusCode, cause });
11260
11356
  this[_a44] = true;
11261
11357
  this.name = name34;
11262
- this.type = "rate_limit_exceeded";
11358
+ this.type = "invalid_request_error";
11263
11359
  }
11264
11360
  static isInstance(error) {
11265
11361
  return GatewayError.hasMarker(error) && symbol44 in error;
11266
11362
  }
11267
11363
  };
11268
- var name44 = "GatewayModelNotFoundError";
11364
+ var name44 = "GatewayRateLimitError";
11269
11365
  var marker54 = `vercel.ai.gateway.error.${name44}`;
11270
11366
  var symbol54 = Symbol.for(marker54);
11271
- var modelNotFoundParamSchema = lazyValidator(
11272
- () => zodSchema2(
11273
- z$1.object({
11274
- modelId: z$1.string()
11275
- })
11276
- )
11277
- );
11278
11367
  var _a54;
11279
11368
  var _b52;
11280
- var GatewayModelNotFoundError = class extends (_b52 = GatewayError, _a54 = symbol54, _b52) {
11369
+ var GatewayRateLimitError = class extends (_b52 = GatewayError, _a54 = symbol54, _b52) {
11281
11370
  constructor({
11282
- message = "Model not found",
11283
- statusCode = 404,
11284
- modelId,
11371
+ message = "Rate limit exceeded",
11372
+ statusCode = 429,
11285
11373
  cause
11286
11374
  } = {}) {
11287
11375
  super({ message, statusCode, cause });
11288
11376
  this[_a54] = true;
11289
11377
  this.name = name44;
11290
- this.type = "model_not_found";
11291
- this.modelId = modelId;
11378
+ this.type = "rate_limit_exceeded";
11292
11379
  }
11293
11380
  static isInstance(error) {
11294
11381
  return GatewayError.hasMarker(error) && symbol54 in error;
11295
11382
  }
11296
11383
  };
11297
- var name54 = "GatewayInternalServerError";
11384
+ var name54 = "GatewayModelNotFoundError";
11298
11385
  var marker64 = `vercel.ai.gateway.error.${name54}`;
11299
11386
  var symbol64 = Symbol.for(marker64);
11387
+ var modelNotFoundParamSchema = lazyValidator(
11388
+ () => zodSchema2(
11389
+ z$1.object({
11390
+ modelId: z$1.string()
11391
+ })
11392
+ )
11393
+ );
11300
11394
  var _a64;
11301
11395
  var _b62;
11302
- var GatewayInternalServerError = class extends (_b62 = GatewayError, _a64 = symbol64, _b62) {
11396
+ var GatewayModelNotFoundError = class extends (_b62 = GatewayError, _a64 = symbol64, _b62) {
11303
11397
  constructor({
11304
- message = "Internal server error",
11305
- statusCode = 500,
11398
+ message = "Model not found",
11399
+ statusCode = 404,
11400
+ modelId,
11306
11401
  cause
11307
11402
  } = {}) {
11308
11403
  super({ message, statusCode, cause });
11309
11404
  this[_a64] = true;
11310
11405
  this.name = name54;
11311
- this.type = "internal_server_error";
11406
+ this.type = "model_not_found";
11407
+ this.modelId = modelId;
11312
11408
  }
11313
11409
  static isInstance(error) {
11314
11410
  return GatewayError.hasMarker(error) && symbol64 in error;
11315
11411
  }
11316
11412
  };
11317
- var name64 = "GatewayResponseError";
11413
+ var name64 = "GatewayInternalServerError";
11318
11414
  var marker74 = `vercel.ai.gateway.error.${name64}`;
11319
11415
  var symbol74 = Symbol.for(marker74);
11320
11416
  var _a74;
11321
11417
  var _b72;
11322
- var GatewayResponseError = class extends (_b72 = GatewayError, _a74 = symbol74, _b72) {
11418
+ var GatewayInternalServerError = class extends (_b72 = GatewayError, _a74 = symbol74, _b72) {
11419
+ constructor({
11420
+ message = "Internal server error",
11421
+ statusCode = 500,
11422
+ cause
11423
+ } = {}) {
11424
+ super({ message, statusCode, cause });
11425
+ this[_a74] = true;
11426
+ this.name = name64;
11427
+ this.type = "internal_server_error";
11428
+ }
11429
+ static isInstance(error) {
11430
+ return GatewayError.hasMarker(error) && symbol74 in error;
11431
+ }
11432
+ };
11433
+ var name74 = "GatewayResponseError";
11434
+ var marker84 = `vercel.ai.gateway.error.${name74}`;
11435
+ var symbol84 = Symbol.for(marker84);
11436
+ var _a84;
11437
+ var _b82;
11438
+ var GatewayResponseError = class extends (_b82 = GatewayError, _a84 = symbol84, _b82) {
11323
11439
  constructor({
11324
11440
  message = "Invalid response from Gateway",
11325
11441
  statusCode = 502,
@@ -11328,14 +11444,14 @@ var GatewayResponseError = class extends (_b72 = GatewayError, _a74 = symbol74,
11328
11444
  cause
11329
11445
  } = {}) {
11330
11446
  super({ message, statusCode, cause });
11331
- this[_a74] = true;
11332
- this.name = name64;
11447
+ this[_a84] = true;
11448
+ this.name = name74;
11333
11449
  this.type = "response_error";
11334
11450
  this.response = response;
11335
11451
  this.validationError = validationError;
11336
11452
  }
11337
11453
  static isInstance(error) {
11338
- return GatewayError.hasMarker(error) && symbol74 in error;
11454
+ return GatewayError.hasMarker(error) && symbol84 in error;
11339
11455
  }
11340
11456
  };
11341
11457
  async function createGatewayErrorFromResponse({
@@ -11387,6 +11503,8 @@ async function createGatewayErrorFromResponse({
11387
11503
  }
11388
11504
  case "internal_server_error":
11389
11505
  return new GatewayInternalServerError({ message, statusCode, cause });
11506
+ case "forbidden":
11507
+ return new GatewayForbiddenError({ message, statusCode, cause });
11390
11508
  default:
11391
11509
  return new GatewayInternalServerError({ message, statusCode, cause });
11392
11510
  }
@@ -11416,24 +11534,24 @@ function extractApiCallResponse(error) {
11416
11534
  }
11417
11535
  return {};
11418
11536
  }
11419
- var name74 = "GatewayTimeoutError";
11420
- var marker84 = `vercel.ai.gateway.error.${name74}`;
11421
- var symbol84 = Symbol.for(marker84);
11422
- var _a84;
11423
- var _b82;
11424
- var GatewayTimeoutError = class _GatewayTimeoutError extends (_b82 = GatewayError, _a84 = symbol84, _b82) {
11537
+ var name84 = "GatewayTimeoutError";
11538
+ var marker94 = `vercel.ai.gateway.error.${name84}`;
11539
+ var symbol94 = Symbol.for(marker94);
11540
+ var _a94;
11541
+ var _b92;
11542
+ var GatewayTimeoutError = class _GatewayTimeoutError extends (_b92 = GatewayError, _a94 = symbol94, _b92) {
11425
11543
  constructor({
11426
11544
  message = "Request timed out",
11427
11545
  statusCode = 408,
11428
11546
  cause
11429
11547
  } = {}) {
11430
11548
  super({ message, statusCode, cause });
11431
- this[_a84] = true;
11432
- this.name = name74;
11549
+ this[_a94] = true;
11550
+ this.name = name84;
11433
11551
  this.type = "timeout_error";
11434
11552
  }
11435
11553
  static isInstance(error) {
11436
- return GatewayError.hasMarker(error) && symbol84 in error;
11554
+ return GatewayError.hasMarker(error) && symbol94 in error;
11437
11555
  }
11438
11556
  /**
11439
11557
  * Creates a helpful timeout error message with troubleshooting guidance
@@ -11469,7 +11587,7 @@ function isTimeoutError(error) {
11469
11587
  return false;
11470
11588
  }
11471
11589
  async function asGatewayError(error, authMethod) {
11472
- var _a932;
11590
+ var _a1032;
11473
11591
  if (GatewayError.isInstance(error)) {
11474
11592
  return error;
11475
11593
  }
@@ -11488,7 +11606,7 @@ async function asGatewayError(error, authMethod) {
11488
11606
  }
11489
11607
  return await createGatewayErrorFromResponse({
11490
11608
  response: extractApiCallResponse(error),
11491
- statusCode: (_a932 = error.statusCode) != null ? _a932 : 500,
11609
+ statusCode: (_a1032 = error.statusCode) != null ? _a1032 : 500,
11492
11610
  defaultMessage: "Gateway request failed",
11493
11611
  cause: error,
11494
11612
  authMethod
@@ -11948,7 +12066,7 @@ var GatewayEmbeddingModel = class {
11948
12066
  abortSignal,
11949
12067
  providerOptions
11950
12068
  }) {
11951
- var _a932;
12069
+ var _a1032;
11952
12070
  const resolvedHeaders = await resolve(this.config.headers());
11953
12071
  try {
11954
12072
  const {
@@ -11979,7 +12097,7 @@ var GatewayEmbeddingModel = class {
11979
12097
  });
11980
12098
  return {
11981
12099
  embeddings: responseBody.embeddings,
11982
- usage: (_a932 = responseBody.usage) != null ? _a932 : void 0,
12100
+ usage: (_a1032 = responseBody.usage) != null ? _a1032 : void 0,
11983
12101
  providerMetadata: responseBody.providerMetadata,
11984
12102
  response: { headers: responseHeaders, body: rawValue }
11985
12103
  };
@@ -12026,7 +12144,7 @@ var GatewayImageModel = class {
12026
12144
  headers,
12027
12145
  abortSignal
12028
12146
  }) {
12029
- var _a932, _b93, _c, _d;
12147
+ var _a1032, _b104, _c, _d;
12030
12148
  const resolvedHeaders = await resolve(this.config.headers());
12031
12149
  try {
12032
12150
  const {
@@ -12061,7 +12179,7 @@ var GatewayImageModel = class {
12061
12179
  return {
12062
12180
  images: responseBody.images,
12063
12181
  // Always base64 strings from server
12064
- warnings: (_a932 = responseBody.warnings) != null ? _a932 : [],
12182
+ warnings: (_a1032 = responseBody.warnings) != null ? _a1032 : [],
12065
12183
  providerMetadata: responseBody.providerMetadata,
12066
12184
  response: {
12067
12185
  timestamp: /* @__PURE__ */ new Date(),
@@ -12070,7 +12188,7 @@ var GatewayImageModel = class {
12070
12188
  },
12071
12189
  ...responseBody.usage != null && {
12072
12190
  usage: {
12073
- inputTokens: (_b93 = responseBody.usage.inputTokens) != null ? _b93 : void 0,
12191
+ inputTokens: (_b104 = responseBody.usage.inputTokens) != null ? _b104 : void 0,
12074
12192
  outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,
12075
12193
  totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0
12076
12194
  }
@@ -12285,18 +12403,18 @@ var gatewayTools = {
12285
12403
  perplexitySearch
12286
12404
  };
12287
12405
  async function getVercelRequestId() {
12288
- var _a932;
12289
- return (_a932 = getContext().headers) == null ? void 0 : _a932["x-vercel-id"];
12406
+ var _a1032;
12407
+ return (_a1032 = getContext().headers) == null ? void 0 : _a1032["x-vercel-id"];
12290
12408
  }
12291
- var VERSION3 = "2.0.88";
12409
+ var VERSION3 = "2.0.109";
12292
12410
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
12293
12411
  function createGatewayProvider(options = {}) {
12294
- var _a932, _b93;
12412
+ var _a1032, _b104;
12295
12413
  let pendingMetadata = null;
12296
12414
  let metadataCache = null;
12297
- const cacheRefreshMillis = (_a932 = options.metadataCacheRefreshMillis) != null ? _a932 : 1e3 * 60 * 5;
12415
+ const cacheRefreshMillis = (_a1032 = options.metadataCacheRefreshMillis) != null ? _a1032 : 1e3 * 60 * 5;
12298
12416
  let lastFetchTime = 0;
12299
- const baseURL = (_b93 = withoutTrailingSlash(options.baseURL)) != null ? _b93 : "https://ai-gateway.vercel.sh/v1/ai";
12417
+ const baseURL = (_b104 = withoutTrailingSlash(options.baseURL)) != null ? _b104 : "https://ai-gateway.vercel.sh/v1/ai";
12300
12418
  const getHeaders = async () => {
12301
12419
  const auth = await getGatewayAuthToken(options);
12302
12420
  if (auth) {
@@ -12354,8 +12472,8 @@ function createGatewayProvider(options = {}) {
12354
12472
  });
12355
12473
  };
12356
12474
  const getAvailableModels = async () => {
12357
- var _a1022, _b103, _c;
12358
- const now2 = (_c = (_b103 = (_a1022 = options._internal) == null ? void 0 : _a1022.currentDate) == null ? void 0 : _b103.call(_a1022).getTime()) != null ? _c : Date.now();
12475
+ var _a1122, _b113, _c;
12476
+ const now2 = (_c = (_b113 = (_a1122 = options._internal) == null ? void 0 : _a1122.currentDate) == null ? void 0 : _b113.call(_a1122).getTime()) != null ? _c : Date.now();
12359
12477
  if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) {
12360
12478
  lastFetchTime = now2;
12361
12479
  pendingMetadata = new GatewayFetchMetadata({
@@ -12559,12 +12677,12 @@ function registerGlobal2(type, instance, diag, allowOverride) {
12559
12677
  return true;
12560
12678
  }
12561
12679
  function getGlobal2(type) {
12562
- var _a163, _b93;
12680
+ var _a163, _b104;
12563
12681
  var globalVersion = (_a163 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) === null || _a163 === void 0 ? void 0 : _a163.version;
12564
12682
  if (!globalVersion || !isCompatible2(globalVersion)) {
12565
12683
  return;
12566
12684
  }
12567
- return (_b93 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) === null || _b93 === void 0 ? void 0 : _b93[type];
12685
+ return (_b104 = _global2[GLOBAL_OPENTELEMETRY_API_KEY2]) === null || _b104 === void 0 ? void 0 : _b104[type];
12568
12686
  }
12569
12687
  function unregisterGlobal2(type, diag) {
12570
12688
  diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION22 + ".");
@@ -12727,15 +12845,15 @@ var DiagAPI2 = (
12727
12845
  return logger[funcName].apply(logger, __spreadArray22([], __read22(args), false));
12728
12846
  };
12729
12847
  }
12730
- var self = this;
12848
+ var self2 = this;
12731
12849
  var setLogger = function(logger, optionsOrLogLevel) {
12732
- var _a163, _b93, _c;
12850
+ var _a163, _b104, _c;
12733
12851
  if (optionsOrLogLevel === void 0) {
12734
12852
  optionsOrLogLevel = { logLevel: DiagLogLevel2.INFO };
12735
12853
  }
12736
- if (logger === self) {
12854
+ if (logger === self2) {
12737
12855
  var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
12738
- self.error((_a163 = err.stack) !== null && _a163 !== void 0 ? _a163 : err.message);
12856
+ self2.error((_a163 = err.stack) !== null && _a163 !== void 0 ? _a163 : err.message);
12739
12857
  return false;
12740
12858
  }
12741
12859
  if (typeof optionsOrLogLevel === "number") {
@@ -12744,26 +12862,26 @@ var DiagAPI2 = (
12744
12862
  };
12745
12863
  }
12746
12864
  var oldLogger = getGlobal2("diag");
12747
- var newLogger = createLogLevelDiagLogger2((_b93 = optionsOrLogLevel.logLevel) !== null && _b93 !== void 0 ? _b93 : DiagLogLevel2.INFO, logger);
12865
+ var newLogger = createLogLevelDiagLogger2((_b104 = optionsOrLogLevel.logLevel) !== null && _b104 !== void 0 ? _b104 : DiagLogLevel2.INFO, logger);
12748
12866
  if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
12749
12867
  var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
12750
12868
  oldLogger.warn("Current logger will be overwritten from " + stack);
12751
12869
  newLogger.warn("Current logger will overwrite one already registered from " + stack);
12752
12870
  }
12753
- return registerGlobal2("diag", newLogger, self, true);
12871
+ return registerGlobal2("diag", newLogger, self2, true);
12754
12872
  };
12755
- self.setLogger = setLogger;
12756
- self.disable = function() {
12757
- unregisterGlobal2(API_NAME4, self);
12873
+ self2.setLogger = setLogger;
12874
+ self2.disable = function() {
12875
+ unregisterGlobal2(API_NAME4, self2);
12758
12876
  };
12759
- self.createComponentLogger = function(options) {
12877
+ self2.createComponentLogger = function(options) {
12760
12878
  return new DiagComponentLogger2(options);
12761
12879
  };
12762
- self.verbose = _logProxy("verbose");
12763
- self.debug = _logProxy("debug");
12764
- self.info = _logProxy("info");
12765
- self.warn = _logProxy("warn");
12766
- self.error = _logProxy("error");
12880
+ self2.verbose = _logProxy("verbose");
12881
+ self2.debug = _logProxy("debug");
12882
+ self2.info = _logProxy("info");
12883
+ self2.warn = _logProxy("warn");
12884
+ self2.error = _logProxy("error");
12767
12885
  }
12768
12886
  DiagAPI22.instance = function() {
12769
12887
  if (!this._instance) {
@@ -12781,18 +12899,18 @@ var BaseContext2 = (
12781
12899
  /** @class */
12782
12900
  /* @__PURE__ */ (function() {
12783
12901
  function BaseContext22(parentContext) {
12784
- var self = this;
12785
- self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
12786
- self.getValue = function(key) {
12787
- return self._currentContext.get(key);
12902
+ var self2 = this;
12903
+ self2._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
12904
+ self2.getValue = function(key) {
12905
+ return self2._currentContext.get(key);
12788
12906
  };
12789
- self.setValue = function(key, value) {
12790
- var context2 = new BaseContext22(self._currentContext);
12907
+ self2.setValue = function(key, value) {
12908
+ var context2 = new BaseContext22(self2._currentContext);
12791
12909
  context2._currentContext.set(key, value);
12792
12910
  return context2;
12793
12911
  };
12794
- self.deleteValue = function(key) {
12795
- var context2 = new BaseContext22(self._currentContext);
12912
+ self2.deleteValue = function(key) {
12913
+ var context2 = new BaseContext22(self2._currentContext);
12796
12914
  context2._currentContext.delete(key);
12797
12915
  return context2;
12798
12916
  };
@@ -13275,7 +13393,7 @@ function getGlobalProvider() {
13275
13393
  var _a163;
13276
13394
  return (_a163 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a163 : gateway;
13277
13395
  }
13278
- var VERSION32 = "5.0.186";
13396
+ var VERSION32 = "5.0.210";
13279
13397
  var dataContentSchema2 = z$1.union([
13280
13398
  z$1.string(),
13281
13399
  z$1.instanceof(Uint8Array),
@@ -13283,8 +13401,8 @@ var dataContentSchema2 = z$1.union([
13283
13401
  z$1.custom(
13284
13402
  // Buffer might not be available in some environments such as CloudFlare:
13285
13403
  (value) => {
13286
- var _a163, _b93;
13287
- return (_b93 = (_a163 = globalThis.Buffer) == null ? void 0 : _a163.isBuffer(value)) != null ? _b93 : false;
13404
+ var _a163, _b104;
13405
+ return (_b104 = (_a163 = globalThis.Buffer) == null ? void 0 : _a163.isBuffer(value)) != null ? _b104 : false;
13288
13406
  },
13289
13407
  { message: "Must be a Buffer" }
13290
13408
  )
@@ -14808,6 +14926,90 @@ function convertUint8ArrayToBase643(array2) {
14808
14926
  }
14809
14927
  return btoa3(latin1string);
14810
14928
  }
14929
+ async function cancelResponseBody2(response) {
14930
+ var _a223;
14931
+ try {
14932
+ await ((_a223 = response.body) == null ? void 0 : _a223.cancel());
14933
+ } catch (e) {
14934
+ }
14935
+ }
14936
+ var name144 = "AI_DownloadError";
14937
+ var marker154 = `vercel.ai.error.${name144}`;
14938
+ var symbol154 = Symbol.for(marker154);
14939
+ var _a154;
14940
+ var _b152;
14941
+ var DownloadError2 = class extends (_b152 = AISDKError3, _a154 = symbol154, _b152) {
14942
+ constructor({
14943
+ url,
14944
+ statusCode,
14945
+ statusText,
14946
+ cause,
14947
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
14948
+ }) {
14949
+ super({ name: name144, message, cause });
14950
+ this[_a154] = true;
14951
+ this.url = url;
14952
+ this.statusCode = statusCode;
14953
+ this.statusText = statusText;
14954
+ }
14955
+ static isInstance(error) {
14956
+ return AISDKError3.hasMarker(error, marker154);
14957
+ }
14958
+ };
14959
+ var DEFAULT_MAX_DOWNLOAD_SIZE2 = 2 * 1024 * 1024 * 1024;
14960
+ async function readResponseWithSizeLimit2({
14961
+ response,
14962
+ url,
14963
+ maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE2
14964
+ }) {
14965
+ const contentLength = response.headers.get("content-length");
14966
+ if (contentLength != null) {
14967
+ const length = parseInt(contentLength, 10);
14968
+ if (!isNaN(length) && length > maxBytes) {
14969
+ await cancelResponseBody2(response);
14970
+ throw new DownloadError2({
14971
+ url,
14972
+ message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`
14973
+ });
14974
+ }
14975
+ }
14976
+ const body = response.body;
14977
+ if (body == null) {
14978
+ return new Uint8Array(0);
14979
+ }
14980
+ const reader = body.getReader();
14981
+ const chunks = [];
14982
+ let totalBytes = 0;
14983
+ try {
14984
+ while (true) {
14985
+ const { done, value } = await reader.read();
14986
+ if (done) {
14987
+ break;
14988
+ }
14989
+ totalBytes += value.length;
14990
+ if (totalBytes > maxBytes) {
14991
+ throw new DownloadError2({
14992
+ url,
14993
+ message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`
14994
+ });
14995
+ }
14996
+ chunks.push(value);
14997
+ }
14998
+ } finally {
14999
+ try {
15000
+ await reader.cancel();
15001
+ } finally {
15002
+ reader.releaseLock();
15003
+ }
15004
+ }
15005
+ const result = new Uint8Array(totalBytes);
15006
+ let offset = 0;
15007
+ for (const chunk of chunks) {
15008
+ result.set(chunk, offset);
15009
+ offset += chunk.length;
15010
+ }
15011
+ return result;
15012
+ }
14811
15013
  var createIdGenerator3 = ({
14812
15014
  prefix,
14813
15015
  size = 16,
@@ -14903,11 +15105,11 @@ function handleFetchError2({
14903
15105
  return error;
14904
15106
  }
14905
15107
  function getRuntimeEnvironmentUserAgent2(globalThisAny = globalThis) {
14906
- var _a224, _b222, _c;
15108
+ var _a223, _b222, _c;
14907
15109
  if (globalThisAny.window) {
14908
15110
  return `runtime/browser`;
14909
15111
  }
14910
- if ((_a224 = globalThisAny.navigator) == null ? void 0 : _a224.userAgent) {
15112
+ if ((_a223 = globalThisAny.navigator) == null ? void 0 : _a223.userAgent) {
14911
15113
  return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
14912
15114
  }
14913
15115
  if ((_c = (_b222 = globalThisAny.process) == null ? void 0 : _b222.versions) == null ? void 0 : _c.node) {
@@ -14948,7 +15150,7 @@ function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
14948
15150
  );
14949
15151
  return Object.fromEntries(normalizedHeaders.entries());
14950
15152
  }
14951
- var VERSION4 = "4.0.27";
15153
+ var VERSION4 = "4.0.38";
14952
15154
  var getOriginalFetch3 = () => globalThis.fetch;
14953
15155
  var getFromApi2 = async ({
14954
15156
  url,
@@ -15149,11 +15351,11 @@ function parseAnyDef3() {
15149
15351
  return {};
15150
15352
  }
15151
15353
  function parseArrayDef3(def, refs) {
15152
- var _a224, _b222, _c;
15354
+ var _a223, _b222, _c;
15153
15355
  const res = {
15154
15356
  type: "array"
15155
15357
  };
15156
- 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) {
15358
+ if (((_a223 = def.type) == null ? void 0 : _a223._def) && ((_c = (_b222 = def.type) == null ? void 0 : _b222._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
15157
15359
  res.items = parseDef3(def.type._def, {
15158
15360
  ...refs,
15159
15361
  currentPath: [...refs.currentPath, "items"]
@@ -15512,8 +15714,8 @@ function escapeNonAlphaNumeric3(source) {
15512
15714
  return result;
15513
15715
  }
15514
15716
  function addFormat3(schema, value, message, refs) {
15515
- var _a224;
15516
- if (schema.format || ((_a224 = schema.anyOf) == null ? void 0 : _a224.some((x) => x.format))) {
15717
+ var _a223;
15718
+ if (schema.format || ((_a223 = schema.anyOf) == null ? void 0 : _a223.some((x) => x.format))) {
15517
15719
  if (!schema.anyOf) {
15518
15720
  schema.anyOf = [];
15519
15721
  }
@@ -15532,8 +15734,8 @@ function addFormat3(schema, value, message, refs) {
15532
15734
  }
15533
15735
  }
15534
15736
  function addPattern3(schema, regex, message, refs) {
15535
- var _a224;
15536
- if (schema.pattern || ((_a224 = schema.allOf) == null ? void 0 : _a224.some((x) => x.pattern))) {
15737
+ var _a223;
15738
+ if (schema.pattern || ((_a223 = schema.allOf) == null ? void 0 : _a223.some((x) => x.pattern))) {
15537
15739
  if (!schema.allOf) {
15538
15740
  schema.allOf = [];
15539
15741
  }
@@ -15552,7 +15754,7 @@ function addPattern3(schema, regex, message, refs) {
15552
15754
  }
15553
15755
  }
15554
15756
  function stringifyRegExpWithFlags3(regex, refs) {
15555
- var _a224;
15757
+ var _a223;
15556
15758
  if (!refs.applyRegexFlags || !regex.flags) {
15557
15759
  return regex.source;
15558
15760
  }
@@ -15582,7 +15784,7 @@ function stringifyRegExpWithFlags3(regex, refs) {
15582
15784
  pattern += source[i];
15583
15785
  pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
15584
15786
  inCharRange = false;
15585
- } else if (source[i + 1] === "-" && ((_a224 = source[i + 2]) == null ? void 0 : _a224.match(/[a-z]/))) {
15787
+ } else if (source[i + 1] === "-" && ((_a223 = source[i + 2]) == null ? void 0 : _a223.match(/[a-z]/))) {
15586
15788
  pattern += source[i];
15587
15789
  inCharRange = true;
15588
15790
  } else {
@@ -15624,13 +15826,13 @@ function stringifyRegExpWithFlags3(regex, refs) {
15624
15826
  return pattern;
15625
15827
  }
15626
15828
  function parseRecordDef3(def, refs) {
15627
- var _a224, _b222, _c, _d, _e, _f;
15829
+ var _a223, _b222, _c, _d, _e, _f;
15628
15830
  const schema = {
15629
15831
  type: "object",
15630
- additionalProperties: (_a224 = parseDef3(def.valueType._def, {
15832
+ additionalProperties: (_a223 = parseDef3(def.valueType._def, {
15631
15833
  ...refs,
15632
15834
  currentPath: [...refs.currentPath, "additionalProperties"]
15633
- })) != null ? _a224 : refs.allowedAdditionalProperties
15835
+ })) != null ? _a223 : refs.allowedAdditionalProperties
15634
15836
  };
15635
15837
  if (((_b222 = def.keyType) == null ? void 0 : _b222._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
15636
15838
  const { type, ...keyType } = parseStringDef3(def.keyType._def, refs);
@@ -15887,8 +16089,8 @@ function safeIsOptional3(schema) {
15887
16089
  }
15888
16090
  }
15889
16091
  var parseOptionalDef3 = (def, refs) => {
15890
- var _a224;
15891
- if (refs.currentPath.toString() === ((_a224 = refs.propertyPath) == null ? void 0 : _a224.toString())) {
16092
+ var _a223;
16093
+ if (refs.currentPath.toString() === ((_a223 = refs.propertyPath) == null ? void 0 : _a223.toString())) {
15892
16094
  return parseDef3(def.innerType._def, refs);
15893
16095
  }
15894
16096
  const innerSchema = parseDef3(def.innerType._def, {
@@ -16065,10 +16267,10 @@ var getRelativePath3 = (pathA, pathB) => {
16065
16267
  return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
16066
16268
  };
16067
16269
  function parseDef3(def, refs, forceResolution = false) {
16068
- var _a224;
16270
+ var _a223;
16069
16271
  const seenItem = refs.seen.get(def);
16070
16272
  if (refs.override) {
16071
- const overrideResult = (_a224 = refs.override) == null ? void 0 : _a224.call(
16273
+ const overrideResult = (_a223 = refs.override) == null ? void 0 : _a223.call(
16072
16274
  refs,
16073
16275
  def,
16074
16276
  refs,
@@ -16134,11 +16336,11 @@ var getRefs3 = (options) => {
16134
16336
  currentPath,
16135
16337
  propertyPath: void 0,
16136
16338
  seen: new Map(
16137
- Object.entries(_options.definitions).map(([name224, def]) => [
16339
+ Object.entries(_options.definitions).map(([name223, def]) => [
16138
16340
  def._def,
16139
16341
  {
16140
16342
  def: def._def,
16141
- path: [..._options.basePath, _options.definitionPath, name224],
16343
+ path: [..._options.basePath, _options.definitionPath, name223],
16142
16344
  // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
16143
16345
  jsonSchema: void 0
16144
16346
  }
@@ -16147,50 +16349,50 @@ var getRefs3 = (options) => {
16147
16349
  };
16148
16350
  };
16149
16351
  var zod3ToJsonSchema = (schema, options) => {
16150
- var _a224;
16352
+ var _a223;
16151
16353
  const refs = getRefs3(options);
16152
16354
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
16153
- (acc, [name324, schema2]) => {
16154
- var _a324;
16355
+ (acc, [name323, schema2]) => {
16356
+ var _a323;
16155
16357
  return {
16156
16358
  ...acc,
16157
- [name324]: (_a324 = parseDef3(
16359
+ [name323]: (_a323 = parseDef3(
16158
16360
  schema2._def,
16159
16361
  {
16160
16362
  ...refs,
16161
- currentPath: [...refs.basePath, refs.definitionPath, name324]
16363
+ currentPath: [...refs.basePath, refs.definitionPath, name323]
16162
16364
  },
16163
16365
  true
16164
- )) != null ? _a324 : parseAnyDef3()
16366
+ )) != null ? _a323 : parseAnyDef3()
16165
16367
  };
16166
16368
  },
16167
16369
  {}
16168
16370
  ) : void 0;
16169
- const name224 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
16170
- const main = (_a224 = parseDef3(
16371
+ const name223 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
16372
+ const main = (_a223 = parseDef3(
16171
16373
  schema._def,
16172
- name224 === void 0 ? refs : {
16374
+ name223 === void 0 ? refs : {
16173
16375
  ...refs,
16174
- currentPath: [...refs.basePath, refs.definitionPath, name224]
16376
+ currentPath: [...refs.basePath, refs.definitionPath, name223]
16175
16377
  },
16176
16378
  false
16177
- )) != null ? _a224 : parseAnyDef3();
16379
+ )) != null ? _a223 : parseAnyDef3();
16178
16380
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
16179
16381
  if (title !== void 0) {
16180
16382
  main.title = title;
16181
16383
  }
16182
- const combined = name224 === void 0 ? definitions ? {
16384
+ const combined = name223 === void 0 ? definitions ? {
16183
16385
  ...main,
16184
16386
  [refs.definitionPath]: definitions
16185
16387
  } : main : {
16186
16388
  $ref: [
16187
16389
  ...refs.$refStrategy === "relative" ? [] : refs.basePath,
16188
16390
  refs.definitionPath,
16189
- name224
16391
+ name223
16190
16392
  ].join("/"),
16191
16393
  [refs.definitionPath]: {
16192
16394
  ...definitions,
16193
- [name224]: main
16395
+ [name223]: main
16194
16396
  }
16195
16397
  };
16196
16398
  combined.$schema = "http://json-schema.org/draft-07/schema#";
@@ -16226,7 +16428,11 @@ function isSchema3(value) {
16226
16428
  return typeof value === "object" && value !== null && schemaSymbol3 in value && value[schemaSymbol3] === true && "jsonSchema" in value && "validate" in value;
16227
16429
  }
16228
16430
  function asSchema3(schema) {
16229
- return schema == null ? jsonSchema3({ properties: {}, additionalProperties: false }) : isSchema3(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema3(schema) : standardSchema(schema) : schema();
16431
+ return schema == null ? jsonSchema3({
16432
+ type: "object",
16433
+ properties: {},
16434
+ additionalProperties: false
16435
+ }) : isSchema3(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema3(schema) : standardSchema(schema) : schema();
16230
16436
  }
16231
16437
  function standardSchema(standardSchema2) {
16232
16438
  return jsonSchema3(
@@ -16250,8 +16456,8 @@ function standardSchema(standardSchema2) {
16250
16456
  );
16251
16457
  }
16252
16458
  function zod3Schema2(zodSchema22, options) {
16253
- var _a224;
16254
- const useReferences = (_a224 = void 0 ) != null ? _a224 : false;
16459
+ var _a223;
16460
+ const useReferences = (_a223 = void 0 ) != null ? _a223 : false;
16255
16461
  return jsonSchema3(
16256
16462
  // defer json schema creation to avoid unnecessary computation when only validation is needed
16257
16463
  () => zod3ToJsonSchema(zodSchema22, {
@@ -16266,8 +16472,8 @@ function zod3Schema2(zodSchema22, options) {
16266
16472
  );
16267
16473
  }
16268
16474
  function zod4Schema2(zodSchema22, options) {
16269
- var _a224;
16270
- const useReferences = (_a224 = void 0 ) != null ? _a224 : false;
16475
+ var _a223;
16476
+ const useReferences = (_a223 = void 0 ) != null ? _a223 : false;
16271
16477
  return jsonSchema3(
16272
16478
  // defer json schema creation to avoid unnecessary computation when only validation is needed
16273
16479
  () => addAdditionalPropertiesToJsonSchema2(
@@ -16514,12 +16720,101 @@ async function resolve2(value) {
16514
16720
  }
16515
16721
  return Promise.resolve(value);
16516
16722
  }
16723
+ var retryWithExponentialBackoff2 = ({
16724
+ maxRetries = 2,
16725
+ initialDelayInMs = 2e3,
16726
+ backoffFactor = 2,
16727
+ abortSignal,
16728
+ shouldRetry,
16729
+ getDelayInMs = ({ exponentialBackoffDelay }) => exponentialBackoffDelay,
16730
+ createRetryError = ({ message }) => new Error(message)
16731
+ }) => async (f) => retryWithExponentialBackoffInternal(f, {
16732
+ maxRetries,
16733
+ delayInMs: initialDelayInMs,
16734
+ backoffFactor,
16735
+ abortSignal,
16736
+ shouldRetry,
16737
+ getDelayInMs,
16738
+ createRetryError
16739
+ });
16740
+ async function retryWithExponentialBackoffInternal(f, {
16741
+ maxRetries,
16742
+ delayInMs,
16743
+ backoffFactor,
16744
+ abortSignal,
16745
+ shouldRetry,
16746
+ getDelayInMs,
16747
+ createRetryError
16748
+ }, errors = []) {
16749
+ try {
16750
+ return await f();
16751
+ } catch (error) {
16752
+ if (isAbortError5(error)) {
16753
+ throw error;
16754
+ }
16755
+ if (maxRetries === 0) {
16756
+ throw error;
16757
+ }
16758
+ const errorMessage = getErrorMessage23(error);
16759
+ const newErrors = [...errors, error];
16760
+ const tryNumber = newErrors.length;
16761
+ if (tryNumber > maxRetries) {
16762
+ throw createRetryError({
16763
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
16764
+ reason: "maxRetriesExceeded",
16765
+ errors: newErrors
16766
+ });
16767
+ }
16768
+ if (await shouldRetry(error) && tryNumber <= maxRetries) {
16769
+ await delay3(
16770
+ getDelayInMs({
16771
+ error,
16772
+ exponentialBackoffDelay: delayInMs
16773
+ }),
16774
+ { abortSignal }
16775
+ );
16776
+ return retryWithExponentialBackoffInternal(
16777
+ f,
16778
+ {
16779
+ maxRetries,
16780
+ delayInMs: backoffFactor * delayInMs,
16781
+ backoffFactor,
16782
+ abortSignal,
16783
+ shouldRetry,
16784
+ getDelayInMs,
16785
+ createRetryError
16786
+ },
16787
+ newErrors
16788
+ );
16789
+ }
16790
+ if (tryNumber === 1) {
16791
+ throw error;
16792
+ }
16793
+ throw createRetryError({
16794
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
16795
+ reason: "errorNotRetryable",
16796
+ errors: newErrors
16797
+ });
16798
+ }
16799
+ }
16800
+ var textDecoder2 = new TextDecoder();
16801
+ async function readResponseBodyAsText2({
16802
+ response,
16803
+ url
16804
+ }) {
16805
+ return textDecoder2.decode(
16806
+ await readResponseWithSizeLimit2({
16807
+ response,
16808
+ url
16809
+ })
16810
+ );
16811
+ }
16517
16812
  var createJsonErrorResponseHandler2 = ({
16518
16813
  errorSchema,
16519
16814
  errorToMessage,
16520
16815
  isRetryable
16521
16816
  }) => async ({ response, url, requestBodyValues }) => {
16522
- const responseBody = await response.text();
16817
+ const responseBody = await readResponseBodyAsText2({ response, url });
16523
16818
  const responseHeaders = extractResponseHeaders2(response);
16524
16819
  if (responseBody.trim() === "") {
16525
16820
  return {
@@ -16582,7 +16877,7 @@ var createEventSourceResponseHandler2 = (chunkSchema) => async ({ response }) =>
16582
16877
  };
16583
16878
  };
16584
16879
  var createJsonResponseHandler2 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
16585
- const responseBody = await response.text();
16880
+ const responseBody = await readResponseBodyAsText2({ response, url });
16586
16881
  const parsedResult = await safeParseJSON3({
16587
16882
  text: responseBody,
16588
16883
  schema: responseSchema
@@ -16628,13 +16923,19 @@ var GatewayError2 = class _GatewayError2 extends (_b18 = Error, _a20 = symbol20,
16628
16923
  message,
16629
16924
  statusCode = 500,
16630
16925
  cause,
16631
- generationId
16926
+ generationId,
16927
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
16928
+ statusCode === 409 || // conflict
16929
+ statusCode === 429 || // too many requests
16930
+ statusCode >= 500)
16931
+ // server error
16632
16932
  }) {
16633
16933
  super(generationId ? `${message} [${generationId}]` : message);
16634
16934
  this[_a20] = true;
16635
16935
  this.statusCode = statusCode;
16636
16936
  this.cause = cause;
16637
16937
  this.generationId = generationId;
16938
+ this.isRetryable = isRetryable;
16638
16939
  }
16639
16940
  /**
16640
16941
  * Checks if the given error is a Gateway Error.
@@ -16803,58 +17104,109 @@ var GatewayInternalServerError2 = class extends (_b64 = GatewayError2, _a66 = sy
16803
17104
  return GatewayError2.hasMarker(error) && symbol66 in error;
16804
17105
  }
16805
17106
  };
16806
- var name66 = "GatewayResponseError";
17107
+ var name66 = "GatewayFailedDependencyError";
16807
17108
  var marker76 = `vercel.ai.gateway.error.${name66}`;
16808
17109
  var symbol76 = Symbol.for(marker76);
16809
17110
  var _a76;
16810
17111
  var _b74;
16811
- var GatewayResponseError2 = class extends (_b74 = GatewayError2, _a76 = symbol76, _b74) {
17112
+ var GatewayFailedDependencyError = class extends (_b74 = GatewayError2, _a76 = symbol76, _b74) {
16812
17113
  constructor({
16813
- message = "Invalid response from Gateway",
16814
- statusCode = 502,
16815
- response,
16816
- validationError,
17114
+ message = "Failed dependency",
17115
+ statusCode = 424,
16817
17116
  cause,
16818
17117
  generationId
16819
17118
  } = {}) {
16820
17119
  super({ message, statusCode, cause, generationId });
16821
17120
  this[_a76] = true;
16822
17121
  this.name = name66;
16823
- this.type = "response_error";
16824
- this.response = response;
16825
- this.validationError = validationError;
17122
+ this.type = "failed_dependency";
16826
17123
  }
16827
17124
  static isInstance(error) {
16828
17125
  return GatewayError2.hasMarker(error) && symbol76 in error;
16829
17126
  }
16830
17127
  };
16831
- async function createGatewayErrorFromResponse2({
16832
- response,
16833
- statusCode,
16834
- defaultMessage = "Gateway request failed",
16835
- cause,
16836
- authMethod
16837
- }) {
16838
- var _a932;
16839
- const parseResult = await safeValidateTypes3({
16840
- value: response,
16841
- schema: gatewayErrorResponseSchema2
16842
- });
16843
- if (!parseResult.success) {
16844
- const rawGenerationId = typeof response === "object" && response !== null && "generationId" in response ? response.generationId : void 0;
16845
- return new GatewayResponseError2({
16846
- message: `Invalid error response format: ${defaultMessage}`,
16847
- statusCode,
16848
- response,
16849
- validationError: parseResult.error,
16850
- cause,
16851
- generationId: rawGenerationId
16852
- });
17128
+ var name76 = "GatewayForbiddenError";
17129
+ var marker86 = `vercel.ai.gateway.error.${name76}`;
17130
+ var symbol86 = Symbol.for(marker86);
17131
+ var forbiddenParamSchema = lazySchema2(
17132
+ () => zodSchema3(
17133
+ z$1.object({
17134
+ ruleId: z$1.string()
17135
+ })
17136
+ )
17137
+ );
17138
+ var _a86;
17139
+ var _b84;
17140
+ var GatewayForbiddenError2 = class extends (_b84 = GatewayError2, _a86 = symbol86, _b84) {
17141
+ constructor({
17142
+ message = "Forbidden",
17143
+ statusCode = 403,
17144
+ cause,
17145
+ generationId,
17146
+ ruleId
17147
+ } = {}) {
17148
+ super({ message, statusCode, cause, generationId });
17149
+ this[_a86] = true;
17150
+ this.name = name76;
17151
+ this.type = "forbidden";
17152
+ this.ruleId = ruleId;
17153
+ }
17154
+ static isInstance(error) {
17155
+ return GatewayError2.hasMarker(error) && symbol86 in error;
17156
+ }
17157
+ };
17158
+ var name86 = "GatewayResponseError";
17159
+ var marker96 = `vercel.ai.gateway.error.${name86}`;
17160
+ var symbol96 = Symbol.for(marker96);
17161
+ var _a96;
17162
+ var _b94;
17163
+ var GatewayResponseError2 = class extends (_b94 = GatewayError2, _a96 = symbol96, _b94) {
17164
+ constructor({
17165
+ message = "Invalid response from Gateway",
17166
+ statusCode = 502,
17167
+ response,
17168
+ validationError,
17169
+ cause,
17170
+ generationId
17171
+ } = {}) {
17172
+ super({ message, statusCode, cause, generationId });
17173
+ this[_a96] = true;
17174
+ this.name = name86;
17175
+ this.type = "response_error";
17176
+ this.response = response;
17177
+ this.validationError = validationError;
17178
+ }
17179
+ static isInstance(error) {
17180
+ return GatewayError2.hasMarker(error) && symbol96 in error;
17181
+ }
17182
+ };
17183
+ async function createGatewayErrorFromResponse2({
17184
+ response,
17185
+ statusCode,
17186
+ defaultMessage = "Gateway request failed",
17187
+ cause,
17188
+ authMethod
17189
+ }) {
17190
+ var _a117;
17191
+ const parseResult = await safeValidateTypes3({
17192
+ value: response,
17193
+ schema: gatewayErrorResponseSchema2
17194
+ });
17195
+ if (!parseResult.success) {
17196
+ const rawGenerationId = typeof response === "object" && response !== null && "generationId" in response ? response.generationId : void 0;
17197
+ return new GatewayResponseError2({
17198
+ message: `Invalid error response format: ${defaultMessage}`,
17199
+ statusCode,
17200
+ response,
17201
+ validationError: parseResult.error,
17202
+ cause,
17203
+ generationId: rawGenerationId
17204
+ });
16853
17205
  }
16854
17206
  const validatedResponse = parseResult.value;
16855
17207
  const errorType = validatedResponse.error.type;
16856
17208
  const message = validatedResponse.error.message;
16857
- const generationId = (_a932 = validatedResponse.generationId) != null ? _a932 : void 0;
17209
+ const generationId = (_a117 = validatedResponse.generationId) != null ? _a117 : void 0;
16858
17210
  switch (errorType) {
16859
17211
  case "authentication_error":
16860
17212
  return GatewayAuthenticationError2.createContextualError({
@@ -16898,6 +17250,26 @@ async function createGatewayErrorFromResponse2({
16898
17250
  cause,
16899
17251
  generationId
16900
17252
  });
17253
+ case "failed_dependency":
17254
+ return new GatewayFailedDependencyError({
17255
+ message,
17256
+ statusCode,
17257
+ cause,
17258
+ generationId
17259
+ });
17260
+ case "forbidden": {
17261
+ const ruleResult = await safeValidateTypes3({
17262
+ value: validatedResponse.error.param,
17263
+ schema: forbiddenParamSchema
17264
+ });
17265
+ return new GatewayForbiddenError2({
17266
+ message,
17267
+ statusCode,
17268
+ cause,
17269
+ generationId,
17270
+ ruleId: ruleResult.success ? ruleResult.value.ruleId : void 0
17271
+ });
17272
+ }
16901
17273
  default:
16902
17274
  return new GatewayInternalServerError2({
16903
17275
  message,
@@ -16926,19 +17298,19 @@ function extractApiCallResponse2(error) {
16926
17298
  }
16927
17299
  if (error.responseBody != null) {
16928
17300
  try {
16929
- return JSON.parse(error.responseBody);
17301
+ return secureJsonParse2(error.responseBody);
16930
17302
  } catch (e) {
16931
17303
  return error.responseBody;
16932
17304
  }
16933
17305
  }
16934
17306
  return {};
16935
17307
  }
16936
- var name76 = "GatewayTimeoutError";
16937
- var marker86 = `vercel.ai.gateway.error.${name76}`;
16938
- var symbol86 = Symbol.for(marker86);
16939
- var _a86;
16940
- var _b84;
16941
- var GatewayTimeoutError2 = class _GatewayTimeoutError2 extends (_b84 = GatewayError2, _a86 = symbol86, _b84) {
17308
+ var name96 = "GatewayTimeoutError";
17309
+ var marker106 = `vercel.ai.gateway.error.${name96}`;
17310
+ var symbol106 = Symbol.for(marker106);
17311
+ var _a106;
17312
+ var _b103;
17313
+ var GatewayTimeoutError2 = class _GatewayTimeoutError2 extends (_b103 = GatewayError2, _a106 = symbol106, _b103) {
16942
17314
  constructor({
16943
17315
  message = "Request timed out",
16944
17316
  statusCode = 408,
@@ -16946,12 +17318,12 @@ var GatewayTimeoutError2 = class _GatewayTimeoutError2 extends (_b84 = GatewayEr
16946
17318
  generationId
16947
17319
  } = {}) {
16948
17320
  super({ message, statusCode, cause, generationId });
16949
- this[_a86] = true;
16950
- this.name = name76;
17321
+ this[_a106] = true;
17322
+ this.name = name96;
16951
17323
  this.type = "timeout_error";
16952
17324
  }
16953
17325
  static isInstance(error) {
16954
- return GatewayError2.hasMarker(error) && symbol86 in error;
17326
+ return GatewayError2.hasMarker(error) && symbol106 in error;
16955
17327
  }
16956
17328
  /**
16957
17329
  * Creates a helpful timeout error message with troubleshooting guidance
@@ -16989,7 +17361,7 @@ function isTimeoutError2(error) {
16989
17361
  return false;
16990
17362
  }
16991
17363
  async function asGatewayError2(error, authMethod) {
16992
- var _a932;
17364
+ var _a117;
16993
17365
  if (GatewayError2.isInstance(error)) {
16994
17366
  return error;
16995
17367
  }
@@ -17008,7 +17380,7 @@ async function asGatewayError2(error, authMethod) {
17008
17380
  }
17009
17381
  return await createGatewayErrorFromResponse2({
17010
17382
  response: extractApiCallResponse2(error),
17011
- statusCode: (_a932 = error.statusCode) != null ? _a932 : 500,
17383
+ statusCode: (_a117 = error.statusCode) != null ? _a117 : 500,
17012
17384
  defaultMessage: "Gateway request failed",
17013
17385
  cause: error,
17014
17386
  authMethod
@@ -17038,6 +17410,8 @@ var KNOWN_MODEL_TYPES2 = [
17038
17410
  "image",
17039
17411
  "language",
17040
17412
  "reranking",
17413
+ "speech",
17414
+ "transcription",
17041
17415
  "video"
17042
17416
  ];
17043
17417
  var GatewayFetchMetadata2 = class {
@@ -17474,7 +17848,7 @@ var GatewayEmbeddingModel2 = class {
17474
17848
  abortSignal,
17475
17849
  providerOptions
17476
17850
  }) {
17477
- var _a932;
17851
+ var _a117, _b113;
17478
17852
  const resolvedHeaders = await resolve2(this.config.headers());
17479
17853
  try {
17480
17854
  const {
@@ -17505,10 +17879,10 @@ var GatewayEmbeddingModel2 = class {
17505
17879
  });
17506
17880
  return {
17507
17881
  embeddings: responseBody.embeddings,
17508
- usage: (_a932 = responseBody.usage) != null ? _a932 : void 0,
17882
+ usage: (_a117 = responseBody.usage) != null ? _a117 : void 0,
17509
17883
  providerMetadata: responseBody.providerMetadata,
17510
17884
  response: { headers: responseHeaders, body: rawValue },
17511
- warnings: []
17885
+ warnings: (_b113 = responseBody.warnings) != null ? _b113 : []
17512
17886
  };
17513
17887
  } catch (error) {
17514
17888
  throw await asGatewayError2(error, await parseAuthMethod2(resolvedHeaders));
@@ -17524,15 +17898,37 @@ var GatewayEmbeddingModel2 = class {
17524
17898
  };
17525
17899
  }
17526
17900
  };
17901
+ var gatewayEmbeddingWarningSchema = z$1.discriminatedUnion("type", [
17902
+ z$1.object({
17903
+ type: z$1.literal("unsupported"),
17904
+ feature: z$1.string(),
17905
+ details: z$1.string().optional()
17906
+ }),
17907
+ z$1.object({
17908
+ type: z$1.literal("compatibility"),
17909
+ feature: z$1.string(),
17910
+ details: z$1.string().optional()
17911
+ }),
17912
+ z$1.object({
17913
+ type: z$1.literal("other"),
17914
+ message: z$1.string()
17915
+ })
17916
+ ]);
17527
17917
  var gatewayEmbeddingResponseSchema2 = lazySchema2(
17528
17918
  () => zodSchema3(
17529
17919
  z$1.object({
17530
17920
  embeddings: z$1.array(z$1.array(z$1.number())),
17531
17921
  usage: z$1.object({ tokens: z$1.number() }).nullish(),
17922
+ warnings: z$1.array(gatewayEmbeddingWarningSchema).optional(),
17532
17923
  providerMetadata: z$1.record(z$1.string(), z$1.record(z$1.string(), z$1.unknown())).optional()
17533
17924
  })
17534
17925
  )
17535
17926
  );
17927
+ function mapGatewayWarnings(warnings) {
17928
+ return (warnings != null ? warnings : []).map(
17929
+ (warning) => warning.type === "deprecated" ? { type: "other", message: warning.message } : warning
17930
+ );
17931
+ }
17536
17932
  var GatewayImageModel2 = class {
17537
17933
  constructor(modelId, config) {
17538
17934
  this.modelId = modelId;
@@ -17555,7 +17951,7 @@ var GatewayImageModel2 = class {
17555
17951
  headers,
17556
17952
  abortSignal
17557
17953
  }) {
17558
- var _a932, _b93, _c, _d;
17954
+ var _a117, _b113, _c;
17559
17955
  const resolvedHeaders = await resolve2(this.config.headers());
17560
17956
  try {
17561
17957
  const {
@@ -17594,7 +17990,7 @@ var GatewayImageModel2 = class {
17594
17990
  return {
17595
17991
  images: responseBody.images,
17596
17992
  // Always base64 strings from server
17597
- warnings: (_a932 = responseBody.warnings) != null ? _a932 : [],
17993
+ warnings: mapGatewayWarnings(responseBody.warnings),
17598
17994
  providerMetadata: responseBody.providerMetadata,
17599
17995
  response: {
17600
17996
  timestamp: /* @__PURE__ */ new Date(),
@@ -17603,9 +17999,9 @@ var GatewayImageModel2 = class {
17603
17999
  },
17604
18000
  ...responseBody.usage != null && {
17605
18001
  usage: {
17606
- inputTokens: (_b93 = responseBody.usage.inputTokens) != null ? _b93 : void 0,
17607
- outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,
17608
- totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0
18002
+ inputTokens: (_a117 = responseBody.usage.inputTokens) != null ? _a117 : void 0,
18003
+ outputTokens: (_b113 = responseBody.usage.outputTokens) != null ? _b113 : void 0,
18004
+ totalTokens: (_c = responseBody.usage.totalTokens) != null ? _c : void 0
17609
18005
  }
17610
18006
  }
17611
18007
  };
@@ -17646,6 +18042,11 @@ var gatewayImageWarningSchema = z$1.discriminatedUnion("type", [
17646
18042
  feature: z$1.string(),
17647
18043
  details: z$1.string().optional()
17648
18044
  }),
18045
+ z$1.object({
18046
+ type: z$1.literal("deprecated"),
18047
+ setting: z$1.string(),
18048
+ message: z$1.string()
18049
+ }),
17649
18050
  z$1.object({
17650
18051
  type: z$1.literal("other"),
17651
18052
  message: z$1.string()
@@ -17681,12 +18082,14 @@ var GatewayVideoModel = class {
17681
18082
  duration,
17682
18083
  fps,
17683
18084
  seed,
18085
+ generateAudio,
17684
18086
  image,
18087
+ frameImages,
18088
+ inputReferences,
17685
18089
  providerOptions,
17686
18090
  headers,
17687
18091
  abortSignal
17688
18092
  }) {
17689
- var _a932;
17690
18093
  const resolvedHeaders = await resolve2(this.config.headers());
17691
18094
  try {
17692
18095
  const { responseHeaders, value: responseBody } = await postJsonToApi2({
@@ -17706,8 +18109,20 @@ var GatewayVideoModel = class {
17706
18109
  ...duration && { duration },
17707
18110
  ...fps && { fps },
17708
18111
  ...seed && { seed },
18112
+ ...generateAudio !== void 0 && { generateAudio },
17709
18113
  ...providerOptions && { providerOptions },
17710
- ...image && { image: maybeEncodeVideoFile(image) }
18114
+ ...image && { image: maybeEncodeVideoFile(image) },
18115
+ ...frameImages && {
18116
+ frameImages: frameImages.map((frame) => ({
18117
+ ...frame,
18118
+ image: maybeEncodeVideoFile(frame.image)
18119
+ }))
18120
+ },
18121
+ ...inputReferences && {
18122
+ inputReferences: inputReferences.map(
18123
+ (reference) => maybeEncodeVideoFile(reference)
18124
+ )
18125
+ }
17711
18126
  },
17712
18127
  successfulResponseHandler: async ({
17713
18128
  response,
@@ -17782,7 +18197,7 @@ var GatewayVideoModel = class {
17782
18197
  });
17783
18198
  return {
17784
18199
  videos: responseBody.videos,
17785
- warnings: (_a932 = responseBody.warnings) != null ? _a932 : [],
18200
+ warnings: mapGatewayWarnings(responseBody.warnings),
17786
18201
  providerMetadata: responseBody.providerMetadata,
17787
18202
  response: {
17788
18203
  timestamp: /* @__PURE__ */ new Date(),
@@ -17839,6 +18254,11 @@ var gatewayVideoWarningSchema = z$1.discriminatedUnion("type", [
17839
18254
  feature: z$1.string(),
17840
18255
  details: z$1.string().optional()
17841
18256
  }),
18257
+ z$1.object({
18258
+ type: z$1.literal("deprecated"),
18259
+ setting: z$1.string(),
18260
+ message: z$1.string()
18261
+ }),
17842
18262
  z$1.object({
17843
18263
  type: z$1.literal("other"),
17844
18264
  message: z$1.string()
@@ -17876,6 +18296,7 @@ var GatewayRerankingModel = class {
17876
18296
  abortSignal,
17877
18297
  providerOptions
17878
18298
  }) {
18299
+ var _a117;
17879
18300
  const resolvedHeaders = await resolve2(this.config.headers());
17880
18301
  try {
17881
18302
  const {
@@ -17910,7 +18331,7 @@ var GatewayRerankingModel = class {
17910
18331
  ranking: responseBody.ranking,
17911
18332
  providerMetadata: responseBody.providerMetadata,
17912
18333
  response: { headers: responseHeaders, body: rawValue },
17913
- warnings: []
18334
+ warnings: (_a117 = responseBody.warnings) != null ? _a117 : []
17914
18335
  };
17915
18336
  } catch (error) {
17916
18337
  throw await asGatewayError2(error, await parseAuthMethod2(resolvedHeaders));
@@ -17926,6 +18347,22 @@ var GatewayRerankingModel = class {
17926
18347
  };
17927
18348
  }
17928
18349
  };
18350
+ var gatewayRerankingWarningSchema = z$1.discriminatedUnion("type", [
18351
+ z$1.object({
18352
+ type: z$1.literal("unsupported"),
18353
+ feature: z$1.string(),
18354
+ details: z$1.string().optional()
18355
+ }),
18356
+ z$1.object({
18357
+ type: z$1.literal("compatibility"),
18358
+ feature: z$1.string(),
18359
+ details: z$1.string().optional()
18360
+ }),
18361
+ z$1.object({
18362
+ type: z$1.literal("other"),
18363
+ message: z$1.string()
18364
+ })
18365
+ ]);
17929
18366
  var gatewayRerankingResponseSchema = lazySchema2(
17930
18367
  () => zodSchema3(
17931
18368
  z$1.object({
@@ -17935,144 +18372,495 @@ var gatewayRerankingResponseSchema = lazySchema2(
17935
18372
  relevanceScore: z$1.number()
17936
18373
  })
17937
18374
  ),
18375
+ warnings: z$1.array(gatewayRerankingWarningSchema).optional(),
17938
18376
  providerMetadata: z$1.record(z$1.string(), z$1.record(z$1.string(), z$1.unknown())).optional()
17939
18377
  })
17940
18378
  )
17941
18379
  );
17942
- var parallelSearchInputSchema2 = lazySchema2(
17943
- () => zodSchema3(
17944
- z.object({
17945
- objective: z.string().describe(
17946
- "Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."
17947
- ),
17948
- search_queries: z.array(z.string()).optional().describe(
17949
- "Optional search queries to supplement the objective. Maximum 200 characters per query."
17950
- ),
17951
- mode: z.enum(["one-shot", "agentic"]).optional().describe(
17952
- 'Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'
17953
- ),
17954
- max_results: z.number().optional().describe(
17955
- "Maximum number of results to return (1-20). Defaults to 10 if not specified."
17956
- ),
17957
- source_policy: z.object({
17958
- include_domains: z.array(z.string()).optional().describe("List of domains to include in search results."),
17959
- exclude_domains: z.array(z.string()).optional().describe("List of domains to exclude from search results."),
17960
- after_date: z.string().optional().describe(
17961
- "Only include results published after this date (ISO 8601 format)."
17962
- )
17963
- }).optional().describe(
17964
- "Source policy for controlling which domains to include/exclude and freshness."
17965
- ),
17966
- excerpts: z.object({
17967
- max_chars_per_result: z.number().optional().describe("Maximum characters per result."),
17968
- max_chars_total: z.number().optional().describe("Maximum total characters across all results.")
17969
- }).optional().describe("Excerpt configuration for controlling result length."),
17970
- fetch_policy: z.object({
17971
- max_age_seconds: z.number().optional().describe(
17972
- "Maximum age in seconds for cached content. Set to 0 to always fetch fresh content."
17973
- )
17974
- }).optional().describe("Fetch policy for controlling content freshness.")
17975
- })
17976
- )
17977
- );
17978
- var parallelSearchOutputSchema2 = lazySchema2(
17979
- () => zodSchema3(
17980
- z.union([
17981
- // Success response
17982
- z.object({
17983
- searchId: z.string(),
17984
- results: z.array(
17985
- z.object({
17986
- url: z.string(),
17987
- title: z.string(),
17988
- excerpt: z.string(),
17989
- publishDate: z.string().nullable().optional(),
17990
- relevanceScore: z.number().optional()
17991
- })
17992
- )
17993
- }),
17994
- // Error response
17995
- z.object({
17996
- error: z.enum([
17997
- "api_error",
17998
- "rate_limit",
17999
- "timeout",
18000
- "invalid_input",
18001
- "configuration_error",
18002
- "unknown"
18003
- ]),
18004
- statusCode: z.number().optional(),
18005
- message: z.string()
18006
- })
18007
- ])
18008
- )
18009
- );
18010
- var parallelSearchToolFactory2 = createProviderToolFactoryWithOutputSchema({
18011
- id: "gateway.parallel_search",
18012
- inputSchema: parallelSearchInputSchema2,
18013
- outputSchema: parallelSearchOutputSchema2
18014
- });
18015
- var parallelSearch2 = (config = {}) => parallelSearchToolFactory2(config);
18016
- var perplexitySearchInputSchema2 = lazySchema2(
18017
- () => zodSchema3(
18018
- z.object({
18019
- query: z.union([z.string(), z.array(z.string())]).describe(
18020
- "Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."
18021
- ),
18022
- max_results: z.number().optional().describe(
18023
- "Maximum number of search results to return (1-20, default: 10)"
18024
- ),
18025
- max_tokens_per_page: z.number().optional().describe(
18026
- "Maximum number of tokens to extract per search result page (256-2048, default: 2048)"
18027
- ),
18028
- max_tokens: z.number().optional().describe(
18029
- "Maximum total tokens across all search results (default: 25000, max: 1000000)"
18030
- ),
18031
- country: z.string().optional().describe(
18032
- "Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"
18033
- ),
18034
- search_domain_filter: z.array(z.string()).optional().describe(
18035
- "List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"
18036
- ),
18037
- search_language_filter: z.array(z.string()).optional().describe(
18038
- "List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"
18039
- ),
18040
- search_after_date: z.string().optional().describe(
18041
- "Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."
18042
- ),
18043
- search_before_date: z.string().optional().describe(
18044
- "Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."
18045
- ),
18046
- last_updated_after_filter: z.string().optional().describe(
18047
- "Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."
18048
- ),
18049
- last_updated_before_filter: z.string().optional().describe(
18050
- "Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."
18051
- ),
18052
- search_recency_filter: z.enum(["day", "week", "month", "year"]).optional().describe(
18053
- "Filter results by relative time period. Cannot be used with search_after_date or search_before_date."
18054
- )
18055
- })
18056
- )
18057
- );
18058
- var perplexitySearchOutputSchema2 = lazySchema2(
18059
- () => zodSchema3(
18060
- z.union([
18061
- // Success response
18062
- z.object({
18063
- results: z.array(
18064
- z.object({
18065
- title: z.string(),
18066
- url: z.string(),
18067
- snippet: z.string(),
18068
- date: z.string().optional(),
18069
- lastUpdated: z.string().optional()
18070
- })
18071
- ),
18072
- id: z.string()
18073
- }),
18074
- // Error response
18075
- z.object({
18380
+ var GatewaySpeechModel = class {
18381
+ constructor(modelId, config) {
18382
+ this.modelId = modelId;
18383
+ this.config = config;
18384
+ this.specificationVersion = "v3";
18385
+ }
18386
+ get provider() {
18387
+ return this.config.provider;
18388
+ }
18389
+ async doGenerate({
18390
+ text: text4,
18391
+ voice,
18392
+ outputFormat,
18393
+ instructions,
18394
+ speed,
18395
+ language,
18396
+ providerOptions,
18397
+ headers,
18398
+ abortSignal
18399
+ }) {
18400
+ const resolvedHeaders = await resolve2(this.config.headers());
18401
+ try {
18402
+ const {
18403
+ responseHeaders,
18404
+ value: responseBody,
18405
+ rawValue
18406
+ } = await postJsonToApi2({
18407
+ url: this.getUrl(),
18408
+ headers: combineHeaders2(
18409
+ resolvedHeaders,
18410
+ headers != null ? headers : {},
18411
+ this.getModelConfigHeaders(),
18412
+ await resolve2(this.config.o11yHeaders)
18413
+ ),
18414
+ body: {
18415
+ text: text4,
18416
+ ...voice && { voice },
18417
+ ...outputFormat && { outputFormat },
18418
+ ...instructions && { instructions },
18419
+ ...speed != null && { speed },
18420
+ ...language && { language },
18421
+ ...providerOptions && { providerOptions }
18422
+ },
18423
+ successfulResponseHandler: createJsonResponseHandler2(
18424
+ gatewaySpeechResponseSchema
18425
+ ),
18426
+ failedResponseHandler: createJsonErrorResponseHandler2({
18427
+ errorSchema: z$1.any(),
18428
+ errorToMessage: (data) => data
18429
+ }),
18430
+ ...abortSignal && { abortSignal },
18431
+ fetch: this.config.fetch
18432
+ });
18433
+ return {
18434
+ audio: responseBody.audio,
18435
+ warnings: mapGatewayWarnings(responseBody.warnings),
18436
+ providerMetadata: responseBody.providerMetadata,
18437
+ response: {
18438
+ timestamp: /* @__PURE__ */ new Date(),
18439
+ modelId: this.modelId,
18440
+ headers: responseHeaders,
18441
+ body: rawValue
18442
+ }
18443
+ };
18444
+ } catch (error) {
18445
+ throw await asGatewayError2(
18446
+ error,
18447
+ await parseAuthMethod2(resolvedHeaders != null ? resolvedHeaders : {})
18448
+ );
18449
+ }
18450
+ }
18451
+ getUrl() {
18452
+ return `${this.config.baseURL}/speech-model`;
18453
+ }
18454
+ getModelConfigHeaders() {
18455
+ return {
18456
+ "ai-speech-model-specification-version": "3",
18457
+ "ai-model-id": this.modelId
18458
+ };
18459
+ }
18460
+ };
18461
+ var providerMetadataEntrySchema3 = z$1.object({}).catchall(z$1.unknown());
18462
+ var gatewaySpeechWarningSchema = z$1.discriminatedUnion("type", [
18463
+ z$1.object({
18464
+ type: z$1.literal("unsupported"),
18465
+ feature: z$1.string(),
18466
+ details: z$1.string().optional()
18467
+ }),
18468
+ z$1.object({
18469
+ type: z$1.literal("compatibility"),
18470
+ feature: z$1.string(),
18471
+ details: z$1.string().optional()
18472
+ }),
18473
+ z$1.object({
18474
+ type: z$1.literal("deprecated"),
18475
+ setting: z$1.string(),
18476
+ message: z$1.string()
18477
+ }),
18478
+ z$1.object({
18479
+ type: z$1.literal("other"),
18480
+ message: z$1.string()
18481
+ })
18482
+ ]);
18483
+ var gatewaySpeechResponseSchema = z$1.object({
18484
+ audio: z$1.string(),
18485
+ warnings: z$1.array(gatewaySpeechWarningSchema).optional(),
18486
+ providerMetadata: z$1.record(z$1.string(), providerMetadataEntrySchema3).optional()
18487
+ });
18488
+ var GatewayTranscriptionModel = class {
18489
+ constructor(modelId, config) {
18490
+ this.modelId = modelId;
18491
+ this.config = config;
18492
+ this.specificationVersion = "v3";
18493
+ }
18494
+ get provider() {
18495
+ return this.config.provider;
18496
+ }
18497
+ async doGenerate({
18498
+ audio,
18499
+ mediaType,
18500
+ providerOptions,
18501
+ headers,
18502
+ abortSignal
18503
+ }) {
18504
+ var _a117, _b113, _c;
18505
+ const resolvedHeaders = await resolve2(this.config.headers());
18506
+ try {
18507
+ const {
18508
+ responseHeaders,
18509
+ value: responseBody,
18510
+ rawValue
18511
+ } = await postJsonToApi2({
18512
+ url: this.getUrl(),
18513
+ headers: combineHeaders2(
18514
+ resolvedHeaders,
18515
+ headers != null ? headers : {},
18516
+ this.getModelConfigHeaders(),
18517
+ await resolve2(this.config.o11yHeaders)
18518
+ ),
18519
+ body: {
18520
+ audio: audio instanceof Uint8Array ? convertUint8ArrayToBase643(audio) : audio,
18521
+ mediaType,
18522
+ ...providerOptions && { providerOptions }
18523
+ },
18524
+ successfulResponseHandler: createJsonResponseHandler2(
18525
+ gatewayTranscriptionResponseSchema
18526
+ ),
18527
+ failedResponseHandler: createJsonErrorResponseHandler2({
18528
+ errorSchema: z$1.any(),
18529
+ errorToMessage: (data) => data
18530
+ }),
18531
+ ...abortSignal && { abortSignal },
18532
+ fetch: this.config.fetch
18533
+ });
18534
+ return {
18535
+ text: responseBody.text,
18536
+ segments: (_a117 = responseBody.segments) != null ? _a117 : [],
18537
+ language: (_b113 = responseBody.language) != null ? _b113 : void 0,
18538
+ durationInSeconds: (_c = responseBody.durationInSeconds) != null ? _c : void 0,
18539
+ warnings: mapGatewayWarnings(responseBody.warnings),
18540
+ providerMetadata: responseBody.providerMetadata,
18541
+ response: {
18542
+ timestamp: /* @__PURE__ */ new Date(),
18543
+ modelId: this.modelId,
18544
+ headers: responseHeaders,
18545
+ body: rawValue
18546
+ }
18547
+ };
18548
+ } catch (error) {
18549
+ throw await asGatewayError2(
18550
+ error,
18551
+ await parseAuthMethod2(resolvedHeaders != null ? resolvedHeaders : {})
18552
+ );
18553
+ }
18554
+ }
18555
+ getUrl() {
18556
+ return `${this.config.baseURL}/transcription-model`;
18557
+ }
18558
+ getModelConfigHeaders() {
18559
+ return {
18560
+ "ai-transcription-model-specification-version": "3",
18561
+ "ai-model-id": this.modelId
18562
+ };
18563
+ }
18564
+ };
18565
+ var providerMetadataEntrySchema4 = z$1.object({}).catchall(z$1.unknown());
18566
+ var gatewayTranscriptionWarningSchema = z$1.discriminatedUnion("type", [
18567
+ z$1.object({
18568
+ type: z$1.literal("unsupported"),
18569
+ feature: z$1.string(),
18570
+ details: z$1.string().optional()
18571
+ }),
18572
+ z$1.object({
18573
+ type: z$1.literal("compatibility"),
18574
+ feature: z$1.string(),
18575
+ details: z$1.string().optional()
18576
+ }),
18577
+ z$1.object({
18578
+ type: z$1.literal("deprecated"),
18579
+ setting: z$1.string(),
18580
+ message: z$1.string()
18581
+ }),
18582
+ z$1.object({
18583
+ type: z$1.literal("other"),
18584
+ message: z$1.string()
18585
+ })
18586
+ ]);
18587
+ var gatewayTranscriptionResponseSchema = z$1.object({
18588
+ text: z$1.string(),
18589
+ segments: z$1.array(
18590
+ z$1.object({
18591
+ text: z$1.string(),
18592
+ startSecond: z$1.number(),
18593
+ endSecond: z$1.number()
18594
+ })
18595
+ ).optional(),
18596
+ language: z$1.string().nullish(),
18597
+ durationInSeconds: z$1.number().nullish(),
18598
+ warnings: z$1.array(gatewayTranscriptionWarningSchema).optional(),
18599
+ providerMetadata: z$1.record(z$1.string(), providerMetadataEntrySchema4).optional()
18600
+ });
18601
+ var exaSearchInputSchema = lazySchema2(
18602
+ () => zodSchema3(
18603
+ z.object({
18604
+ query: z.string().describe("Natural-language web search query. This is required."),
18605
+ type: z.enum(["auto", "fast", "instant"]).optional().describe(
18606
+ "Search method. Use auto for the default balance of speed and quality."
18607
+ ),
18608
+ num_results: z.number().optional().describe("Maximum number of results to return (1-100, default: 10)."),
18609
+ category: z.enum([
18610
+ "company",
18611
+ "people",
18612
+ "research paper",
18613
+ "news",
18614
+ "personal site",
18615
+ "financial report"
18616
+ ]).optional().describe("Optional content category to focus results."),
18617
+ user_location: z.string().optional().describe("Two-letter ISO country code such as 'US'."),
18618
+ include_domains: z.array(z.string()).optional().describe("Only return results from these domains."),
18619
+ exclude_domains: z.array(z.string()).optional().describe("Exclude results from these domains."),
18620
+ start_published_date: z.string().optional().describe("Only return links published after this ISO 8601 date."),
18621
+ end_published_date: z.string().optional().describe("Only return links published before this ISO 8601 date."),
18622
+ contents: z.object({
18623
+ text: z.union([
18624
+ z.boolean(),
18625
+ z.object({
18626
+ max_characters: z.number().optional(),
18627
+ include_html_tags: z.boolean().optional(),
18628
+ verbosity: z.enum(["compact", "standard", "full"]).optional(),
18629
+ include_sections: z.array(
18630
+ z.enum([
18631
+ "header",
18632
+ "navigation",
18633
+ "banner",
18634
+ "body",
18635
+ "sidebar",
18636
+ "footer",
18637
+ "metadata"
18638
+ ])
18639
+ ).optional(),
18640
+ exclude_sections: z.array(
18641
+ z.enum([
18642
+ "header",
18643
+ "navigation",
18644
+ "banner",
18645
+ "body",
18646
+ "sidebar",
18647
+ "footer",
18648
+ "metadata"
18649
+ ])
18650
+ ).optional()
18651
+ })
18652
+ ]).optional(),
18653
+ highlights: z.union([
18654
+ z.boolean(),
18655
+ z.object({
18656
+ query: z.string().optional(),
18657
+ max_characters: z.number().optional()
18658
+ })
18659
+ ]).optional(),
18660
+ max_age_hours: z.number().optional(),
18661
+ livecrawl_timeout: z.number().optional(),
18662
+ subpages: z.number().optional(),
18663
+ subpage_target: z.union([z.string(), z.array(z.string())]).optional(),
18664
+ extras: z.object({
18665
+ links: z.number().optional(),
18666
+ image_links: z.number().optional()
18667
+ }).optional()
18668
+ }).optional().describe("Controls extracted page content and freshness.")
18669
+ })
18670
+ )
18671
+ );
18672
+ var exaSearchOutputSchema = lazySchema2(
18673
+ () => zodSchema3(
18674
+ z.union([
18675
+ z.object({
18676
+ requestId: z.string(),
18677
+ searchType: z.string().optional(),
18678
+ resolvedSearchType: z.string().optional(),
18679
+ results: z.array(
18680
+ z.object({
18681
+ title: z.string(),
18682
+ url: z.string(),
18683
+ id: z.string(),
18684
+ publishedDate: z.string().nullable().optional(),
18685
+ author: z.string().nullable().optional(),
18686
+ image: z.string().nullable().optional(),
18687
+ favicon: z.string().nullable().optional(),
18688
+ text: z.string().optional(),
18689
+ highlights: z.array(z.string()).optional(),
18690
+ highlightScores: z.array(z.number()).optional(),
18691
+ summary: z.string().optional(),
18692
+ subpages: z.array(z.any()).optional(),
18693
+ extras: z.object({
18694
+ links: z.array(z.string()).optional(),
18695
+ imageLinks: z.array(z.string()).optional()
18696
+ }).optional()
18697
+ })
18698
+ ),
18699
+ costDollars: z.object({
18700
+ total: z.number().optional(),
18701
+ search: z.record(z.number()).optional()
18702
+ }).optional()
18703
+ }),
18704
+ z.object({
18705
+ error: z.enum([
18706
+ "api_error",
18707
+ "rate_limit",
18708
+ "timeout",
18709
+ "invalid_input",
18710
+ "configuration_error",
18711
+ "execution_error",
18712
+ "unknown"
18713
+ ]),
18714
+ statusCode: z.number().optional(),
18715
+ message: z.string()
18716
+ })
18717
+ ])
18718
+ )
18719
+ );
18720
+ var exaSearchToolFactory = createProviderToolFactoryWithOutputSchema({
18721
+ id: "gateway.exa_search",
18722
+ inputSchema: exaSearchInputSchema,
18723
+ outputSchema: exaSearchOutputSchema
18724
+ });
18725
+ var exaSearch = (config = {}) => exaSearchToolFactory(config);
18726
+ var parallelSearchInputSchema2 = lazySchema2(
18727
+ () => zodSchema3(
18728
+ z.object({
18729
+ objective: z.string().describe(
18730
+ "Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."
18731
+ ),
18732
+ search_queries: z.array(z.string()).optional().describe(
18733
+ "Optional search queries to supplement the objective. Maximum 200 characters per query."
18734
+ ),
18735
+ mode: z.enum(["one-shot", "agentic"]).optional().describe(
18736
+ 'Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'
18737
+ ),
18738
+ max_results: z.number().optional().describe(
18739
+ "Maximum number of results to return (1-20). Defaults to 10 if not specified."
18740
+ ),
18741
+ source_policy: z.object({
18742
+ include_domains: z.array(z.string()).optional().describe(
18743
+ "Limit results to these domains. Use plain domain names only \u2014 e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."
18744
+ ),
18745
+ exclude_domains: z.array(z.string()).optional().describe(
18746
+ "Exclude results from these domains. Use plain domain names only \u2014 e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."
18747
+ ),
18748
+ after_date: z.string().optional().describe(
18749
+ "Only include results published after this date. Use an ISO 8601 calendar date formatted YYYY-MM-DD (e.g. 2025-01-01); do not include a time."
18750
+ )
18751
+ }).optional().describe(
18752
+ "Source policy for controlling which domains to include/exclude and freshness."
18753
+ ),
18754
+ excerpts: z.object({
18755
+ max_chars_per_result: z.number().optional().describe("Maximum characters per result."),
18756
+ max_chars_total: z.number().optional().describe("Maximum total characters across all results.")
18757
+ }).optional().describe("Excerpt configuration for controlling result length."),
18758
+ fetch_policy: z.object({
18759
+ max_age_seconds: z.number().optional().describe(
18760
+ "Maximum age in seconds for cached content. Set to 0 to always fetch fresh content."
18761
+ )
18762
+ }).optional().describe("Fetch policy for controlling content freshness.")
18763
+ })
18764
+ )
18765
+ );
18766
+ var parallelSearchOutputSchema2 = lazySchema2(
18767
+ () => zodSchema3(
18768
+ z.union([
18769
+ // Success response
18770
+ z.object({
18771
+ searchId: z.string(),
18772
+ results: z.array(
18773
+ z.object({
18774
+ url: z.string(),
18775
+ title: z.string(),
18776
+ excerpt: z.string(),
18777
+ publishDate: z.string().nullable().optional(),
18778
+ relevanceScore: z.number().optional()
18779
+ })
18780
+ )
18781
+ }),
18782
+ // Error response
18783
+ z.object({
18784
+ error: z.enum([
18785
+ "api_error",
18786
+ "rate_limit",
18787
+ "timeout",
18788
+ "invalid_input",
18789
+ "configuration_error",
18790
+ "unknown"
18791
+ ]),
18792
+ statusCode: z.number().optional(),
18793
+ message: z.string()
18794
+ })
18795
+ ])
18796
+ )
18797
+ );
18798
+ var parallelSearchToolFactory2 = createProviderToolFactoryWithOutputSchema({
18799
+ id: "gateway.parallel_search",
18800
+ inputSchema: parallelSearchInputSchema2,
18801
+ outputSchema: parallelSearchOutputSchema2
18802
+ });
18803
+ var parallelSearch2 = (config = {}) => parallelSearchToolFactory2(config);
18804
+ var perplexitySearchInputSchema2 = lazySchema2(
18805
+ () => zodSchema3(
18806
+ z.object({
18807
+ query: z.union([z.string(), z.array(z.string())]).describe(
18808
+ "Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."
18809
+ ),
18810
+ max_results: z.number().optional().describe(
18811
+ "Maximum number of search results to return (1-20, default: 10)"
18812
+ ),
18813
+ max_tokens_per_page: z.number().optional().describe(
18814
+ "Maximum number of tokens to extract per search result page (256-2048, default: 2048)"
18815
+ ),
18816
+ max_tokens: z.number().optional().describe(
18817
+ "Maximum total tokens across all search results (default: 25000, max: 1000000)"
18818
+ ),
18819
+ country: z.string().optional().describe(
18820
+ "Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"
18821
+ ),
18822
+ search_domain_filter: z.array(z.string()).optional().describe(
18823
+ "List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"
18824
+ ),
18825
+ search_language_filter: z.array(z.string()).optional().describe(
18826
+ "List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"
18827
+ ),
18828
+ search_after_date: z.string().optional().describe(
18829
+ "Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."
18830
+ ),
18831
+ search_before_date: z.string().optional().describe(
18832
+ "Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."
18833
+ ),
18834
+ last_updated_after_filter: z.string().optional().describe(
18835
+ "Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."
18836
+ ),
18837
+ last_updated_before_filter: z.string().optional().describe(
18838
+ "Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."
18839
+ ),
18840
+ search_recency_filter: z.enum(["day", "week", "month", "year"]).optional().describe(
18841
+ "Filter results by relative time period. Cannot be used with search_after_date or search_before_date."
18842
+ )
18843
+ })
18844
+ )
18845
+ );
18846
+ var perplexitySearchOutputSchema2 = lazySchema2(
18847
+ () => zodSchema3(
18848
+ z.union([
18849
+ // Success response
18850
+ z.object({
18851
+ results: z.array(
18852
+ z.object({
18853
+ title: z.string(),
18854
+ url: z.string(),
18855
+ snippet: z.string(),
18856
+ date: z.string().optional(),
18857
+ lastUpdated: z.string().optional()
18858
+ })
18859
+ ),
18860
+ id: z.string()
18861
+ }),
18862
+ // Error response
18863
+ z.object({
18076
18864
  error: z.enum([
18077
18865
  "api_error",
18078
18866
  "rate_limit",
@@ -18093,6 +18881,14 @@ var perplexitySearchToolFactory2 = createProviderToolFactoryWithOutputSchema({
18093
18881
  });
18094
18882
  var perplexitySearch2 = (config = {}) => perplexitySearchToolFactory2(config);
18095
18883
  var gatewayTools2 = {
18884
+ /**
18885
+ * Search the web using Exa for current information and token-efficient
18886
+ * excerpts optimized for agent workflows.
18887
+ *
18888
+ * Supports search type, category, domain, date, location, and content
18889
+ * extraction controls.
18890
+ */
18891
+ exaSearch,
18096
18892
  /**
18097
18893
  * Search the web using Parallel AI's Search API for LLM-optimized excerpts.
18098
18894
  *
@@ -18112,18 +18908,18 @@ var gatewayTools2 = {
18112
18908
  perplexitySearch: perplexitySearch2
18113
18909
  };
18114
18910
  async function getVercelRequestId2() {
18115
- var _a932;
18116
- return (_a932 = getContext2().headers) == null ? void 0 : _a932["x-vercel-id"];
18911
+ var _a117;
18912
+ return (_a117 = getContext2().headers) == null ? void 0 : _a117["x-vercel-id"];
18117
18913
  }
18118
- var VERSION5 = "3.0.112";
18914
+ var VERSION5 = "3.0.148";
18119
18915
  var AI_GATEWAY_PROTOCOL_VERSION2 = "0.0.1";
18120
18916
  function createGatewayProvider2(options = {}) {
18121
- var _a932, _b93;
18917
+ var _a117, _b113;
18122
18918
  let pendingMetadata = null;
18123
18919
  let metadataCache = null;
18124
- const cacheRefreshMillis = (_a932 = options.metadataCacheRefreshMillis) != null ? _a932 : 1e3 * 60 * 5;
18920
+ const cacheRefreshMillis = (_a117 = options.metadataCacheRefreshMillis) != null ? _a117 : 1e3 * 60 * 5;
18125
18921
  let lastFetchTime = 0;
18126
- const baseURL = (_b93 = withoutTrailingSlash2(options.baseURL)) != null ? _b93 : "https://ai-gateway.vercel.sh/v3/ai";
18922
+ const baseURL = (_b113 = withoutTrailingSlash2(options.baseURL)) != null ? _b113 : "https://ai-gateway.vercel.sh/v3/ai";
18127
18923
  const getHeaders = async () => {
18128
18924
  try {
18129
18925
  const auth = await getGatewayAuthToken2(options);
@@ -18183,10 +18979,10 @@ function createGatewayProvider2(options = {}) {
18183
18979
  });
18184
18980
  };
18185
18981
  const getAvailableModels = async () => {
18186
- var _a1022, _b103, _c;
18187
- const now2 = (_c = (_b103 = (_a1022 = options._internal) == null ? void 0 : _a1022.currentDate) == null ? void 0 : _b103.call(_a1022).getTime()) != null ? _c : Date.now();
18188
- if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) {
18189
- lastFetchTime = now2;
18982
+ var _a126, _b123, _c;
18983
+ const now = (_c = (_b123 = (_a126 = options._internal) == null ? void 0 : _a126.currentDate) == null ? void 0 : _b123.call(_a126).getTime()) != null ? _c : Date.now();
18984
+ if (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) {
18985
+ lastFetchTime = now;
18190
18986
  pendingMetadata = new GatewayFetchMetadata2({
18191
18987
  baseURL,
18192
18988
  headers: getHeaders,
@@ -18293,6 +19089,28 @@ function createGatewayProvider2(options = {}) {
18293
19089
  };
18294
19090
  provider.rerankingModel = createRerankingModel;
18295
19091
  provider.reranking = createRerankingModel;
19092
+ const createSpeechModel = (modelId) => {
19093
+ return new GatewaySpeechModel(modelId, {
19094
+ provider: "gateway",
19095
+ baseURL,
19096
+ headers: getHeaders,
19097
+ fetch: options.fetch,
19098
+ o11yHeaders: createO11yHeaders()
19099
+ });
19100
+ };
19101
+ provider.speechModel = createSpeechModel;
19102
+ provider.speech = createSpeechModel;
19103
+ const createTranscriptionModel = (modelId) => {
19104
+ return new GatewayTranscriptionModel(modelId, {
19105
+ provider: "gateway",
19106
+ baseURL,
19107
+ headers: getHeaders,
19108
+ fetch: options.fetch,
19109
+ o11yHeaders: createO11yHeaders()
19110
+ });
19111
+ };
19112
+ provider.transcriptionModel = createTranscriptionModel;
19113
+ provider.transcription = createTranscriptionModel;
18296
19114
  provider.chat = provider.languageModel;
18297
19115
  provider.embedding = provider.embeddingModel;
18298
19116
  provider.image = provider.imageModel;
@@ -18318,19 +19136,16 @@ async function getGatewayAuthToken2(options) {
18318
19136
  authMethod: "oidc"
18319
19137
  };
18320
19138
  }
18321
- var _globalThis3 = typeof globalThis === "object" ? globalThis : global;
18322
- var VERSION23 = "1.9.0";
19139
+ var VERSION6 = "1.9.1";
18323
19140
  var re3 = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
18324
19141
  function _makeCompatibilityCheck3(ownVersion) {
18325
- var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
18326
- var rejectedVersions = /* @__PURE__ */ new Set();
18327
- var myVersionMatch = ownVersion.match(re3);
19142
+ const acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
19143
+ const rejectedVersions = /* @__PURE__ */ new Set();
19144
+ const myVersionMatch = ownVersion.match(re3);
18328
19145
  if (!myVersionMatch) {
18329
- return function() {
18330
- return false;
18331
- };
19146
+ return () => false;
18332
19147
  }
18333
- var ownVersionParsed = {
19148
+ const ownVersionParsed = {
18334
19149
  major: +myVersionMatch[1],
18335
19150
  minor: +myVersionMatch[2],
18336
19151
  patch: +myVersionMatch[3],
@@ -18356,11 +19171,11 @@ function _makeCompatibilityCheck3(ownVersion) {
18356
19171
  if (rejectedVersions.has(globalVersion)) {
18357
19172
  return false;
18358
19173
  }
18359
- var globalVersionMatch = globalVersion.match(re3);
19174
+ const globalVersionMatch = globalVersion.match(re3);
18360
19175
  if (!globalVersionMatch) {
18361
19176
  return _reject(globalVersion);
18362
19177
  }
18363
- var globalVersionParsed = {
19178
+ const globalVersionParsed = {
18364
19179
  major: +globalVersionMatch[1],
18365
19180
  minor: +globalVersionMatch[2],
18366
19181
  patch: +globalVersionMatch[3],
@@ -18376,457 +19191,326 @@ function _makeCompatibilityCheck3(ownVersion) {
18376
19191
  if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
18377
19192
  return _accept(globalVersion);
18378
19193
  }
18379
- return _reject(globalVersion);
18380
- }
18381
- if (ownVersionParsed.minor <= globalVersionParsed.minor) {
18382
- return _accept(globalVersion);
18383
- }
18384
- return _reject(globalVersion);
18385
- };
18386
- }
18387
- var isCompatible3 = _makeCompatibilityCheck3(VERSION23);
18388
- var major3 = VERSION23.split(".")[0];
18389
- var GLOBAL_OPENTELEMETRY_API_KEY3 = /* @__PURE__ */ Symbol.for("opentelemetry.js.api." + major3);
18390
- var _global3 = _globalThis3;
18391
- function registerGlobal3(type, instance, diag, allowOverride) {
18392
- var _a21;
18393
- if (allowOverride === void 0) {
18394
- allowOverride = false;
18395
- }
18396
- var api = _global3[GLOBAL_OPENTELEMETRY_API_KEY3] = (_a21 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) !== null && _a21 !== void 0 ? _a21 : {
18397
- version: VERSION23
18398
- };
18399
- if (!allowOverride && api[type]) {
18400
- var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
18401
- diag.error(err.stack || err.message);
18402
- return false;
18403
- }
18404
- if (api.version !== VERSION23) {
18405
- var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION23);
18406
- diag.error(err.stack || err.message);
18407
- return false;
18408
- }
18409
- api[type] = instance;
18410
- diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION23 + ".");
18411
- return true;
18412
- }
18413
- function getGlobal3(type) {
18414
- var _a21, _b93;
18415
- var globalVersion = (_a21 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _a21 === void 0 ? void 0 : _a21.version;
18416
- if (!globalVersion || !isCompatible3(globalVersion)) {
18417
- return;
18418
- }
18419
- return (_b93 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _b93 === void 0 ? void 0 : _b93[type];
18420
- }
18421
- function unregisterGlobal3(type, diag) {
18422
- diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION23 + ".");
18423
- var api = _global3[GLOBAL_OPENTELEMETRY_API_KEY3];
18424
- if (api) {
18425
- delete api[type];
18426
- }
18427
- }
18428
- var __read6 = function(o, n) {
18429
- var m = typeof Symbol === "function" && o[Symbol.iterator];
18430
- if (!m) return o;
18431
- var i = m.call(o), r, ar = [], e;
18432
- try {
18433
- while (!(r = i.next()).done) ar.push(r.value);
18434
- } catch (error) {
18435
- e = { error };
18436
- } finally {
18437
- try {
18438
- if (r && !r.done && (m = i["return"])) m.call(i);
18439
- } finally {
18440
- if (e) throw e.error;
18441
- }
18442
- }
18443
- return ar;
18444
- };
18445
- var __spreadArray6 = function(to, from, pack) {
18446
- if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
18447
- if (ar || !(i in from)) {
18448
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
18449
- ar[i] = from[i];
18450
- }
18451
- }
18452
- return to.concat(ar || Array.prototype.slice.call(from));
18453
- };
18454
- var DiagComponentLogger3 = (
18455
- /** @class */
18456
- (function() {
18457
- function DiagComponentLogger22(props) {
18458
- this._namespace = props.namespace || "DiagComponentLogger";
18459
- }
18460
- DiagComponentLogger22.prototype.debug = function() {
18461
- var args = [];
18462
- for (var _i = 0; _i < arguments.length; _i++) {
18463
- args[_i] = arguments[_i];
18464
- }
18465
- return logProxy3("debug", this._namespace, args);
18466
- };
18467
- DiagComponentLogger22.prototype.error = function() {
18468
- var args = [];
18469
- for (var _i = 0; _i < arguments.length; _i++) {
18470
- args[_i] = arguments[_i];
18471
- }
18472
- return logProxy3("error", this._namespace, args);
18473
- };
18474
- DiagComponentLogger22.prototype.info = function() {
18475
- var args = [];
18476
- for (var _i = 0; _i < arguments.length; _i++) {
18477
- args[_i] = arguments[_i];
18478
- }
18479
- return logProxy3("info", this._namespace, args);
18480
- };
18481
- DiagComponentLogger22.prototype.warn = function() {
18482
- var args = [];
18483
- for (var _i = 0; _i < arguments.length; _i++) {
18484
- args[_i] = arguments[_i];
18485
- }
18486
- return logProxy3("warn", this._namespace, args);
18487
- };
18488
- DiagComponentLogger22.prototype.verbose = function() {
18489
- var args = [];
18490
- for (var _i = 0; _i < arguments.length; _i++) {
18491
- args[_i] = arguments[_i];
18492
- }
18493
- return logProxy3("verbose", this._namespace, args);
18494
- };
18495
- return DiagComponentLogger22;
18496
- })()
18497
- );
18498
- function logProxy3(funcName, namespace, args) {
18499
- var logger = getGlobal3("diag");
18500
- if (!logger) {
18501
- return;
18502
- }
18503
- args.unshift(namespace);
18504
- return logger[funcName].apply(logger, __spreadArray6([], __read6(args), false));
18505
- }
18506
- var DiagLogLevel3;
18507
- (function(DiagLogLevel22) {
18508
- DiagLogLevel22[DiagLogLevel22["NONE"] = 0] = "NONE";
18509
- DiagLogLevel22[DiagLogLevel22["ERROR"] = 30] = "ERROR";
18510
- DiagLogLevel22[DiagLogLevel22["WARN"] = 50] = "WARN";
18511
- DiagLogLevel22[DiagLogLevel22["INFO"] = 60] = "INFO";
18512
- DiagLogLevel22[DiagLogLevel22["DEBUG"] = 70] = "DEBUG";
18513
- DiagLogLevel22[DiagLogLevel22["VERBOSE"] = 80] = "VERBOSE";
18514
- DiagLogLevel22[DiagLogLevel22["ALL"] = 9999] = "ALL";
18515
- })(DiagLogLevel3 || (DiagLogLevel3 = {}));
18516
- function createLogLevelDiagLogger3(maxLevel, logger) {
18517
- if (maxLevel < DiagLogLevel3.NONE) {
18518
- maxLevel = DiagLogLevel3.NONE;
18519
- } else if (maxLevel > DiagLogLevel3.ALL) {
18520
- maxLevel = DiagLogLevel3.ALL;
18521
- }
18522
- logger = logger || {};
18523
- function _filterFunc(funcName, theLevel) {
18524
- var theFunc = logger[funcName];
18525
- if (typeof theFunc === "function" && maxLevel >= theLevel) {
18526
- return theFunc.bind(logger);
18527
- }
18528
- return function() {
18529
- };
18530
- }
18531
- return {
18532
- error: _filterFunc("error", DiagLogLevel3.ERROR),
18533
- warn: _filterFunc("warn", DiagLogLevel3.WARN),
18534
- info: _filterFunc("info", DiagLogLevel3.INFO),
18535
- debug: _filterFunc("debug", DiagLogLevel3.DEBUG),
18536
- verbose: _filterFunc("verbose", DiagLogLevel3.VERBOSE)
18537
- };
18538
- }
18539
- var __read23 = function(o, n) {
18540
- var m = typeof Symbol === "function" && o[Symbol.iterator];
18541
- if (!m) return o;
18542
- var i = m.call(o), r, ar = [], e;
18543
- try {
18544
- while (!(r = i.next()).done) ar.push(r.value);
18545
- } catch (error) {
18546
- e = { error };
18547
- } finally {
18548
- try {
18549
- if (r && !r.done && (m = i["return"])) m.call(i);
18550
- } finally {
18551
- if (e) throw e.error;
18552
- }
18553
- }
18554
- return ar;
18555
- };
18556
- var __spreadArray23 = function(to, from, pack) {
18557
- if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
18558
- if (ar || !(i in from)) {
18559
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
18560
- ar[i] = from[i];
18561
- }
18562
- }
18563
- return to.concat(ar || Array.prototype.slice.call(from));
18564
- };
18565
- var API_NAME5 = "diag";
18566
- var DiagAPI3 = (
18567
- /** @class */
18568
- (function() {
18569
- function DiagAPI22() {
18570
- function _logProxy(funcName) {
18571
- return function() {
18572
- var args = [];
18573
- for (var _i = 0; _i < arguments.length; _i++) {
18574
- args[_i] = arguments[_i];
18575
- }
18576
- var logger = getGlobal3("diag");
18577
- if (!logger)
18578
- return;
18579
- return logger[funcName].apply(logger, __spreadArray23([], __read23(args), false));
18580
- };
18581
- }
18582
- var self = this;
18583
- var setLogger = function(logger, optionsOrLogLevel) {
18584
- var _a21, _b93, _c;
18585
- if (optionsOrLogLevel === void 0) {
18586
- optionsOrLogLevel = { logLevel: DiagLogLevel3.INFO };
18587
- }
18588
- if (logger === self) {
18589
- var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
18590
- self.error((_a21 = err.stack) !== null && _a21 !== void 0 ? _a21 : err.message);
18591
- return false;
18592
- }
18593
- if (typeof optionsOrLogLevel === "number") {
18594
- optionsOrLogLevel = {
18595
- logLevel: optionsOrLogLevel
18596
- };
18597
- }
18598
- var oldLogger = getGlobal3("diag");
18599
- var newLogger = createLogLevelDiagLogger3((_b93 = optionsOrLogLevel.logLevel) !== null && _b93 !== void 0 ? _b93 : DiagLogLevel3.INFO, logger);
18600
- if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
18601
- var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
18602
- oldLogger.warn("Current logger will be overwritten from " + stack);
18603
- newLogger.warn("Current logger will overwrite one already registered from " + stack);
18604
- }
18605
- return registerGlobal3("diag", newLogger, self, true);
18606
- };
18607
- self.setLogger = setLogger;
18608
- self.disable = function() {
18609
- unregisterGlobal3(API_NAME5, self);
18610
- };
18611
- self.createComponentLogger = function(options) {
18612
- return new DiagComponentLogger3(options);
18613
- };
18614
- self.verbose = _logProxy("verbose");
18615
- self.debug = _logProxy("debug");
18616
- self.info = _logProxy("info");
18617
- self.warn = _logProxy("warn");
18618
- self.error = _logProxy("error");
18619
- }
18620
- DiagAPI22.instance = function() {
18621
- if (!this._instance) {
18622
- this._instance = new DiagAPI22();
18623
- }
18624
- return this._instance;
18625
- };
18626
- return DiagAPI22;
18627
- })()
18628
- );
18629
- function createContextKey3(description) {
18630
- return Symbol.for(description);
18631
- }
18632
- var BaseContext3 = (
18633
- /** @class */
18634
- /* @__PURE__ */ (function() {
18635
- function BaseContext22(parentContext) {
18636
- var self = this;
18637
- self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
18638
- self.getValue = function(key) {
18639
- return self._currentContext.get(key);
18640
- };
18641
- self.setValue = function(key, value) {
18642
- var context2 = new BaseContext22(self._currentContext);
18643
- context2._currentContext.set(key, value);
18644
- return context2;
18645
- };
18646
- self.deleteValue = function(key) {
18647
- var context2 = new BaseContext22(self._currentContext);
18648
- context2._currentContext.delete(key);
18649
- return context2;
18650
- };
19194
+ return _reject(globalVersion);
18651
19195
  }
18652
- return BaseContext22;
18653
- })()
18654
- );
18655
- var ROOT_CONTEXT3 = new BaseContext3();
18656
- var __read33 = function(o, n) {
18657
- var m = typeof Symbol === "function" && o[Symbol.iterator];
18658
- if (!m) return o;
18659
- var i = m.call(o), r, ar = [], e;
18660
- try {
18661
- while (!(r = i.next()).done) ar.push(r.value);
18662
- } catch (error) {
18663
- e = { error };
18664
- } finally {
18665
- try {
18666
- if (r && !r.done && (m = i["return"])) m.call(i);
18667
- } finally {
18668
- if (e) throw e.error;
19196
+ if (ownVersionParsed.minor <= globalVersionParsed.minor) {
19197
+ return _accept(globalVersion);
18669
19198
  }
19199
+ return _reject(globalVersion);
19200
+ };
19201
+ }
19202
+ var isCompatible3 = _makeCompatibilityCheck3(VERSION6);
19203
+ var major3 = VERSION6.split(".")[0];
19204
+ var GLOBAL_OPENTELEMETRY_API_KEY3 = /* @__PURE__ */ Symbol.for(`opentelemetry.js.api.${major3}`);
19205
+ var _global3 = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {};
19206
+ function registerGlobal3(type, instance, diag, allowOverride = false) {
19207
+ var _a223;
19208
+ const api = _global3[GLOBAL_OPENTELEMETRY_API_KEY3] = (_a223 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) !== null && _a223 !== void 0 ? _a223 : {
19209
+ version: VERSION6
19210
+ };
19211
+ if (!allowOverride && api[type]) {
19212
+ const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
19213
+ diag.error(err.stack || err.message);
19214
+ return false;
18670
19215
  }
18671
- return ar;
18672
- };
18673
- var __spreadArray33 = function(to, from, pack) {
18674
- if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
18675
- if (ar || !(i in from)) {
18676
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
18677
- ar[i] = from[i];
18678
- }
19216
+ if (api.version !== VERSION6) {
19217
+ const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION6}`);
19218
+ diag.error(err.stack || err.message);
19219
+ return false;
19220
+ }
19221
+ api[type] = instance;
19222
+ diag.debug(`@opentelemetry/api: Registered a global for ${type} v${VERSION6}.`);
19223
+ return true;
19224
+ }
19225
+ function getGlobal3(type) {
19226
+ var _a223, _b19;
19227
+ const globalVersion = (_a223 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _a223 === void 0 ? void 0 : _a223.version;
19228
+ if (!globalVersion || !isCompatible3(globalVersion)) {
19229
+ return;
19230
+ }
19231
+ return (_b19 = _global3[GLOBAL_OPENTELEMETRY_API_KEY3]) === null || _b19 === void 0 ? void 0 : _b19[type];
19232
+ }
19233
+ function unregisterGlobal3(type, diag) {
19234
+ diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${VERSION6}.`);
19235
+ const api = _global3[GLOBAL_OPENTELEMETRY_API_KEY3];
19236
+ if (api) {
19237
+ delete api[type];
19238
+ }
19239
+ }
19240
+ var DiagComponentLogger3 = class {
19241
+ constructor(props) {
19242
+ this._namespace = props.namespace || "DiagComponentLogger";
19243
+ }
19244
+ debug(...args) {
19245
+ return logProxy3("debug", this._namespace, args);
19246
+ }
19247
+ error(...args) {
19248
+ return logProxy3("error", this._namespace, args);
19249
+ }
19250
+ info(...args) {
19251
+ return logProxy3("info", this._namespace, args);
19252
+ }
19253
+ warn(...args) {
19254
+ return logProxy3("warn", this._namespace, args);
19255
+ }
19256
+ verbose(...args) {
19257
+ return logProxy3("verbose", this._namespace, args);
18679
19258
  }
18680
- return to.concat(ar || Array.prototype.slice.call(from));
18681
19259
  };
18682
- var NoopContextManager3 = (
18683
- /** @class */
18684
- (function() {
18685
- function NoopContextManager22() {
19260
+ function logProxy3(funcName, namespace, args) {
19261
+ const logger = getGlobal3("diag");
19262
+ if (!logger) {
19263
+ return;
19264
+ }
19265
+ return logger[funcName](namespace, ...args);
19266
+ }
19267
+ var DiagLogLevel3;
19268
+ (function(DiagLogLevel22) {
19269
+ DiagLogLevel22[DiagLogLevel22["NONE"] = 0] = "NONE";
19270
+ DiagLogLevel22[DiagLogLevel22["ERROR"] = 30] = "ERROR";
19271
+ DiagLogLevel22[DiagLogLevel22["WARN"] = 50] = "WARN";
19272
+ DiagLogLevel22[DiagLogLevel22["INFO"] = 60] = "INFO";
19273
+ DiagLogLevel22[DiagLogLevel22["DEBUG"] = 70] = "DEBUG";
19274
+ DiagLogLevel22[DiagLogLevel22["VERBOSE"] = 80] = "VERBOSE";
19275
+ DiagLogLevel22[DiagLogLevel22["ALL"] = 9999] = "ALL";
19276
+ })(DiagLogLevel3 || (DiagLogLevel3 = {}));
19277
+ function createLogLevelDiagLogger3(maxLevel, logger) {
19278
+ if (maxLevel < DiagLogLevel3.NONE) {
19279
+ maxLevel = DiagLogLevel3.NONE;
19280
+ } else if (maxLevel > DiagLogLevel3.ALL) {
19281
+ maxLevel = DiagLogLevel3.ALL;
19282
+ }
19283
+ logger = logger || {};
19284
+ function _filterFunc(funcName, theLevel) {
19285
+ const theFunc = logger[funcName];
19286
+ if (typeof theFunc === "function" && maxLevel >= theLevel) {
19287
+ return theFunc.bind(logger);
18686
19288
  }
18687
- NoopContextManager22.prototype.active = function() {
18688
- return ROOT_CONTEXT3;
18689
- };
18690
- NoopContextManager22.prototype.with = function(_context, fn, thisArg) {
18691
- var args = [];
18692
- for (var _i = 3; _i < arguments.length; _i++) {
18693
- args[_i - 3] = arguments[_i];
18694
- }
18695
- return fn.call.apply(fn, __spreadArray33([thisArg], __read33(args), false));
18696
- };
18697
- NoopContextManager22.prototype.bind = function(_context, target) {
18698
- return target;
18699
- };
18700
- NoopContextManager22.prototype.enable = function() {
18701
- return this;
18702
- };
18703
- NoopContextManager22.prototype.disable = function() {
18704
- return this;
19289
+ return function() {
18705
19290
  };
18706
- return NoopContextManager22;
18707
- })()
18708
- );
18709
- var __read43 = function(o, n) {
18710
- var m = typeof Symbol === "function" && o[Symbol.iterator];
18711
- if (!m) return o;
18712
- var i = m.call(o), r, ar = [], e;
18713
- try {
18714
- while (!(r = i.next()).done) ar.push(r.value);
18715
- } catch (error) {
18716
- e = { error };
18717
- } finally {
18718
- try {
18719
- if (r && !r.done && (m = i["return"])) m.call(i);
18720
- } finally {
18721
- if (e) throw e.error;
18722
- }
18723
19291
  }
18724
- return ar;
18725
- };
18726
- var __spreadArray43 = function(to, from, pack) {
18727
- if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
18728
- if (ar || !(i in from)) {
18729
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
18730
- ar[i] = from[i];
19292
+ return {
19293
+ error: _filterFunc("error", DiagLogLevel3.ERROR),
19294
+ warn: _filterFunc("warn", DiagLogLevel3.WARN),
19295
+ info: _filterFunc("info", DiagLogLevel3.INFO),
19296
+ debug: _filterFunc("debug", DiagLogLevel3.DEBUG),
19297
+ verbose: _filterFunc("verbose", DiagLogLevel3.VERBOSE)
19298
+ };
19299
+ }
19300
+ var API_NAME5 = "diag";
19301
+ var DiagAPI3 = class _DiagAPI {
19302
+ /** Get the singleton instance of the DiagAPI API */
19303
+ static instance() {
19304
+ if (!this._instance) {
19305
+ this._instance = new _DiagAPI();
18731
19306
  }
19307
+ return this._instance;
18732
19308
  }
18733
- return to.concat(ar || Array.prototype.slice.call(from));
18734
- };
18735
- var API_NAME23 = "context";
18736
- var NOOP_CONTEXT_MANAGER3 = new NoopContextManager3();
18737
- var ContextAPI3 = (
18738
- /** @class */
18739
- (function() {
18740
- function ContextAPI22() {
19309
+ /**
19310
+ * Private internal constructor
19311
+ * @private
19312
+ */
19313
+ constructor() {
19314
+ function _logProxy(funcName) {
19315
+ return function(...args) {
19316
+ const logger = getGlobal3("diag");
19317
+ if (!logger)
19318
+ return;
19319
+ return logger[funcName](...args);
19320
+ };
18741
19321
  }
18742
- ContextAPI22.getInstance = function() {
18743
- if (!this._instance) {
18744
- this._instance = new ContextAPI22();
19322
+ const self2 = this;
19323
+ const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel3.INFO }) => {
19324
+ var _a223, _b19, _c;
19325
+ if (logger === self2) {
19326
+ const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
19327
+ self2.error((_a223 = err.stack) !== null && _a223 !== void 0 ? _a223 : err.message);
19328
+ return false;
19329
+ }
19330
+ if (typeof optionsOrLogLevel === "number") {
19331
+ optionsOrLogLevel = {
19332
+ logLevel: optionsOrLogLevel
19333
+ };
18745
19334
  }
18746
- return this._instance;
18747
- };
18748
- ContextAPI22.prototype.setGlobalContextManager = function(contextManager) {
18749
- return registerGlobal3(API_NAME23, contextManager, DiagAPI3.instance());
18750
- };
18751
- ContextAPI22.prototype.active = function() {
18752
- return this._getContextManager().active();
18753
- };
18754
- ContextAPI22.prototype.with = function(context2, fn, thisArg) {
18755
- var _a21;
18756
- var args = [];
18757
- for (var _i = 3; _i < arguments.length; _i++) {
18758
- args[_i - 3] = arguments[_i];
19335
+ const oldLogger = getGlobal3("diag");
19336
+ const newLogger = createLogLevelDiagLogger3((_b19 = optionsOrLogLevel.logLevel) !== null && _b19 !== void 0 ? _b19 : DiagLogLevel3.INFO, logger);
19337
+ if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
19338
+ const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
19339
+ oldLogger.warn(`Current logger will be overwritten from ${stack}`);
19340
+ newLogger.warn(`Current logger will overwrite one already registered from ${stack}`);
18759
19341
  }
18760
- return (_a21 = this._getContextManager()).with.apply(_a21, __spreadArray43([context2, fn, thisArg], __read43(args), false));
18761
- };
18762
- ContextAPI22.prototype.bind = function(context2, target) {
18763
- return this._getContextManager().bind(context2, target);
19342
+ return registerGlobal3("diag", newLogger, self2, true);
18764
19343
  };
18765
- ContextAPI22.prototype._getContextManager = function() {
18766
- return getGlobal3(API_NAME23) || NOOP_CONTEXT_MANAGER3;
19344
+ self2.setLogger = setLogger;
19345
+ self2.disable = () => {
19346
+ unregisterGlobal3(API_NAME5, self2);
18767
19347
  };
18768
- ContextAPI22.prototype.disable = function() {
18769
- this._getContextManager().disable();
18770
- unregisterGlobal3(API_NAME23, DiagAPI3.instance());
19348
+ self2.createComponentLogger = (options) => {
19349
+ return new DiagComponentLogger3(options);
18771
19350
  };
18772
- return ContextAPI22;
18773
- })()
18774
- );
18775
- var TraceFlags3;
18776
- (function(TraceFlags22) {
18777
- TraceFlags22[TraceFlags22["NONE"] = 0] = "NONE";
18778
- TraceFlags22[TraceFlags22["SAMPLED"] = 1] = "SAMPLED";
18779
- })(TraceFlags3 || (TraceFlags3 = {}));
18780
- var INVALID_SPANID3 = "0000000000000000";
18781
- var INVALID_TRACEID3 = "00000000000000000000000000000000";
18782
- var INVALID_SPAN_CONTEXT3 = {
18783
- traceId: INVALID_TRACEID3,
18784
- spanId: INVALID_SPANID3,
18785
- traceFlags: TraceFlags3.NONE
19351
+ self2.verbose = _logProxy("verbose");
19352
+ self2.debug = _logProxy("debug");
19353
+ self2.info = _logProxy("info");
19354
+ self2.warn = _logProxy("warn");
19355
+ self2.error = _logProxy("error");
19356
+ }
18786
19357
  };
18787
- var NonRecordingSpan3 = (
18788
- /** @class */
18789
- (function() {
18790
- function NonRecordingSpan22(_spanContext) {
18791
- if (_spanContext === void 0) {
18792
- _spanContext = INVALID_SPAN_CONTEXT3;
18793
- }
18794
- this._spanContext = _spanContext;
18795
- }
18796
- NonRecordingSpan22.prototype.spanContext = function() {
18797
- return this._spanContext;
18798
- };
18799
- NonRecordingSpan22.prototype.setAttribute = function(_key, _value) {
18800
- return this;
18801
- };
18802
- NonRecordingSpan22.prototype.setAttributes = function(_attributes) {
18803
- return this;
18804
- };
18805
- NonRecordingSpan22.prototype.addEvent = function(_name, _attributes) {
18806
- return this;
18807
- };
18808
- NonRecordingSpan22.prototype.addLink = function(_link) {
18809
- return this;
18810
- };
18811
- NonRecordingSpan22.prototype.addLinks = function(_links) {
18812
- return this;
18813
- };
18814
- NonRecordingSpan22.prototype.setStatus = function(_status) {
18815
- return this;
18816
- };
18817
- NonRecordingSpan22.prototype.updateName = function(_name) {
18818
- return this;
18819
- };
18820
- NonRecordingSpan22.prototype.end = function(_endTime) {
18821
- };
18822
- NonRecordingSpan22.prototype.isRecording = function() {
18823
- return false;
19358
+ function createContextKey3(description) {
19359
+ return Symbol.for(description);
19360
+ }
19361
+ var BaseContext3 = class _BaseContext {
19362
+ /**
19363
+ * Construct a new context which inherits values from an optional parent context.
19364
+ *
19365
+ * @param parentContext a context from which to inherit values
19366
+ */
19367
+ constructor(parentContext) {
19368
+ const self2 = this;
19369
+ self2._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
19370
+ self2.getValue = (key) => self2._currentContext.get(key);
19371
+ self2.setValue = (key, value) => {
19372
+ const context2 = new _BaseContext(self2._currentContext);
19373
+ context2._currentContext.set(key, value);
19374
+ return context2;
18824
19375
  };
18825
- NonRecordingSpan22.prototype.recordException = function(_exception, _time) {
19376
+ self2.deleteValue = (key) => {
19377
+ const context2 = new _BaseContext(self2._currentContext);
19378
+ context2._currentContext.delete(key);
19379
+ return context2;
18826
19380
  };
18827
- return NonRecordingSpan22;
18828
- })()
18829
- );
19381
+ }
19382
+ };
19383
+ var ROOT_CONTEXT3 = new BaseContext3();
19384
+ var NoopContextManager3 = class {
19385
+ active() {
19386
+ return ROOT_CONTEXT3;
19387
+ }
19388
+ with(_context, fn, thisArg, ...args) {
19389
+ return fn.call(thisArg, ...args);
19390
+ }
19391
+ bind(_context, target) {
19392
+ return target;
19393
+ }
19394
+ enable() {
19395
+ return this;
19396
+ }
19397
+ disable() {
19398
+ return this;
19399
+ }
19400
+ };
19401
+ var API_NAME23 = "context";
19402
+ var NOOP_CONTEXT_MANAGER3 = new NoopContextManager3();
19403
+ var ContextAPI3 = class _ContextAPI {
19404
+ /** Empty private constructor prevents end users from constructing a new instance of the API */
19405
+ constructor() {
19406
+ }
19407
+ /** Get the singleton instance of the Context API */
19408
+ static getInstance() {
19409
+ if (!this._instance) {
19410
+ this._instance = new _ContextAPI();
19411
+ }
19412
+ return this._instance;
19413
+ }
19414
+ /**
19415
+ * Set the current context manager.
19416
+ *
19417
+ * @returns true if the context manager was successfully registered, else false
19418
+ */
19419
+ setGlobalContextManager(contextManager) {
19420
+ return registerGlobal3(API_NAME23, contextManager, DiagAPI3.instance());
19421
+ }
19422
+ /**
19423
+ * Get the currently active context
19424
+ */
19425
+ active() {
19426
+ return this._getContextManager().active();
19427
+ }
19428
+ /**
19429
+ * Execute a function with an active context
19430
+ *
19431
+ * @param context context to be active during function execution
19432
+ * @param fn function to execute in a context
19433
+ * @param thisArg optional receiver to be used for calling fn
19434
+ * @param args optional arguments forwarded to fn
19435
+ */
19436
+ with(context2, fn, thisArg, ...args) {
19437
+ return this._getContextManager().with(context2, fn, thisArg, ...args);
19438
+ }
19439
+ /**
19440
+ * Bind a context to a target function or event emitter
19441
+ *
19442
+ * @param context context to bind to the event emitter or function. Defaults to the currently active context
19443
+ * @param target function or event emitter to bind
19444
+ */
19445
+ bind(context2, target) {
19446
+ return this._getContextManager().bind(context2, target);
19447
+ }
19448
+ _getContextManager() {
19449
+ return getGlobal3(API_NAME23) || NOOP_CONTEXT_MANAGER3;
19450
+ }
19451
+ /** Disable and remove the global context manager */
19452
+ disable() {
19453
+ this._getContextManager().disable();
19454
+ unregisterGlobal3(API_NAME23, DiagAPI3.instance());
19455
+ }
19456
+ };
19457
+ var TraceFlags3;
19458
+ (function(TraceFlags22) {
19459
+ TraceFlags22[TraceFlags22["NONE"] = 0] = "NONE";
19460
+ TraceFlags22[TraceFlags22["SAMPLED"] = 1] = "SAMPLED";
19461
+ })(TraceFlags3 || (TraceFlags3 = {}));
19462
+ var INVALID_SPANID3 = "0000000000000000";
19463
+ var INVALID_TRACEID3 = "00000000000000000000000000000000";
19464
+ var INVALID_SPAN_CONTEXT3 = {
19465
+ traceId: INVALID_TRACEID3,
19466
+ spanId: INVALID_SPANID3,
19467
+ traceFlags: TraceFlags3.NONE
19468
+ };
19469
+ var NonRecordingSpan3 = class {
19470
+ constructor(spanContext = INVALID_SPAN_CONTEXT3) {
19471
+ this._spanContext = spanContext;
19472
+ }
19473
+ // Returns a SpanContext.
19474
+ spanContext() {
19475
+ return this._spanContext;
19476
+ }
19477
+ // By default does nothing
19478
+ setAttribute(_key, _value) {
19479
+ return this;
19480
+ }
19481
+ // By default does nothing
19482
+ setAttributes(_attributes) {
19483
+ return this;
19484
+ }
19485
+ // By default does nothing
19486
+ addEvent(_name, _attributes) {
19487
+ return this;
19488
+ }
19489
+ addLink(_link) {
19490
+ return this;
19491
+ }
19492
+ addLinks(_links) {
19493
+ return this;
19494
+ }
19495
+ // By default does nothing
19496
+ setStatus(_status) {
19497
+ return this;
19498
+ }
19499
+ // By default does nothing
19500
+ updateName(_name) {
19501
+ return this;
19502
+ }
19503
+ // By default does nothing
19504
+ end(_endTime) {
19505
+ }
19506
+ // isRecording always returns false for NonRecordingSpan.
19507
+ isRecording() {
19508
+ return false;
19509
+ }
19510
+ // By default does nothing
19511
+ recordException(_exception, _time) {
19512
+ }
19513
+ };
18830
19514
  var SPAN_KEY3 = createContextKey3("OpenTelemetry Context Key SPAN");
18831
19515
  function getSpan3(context2) {
18832
19516
  return context2.getValue(SPAN_KEY3) || void 0;
@@ -18844,16 +19528,128 @@ function setSpanContext3(context2, spanContext) {
18844
19528
  return setSpan3(context2, new NonRecordingSpan3(spanContext));
18845
19529
  }
18846
19530
  function getSpanContext3(context2) {
18847
- var _a21;
18848
- return (_a21 = getSpan3(context2)) === null || _a21 === void 0 ? void 0 : _a21.spanContext();
19531
+ var _a223;
19532
+ return (_a223 = getSpan3(context2)) === null || _a223 === void 0 ? void 0 : _a223.spanContext();
19533
+ }
19534
+ var isHex = new Uint8Array([
19535
+ 0,
19536
+ 0,
19537
+ 0,
19538
+ 0,
19539
+ 0,
19540
+ 0,
19541
+ 0,
19542
+ 0,
19543
+ 0,
19544
+ 0,
19545
+ 0,
19546
+ 0,
19547
+ 0,
19548
+ 0,
19549
+ 0,
19550
+ 0,
19551
+ 0,
19552
+ 0,
19553
+ 0,
19554
+ 0,
19555
+ 0,
19556
+ 0,
19557
+ 0,
19558
+ 0,
19559
+ 0,
19560
+ 0,
19561
+ 0,
19562
+ 0,
19563
+ 0,
19564
+ 0,
19565
+ 0,
19566
+ 0,
19567
+ 0,
19568
+ 0,
19569
+ 0,
19570
+ 0,
19571
+ 0,
19572
+ 0,
19573
+ 0,
19574
+ 0,
19575
+ 0,
19576
+ 0,
19577
+ 0,
19578
+ 0,
19579
+ 0,
19580
+ 0,
19581
+ 0,
19582
+ 0,
19583
+ 1,
19584
+ 1,
19585
+ 1,
19586
+ 1,
19587
+ 1,
19588
+ 1,
19589
+ 1,
19590
+ 1,
19591
+ 1,
19592
+ 1,
19593
+ 0,
19594
+ 0,
19595
+ 0,
19596
+ 0,
19597
+ 0,
19598
+ 0,
19599
+ 0,
19600
+ 1,
19601
+ 1,
19602
+ 1,
19603
+ 1,
19604
+ 1,
19605
+ 1,
19606
+ 0,
19607
+ 0,
19608
+ 0,
19609
+ 0,
19610
+ 0,
19611
+ 0,
19612
+ 0,
19613
+ 0,
19614
+ 0,
19615
+ 0,
19616
+ 0,
19617
+ 0,
19618
+ 0,
19619
+ 0,
19620
+ 0,
19621
+ 0,
19622
+ 0,
19623
+ 0,
19624
+ 0,
19625
+ 0,
19626
+ 0,
19627
+ 0,
19628
+ 0,
19629
+ 0,
19630
+ 0,
19631
+ 0,
19632
+ 1,
19633
+ 1,
19634
+ 1,
19635
+ 1,
19636
+ 1,
19637
+ 1
19638
+ ]);
19639
+ function isValidHex(id, length) {
19640
+ if (typeof id !== "string" || id.length !== length)
19641
+ return false;
19642
+ let r = 0;
19643
+ for (let i = 0; i < id.length; i += 4) {
19644
+ r += (isHex[id.charCodeAt(i)] | 0) + (isHex[id.charCodeAt(i + 1)] | 0) + (isHex[id.charCodeAt(i + 2)] | 0) + (isHex[id.charCodeAt(i + 3)] | 0);
19645
+ }
19646
+ return r === length;
18849
19647
  }
18850
- var VALID_TRACEID_REGEX3 = /^([0-9a-f]{32})$/i;
18851
- var VALID_SPANID_REGEX3 = /^[0-9a-f]{16}$/i;
18852
19648
  function isValidTraceId3(traceId) {
18853
- return VALID_TRACEID_REGEX3.test(traceId) && traceId !== INVALID_TRACEID3;
19649
+ return isValidHex(traceId, 32) && traceId !== INVALID_TRACEID3;
18854
19650
  }
18855
19651
  function isValidSpanId3(spanId) {
18856
- return VALID_SPANID_REGEX3.test(spanId) && spanId !== INVALID_SPANID3;
19652
+ return isValidHex(spanId, 16) && spanId !== INVALID_SPANID3;
18857
19653
  }
18858
19654
  function isSpanContextValid3(spanContext) {
18859
19655
  return isValidTraceId3(spanContext.traceId) && isValidSpanId3(spanContext.spanId);
@@ -18862,119 +19658,105 @@ function wrapSpanContext3(spanContext) {
18862
19658
  return new NonRecordingSpan3(spanContext);
18863
19659
  }
18864
19660
  var contextApi3 = ContextAPI3.getInstance();
18865
- var NoopTracer3 = (
18866
- /** @class */
18867
- (function() {
18868
- function NoopTracer22() {
19661
+ var NoopTracer3 = class {
19662
+ // startSpan starts a noop span.
19663
+ startSpan(name223, options, context2 = contextApi3.active()) {
19664
+ const root = Boolean(options === null || options === void 0 ? void 0 : options.root);
19665
+ if (root) {
19666
+ return new NonRecordingSpan3();
19667
+ }
19668
+ const parentFromContext = context2 && getSpanContext3(context2);
19669
+ if (isSpanContext3(parentFromContext) && isSpanContextValid3(parentFromContext)) {
19670
+ return new NonRecordingSpan3(parentFromContext);
19671
+ } else {
19672
+ return new NonRecordingSpan3();
18869
19673
  }
18870
- NoopTracer22.prototype.startSpan = function(name21, options, context2) {
18871
- if (context2 === void 0) {
18872
- context2 = contextApi3.active();
18873
- }
18874
- var root = Boolean(options === null || options === void 0 ? void 0 : options.root);
18875
- if (root) {
18876
- return new NonRecordingSpan3();
18877
- }
18878
- var parentFromContext = context2 && getSpanContext3(context2);
18879
- if (isSpanContext3(parentFromContext) && isSpanContextValid3(parentFromContext)) {
18880
- return new NonRecordingSpan3(parentFromContext);
18881
- } else {
18882
- return new NonRecordingSpan3();
18883
- }
18884
- };
18885
- NoopTracer22.prototype.startActiveSpan = function(name21, arg2, arg3, arg4) {
18886
- var opts;
18887
- var ctx;
18888
- var fn;
18889
- if (arguments.length < 2) {
18890
- return;
18891
- } else if (arguments.length === 2) {
18892
- fn = arg2;
18893
- } else if (arguments.length === 3) {
18894
- opts = arg2;
18895
- fn = arg3;
18896
- } else {
18897
- opts = arg2;
18898
- ctx = arg3;
18899
- fn = arg4;
18900
- }
18901
- var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi3.active();
18902
- var span = this.startSpan(name21, opts, parentContext);
18903
- var contextWithSpanSet = setSpan3(parentContext, span);
18904
- return contextApi3.with(contextWithSpanSet, fn, void 0, span);
18905
- };
18906
- return NoopTracer22;
18907
- })()
18908
- );
19674
+ }
19675
+ startActiveSpan(name223, arg2, arg3, arg4) {
19676
+ let opts;
19677
+ let ctx;
19678
+ let fn;
19679
+ if (arguments.length < 2) {
19680
+ return;
19681
+ } else if (arguments.length === 2) {
19682
+ fn = arg2;
19683
+ } else if (arguments.length === 3) {
19684
+ opts = arg2;
19685
+ fn = arg3;
19686
+ } else {
19687
+ opts = arg2;
19688
+ ctx = arg3;
19689
+ fn = arg4;
19690
+ }
19691
+ const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi3.active();
19692
+ const span = this.startSpan(name223, opts, parentContext);
19693
+ const contextWithSpanSet = setSpan3(parentContext, span);
19694
+ return contextApi3.with(contextWithSpanSet, fn, void 0, span);
19695
+ }
19696
+ };
18909
19697
  function isSpanContext3(spanContext) {
18910
- return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
19698
+ return spanContext !== null && typeof spanContext === "object" && "spanId" in spanContext && typeof spanContext["spanId"] === "string" && "traceId" in spanContext && typeof spanContext["traceId"] === "string" && "traceFlags" in spanContext && typeof spanContext["traceFlags"] === "number";
18911
19699
  }
18912
19700
  var NOOP_TRACER3 = new NoopTracer3();
18913
- var ProxyTracer3 = (
18914
- /** @class */
18915
- (function() {
18916
- function ProxyTracer22(_provider, name21, version, options) {
18917
- this._provider = _provider;
18918
- this.name = name21;
18919
- this.version = version;
18920
- this.options = options;
18921
- }
18922
- ProxyTracer22.prototype.startSpan = function(name21, options, context2) {
18923
- return this._getTracer().startSpan(name21, options, context2);
18924
- };
18925
- ProxyTracer22.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
18926
- var tracer = this._getTracer();
18927
- return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
18928
- };
18929
- ProxyTracer22.prototype._getTracer = function() {
18930
- if (this._delegate) {
18931
- return this._delegate;
18932
- }
18933
- var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
18934
- if (!tracer) {
18935
- return NOOP_TRACER3;
18936
- }
18937
- this._delegate = tracer;
19701
+ var ProxyTracer3 = class {
19702
+ constructor(provider, name223, version, options) {
19703
+ this._provider = provider;
19704
+ this.name = name223;
19705
+ this.version = version;
19706
+ this.options = options;
19707
+ }
19708
+ startSpan(name223, options, context2) {
19709
+ return this._getTracer().startSpan(name223, options, context2);
19710
+ }
19711
+ startActiveSpan(_name, _options, _context, _fn) {
19712
+ const tracer = this._getTracer();
19713
+ return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
19714
+ }
19715
+ /**
19716
+ * Try to get a tracer from the proxy tracer provider.
19717
+ * If the proxy tracer provider has no delegate, return a noop tracer.
19718
+ */
19719
+ _getTracer() {
19720
+ if (this._delegate) {
18938
19721
  return this._delegate;
18939
- };
18940
- return ProxyTracer22;
18941
- })()
18942
- );
18943
- var NoopTracerProvider3 = (
18944
- /** @class */
18945
- (function() {
18946
- function NoopTracerProvider22() {
18947
19722
  }
18948
- NoopTracerProvider22.prototype.getTracer = function(_name, _version, _options) {
18949
- return new NoopTracer3();
18950
- };
18951
- return NoopTracerProvider22;
18952
- })()
18953
- );
18954
- var NOOP_TRACER_PROVIDER3 = new NoopTracerProvider3();
18955
- var ProxyTracerProvider3 = (
18956
- /** @class */
18957
- (function() {
18958
- function ProxyTracerProvider22() {
19723
+ const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
19724
+ if (!tracer) {
19725
+ return NOOP_TRACER3;
18959
19726
  }
18960
- ProxyTracerProvider22.prototype.getTracer = function(name21, version, options) {
18961
- var _a21;
18962
- return (_a21 = this.getDelegateTracer(name21, version, options)) !== null && _a21 !== void 0 ? _a21 : new ProxyTracer3(this, name21, version, options);
18963
- };
18964
- ProxyTracerProvider22.prototype.getDelegate = function() {
18965
- var _a21;
18966
- return (_a21 = this._delegate) !== null && _a21 !== void 0 ? _a21 : NOOP_TRACER_PROVIDER3;
18967
- };
18968
- ProxyTracerProvider22.prototype.setDelegate = function(delegate) {
18969
- this._delegate = delegate;
18970
- };
18971
- ProxyTracerProvider22.prototype.getDelegateTracer = function(name21, version, options) {
18972
- var _a21;
18973
- return (_a21 = this._delegate) === null || _a21 === void 0 ? void 0 : _a21.getTracer(name21, version, options);
18974
- };
18975
- return ProxyTracerProvider22;
18976
- })()
18977
- );
19727
+ this._delegate = tracer;
19728
+ return this._delegate;
19729
+ }
19730
+ };
19731
+ var NoopTracerProvider3 = class {
19732
+ getTracer(_name, _version, _options) {
19733
+ return new NoopTracer3();
19734
+ }
19735
+ };
19736
+ var NOOP_TRACER_PROVIDER3 = new NoopTracerProvider3();
19737
+ var ProxyTracerProvider3 = class {
19738
+ /**
19739
+ * Get a {@link ProxyTracer}
19740
+ */
19741
+ getTracer(name223, version, options) {
19742
+ var _a223;
19743
+ return (_a223 = this.getDelegateTracer(name223, version, options)) !== null && _a223 !== void 0 ? _a223 : new ProxyTracer3(this, name223, version, options);
19744
+ }
19745
+ getDelegate() {
19746
+ var _a223;
19747
+ return (_a223 = this._delegate) !== null && _a223 !== void 0 ? _a223 : NOOP_TRACER_PROVIDER3;
19748
+ }
19749
+ /**
19750
+ * Set the delegate tracer provider
19751
+ */
19752
+ setDelegate(delegate) {
19753
+ this._delegate = delegate;
19754
+ }
19755
+ getDelegateTracer(name223, version, options) {
19756
+ var _a223;
19757
+ return (_a223 = this._delegate) === null || _a223 === void 0 ? void 0 : _a223.getTracer(name223, version, options);
19758
+ }
19759
+ };
18978
19760
  var SpanStatusCode3;
18979
19761
  (function(SpanStatusCode22) {
18980
19762
  SpanStatusCode22[SpanStatusCode22["UNSET"] = 0] = "UNSET";
@@ -18983,56 +19765,66 @@ var SpanStatusCode3;
18983
19765
  })(SpanStatusCode3 || (SpanStatusCode3 = {}));
18984
19766
  var context = ContextAPI3.getInstance();
18985
19767
  var API_NAME33 = "trace";
18986
- var TraceAPI3 = (
18987
- /** @class */
18988
- (function() {
18989
- function TraceAPI22() {
18990
- this._proxyTracerProvider = new ProxyTracerProvider3();
18991
- this.wrapSpanContext = wrapSpanContext3;
18992
- this.isSpanContextValid = isSpanContextValid3;
18993
- this.deleteSpan = deleteSpan3;
18994
- this.getSpan = getSpan3;
18995
- this.getActiveSpan = getActiveSpan3;
18996
- this.getSpanContext = getSpanContext3;
18997
- this.setSpan = setSpan3;
18998
- this.setSpanContext = setSpanContext3;
19768
+ var TraceAPI3 = class _TraceAPI {
19769
+ /** Empty private constructor prevents end users from constructing a new instance of the API */
19770
+ constructor() {
19771
+ this._proxyTracerProvider = new ProxyTracerProvider3();
19772
+ this.wrapSpanContext = wrapSpanContext3;
19773
+ this.isSpanContextValid = isSpanContextValid3;
19774
+ this.deleteSpan = deleteSpan3;
19775
+ this.getSpan = getSpan3;
19776
+ this.getActiveSpan = getActiveSpan3;
19777
+ this.getSpanContext = getSpanContext3;
19778
+ this.setSpan = setSpan3;
19779
+ this.setSpanContext = setSpanContext3;
19780
+ }
19781
+ /** Get the singleton instance of the Trace API */
19782
+ static getInstance() {
19783
+ if (!this._instance) {
19784
+ this._instance = new _TraceAPI();
19785
+ }
19786
+ return this._instance;
19787
+ }
19788
+ /**
19789
+ * Set the current global tracer.
19790
+ *
19791
+ * @returns true if the tracer provider was successfully registered, else false
19792
+ */
19793
+ setGlobalTracerProvider(provider) {
19794
+ const success = registerGlobal3(API_NAME33, this._proxyTracerProvider, DiagAPI3.instance());
19795
+ if (success) {
19796
+ this._proxyTracerProvider.setDelegate(provider);
18999
19797
  }
19000
- TraceAPI22.getInstance = function() {
19001
- if (!this._instance) {
19002
- this._instance = new TraceAPI22();
19003
- }
19004
- return this._instance;
19005
- };
19006
- TraceAPI22.prototype.setGlobalTracerProvider = function(provider) {
19007
- var success = registerGlobal3(API_NAME33, this._proxyTracerProvider, DiagAPI3.instance());
19008
- if (success) {
19009
- this._proxyTracerProvider.setDelegate(provider);
19010
- }
19011
- return success;
19012
- };
19013
- TraceAPI22.prototype.getTracerProvider = function() {
19014
- return getGlobal3(API_NAME33) || this._proxyTracerProvider;
19015
- };
19016
- TraceAPI22.prototype.getTracer = function(name21, version) {
19017
- return this.getTracerProvider().getTracer(name21, version);
19018
- };
19019
- TraceAPI22.prototype.disable = function() {
19020
- unregisterGlobal3(API_NAME33, DiagAPI3.instance());
19021
- this._proxyTracerProvider = new ProxyTracerProvider3();
19022
- };
19023
- return TraceAPI22;
19024
- })()
19025
- );
19798
+ return success;
19799
+ }
19800
+ /**
19801
+ * Returns the global tracer provider.
19802
+ */
19803
+ getTracerProvider() {
19804
+ return getGlobal3(API_NAME33) || this._proxyTracerProvider;
19805
+ }
19806
+ /**
19807
+ * Returns a tracer from the global tracer provider.
19808
+ */
19809
+ getTracer(name223, version) {
19810
+ return this.getTracerProvider().getTracer(name223, version);
19811
+ }
19812
+ /** Remove the global tracer provider */
19813
+ disable() {
19814
+ unregisterGlobal3(API_NAME33, DiagAPI3.instance());
19815
+ this._proxyTracerProvider = new ProxyTracerProvider3();
19816
+ }
19817
+ };
19026
19818
  var trace3 = TraceAPI3.getInstance();
19027
19819
  var __defProp4 = Object.defineProperty;
19028
19820
  var __export3 = (target, all) => {
19029
- for (var name21 in all)
19030
- __defProp4(target, name21, { get: all[name21], enumerable: true });
19821
+ for (var name223 in all)
19822
+ __defProp4(target, name223, { get: all[name223], enumerable: true });
19031
19823
  };
19032
- var name86 = "AI_InvalidArgumentError";
19033
- var marker96 = `vercel.ai.error.${name86}`;
19034
- var symbol96 = Symbol.for(marker96);
19035
- var _a96;
19824
+ var name21 = "AI_InvalidArgumentError";
19825
+ var marker21 = `vercel.ai.error.${name21}`;
19826
+ var symbol21 = Symbol.for(marker21);
19827
+ var _a21;
19036
19828
  var InvalidArgumentError23 = class extends AISDKError3 {
19037
19829
  constructor({
19038
19830
  parameter,
@@ -19040,22 +19832,22 @@ var InvalidArgumentError23 = class extends AISDKError3 {
19040
19832
  message
19041
19833
  }) {
19042
19834
  super({
19043
- name: name86,
19835
+ name: name21,
19044
19836
  message: `Invalid argument for parameter ${parameter}: ${message}`
19045
19837
  });
19046
- this[_a96] = true;
19838
+ this[_a21] = true;
19047
19839
  this.parameter = parameter;
19048
19840
  this.value = value;
19049
19841
  }
19050
19842
  static isInstance(error) {
19051
- return AISDKError3.hasMarker(error, marker96);
19843
+ return AISDKError3.hasMarker(error, marker21);
19052
19844
  }
19053
19845
  };
19054
- _a96 = symbol96;
19055
- var name823 = "AI_NoObjectGeneratedError";
19056
- var marker823 = `vercel.ai.error.${name823}`;
19057
- var symbol823 = Symbol.for(marker823);
19058
- var _a823;
19846
+ _a21 = symbol21;
19847
+ var name97 = "AI_NoObjectGeneratedError";
19848
+ var marker97 = `vercel.ai.error.${name97}`;
19849
+ var symbol97 = Symbol.for(marker97);
19850
+ var _a97;
19059
19851
  var NoObjectGeneratedError3 = class extends AISDKError3 {
19060
19852
  constructor({
19061
19853
  message = "No object generated.",
@@ -19065,18 +19857,18 @@ var NoObjectGeneratedError3 = class extends AISDKError3 {
19065
19857
  usage,
19066
19858
  finishReason
19067
19859
  }) {
19068
- super({ name: name823, message, cause });
19069
- this[_a823] = true;
19860
+ super({ name: name97, message, cause });
19861
+ this[_a97] = true;
19070
19862
  this.text = text22;
19071
19863
  this.response = response;
19072
19864
  this.usage = usage;
19073
19865
  this.finishReason = finishReason;
19074
19866
  }
19075
19867
  static isInstance(error) {
19076
- return AISDKError3.hasMarker(error, marker823);
19868
+ return AISDKError3.hasMarker(error, marker97);
19077
19869
  }
19078
19870
  };
19079
- _a823 = symbol823;
19871
+ _a97 = symbol97;
19080
19872
  var UnsupportedModelVersionError3 = class extends AISDKError3 {
19081
19873
  constructor(options) {
19082
19874
  super({
@@ -19088,27 +19880,27 @@ var UnsupportedModelVersionError3 = class extends AISDKError3 {
19088
19880
  this.modelId = options.modelId;
19089
19881
  }
19090
19882
  };
19091
- var name192 = "AI_RetryError";
19092
- var marker192 = `vercel.ai.error.${name192}`;
19093
- var symbol192 = Symbol.for(marker192);
19094
- var _a192;
19883
+ var name202 = "AI_RetryError";
19884
+ var marker202 = `vercel.ai.error.${name202}`;
19885
+ var symbol202 = Symbol.for(marker202);
19886
+ var _a202;
19095
19887
  var RetryError3 = class extends AISDKError3 {
19096
19888
  constructor({
19097
19889
  message,
19098
19890
  reason,
19099
19891
  errors
19100
19892
  }) {
19101
- super({ name: name192, message });
19102
- this[_a192] = true;
19893
+ super({ name: name202, message });
19894
+ this[_a202] = true;
19103
19895
  this.reason = reason;
19104
19896
  this.errors = errors;
19105
19897
  this.lastError = errors[errors.length - 1];
19106
19898
  }
19107
19899
  static isInstance(error) {
19108
- return AISDKError3.hasMarker(error, marker192);
19900
+ return AISDKError3.hasMarker(error, marker202);
19109
19901
  }
19110
19902
  };
19111
- _a192 = symbol192;
19903
+ _a202 = symbol202;
19112
19904
  function formatWarning({
19113
19905
  warning,
19114
19906
  provider,
@@ -19213,8 +20005,8 @@ function resolveEmbeddingModel2(model) {
19213
20005
  return getGlobalProvider2().embeddingModel(model);
19214
20006
  }
19215
20007
  function getGlobalProvider2() {
19216
- var _a21;
19217
- return (_a21 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a21 : gateway2;
20008
+ var _a223;
20009
+ return (_a223 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a223 : gateway2;
19218
20010
  }
19219
20011
  function getTotalTimeoutMs(timeout) {
19220
20012
  if (timeout == null) {
@@ -19225,7 +20017,7 @@ function getTotalTimeoutMs(timeout) {
19225
20017
  }
19226
20018
  return timeout.totalMs;
19227
20019
  }
19228
- var VERSION33 = "6.0.177";
20020
+ var VERSION23 = "6.0.224";
19229
20021
  var dataContentSchema3 = z$1.union([
19230
20022
  z$1.string(),
19231
20023
  z$1.instanceof(Uint8Array),
@@ -19233,8 +20025,8 @@ var dataContentSchema3 = z$1.union([
19233
20025
  z$1.custom(
19234
20026
  // Buffer might not be available in some environments such as CloudFlare:
19235
20027
  (value) => {
19236
- var _a21, _b93;
19237
- return (_b93 = (_a21 = globalThis.Buffer) == null ? void 0 : _a21.isBuffer(value)) != null ? _b93 : false;
20028
+ var _a223, _b19;
20029
+ return (_b19 = (_a223 = globalThis.Buffer) == null ? void 0 : _a223.isBuffer(value)) != null ? _b19 : false;
19238
20030
  },
19239
20031
  { message: "Must be a Buffer" }
19240
20032
  )
@@ -19448,7 +20240,7 @@ function getBaseTelemetryAttributes3({
19448
20240
  telemetry,
19449
20241
  headers
19450
20242
  }) {
19451
- var _a21;
20243
+ var _a223;
19452
20244
  return {
19453
20245
  "ai.model.provider": model.provider,
19454
20246
  "ai.model.id": model.modelId,
@@ -19467,7 +20259,7 @@ function getBaseTelemetryAttributes3({
19467
20259
  return attributes;
19468
20260
  }, {}),
19469
20261
  // add metadata as attributes:
19470
- ...Object.entries((_a21 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a21 : {}).reduce(
20262
+ ...Object.entries((_a223 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a223 : {}).reduce(
19471
20263
  (attributes, [key, value]) => {
19472
20264
  attributes[`ai.telemetry.metadata.${key}`] = value;
19473
20265
  return attributes;
@@ -19487,7 +20279,7 @@ var noopTracer3 = {
19487
20279
  startSpan() {
19488
20280
  return noopSpan3;
19489
20281
  },
19490
- startActiveSpan(name21, arg1, arg2, arg3) {
20282
+ startActiveSpan(name223, arg1, arg2, arg3) {
19491
20283
  if (typeof arg1 === "function") {
19492
20284
  return arg1(noopSpan3);
19493
20285
  }
@@ -19552,14 +20344,14 @@ function getTracer3({
19552
20344
  return trace3.getTracer("ai");
19553
20345
  }
19554
20346
  async function recordSpan3({
19555
- name: name21,
20347
+ name: name223,
19556
20348
  tracer,
19557
20349
  attributes,
19558
20350
  fn,
19559
20351
  endWhenDone = true
19560
20352
  }) {
19561
20353
  return tracer.startActiveSpan(
19562
- name21,
20354
+ name223,
19563
20355
  { attributes: await attributes },
19564
20356
  async (span) => {
19565
20357
  const ctx = context.active();
@@ -19595,6 +20387,28 @@ function recordErrorOnSpan3(span, error) {
19595
20387
  span.setStatus({ code: SpanStatusCode3.ERROR });
19596
20388
  }
19597
20389
  }
20390
+ function isPrimitiveAttributeValue(value) {
20391
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
20392
+ }
20393
+ function sanitizeAttributeValue(value) {
20394
+ if (!Array.isArray(value)) {
20395
+ return value;
20396
+ }
20397
+ const primitiveTypes = new Set(
20398
+ value.filter(isPrimitiveAttributeValue).map((item) => typeof item)
20399
+ );
20400
+ if (primitiveTypes.size !== 1) {
20401
+ return void 0;
20402
+ }
20403
+ const [primitiveType] = primitiveTypes;
20404
+ if (primitiveType === "string") {
20405
+ return value.filter((item) => typeof item === "string");
20406
+ }
20407
+ if (primitiveType === "number") {
20408
+ return value.filter((item) => typeof item === "number");
20409
+ }
20410
+ return value.filter((item) => typeof item === "boolean");
20411
+ }
19598
20412
  async function selectTelemetryAttributes3({
19599
20413
  telemetry,
19600
20414
  attributes
@@ -19613,7 +20427,9 @@ async function selectTelemetryAttributes3({
19613
20427
  }
19614
20428
  const result = await value.input();
19615
20429
  if (result != null) {
19616
- resultAttributes[key] = result;
20430
+ const sanitized2 = sanitizeAttributeValue(result);
20431
+ if (sanitized2 != null)
20432
+ resultAttributes[key] = sanitized2;
19617
20433
  }
19618
20434
  continue;
19619
20435
  }
@@ -19623,11 +20439,15 @@ async function selectTelemetryAttributes3({
19623
20439
  }
19624
20440
  const result = await value.output();
19625
20441
  if (result != null) {
19626
- resultAttributes[key] = result;
20442
+ const sanitized2 = sanitizeAttributeValue(result);
20443
+ if (sanitized2 != null)
20444
+ resultAttributes[key] = sanitized2;
19627
20445
  }
19628
20446
  continue;
19629
20447
  }
19630
- resultAttributes[key] = value;
20448
+ const sanitized = sanitizeAttributeValue(value);
20449
+ if (sanitized != null)
20450
+ resultAttributes[key] = sanitized;
19631
20451
  }
19632
20452
  return resultAttributes;
19633
20453
  }
@@ -19635,7 +20455,7 @@ function getRetryDelayInMs2({
19635
20455
  error,
19636
20456
  exponentialBackoffDelay
19637
20457
  }) {
19638
- const headers = error.responseHeaders;
20458
+ const headers = APICallError3.isInstance(error) ? error.responseHeaders : APICallError3.isInstance(error.cause) ? error.cause.responseHeaders : void 0;
19639
20459
  if (!headers)
19640
20460
  return exponentialBackoffDelay;
19641
20461
  let ms;
@@ -19665,66 +20485,18 @@ var retryWithExponentialBackoffRespectingRetryHeaders2 = ({
19665
20485
  initialDelayInMs = 2e3,
19666
20486
  backoffFactor = 2,
19667
20487
  abortSignal
19668
- } = {}) => async (f) => _retryWithExponentialBackoff3(f, {
20488
+ } = {}) => retryWithExponentialBackoff2({
19669
20489
  maxRetries,
19670
- delayInMs: initialDelayInMs,
20490
+ initialDelayInMs,
19671
20491
  backoffFactor,
19672
- abortSignal
20492
+ abortSignal,
20493
+ shouldRetry: (error) => error instanceof Error && (APICallError3.isInstance(error) && error.isRetryable === true || GatewayError2.isInstance(error) && error.isRetryable === true),
20494
+ getDelayInMs: ({ error, exponentialBackoffDelay }) => getRetryDelayInMs2({
20495
+ error,
20496
+ exponentialBackoffDelay
20497
+ }),
20498
+ createRetryError: ({ message, reason, errors }) => new RetryError3({ message, reason, errors })
19673
20499
  });
19674
- async function _retryWithExponentialBackoff3(f, {
19675
- maxRetries,
19676
- delayInMs,
19677
- backoffFactor,
19678
- abortSignal
19679
- }, errors = []) {
19680
- try {
19681
- return await f();
19682
- } catch (error) {
19683
- if (isAbortError5(error)) {
19684
- throw error;
19685
- }
19686
- if (maxRetries === 0) {
19687
- throw error;
19688
- }
19689
- const errorMessage = getErrorMessage23(error);
19690
- const newErrors = [...errors, error];
19691
- const tryNumber = newErrors.length;
19692
- if (tryNumber > maxRetries) {
19693
- throw new RetryError3({
19694
- message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
19695
- reason: "maxRetriesExceeded",
19696
- errors: newErrors
19697
- });
19698
- }
19699
- if (error instanceof Error && APICallError3.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
19700
- await delay3(
19701
- getRetryDelayInMs2({
19702
- error,
19703
- exponentialBackoffDelay: delayInMs
19704
- }),
19705
- { abortSignal }
19706
- );
19707
- return _retryWithExponentialBackoff3(
19708
- f,
19709
- {
19710
- maxRetries,
19711
- delayInMs: backoffFactor * delayInMs,
19712
- backoffFactor,
19713
- abortSignal
19714
- },
19715
- newErrors
19716
- );
19717
- }
19718
- if (tryNumber === 1) {
19719
- throw error;
19720
- }
19721
- throw new RetryError3({
19722
- message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
19723
- reason: "errorNotRetryable",
19724
- errors: newErrors
19725
- });
19726
- }
19727
- }
19728
20500
  function prepareRetries3({
19729
20501
  maxRetries,
19730
20502
  abortSignal
@@ -19754,6 +20526,7 @@ function prepareRetries3({
19754
20526
  })
19755
20527
  };
19756
20528
  }
20529
+ new TextEncoder();
19757
20530
  var output_exports3 = {};
19758
20531
  __export3(output_exports3, {
19759
20532
  array: () => array,
@@ -19766,6 +20539,10 @@ function fixJson3(input) {
19766
20539
  const stack = ["ROOT"];
19767
20540
  let lastValidIndex = -1;
19768
20541
  let literalStart = null;
20542
+ let unicodeEscapeDigits = 0;
20543
+ function isHexDigit(char) {
20544
+ return char >= "0" && char <= "9" || char >= "A" && char <= "F" || char >= "a" && char <= "f";
20545
+ }
19769
20546
  function processValueStart(char, i, swapState) {
19770
20547
  {
19771
20548
  switch (char) {
@@ -19970,7 +20747,22 @@ function fixJson3(input) {
19970
20747
  }
19971
20748
  case "INSIDE_STRING_ESCAPE": {
19972
20749
  stack.pop();
19973
- lastValidIndex = i;
20750
+ if (char === "u") {
20751
+ unicodeEscapeDigits = 0;
20752
+ stack.push("INSIDE_STRING_UNICODE_ESCAPE");
20753
+ } else {
20754
+ lastValidIndex = i;
20755
+ }
20756
+ break;
20757
+ }
20758
+ case "INSIDE_STRING_UNICODE_ESCAPE": {
20759
+ if (isHexDigit(char)) {
20760
+ unicodeEscapeDigits++;
20761
+ if (unicodeEscapeDigits === 4) {
20762
+ stack.pop();
20763
+ lastValidIndex = i;
20764
+ }
20765
+ }
19974
20766
  break;
19975
20767
  }
19976
20768
  case "INSIDE_NUMBER": {
@@ -20107,7 +20899,7 @@ var text3 = () => ({
20107
20899
  });
20108
20900
  var object3 = ({
20109
20901
  schema: inputSchema,
20110
- name: name21,
20902
+ name: name223,
20111
20903
  description
20112
20904
  }) => {
20113
20905
  const schema = asSchema3(inputSchema);
@@ -20116,7 +20908,7 @@ var object3 = ({
20116
20908
  responseFormat: resolve2(schema.jsonSchema).then((jsonSchema22) => ({
20117
20909
  type: "json",
20118
20910
  schema: jsonSchema22,
20119
- ...name21 != null && { name: name21 },
20911
+ ...name223 != null && { name: name223 },
20120
20912
  ...description != null && { description }
20121
20913
  })),
20122
20914
  async parseCompleteOutput({ text: text22 }, context2) {
@@ -20170,7 +20962,7 @@ var object3 = ({
20170
20962
  };
20171
20963
  var array = ({
20172
20964
  element: inputElementSchema,
20173
- name: name21,
20965
+ name: name223,
20174
20966
  description
20175
20967
  }) => {
20176
20968
  const elementSchema = asSchema3(inputElementSchema);
@@ -20190,7 +20982,7 @@ var array = ({
20190
20982
  required: ["elements"],
20191
20983
  additionalProperties: false
20192
20984
  },
20193
- ...name21 != null && { name: name21 },
20985
+ ...name223 != null && { name: name223 },
20194
20986
  ...description != null && { description }
20195
20987
  };
20196
20988
  }),
@@ -20220,6 +21012,7 @@ var array = ({
20220
21012
  finishReason: context2.finishReason
20221
21013
  });
20222
21014
  }
21015
+ const validatedElements = [];
20223
21016
  for (const element of outerValue.elements) {
20224
21017
  const validationResult = await safeValidateTypes3({
20225
21018
  value: element,
@@ -20235,8 +21028,9 @@ var array = ({
20235
21028
  finishReason: context2.finishReason
20236
21029
  });
20237
21030
  }
21031
+ validatedElements.push(validationResult.value);
20238
21032
  }
20239
- return outerValue.elements;
21033
+ return validatedElements;
20240
21034
  },
20241
21035
  async parsePartialOutput({ text: text22 }) {
20242
21036
  const result = await parsePartialJson3(text22);
@@ -20282,7 +21076,7 @@ var array = ({
20282
21076
  };
20283
21077
  var choice = ({
20284
21078
  options: choiceOptions,
20285
- name: name21,
21079
+ name: name223,
20286
21080
  description
20287
21081
  }) => {
20288
21082
  return {
@@ -20299,7 +21093,7 @@ var choice = ({
20299
21093
  required: ["result"],
20300
21094
  additionalProperties: false
20301
21095
  },
20302
- ...name21 != null && { name: name21 },
21096
+ ...name223 != null && { name: name223 },
20303
21097
  ...description != null && { description }
20304
21098
  }),
20305
21099
  async parseCompleteOutput({ text: text22 }, context2) {
@@ -20360,14 +21154,14 @@ var choice = ({
20360
21154
  };
20361
21155
  };
20362
21156
  var json = ({
20363
- name: name21,
21157
+ name: name223,
20364
21158
  description
20365
21159
  } = {}) => {
20366
21160
  return {
20367
21161
  name: "json",
20368
21162
  responseFormat: Promise.resolve({
20369
21163
  type: "json",
20370
- ...name21 != null && { name: name21 },
21164
+ ...name223 != null && { name: name223 },
20371
21165
  ...description != null && { description }
20372
21166
  }),
20373
21167
  async parseCompleteOutput({ text: text22 }, context2) {
@@ -20445,7 +21239,7 @@ async function embedMany3({
20445
21239
  });
20446
21240
  const headersWithUserAgent = withUserAgentSuffix2(
20447
21241
  headers != null ? headers : {},
20448
- `ai/${VERSION33}`
21242
+ `ai/${VERSION23}`
20449
21243
  );
20450
21244
  const baseTelemetryAttributes = getBaseTelemetryAttributes3({
20451
21245
  model,
@@ -20469,7 +21263,7 @@ async function embedMany3({
20469
21263
  }),
20470
21264
  tracer,
20471
21265
  fn: async (span) => {
20472
- var _a21;
21266
+ var _a223;
20473
21267
  const [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all([
20474
21268
  model.maxEmbeddingsPerCall,
20475
21269
  model.supportsParallelCalls
@@ -20494,7 +21288,7 @@ async function embedMany3({
20494
21288
  }),
20495
21289
  tracer,
20496
21290
  fn: async (doEmbedSpan) => {
20497
- var _a2222;
21291
+ var _a232, _b19;
20498
21292
  const modelResponse = await model.doEmbed({
20499
21293
  values,
20500
21294
  abortSignal,
@@ -20502,7 +21296,7 @@ async function embedMany3({
20502
21296
  providerOptions
20503
21297
  });
20504
21298
  const embeddings3 = modelResponse.embeddings;
20505
- const usage2 = (_a2222 = modelResponse.usage) != null ? _a2222 : { tokens: NaN };
21299
+ const usage2 = (_a232 = modelResponse.usage) != null ? _a232 : { tokens: NaN };
20506
21300
  doEmbedSpan.setAttributes(
20507
21301
  await selectTelemetryAttributes3({
20508
21302
  telemetry,
@@ -20519,7 +21313,7 @@ async function embedMany3({
20519
21313
  return {
20520
21314
  embeddings: embeddings3,
20521
21315
  usage: usage2,
20522
- warnings: modelResponse.warnings,
21316
+ warnings: (_b19 = modelResponse.warnings) != null ? _b19 : [],
20523
21317
  providerMetadata: modelResponse.providerMetadata,
20524
21318
  response: modelResponse.response
20525
21319
  };
@@ -20583,7 +21377,7 @@ async function embedMany3({
20583
21377
  }),
20584
21378
  tracer,
20585
21379
  fn: async (doEmbedSpan) => {
20586
- var _a2222;
21380
+ var _a232, _b19;
20587
21381
  const modelResponse = await model.doEmbed({
20588
21382
  values: chunk,
20589
21383
  abortSignal,
@@ -20591,7 +21385,7 @@ async function embedMany3({
20591
21385
  providerOptions
20592
21386
  });
20593
21387
  const embeddings2 = modelResponse.embeddings;
20594
- const usage = (_a2222 = modelResponse.usage) != null ? _a2222 : { tokens: NaN };
21388
+ const usage = (_a232 = modelResponse.usage) != null ? _a232 : { tokens: NaN };
20595
21389
  doEmbedSpan.setAttributes(
20596
21390
  await selectTelemetryAttributes3({
20597
21391
  telemetry,
@@ -20608,7 +21402,7 @@ async function embedMany3({
20608
21402
  return {
20609
21403
  embeddings: embeddings2,
20610
21404
  usage,
20611
- warnings: modelResponse.warnings,
21405
+ warnings: (_b19 = modelResponse.warnings) != null ? _b19 : [],
20612
21406
  providerMetadata: modelResponse.providerMetadata,
20613
21407
  response: modelResponse.response
20614
21408
  };
@@ -20630,7 +21424,7 @@ async function embedMany3({
20630
21424
  result.providerMetadata
20631
21425
  )) {
20632
21426
  providerMetadata[providerName] = {
20633
- ...(_a21 = providerMetadata[providerName]) != null ? _a21 : {},
21427
+ ...(_a223 = providerMetadata[providerName]) != null ? _a223 : {},
20634
21428
  ...metadata
20635
21429
  };
20636
21430
  }
@@ -22349,8 +23143,8 @@ async function listThreadsForResource({
22349
23143
  const title = thread.title || "(untitled)";
22350
23144
  const updated = formatTimestamp(thread.updatedAt);
22351
23145
  const created = formatTimestamp(thread.createdAt);
22352
- const marker21 = isCurrent ? " \u2190 current" : "";
22353
- lines.push(`- **${title}**${marker21}`);
23146
+ const marker28 = isCurrent ? " \u2190 current" : "";
23147
+ lines.push(`- **${title}**${marker28}`);
22354
23148
  lines.push(` id: ${thread.id}`);
22355
23149
  lines.push(` updated: ${updated} | created: ${created}`);
22356
23150
  }
@@ -23509,8 +24303,8 @@ var __experimental_updateWorkingMemoryToolVNext = (config) => {
23509
24303
  function createWorkingMemoryTool(config, options = {}) {
23510
24304
  const useStateSignals = config.workingMemory?.useStateSignals === true;
23511
24305
  const tool3 = options.vNext ? __experimental_updateWorkingMemoryToolVNext(config) : updateWorkingMemoryTool(config);
23512
- const name21 = useStateSignals ? SET_WORKING_MEMORY_TOOL_NAME : UPDATE_WORKING_MEMORY_TOOL_NAME;
23513
- return { name: name21, tool: tool3 };
24306
+ const name28 = useStateSignals ? SET_WORKING_MEMORY_TOOL_NAME : UPDATE_WORKING_MEMORY_TOOL_NAME;
24307
+ return { name: name28, tool: tool3 };
23514
24308
  }
23515
24309
  var WORKING_MEMORY_START_TAG = "<working_memory>";
23516
24310
  var WORKING_MEMORY_END_TAG = "</working_memory>";
@@ -23935,7 +24729,7 @@ var Memory = class extends MastraMemory {
23935
24729
  const separator = this.vector.indexSeparator ?? "_";
23936
24730
  const prefix = `memory${separator}messages`;
23937
24731
  const indexes = await this.vector.listIndexes();
23938
- return indexes.filter((name21) => name21.startsWith(prefix));
24732
+ return indexes.filter((name28) => name28.startsWith(prefix));
23939
24733
  }
23940
24734
  /**
23941
24735
  * Deletes all vector embeddings associated with a thread.
@@ -24599,7 +25393,7 @@ ${workingMemory}`;
24599
25393
  "Observational memory requires @mastra/core support for request-response-id-rotation. Please bump @mastra/core to a newer version."
24600
25394
  );
24601
25395
  }
24602
- const { ObservationalMemory: OMClass } = await import('./observational-memory-GAYCVM5R.js');
25396
+ const { ObservationalMemory: OMClass } = await import('./observational-memory-OJN26RQ4.js');
24603
25397
  const onIndexObservations = this.hasRetrievalSearch(omConfig.retrieval) ? async (observation) => {
24604
25398
  await this.indexObservation(observation);
24605
25399
  } : void 0;
@@ -25057,10 +25851,10 @@ Notes:
25057
25851
  const tools = {};
25058
25852
  const workingMemoryConfig = mergedConfig.workingMemory;
25059
25853
  if (workingMemoryConfig?.enabled && workingMemoryConfig.agentManaged !== false && !mergedConfig.readOnly) {
25060
- const { name: name21, tool: tool3 } = createWorkingMemoryTool(mergedConfig, {
25854
+ const { name: name28, tool: tool3 } = createWorkingMemoryTool(mergedConfig, {
25061
25855
  vNext: this.isVNextWorkingMemoryConfig(mergedConfig)
25062
25856
  });
25063
- tools[name21] = tool3;
25857
+ tools[name28] = tool3;
25064
25858
  }
25065
25859
  const omConfig = normalizeObservationalMemoryConfig(mergedConfig.observationalMemory);
25066
25860
  if (omConfig?.retrieval) {
@@ -25647,7 +26441,7 @@ Notes:
25647
26441
  if (!effectiveConfig) return null;
25648
26442
  const engine = await this.omEngine;
25649
26443
  if (!engine) return null;
25650
- const { ObservationalMemoryProcessor: ObservationalMemoryProcessor2 } = await import('./observational-memory-GAYCVM5R.js');
26444
+ const { ObservationalMemoryProcessor: ObservationalMemoryProcessor2 } = await import('./observational-memory-OJN26RQ4.js');
25651
26445
  return new ObservationalMemoryProcessor2(engine, this, {
25652
26446
  temporalMarkers: effectiveConfig.temporalMarkers
25653
26447
  });
@@ -28304,16 +29098,16 @@ Async buffering is enabled by default \u2014 this opt-out is only needed when us
28304
29098
  * (data-* parts are filtered out before sending to the LLM, so they don't affect model calls.)
28305
29099
  * @internal Used by ReflectorRunner. Do not call directly.
28306
29100
  */
28307
- async persistMarkerToMessage(marker21, messageList, threadId, resourceId) {
29101
+ async persistMarkerToMessage(marker28, messageList, threadId, resourceId) {
28308
29102
  if (!messageList) return;
28309
29103
  const allMsgs = messageList.get.all.db();
28310
29104
  for (let i = allMsgs.length - 1; i >= 0; i--) {
28311
29105
  const msg = allMsgs[i];
28312
29106
  if (msg?.role === "assistant" && msg.content?.parts && Array.isArray(msg.content.parts)) {
28313
- const markerData = marker21.data;
28314
- const alreadyPresent = markerData?.cycleId && msg.content.parts.some((p) => p?.type === marker21.type && p?.data?.cycleId === markerData.cycleId);
29107
+ const markerData = marker28.data;
29108
+ const alreadyPresent = markerData?.cycleId && msg.content.parts.some((p) => p?.type === marker28.type && p?.data?.cycleId === markerData.cycleId);
28315
29109
  if (!alreadyPresent) {
28316
- msg.content.parts.push(marker21);
29110
+ msg.content.parts.push(marker28);
28317
29111
  }
28318
29112
  try {
28319
29113
  await this.messageHistory.persistMessages({
@@ -28334,7 +29128,7 @@ Async buffering is enabled by default \u2014 this opt-out is only needed when us
28334
29128
  * so it works even when no MessageList is available (e.g. async buffering ops).
28335
29129
  * @internal Used by observation strategies. Do not call directly.
28336
29130
  */
28337
- async persistMarkerToStorage(marker21, threadId, resourceId) {
29131
+ async persistMarkerToStorage(marker28, threadId, resourceId) {
28338
29132
  try {
28339
29133
  const result = await this.storage.listMessages({
28340
29134
  threadId,
@@ -28344,10 +29138,10 @@ Async buffering is enabled by default \u2014 this opt-out is only needed when us
28344
29138
  const messages = result?.messages ?? [];
28345
29139
  for (const msg of messages) {
28346
29140
  if (msg?.role === "assistant" && msg.content?.parts && Array.isArray(msg.content.parts)) {
28347
- const markerData = marker21.data;
28348
- const alreadyPresent = markerData?.cycleId && msg.content.parts.some((p) => p?.type === marker21.type && p?.data?.cycleId === markerData.cycleId);
29141
+ const markerData = marker28.data;
29142
+ const alreadyPresent = markerData?.cycleId && msg.content.parts.some((p) => p?.type === marker28.type && p?.data?.cycleId === markerData.cycleId);
28349
29143
  if (!alreadyPresent) {
28350
- msg.content.parts.push(marker21);
29144
+ msg.content.parts.push(marker28);
28351
29145
  }
28352
29146
  await this.messageHistory.persistMessages({
28353
29147
  messages: [msg],
@@ -30600,5 +31394,5 @@ function getObservationsAsOf(activeObservations, asOf) {
30600
31394
  }
30601
31395
 
30602
31396
  export { Extractor, Memory, ModelByInputTokens, OBSERVER_SYSTEM_PROMPT, ObservationalMemory, ObservationalMemoryProcessor, SUMMARIZE_THREAD_DEFAULTS, TokenCounter, WorkingMemoryExtractor, buildObserverPrompt, buildObserverSystemPrompt, combineObservationGroupRanges, deepMergeWorkingMemory, deriveObservationGroupProvenance, extractCurrentTask, extractWorkingMemoryContent, extractWorkingMemoryTags, formatMessagesForObserver, getObservationsAsOf, hasCurrentTaskSection, injectAnchorIds, optimizeObservationsForContext, parseAnchorId, parseObservationGroups, parseObserverOutput, reconcileObservationGroupsFromReflection, removeWorkingMemoryTags, renderObservationGroupsForReflection, stripEphemeralAnchorIds, stripObservationGroups, summarizeConversation, wrapInObservationGroup };
30603
- //# sourceMappingURL=chunk-FNWCP2TI.js.map
30604
- //# sourceMappingURL=chunk-FNWCP2TI.js.map
31397
+ //# sourceMappingURL=chunk-6ACCFKAN.js.map
31398
+ //# sourceMappingURL=chunk-6ACCFKAN.js.map