@hongymagic/q 2026.402.0 → 2026.421.0-next.3092c36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/q.js +2736 -456
  2. package/package.json +19 -15
package/dist/q.js CHANGED
@@ -1537,13 +1537,14 @@ var require_auth_config = __commonJS((exports, module) => {
1537
1537
  }
1538
1538
  fs.writeFileSync(authPath, JSON.stringify(config2, null, 2), { mode: 384 });
1539
1539
  }
1540
- function isValidAccessToken(authConfig) {
1540
+ function isValidAccessToken(authConfig, expirationBufferMs = 0) {
1541
1541
  if (!authConfig.token)
1542
1542
  return false;
1543
1543
  if (typeof authConfig.expiresAt !== "number")
1544
1544
  return true;
1545
1545
  const nowInSeconds = Math.floor(Date.now() / 1000);
1546
- return authConfig.expiresAt >= nowInSeconds;
1546
+ const bufferInSeconds = expirationBufferMs / 1000;
1547
+ return authConfig.expiresAt >= nowInSeconds + bufferInSeconds;
1547
1548
  }
1548
1549
  });
1549
1550
 
@@ -1633,6 +1634,47 @@ var require_oauth = __commonJS((exports, module) => {
1633
1634
  }
1634
1635
  });
1635
1636
 
1637
+ // node_modules/@vercel/oidc/dist/auth-errors.js
1638
+ var require_auth_errors = __commonJS((exports, module) => {
1639
+ var __defProp2 = Object.defineProperty;
1640
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1641
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1642
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1643
+ var __export2 = (target, all) => {
1644
+ for (var name15 in all)
1645
+ __defProp2(target, name15, { get: all[name15], enumerable: true });
1646
+ };
1647
+ var __copyProps = (to, from, except, desc) => {
1648
+ if (from && typeof from === "object" || typeof from === "function") {
1649
+ for (let key of __getOwnPropNames2(from))
1650
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1651
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1652
+ }
1653
+ return to;
1654
+ };
1655
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1656
+ var auth_errors_exports = {};
1657
+ __export2(auth_errors_exports, {
1658
+ AccessTokenMissingError: () => AccessTokenMissingError2,
1659
+ RefreshAccessTokenFailedError: () => RefreshAccessTokenFailedError2
1660
+ });
1661
+ module.exports = __toCommonJS(auth_errors_exports);
1662
+
1663
+ class AccessTokenMissingError2 extends Error {
1664
+ constructor() {
1665
+ super("No authentication found. Please log in with the Vercel CLI (vercel login).");
1666
+ this.name = "AccessTokenMissingError";
1667
+ }
1668
+ }
1669
+
1670
+ class RefreshAccessTokenFailedError2 extends Error {
1671
+ constructor(cause) {
1672
+ super("Failed to refresh authentication token.", { cause });
1673
+ this.name = "RefreshAccessTokenFailedError";
1674
+ }
1675
+ }
1676
+ });
1677
+
1636
1678
  // node_modules/@vercel/oidc/dist/token-util.js
1637
1679
  var require_token_util = __commonJS((exports, module) => {
1638
1680
  var __create2 = Object.create;
@@ -1660,9 +1702,9 @@ var require_token_util = __commonJS((exports, module) => {
1660
1702
  assertVercelOidcTokenResponse: () => assertVercelOidcTokenResponse,
1661
1703
  findProjectInfo: () => findProjectInfo,
1662
1704
  getTokenPayload: () => getTokenPayload,
1663
- getVercelCliToken: () => getVercelCliToken,
1664
1705
  getVercelDataDir: () => getVercelDataDir,
1665
1706
  getVercelOidcToken: () => getVercelOidcToken2,
1707
+ getVercelToken: () => getVercelToken2,
1666
1708
  isExpired: () => isExpired,
1667
1709
  loadToken: () => loadToken,
1668
1710
  saveToken: () => saveToken
@@ -1674,6 +1716,7 @@ var require_token_util = __commonJS((exports, module) => {
1674
1716
  var import_token_io = require_token_io();
1675
1717
  var import_auth_config = require_auth_config();
1676
1718
  var import_oauth = require_oauth();
1719
+ var import_auth_errors = require_auth_errors();
1677
1720
  function getVercelDataDir() {
1678
1721
  const vercelFolder = "com.vercel.cli";
1679
1722
  const dataDir = (0, import_token_io.getUserDataDir)();
@@ -1682,17 +1725,17 @@ var require_token_util = __commonJS((exports, module) => {
1682
1725
  }
1683
1726
  return path2.join(dataDir, vercelFolder);
1684
1727
  }
1685
- async function getVercelCliToken() {
1728
+ async function getVercelToken2(options) {
1686
1729
  const authConfig = (0, import_auth_config.readAuthConfig)();
1687
- if (!authConfig) {
1688
- return null;
1730
+ if (!authConfig?.token) {
1731
+ throw new import_auth_errors.AccessTokenMissingError;
1689
1732
  }
1690
- if ((0, import_auth_config.isValidAccessToken)(authConfig)) {
1691
- return authConfig.token || null;
1733
+ if ((0, import_auth_config.isValidAccessToken)(authConfig, options?.expirationBufferMs)) {
1734
+ return authConfig.token;
1692
1735
  }
1693
1736
  if (!authConfig.refreshToken) {
1694
1737
  (0, import_auth_config.writeAuthConfig)({});
1695
- return null;
1738
+ throw new import_auth_errors.RefreshAccessTokenFailedError("No refresh token available");
1696
1739
  }
1697
1740
  try {
1698
1741
  const tokenResponse = await (0, import_oauth.refreshTokenRequest)({
@@ -1701,7 +1744,7 @@ var require_token_util = __commonJS((exports, module) => {
1701
1744
  const [tokensError, tokens] = await (0, import_oauth.processTokenResponse)(tokenResponse);
1702
1745
  if (tokensError || !tokens) {
1703
1746
  (0, import_auth_config.writeAuthConfig)({});
1704
- return null;
1747
+ throw new import_auth_errors.RefreshAccessTokenFailedError(tokensError);
1705
1748
  }
1706
1749
  const updatedConfig = {
1707
1750
  token: tokens.access_token,
@@ -1711,10 +1754,13 @@ var require_token_util = __commonJS((exports, module) => {
1711
1754
  updatedConfig.refreshToken = tokens.refresh_token;
1712
1755
  }
1713
1756
  (0, import_auth_config.writeAuthConfig)(updatedConfig);
1714
- return updatedConfig.token ?? null;
1757
+ return updatedConfig.token;
1715
1758
  } catch (error48) {
1716
1759
  (0, import_auth_config.writeAuthConfig)({});
1717
- return null;
1760
+ if (error48 instanceof import_auth_errors.AccessTokenMissingError || error48 instanceof import_auth_errors.RefreshAccessTokenFailedError) {
1761
+ throw error48;
1762
+ }
1763
+ throw new import_auth_errors.RefreshAccessTokenFailedError(error48);
1718
1764
  }
1719
1765
  }
1720
1766
  async function getVercelOidcToken2(authToken, projectId, teamId) {
@@ -1789,8 +1835,8 @@ var require_token_util = __commonJS((exports, module) => {
1789
1835
  const padded = base643.padEnd(base643.length + (4 - base643.length % 4) % 4, "=");
1790
1836
  return JSON.parse(Buffer.from(padded, "base64").toString("utf8"));
1791
1837
  }
1792
- function isExpired(token) {
1793
- return token.exp * 1000 < Date.now();
1838
+ function isExpired(token, bufferMs = 0) {
1839
+ return token.exp * 1000 < Date.now() + bufferMs;
1794
1840
  }
1795
1841
  });
1796
1842
 
@@ -1820,17 +1866,26 @@ var require_token = __commonJS((exports, module) => {
1820
1866
  module.exports = __toCommonJS(token_exports);
1821
1867
  var import_token_error = require_token_error();
1822
1868
  var import_token_util = require_token_util();
1823
- async function refreshToken() {
1824
- const { projectId, teamId } = (0, import_token_util.findProjectInfo)();
1869
+ async function refreshToken(options) {
1870
+ let projectId = options?.project;
1871
+ let teamId = options?.team;
1872
+ if (!projectId && !teamId) {
1873
+ const projectInfo = (0, import_token_util.findProjectInfo)();
1874
+ projectId = projectInfo.projectId;
1875
+ teamId = projectInfo.teamId;
1876
+ } else if (!projectId || !teamId) {
1877
+ const projectInfo = (0, import_token_util.findProjectInfo)();
1878
+ projectId = projectId ?? projectInfo.projectId;
1879
+ teamId = teamId ?? projectInfo.teamId;
1880
+ }
1881
+ if (!projectId) {
1882
+ throw new import_token_error.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");
1883
+ }
1825
1884
  let maybeToken = (0, import_token_util.loadToken)(projectId);
1826
- if (!maybeToken || (0, import_token_util.isExpired)((0, import_token_util.getTokenPayload)(maybeToken.token))) {
1827
- const authToken = await (0, import_token_util.getVercelCliToken)();
1828
- if (!authToken) {
1829
- throw new import_token_error.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");
1830
- }
1831
- if (!projectId) {
1832
- throw new import_token_error.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");
1833
- }
1885
+ if (!maybeToken || (0, import_token_util.isExpired)((0, import_token_util.getTokenPayload)(maybeToken.token), options?.expirationBufferMs)) {
1886
+ const authToken = await (0, import_token_util.getVercelToken)({
1887
+ expirationBufferMs: options?.expirationBufferMs
1888
+ });
1834
1889
  maybeToken = await (0, import_token_util.getVercelOidcToken)(authToken, projectId, teamId);
1835
1890
  if (!maybeToken) {
1836
1891
  throw new import_token_error.VercelOidcTokenError("Failed to refresh OIDC token");
@@ -1869,7 +1924,7 @@ var require_get_vercel_oidc_token = __commonJS((exports, module) => {
1869
1924
  module.exports = __toCommonJS(get_vercel_oidc_token_exports);
1870
1925
  var import_get_context = require_get_context();
1871
1926
  var import_token_error = require_token_error();
1872
- async function getVercelOidcToken2() {
1927
+ async function getVercelOidcToken2(options) {
1873
1928
  let token = "";
1874
1929
  let err;
1875
1930
  try {
@@ -1882,8 +1937,8 @@ var require_get_vercel_oidc_token = __commonJS((exports, module) => {
1882
1937
  await Promise.resolve().then(() => __toESM(require_token_util())),
1883
1938
  await Promise.resolve().then(() => __toESM(require_token()))
1884
1939
  ]);
1885
- if (!token || isExpired(getTokenPayload(token))) {
1886
- await refreshToken();
1940
+ if (!token || isExpired(getTokenPayload(token), options?.expirationBufferMs)) {
1941
+ await refreshToken(options);
1887
1942
  token = getVercelOidcTokenSync2();
1888
1943
  }
1889
1944
  } catch (error48) {
@@ -1929,13 +1984,18 @@ var require_dist = __commonJS((exports, module) => {
1929
1984
  var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1930
1985
  var src_exports = {};
1931
1986
  __export2(src_exports, {
1987
+ AccessTokenMissingError: () => import_auth_errors.AccessTokenMissingError,
1988
+ RefreshAccessTokenFailedError: () => import_auth_errors.RefreshAccessTokenFailedError,
1932
1989
  getContext: () => import_get_context.getContext,
1933
1990
  getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
1934
- getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
1991
+ getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync,
1992
+ getVercelToken: () => import_token_util.getVercelToken
1935
1993
  });
1936
1994
  module.exports = __toCommonJS(src_exports);
1937
1995
  var import_get_vercel_oidc_token = require_get_vercel_oidc_token();
1938
1996
  var import_get_context = require_get_context();
1997
+ var import_auth_errors = require_auth_errors();
1998
+ var import_token_util = require_token_util();
1939
1999
  });
1940
2000
 
1941
2001
  // node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js
@@ -12055,7 +12115,7 @@ var init_main_sync = __esm(() => {
12055
12115
 
12056
12116
  // node_modules/execa/lib/ipc/get-one.js
12057
12117
  import { once as once5, on as on2 } from "node:events";
12058
- var getOneMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = true, filter: filter2 } = {}) => {
12118
+ var getOneMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = true, filter: filter3 } = {}) => {
12059
12119
  validateIpcMethod({
12060
12120
  methodName: "getOneMessage",
12061
12121
  isSubprocess,
@@ -12066,16 +12126,16 @@ var getOneMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = t
12066
12126
  anyProcess,
12067
12127
  channel,
12068
12128
  isSubprocess,
12069
- filter: filter2,
12129
+ filter: filter3,
12070
12130
  reference
12071
12131
  });
12072
- }, getOneMessageAsync = async ({ anyProcess, channel, isSubprocess, filter: filter2, reference }) => {
12132
+ }, getOneMessageAsync = async ({ anyProcess, channel, isSubprocess, filter: filter3, reference }) => {
12073
12133
  addReference(channel, reference);
12074
12134
  const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);
12075
12135
  const controller = new AbortController;
12076
12136
  try {
12077
12137
  return await Promise.race([
12078
- getMessage(ipcEmitter, filter2, controller),
12138
+ getMessage(ipcEmitter, filter3, controller),
12079
12139
  throwOnDisconnect2(ipcEmitter, isSubprocess, controller),
12080
12140
  throwOnStrictError(ipcEmitter, isSubprocess, controller)
12081
12141
  ]);
@@ -12086,13 +12146,13 @@ var getOneMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = t
12086
12146
  controller.abort();
12087
12147
  removeReference(channel, reference);
12088
12148
  }
12089
- }, getMessage = async (ipcEmitter, filter2, { signal }) => {
12090
- if (filter2 === undefined) {
12149
+ }, getMessage = async (ipcEmitter, filter3, { signal }) => {
12150
+ if (filter3 === undefined) {
12091
12151
  const [message] = await once5(ipcEmitter, "message", { signal });
12092
12152
  return message;
12093
12153
  }
12094
12154
  for await (const [message] of on2(ipcEmitter, "message", { signal })) {
12095
- if (filter2(message)) {
12155
+ if (filter3(message)) {
12096
12156
  return message;
12097
12157
  }
12098
12158
  }
@@ -12443,7 +12503,7 @@ var getHighWaterMark = (streams, objectMode) => {
12443
12503
  if (signal.aborted || !streams.has(stream)) {
12444
12504
  return;
12445
12505
  }
12446
- if (isAbortError2(error48)) {
12506
+ if (isAbortError3(error48)) {
12447
12507
  aborted2.add(stream);
12448
12508
  } else {
12449
12509
  errorStream(passThroughStream, error48);
@@ -12462,12 +12522,12 @@ var getHighWaterMark = (streams, objectMode) => {
12462
12522
  stream.end();
12463
12523
  }
12464
12524
  }, errorOrAbortStream = (stream, error48) => {
12465
- if (isAbortError2(error48)) {
12525
+ if (isAbortError3(error48)) {
12466
12526
  abortStream(stream);
12467
12527
  } else {
12468
12528
  errorStream(stream, error48);
12469
12529
  }
12470
- }, isAbortError2 = (error48) => error48?.code === "ERR_STREAM_PREMATURE_CLOSE", abortStream = (stream) => {
12530
+ }, isAbortError3 = (error48) => error48?.code === "ERR_STREAM_PREMATURE_CLOSE", abortStream = (stream) => {
12471
12531
  if (stream.readable || stream.writable) {
12472
12532
  stream.destroy();
12473
12533
  }
@@ -14712,7 +14772,7 @@ import { parseArgs } from "node:util";
14712
14772
  // package.json
14713
14773
  var package_default = {
14714
14774
  name: "@hongymagic/q",
14715
- version: "2026.402.0",
14775
+ version: "2026.421.0-next.3092c36",
14716
14776
  description: "Quick AI answers from the command line",
14717
14777
  main: "dist/q.js",
14718
14778
  type: "module",
@@ -14762,15 +14822,15 @@ var package_default = {
14762
14822
  "release:dry": "bun run scripts/release.ts --dry-run"
14763
14823
  },
14764
14824
  dependencies: {
14765
- "@ai-sdk/amazon-bedrock": "4.0.85",
14766
- "@ai-sdk/anthropic": "3.0.64",
14767
- "@ai-sdk/azure": "3.0.50",
14768
- "@ai-sdk/google": "3.0.54",
14769
- "@ai-sdk/groq": "3.0.31",
14770
- "@ai-sdk/openai": "3.0.49",
14771
- "@ai-sdk/openai-compatible": "2.0.37",
14825
+ "@ai-sdk/amazon-bedrock": "4.0.96",
14826
+ "@ai-sdk/anthropic": "3.0.71",
14827
+ "@ai-sdk/azure": "3.0.54",
14828
+ "@ai-sdk/google": "3.0.64",
14829
+ "@ai-sdk/groq": "3.0.35",
14830
+ "@ai-sdk/openai": "3.0.53",
14831
+ "@ai-sdk/openai-compatible": "2.0.41",
14772
14832
  "@t3-oss/env-core": "0.13.11",
14773
- ai: "6.0.142",
14833
+ ai: "6.0.168",
14774
14834
  clipboardy: "5.3.1",
14775
14835
  "env-paths": "4.0.0",
14776
14836
  "ollama-ai-provider-v2": "3.5.0",
@@ -14778,12 +14838,16 @@ var package_default = {
14778
14838
  zod: "4.3.6"
14779
14839
  },
14780
14840
  devDependencies: {
14781
- "@biomejs/biome": "2.4.10",
14782
- "@types/bun": "1.3.11",
14783
- "@vitest/coverage-v8": "4.1.2",
14784
- lefthook: "2.1.4",
14785
- typescript: "6.0.2",
14786
- vitest: "4.1.2"
14841
+ "@biomejs/biome": "2.4.12",
14842
+ "@types/bun": "1.3.12",
14843
+ "@vitest/coverage-v8": "4.1.5",
14844
+ lefthook: "2.1.6",
14845
+ typescript: "6.0.3",
14846
+ vitest: "4.1.5"
14847
+ },
14848
+ overrides: {
14849
+ vite: "7.3.2",
14850
+ picomatch: "4.0.4"
14787
14851
  }
14788
14852
  };
14789
14853
 
@@ -34848,10 +34912,13 @@ function validateDownloadUrl(url2) {
34848
34912
  message: `Invalid URL: ${url2}`
34849
34913
  });
34850
34914
  }
34915
+ if (parsed.protocol === "data:") {
34916
+ return;
34917
+ }
34851
34918
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
34852
34919
  throw new DownloadError({
34853
34920
  url: url2,
34854
- message: `URL scheme must be http or https, got ${parsed.protocol}`
34921
+ message: `URL scheme must be http, https, or data, got ${parsed.protocol}`
34855
34922
  });
34856
34923
  }
34857
34924
  const hostname3 = parsed.hostname;
@@ -35109,7 +35176,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
35109
35176
  normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
35110
35177
  return Object.fromEntries(normalizedHeaders.entries());
35111
35178
  }
35112
- var VERSION2 = "4.0.21";
35179
+ var VERSION2 = "4.0.23";
35113
35180
  var getOriginalFetch = () => globalThis.fetch;
35114
35181
  var getFromApi = async ({
35115
35182
  url: url2,
@@ -35205,7 +35272,7 @@ function loadApiKey({
35205
35272
  }
35206
35273
  if (typeof process === "undefined") {
35207
35274
  throw new LoadAPIKeyError({
35208
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
35275
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.`
35209
35276
  });
35210
35277
  }
35211
35278
  apiKey = process.env[environmentVariableName];
@@ -35253,7 +35320,7 @@ function loadSetting({
35253
35320
  }
35254
35321
  if (typeof process === "undefined") {
35255
35322
  throw new LoadSettingError({
35256
- message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.`
35323
+ message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables are not supported in this environment.`
35257
35324
  });
35258
35325
  }
35259
35326
  settingValue = process.env[environmentVariableName];
@@ -36877,7 +36944,7 @@ async function* executeTool({
36877
36944
  }
36878
36945
 
36879
36946
  // node_modules/@ai-sdk/anthropic/dist/index.mjs
36880
- var VERSION3 = "3.0.64";
36947
+ var VERSION3 = "3.0.71";
36881
36948
  var anthropicErrorDataSchema = lazySchema(() => zodSchema(exports_external.object({
36882
36949
  type: exports_external.literal("error"),
36883
36950
  error: exports_external.object({
@@ -37566,7 +37633,8 @@ var anthropicLanguageModelOptions = exports_external.object({
37566
37633
  structuredOutputMode: exports_external.enum(["outputFormat", "jsonTool", "auto"]).optional(),
37567
37634
  thinking: exports_external.discriminatedUnion("type", [
37568
37635
  exports_external.object({
37569
- type: exports_external.literal("adaptive")
37636
+ type: exports_external.literal("adaptive"),
37637
+ display: exports_external.enum(["omitted", "summarized"]).optional()
37570
37638
  }),
37571
37639
  exports_external.object({
37572
37640
  type: exports_external.literal("enabled"),
@@ -37603,8 +37671,14 @@ var anthropicLanguageModelOptions = exports_external.object({
37603
37671
  })).optional()
37604
37672
  }).optional(),
37605
37673
  toolStreaming: exports_external.boolean().optional(),
37606
- effort: exports_external.enum(["low", "medium", "high", "max"]).optional(),
37674
+ effort: exports_external.enum(["low", "medium", "high", "xhigh", "max"]).optional(),
37675
+ taskBudget: exports_external.object({
37676
+ type: exports_external.literal("tokens"),
37677
+ total: exports_external.number().int().min(20000),
37678
+ remaining: exports_external.number().int().min(0).optional()
37679
+ }).optional(),
37607
37680
  speed: exports_external.enum(["fast", "standard"]).optional(),
37681
+ inferenceGeo: exports_external.enum(["us", "global"]).optional(),
37608
37682
  anthropicBeta: exports_external.array(exports_external.string()).optional(),
37609
37683
  contextManagement: exports_external.object({
37610
37684
  edits: exports_external.array(exports_external.discriminatedUnion("type", [
@@ -37863,9 +37937,10 @@ async function prepareTools({
37863
37937
  disableParallelToolUse,
37864
37938
  cacheControlValidator,
37865
37939
  supportsStructuredOutput,
37866
- supportsStrictTools
37940
+ supportsStrictTools,
37941
+ defaultEagerInputStreaming = false
37867
37942
  }) {
37868
- var _a16;
37943
+ var _a16, _b16;
37869
37944
  tools = (tools == null ? undefined : tools.length) ? tools : undefined;
37870
37945
  const toolWarnings = [];
37871
37946
  const betas = /* @__PURE__ */ new Set;
@@ -37882,7 +37957,7 @@ async function prepareTools({
37882
37957
  canCache: true
37883
37958
  });
37884
37959
  const anthropicOptions = (_a16 = tool2.providerOptions) == null ? undefined : _a16.anthropic;
37885
- const eagerInputStreaming = anthropicOptions == null ? undefined : anthropicOptions.eagerInputStreaming;
37960
+ const eagerInputStreaming = (_b16 = anthropicOptions == null ? undefined : anthropicOptions.eagerInputStreaming) != null ? _b16 : defaultEagerInputStreaming;
37886
37961
  const deferLoading = anthropicOptions == null ? undefined : anthropicOptions.deferLoading;
37887
37962
  const allowedCallers = anthropicOptions == null ? undefined : anthropicOptions.allowedCallers;
37888
37963
  if (!supportsStrictTools && tool2.strict != null) {
@@ -39344,7 +39419,7 @@ var AnthropicMessagesLanguageModel = class {
39344
39419
  providerOptions,
39345
39420
  stream
39346
39421
  }) {
39347
- var _a16, _b16, _c, _d, _e, _f, _g, _h, _i;
39422
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j;
39348
39423
  const warnings = [];
39349
39424
  if (frequencyPenalty != null) {
39350
39425
  warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
@@ -39395,8 +39470,36 @@ var AnthropicMessagesLanguageModel = class {
39395
39470
  const {
39396
39471
  maxOutputTokens: maxOutputTokensForModel,
39397
39472
  supportsStructuredOutput: modelSupportsStructuredOutput,
39473
+ rejectsSamplingParameters,
39398
39474
  isKnownModel
39399
39475
  } = getModelCapabilities(this.modelId);
39476
+ if (rejectsSamplingParameters) {
39477
+ if (temperature != null) {
39478
+ warnings.push({
39479
+ type: "unsupported",
39480
+ feature: "temperature",
39481
+ details: `temperature is not supported by ${this.modelId} and will be ignored`
39482
+ });
39483
+ temperature = undefined;
39484
+ }
39485
+ if (topK != null) {
39486
+ warnings.push({
39487
+ type: "unsupported",
39488
+ feature: "topK",
39489
+ details: `topK is not supported by ${this.modelId} and will be ignored`
39490
+ });
39491
+ topK = undefined;
39492
+ }
39493
+ if (topP != null) {
39494
+ warnings.push({
39495
+ type: "unsupported",
39496
+ feature: "topP",
39497
+ details: `topP is not supported by ${this.modelId} and will be ignored`
39498
+ });
39499
+ topP = undefined;
39500
+ }
39501
+ }
39502
+ const isAnthropicModel = isKnownModel || this.modelId.startsWith("claude-");
39400
39503
  const supportsStructuredOutput = ((_a16 = this.config.supportsNativeStructuredOutput) != null ? _a16 : true) && modelSupportsStructuredOutput;
39401
39504
  const supportsStrictTools = ((_b16 = this.config.supportsStrictTools) != null ? _b16 : true) && modelSupportsStructuredOutput;
39402
39505
  const structureOutputMode = (_c = anthropicOptions == null ? undefined : anthropicOptions.structuredOutputMode) != null ? _c : "auto";
@@ -39442,6 +39545,7 @@ var AnthropicMessagesLanguageModel = class {
39442
39545
  const thinkingType = (_e = anthropicOptions == null ? undefined : anthropicOptions.thinking) == null ? undefined : _e.type;
39443
39546
  const isThinking = thinkingType === "enabled" || thinkingType === "adaptive";
39444
39547
  let thinkingBudget = thinkingType === "enabled" ? (_f = anthropicOptions == null ? undefined : anthropicOptions.thinking) == null ? undefined : _f.budgetTokens : undefined;
39548
+ const thinkingDisplay = thinkingType === "adaptive" ? (_g = anthropicOptions == null ? undefined : anthropicOptions.thinking) == null ? undefined : _g.display : undefined;
39445
39549
  const maxTokens = maxOutputTokens != null ? maxOutputTokens : maxOutputTokensForModel;
39446
39550
  const baseArgs = {
39447
39551
  model: this.modelId,
@@ -39453,14 +39557,24 @@ var AnthropicMessagesLanguageModel = class {
39453
39557
  ...isThinking && {
39454
39558
  thinking: {
39455
39559
  type: thinkingType,
39456
- ...thinkingBudget != null && { budget_tokens: thinkingBudget }
39560
+ ...thinkingBudget != null && { budget_tokens: thinkingBudget },
39561
+ ...thinkingDisplay != null && { display: thinkingDisplay }
39457
39562
  }
39458
39563
  },
39459
- ...((anthropicOptions == null ? undefined : anthropicOptions.effort) || useStructuredOutput && (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null) && {
39564
+ ...((anthropicOptions == null ? undefined : anthropicOptions.effort) || (anthropicOptions == null ? undefined : anthropicOptions.taskBudget) || useStructuredOutput && (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null) && {
39460
39565
  output_config: {
39461
39566
  ...(anthropicOptions == null ? undefined : anthropicOptions.effort) && {
39462
39567
  effort: anthropicOptions.effort
39463
39568
  },
39569
+ ...(anthropicOptions == null ? undefined : anthropicOptions.taskBudget) && {
39570
+ task_budget: {
39571
+ type: anthropicOptions.taskBudget.type,
39572
+ total: anthropicOptions.taskBudget.total,
39573
+ ...anthropicOptions.taskBudget.remaining != null && {
39574
+ remaining: anthropicOptions.taskBudget.remaining
39575
+ }
39576
+ }
39577
+ },
39464
39578
  ...useStructuredOutput && (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null && {
39465
39579
  format: {
39466
39580
  type: "json_schema",
@@ -39472,10 +39586,13 @@ var AnthropicMessagesLanguageModel = class {
39472
39586
  ...(anthropicOptions == null ? undefined : anthropicOptions.speed) && {
39473
39587
  speed: anthropicOptions.speed
39474
39588
  },
39589
+ ...(anthropicOptions == null ? undefined : anthropicOptions.inferenceGeo) && {
39590
+ inference_geo: anthropicOptions.inferenceGeo
39591
+ },
39475
39592
  ...(anthropicOptions == null ? undefined : anthropicOptions.cacheControl) && {
39476
39593
  cache_control: anthropicOptions.cacheControl
39477
39594
  },
39478
- ...((_g = anthropicOptions == null ? undefined : anthropicOptions.metadata) == null ? undefined : _g.userId) != null && {
39595
+ ...((_h = anthropicOptions == null ? undefined : anthropicOptions.metadata) == null ? undefined : _h.userId) != null && {
39479
39596
  metadata: { user_id: anthropicOptions.metadata.userId }
39480
39597
  },
39481
39598
  ...(anthropicOptions == null ? undefined : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0 && {
@@ -39592,7 +39709,7 @@ var AnthropicMessagesLanguageModel = class {
39592
39709
  }
39593
39710
  baseArgs.max_tokens = maxTokens + (thinkingBudget != null ? thinkingBudget : 0);
39594
39711
  } else {
39595
- if (topP != null && temperature != null) {
39712
+ if (isAnthropicModel && topP != null && temperature != null) {
39596
39713
  warnings.push({
39597
39714
  type: "unsupported",
39598
39715
  feature: "topP",
@@ -39634,12 +39751,13 @@ var AnthropicMessagesLanguageModel = class {
39634
39751
  if (anthropicOptions == null ? undefined : anthropicOptions.effort) {
39635
39752
  betas.add("effort-2025-11-24");
39636
39753
  }
39754
+ if (anthropicOptions == null ? undefined : anthropicOptions.taskBudget) {
39755
+ betas.add("task-budgets-2026-03-13");
39756
+ }
39637
39757
  if ((anthropicOptions == null ? undefined : anthropicOptions.speed) === "fast") {
39638
39758
  betas.add("fast-mode-2026-02-01");
39639
39759
  }
39640
- if (stream && ((_h = anthropicOptions == null ? undefined : anthropicOptions.toolStreaming) != null ? _h : true)) {
39641
- betas.add("fine-grained-tool-streaming-2025-05-14");
39642
- }
39760
+ const defaultEagerInputStreaming = stream && ((_i = anthropicOptions == null ? undefined : anthropicOptions.toolStreaming) != null ? _i : true);
39643
39761
  const {
39644
39762
  tools: anthropicTools2,
39645
39763
  toolChoice: anthropicToolChoice,
@@ -39651,14 +39769,16 @@ var AnthropicMessagesLanguageModel = class {
39651
39769
  disableParallelToolUse: true,
39652
39770
  cacheControlValidator,
39653
39771
  supportsStructuredOutput: false,
39654
- supportsStrictTools
39772
+ supportsStrictTools,
39773
+ defaultEagerInputStreaming
39655
39774
  } : {
39656
39775
  tools: tools != null ? tools : [],
39657
39776
  toolChoice,
39658
39777
  disableParallelToolUse: anthropicOptions == null ? undefined : anthropicOptions.disableParallelToolUse,
39659
39778
  cacheControlValidator,
39660
39779
  supportsStructuredOutput,
39661
- supportsStrictTools
39780
+ supportsStrictTools,
39781
+ defaultEagerInputStreaming
39662
39782
  });
39663
39783
  const cacheWarnings = cacheControlValidator.getWarnings();
39664
39784
  return {
@@ -39673,7 +39793,7 @@ var AnthropicMessagesLanguageModel = class {
39673
39793
  ...betas,
39674
39794
  ...toolsBetas,
39675
39795
  ...userSuppliedBetas,
39676
- ...(_i = anthropicOptions == null ? undefined : anthropicOptions.anthropicBeta) != null ? _i : []
39796
+ ...(_j = anthropicOptions == null ? undefined : anthropicOptions.anthropicBeta) != null ? _j : []
39677
39797
  ]),
39678
39798
  usesJsonResponseTool: jsonResponseTool != null,
39679
39799
  toolNameMapping,
@@ -40877,46 +40997,60 @@ var AnthropicMessagesLanguageModel = class {
40877
40997
  }
40878
40998
  };
40879
40999
  function getModelCapabilities(modelId) {
40880
- if (modelId.includes("claude-sonnet-4-6") || modelId.includes("claude-opus-4-6")) {
41000
+ if (modelId.includes("claude-opus-4-7")) {
40881
41001
  return {
40882
41002
  maxOutputTokens: 128000,
40883
41003
  supportsStructuredOutput: true,
41004
+ rejectsSamplingParameters: true,
41005
+ isKnownModel: true
41006
+ };
41007
+ } else if (modelId.includes("claude-sonnet-4-6") || modelId.includes("claude-opus-4-6")) {
41008
+ return {
41009
+ maxOutputTokens: 128000,
41010
+ supportsStructuredOutput: true,
41011
+ rejectsSamplingParameters: false,
40884
41012
  isKnownModel: true
40885
41013
  };
40886
41014
  } else if (modelId.includes("claude-sonnet-4-5") || modelId.includes("claude-opus-4-5") || modelId.includes("claude-haiku-4-5")) {
40887
41015
  return {
40888
41016
  maxOutputTokens: 64000,
40889
41017
  supportsStructuredOutput: true,
41018
+ rejectsSamplingParameters: false,
40890
41019
  isKnownModel: true
40891
41020
  };
40892
41021
  } else if (modelId.includes("claude-opus-4-1")) {
40893
41022
  return {
40894
41023
  maxOutputTokens: 32000,
40895
41024
  supportsStructuredOutput: true,
41025
+ rejectsSamplingParameters: false,
40896
41026
  isKnownModel: true
40897
41027
  };
40898
41028
  } else if (modelId.includes("claude-sonnet-4-")) {
40899
41029
  return {
40900
41030
  maxOutputTokens: 64000,
40901
41031
  supportsStructuredOutput: false,
41032
+ rejectsSamplingParameters: false,
40902
41033
  isKnownModel: true
40903
41034
  };
40904
41035
  } else if (modelId.includes("claude-opus-4-")) {
40905
41036
  return {
40906
41037
  maxOutputTokens: 32000,
40907
41038
  supportsStructuredOutput: false,
41039
+ rejectsSamplingParameters: false,
40908
41040
  isKnownModel: true
40909
41041
  };
40910
41042
  } else if (modelId.includes("claude-3-haiku")) {
40911
41043
  return {
40912
41044
  maxOutputTokens: 4096,
40913
41045
  supportsStructuredOutput: false,
41046
+ rejectsSamplingParameters: false,
40914
41047
  isKnownModel: true
40915
41048
  };
40916
41049
  } else {
40917
41050
  return {
40918
41051
  maxOutputTokens: 4096,
40919
41052
  supportsStructuredOutput: false,
41053
+ rejectsSamplingParameters: false,
40920
41054
  isKnownModel: false
40921
41055
  };
40922
41056
  }
@@ -41311,6 +41445,9 @@ function convertOpenAIChatUsage(usage) {
41311
41445
  raw: usage
41312
41446
  };
41313
41447
  }
41448
+ function serializeToolCallArguments(input) {
41449
+ return JSON.stringify(input === undefined ? {} : input);
41450
+ }
41314
41451
  function convertToOpenAIChatMessages({
41315
41452
  prompt,
41316
41453
  systemMessageMode = "system"
@@ -41438,7 +41575,7 @@ function convertToOpenAIChatMessages({
41438
41575
  type: "function",
41439
41576
  function: {
41440
41577
  name: part.toolName,
41441
- arguments: JSON.stringify(part.input)
41578
+ arguments: serializeToolCallArguments(part.input)
41442
41579
  }
41443
41580
  });
41444
41581
  break;
@@ -43307,6 +43444,9 @@ var toolSearchToolFactory = createProviderToolFactoryWithOutputSchema({
43307
43444
  inputSchema: toolSearchInputSchema,
43308
43445
  outputSchema: toolSearchOutputSchema
43309
43446
  });
43447
+ function serializeToolCallArguments2(input) {
43448
+ return JSON.stringify(input === undefined ? {} : input);
43449
+ }
43310
43450
  function isFileId(data, prefixes) {
43311
43451
  if (!prefixes)
43312
43452
  return false;
@@ -43527,7 +43667,7 @@ async function convertToOpenAIResponsesInput({
43527
43667
  type: "function_call",
43528
43668
  call_id: part.toolCallId,
43529
43669
  name: resolvedToolName,
43530
- arguments: JSON.stringify(part.input),
43670
+ arguments: serializeToolCallArguments2(part.input),
43531
43671
  id
43532
43672
  });
43533
43673
  break;
@@ -46929,7 +47069,7 @@ var azureOpenaiTools = {
46929
47069
  imageGeneration,
46930
47070
  webSearchPreview
46931
47071
  };
46932
- var VERSION4 = "3.0.50";
47072
+ var VERSION4 = "3.0.54";
46933
47073
  function createAzure(options = {}) {
46934
47074
  var _a16;
46935
47075
  const getHeaders = () => {
@@ -47729,7 +47869,8 @@ var anthropicLanguageModelOptions2 = exports_external.object({
47729
47869
  structuredOutputMode: exports_external.enum(["outputFormat", "jsonTool", "auto"]).optional(),
47730
47870
  thinking: exports_external.discriminatedUnion("type", [
47731
47871
  exports_external.object({
47732
- type: exports_external.literal("adaptive")
47872
+ type: exports_external.literal("adaptive"),
47873
+ display: exports_external.enum(["omitted", "summarized"]).optional()
47733
47874
  }),
47734
47875
  exports_external.object({
47735
47876
  type: exports_external.literal("enabled"),
@@ -47766,8 +47907,14 @@ var anthropicLanguageModelOptions2 = exports_external.object({
47766
47907
  })).optional()
47767
47908
  }).optional(),
47768
47909
  toolStreaming: exports_external.boolean().optional(),
47769
- effort: exports_external.enum(["low", "medium", "high", "max"]).optional(),
47910
+ effort: exports_external.enum(["low", "medium", "high", "xhigh", "max"]).optional(),
47911
+ taskBudget: exports_external.object({
47912
+ type: exports_external.literal("tokens"),
47913
+ total: exports_external.number().int().min(20000),
47914
+ remaining: exports_external.number().int().min(0).optional()
47915
+ }).optional(),
47770
47916
  speed: exports_external.enum(["fast", "standard"]).optional(),
47917
+ inferenceGeo: exports_external.enum(["us", "global"]).optional(),
47771
47918
  anthropicBeta: exports_external.array(exports_external.string()).optional(),
47772
47919
  contextManagement: exports_external.object({
47773
47920
  edits: exports_external.array(exports_external.discriminatedUnion("type", [
@@ -48026,9 +48173,10 @@ async function prepareTools2({
48026
48173
  disableParallelToolUse,
48027
48174
  cacheControlValidator,
48028
48175
  supportsStructuredOutput,
48029
- supportsStrictTools
48176
+ supportsStrictTools,
48177
+ defaultEagerInputStreaming = false
48030
48178
  }) {
48031
- var _a16;
48179
+ var _a16, _b16;
48032
48180
  tools = (tools == null ? undefined : tools.length) ? tools : undefined;
48033
48181
  const toolWarnings = [];
48034
48182
  const betas = /* @__PURE__ */ new Set;
@@ -48045,7 +48193,7 @@ async function prepareTools2({
48045
48193
  canCache: true
48046
48194
  });
48047
48195
  const anthropicOptions = (_a16 = tool2.providerOptions) == null ? undefined : _a16.anthropic;
48048
- const eagerInputStreaming = anthropicOptions == null ? undefined : anthropicOptions.eagerInputStreaming;
48196
+ const eagerInputStreaming = (_b16 = anthropicOptions == null ? undefined : anthropicOptions.eagerInputStreaming) != null ? _b16 : defaultEagerInputStreaming;
48049
48197
  const deferLoading = anthropicOptions == null ? undefined : anthropicOptions.deferLoading;
48050
48198
  const allowedCallers = anthropicOptions == null ? undefined : anthropicOptions.allowedCallers;
48051
48199
  if (!supportsStrictTools && tool2.strict != null) {
@@ -49411,9 +49559,11 @@ var amazonBedrockLanguageModelOptions = exports_external.object({
49411
49559
  exports_external.literal("adaptive")
49412
49560
  ]).optional(),
49413
49561
  budgetTokens: exports_external.number().optional(),
49414
- maxReasoningEffort: exports_external.enum(["low", "medium", "high", "max"]).optional()
49562
+ maxReasoningEffort: exports_external.enum(["low", "medium", "high", "xhigh", "max"]).optional(),
49563
+ display: exports_external.enum(["omitted", "summarized"]).optional()
49415
49564
  }).optional(),
49416
- anthropicBeta: exports_external.array(exports_external.string()).optional()
49565
+ anthropicBeta: exports_external.array(exports_external.string()).optional(),
49566
+ serviceTier: exports_external.enum(["reserved", "priority", "default", "flex"]).optional()
49417
49567
  });
49418
49568
  var BedrockErrorSchema = exports_external.object({
49419
49569
  message: exports_external.string(),
@@ -49838,12 +49988,13 @@ async function convertToBedrockChatMessages(prompt, isMistral = false) {
49838
49988
  const message = block.messages[j];
49839
49989
  const isLastMessage = j === block.messages.length - 1;
49840
49990
  const { content } = message;
49991
+ const hasReasoningBlocks = content.some((part) => part.type === "reasoning");
49841
49992
  for (let k = 0;k < content.length; k++) {
49842
49993
  const part = content[k];
49843
49994
  const isLastContentPart = k === content.length - 1;
49844
49995
  switch (part.type) {
49845
49996
  case "text": {
49846
- if (!part.text.trim()) {
49997
+ if (!part.text.trim() && !hasReasoningBlocks) {
49847
49998
  break;
49848
49999
  }
49849
50000
  bedrockContent.push({
@@ -50027,7 +50178,7 @@ var BedrockChatLanguageModel = class {
50027
50178
  toolChoice,
50028
50179
  providerOptions
50029
50180
  }) {
50030
- var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
50181
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
50031
50182
  const bedrockOptions = (_a16 = await parseProviderOptions({
50032
50183
  provider: "bedrock",
50033
50184
  providerOptions,
@@ -50105,6 +50256,7 @@ var BedrockChatLanguageModel = class {
50105
50256
  }
50106
50257
  const thinkingType = (_e = bedrockOptions.reasoningConfig) == null ? undefined : _e.type;
50107
50258
  const thinkingBudget = thinkingType === "enabled" ? (_f = bedrockOptions.reasoningConfig) == null ? undefined : _f.budgetTokens : undefined;
50259
+ const thinkingDisplay = thinkingType === "adaptive" ? (_g = bedrockOptions.reasoningConfig) == null ? undefined : _g.display : undefined;
50108
50260
  const isAnthropicThinkingEnabled = isAnthropicModel && isThinkingEnabled;
50109
50261
  const inferenceConfig = {
50110
50262
  ...maxOutputTokens != null && { maxTokens: maxOutputTokens },
@@ -50131,12 +50283,13 @@ var BedrockChatLanguageModel = class {
50131
50283
  bedrockOptions.additionalModelRequestFields = {
50132
50284
  ...bedrockOptions.additionalModelRequestFields,
50133
50285
  thinking: {
50134
- type: "adaptive"
50286
+ type: "adaptive",
50287
+ ...thinkingDisplay != null && { display: thinkingDisplay }
50135
50288
  }
50136
50289
  };
50137
50290
  }
50138
50291
  } else if (!isAnthropicModel) {
50139
- if (((_g = bedrockOptions.reasoningConfig) == null ? undefined : _g.budgetTokens) != null) {
50292
+ if (((_h = bedrockOptions.reasoningConfig) == null ? undefined : _h.budgetTokens) != null) {
50140
50293
  warnings.push({
50141
50294
  type: "unsupported",
50142
50295
  feature: "budgetTokens",
@@ -50151,14 +50304,14 @@ var BedrockChatLanguageModel = class {
50151
50304
  });
50152
50305
  }
50153
50306
  }
50154
- const maxReasoningEffort = (_h = bedrockOptions.reasoningConfig) == null ? undefined : _h.maxReasoningEffort;
50307
+ const maxReasoningEffort = (_i = bedrockOptions.reasoningConfig) == null ? undefined : _i.maxReasoningEffort;
50155
50308
  const isOpenAIModel = this.modelId.startsWith("openai.");
50156
50309
  if (maxReasoningEffort != null) {
50157
50310
  if (isAnthropicModel) {
50158
50311
  bedrockOptions.additionalModelRequestFields = {
50159
50312
  ...bedrockOptions.additionalModelRequestFields,
50160
50313
  output_config: {
50161
- ...(_i = bedrockOptions.additionalModelRequestFields) == null ? undefined : _i.output_config,
50314
+ ...(_j = bedrockOptions.additionalModelRequestFields) == null ? undefined : _j.output_config,
50162
50315
  effort: maxReasoningEffort
50163
50316
  }
50164
50317
  };
@@ -50182,7 +50335,7 @@ var BedrockChatLanguageModel = class {
50182
50335
  bedrockOptions.additionalModelRequestFields = {
50183
50336
  ...bedrockOptions.additionalModelRequestFields,
50184
50337
  output_config: {
50185
- ...(_j = bedrockOptions.additionalModelRequestFields) == null ? undefined : _j.output_config,
50338
+ ...(_k = bedrockOptions.additionalModelRequestFields) == null ? undefined : _k.output_config,
50186
50339
  format: {
50187
50340
  type: "json_schema",
50188
50341
  schema: responseFormat.schema
@@ -50214,7 +50367,7 @@ var BedrockChatLanguageModel = class {
50214
50367
  details: "topK is not supported when thinking is enabled"
50215
50368
  });
50216
50369
  }
50217
- const hasAnyTools = ((_l = (_k = toolConfig.tools) == null ? undefined : _k.length) != null ? _l : 0) > 0 || additionalTools;
50370
+ const hasAnyTools = ((_m = (_l = toolConfig.tools) == null ? undefined : _l.length) != null ? _m : 0) > 0 || additionalTools;
50218
50371
  let filteredPrompt = prompt;
50219
50372
  if (!hasAnyTools) {
50220
50373
  const hasToolContent = prompt.some((message) => ("content" in message) && Array.isArray(message.content) && message.content.some((part) => part.type === "tool-call" || part.type === "tool-result"));
@@ -50235,6 +50388,7 @@ var BedrockChatLanguageModel = class {
50235
50388
  const {
50236
50389
  reasoningConfig: _,
50237
50390
  additionalModelRequestFields: __,
50391
+ serviceTier: ___,
50238
50392
  ...filteredBedrockOptions
50239
50393
  } = (providerOptions == null ? undefined : providerOptions.bedrock) || {};
50240
50394
  const additionalModelResponseFieldPaths = isAnthropicModel ? ["/delta/stop_sequence"] : undefined;
@@ -50249,6 +50403,11 @@ var BedrockChatLanguageModel = class {
50249
50403
  ...Object.keys(inferenceConfig).length > 0 && {
50250
50404
  inferenceConfig
50251
50405
  },
50406
+ ...bedrockOptions.serviceTier != null && {
50407
+ serviceTier: {
50408
+ type: bedrockOptions.serviceTier
50409
+ }
50410
+ },
50252
50411
  ...filteredBedrockOptions,
50253
50412
  ...toolConfig.tools !== undefined && toolConfig.tools.length > 0 ? { toolConfig } : {}
50254
50413
  },
@@ -50288,7 +50447,7 @@ var BedrockChatLanguageModel = class {
50288
50447
  const content = [];
50289
50448
  let isJsonResponseFromTool = false;
50290
50449
  for (const part of response.output.message.content) {
50291
- if (part.text) {
50450
+ if (part.text != null) {
50292
50451
  content.push({ type: "text", text: part.text });
50293
50452
  }
50294
50453
  if (part.reasoningContent) {
@@ -50575,6 +50734,13 @@ var BedrockChatLanguageModel = class {
50575
50734
  delta: reasoningContent.text
50576
50735
  });
50577
50736
  } else if ("signature" in reasoningContent && reasoningContent.signature) {
50737
+ if (contentBlocks[blockIndex] == null) {
50738
+ contentBlocks[blockIndex] = { type: "reasoning" };
50739
+ controller.enqueue({
50740
+ type: "reasoning-start",
50741
+ id: String(blockIndex)
50742
+ });
50743
+ }
50578
50744
  controller.enqueue({
50579
50745
  type: "reasoning-delta",
50580
50746
  id: String(blockIndex),
@@ -50586,6 +50752,13 @@ var BedrockChatLanguageModel = class {
50586
50752
  }
50587
50753
  });
50588
50754
  } else if ("data" in reasoningContent && reasoningContent.data) {
50755
+ if (contentBlocks[blockIndex] == null) {
50756
+ contentBlocks[blockIndex] = { type: "reasoning" };
50757
+ controller.enqueue({
50758
+ type: "reasoning-start",
50759
+ id: String(blockIndex)
50760
+ });
50761
+ }
50589
50762
  controller.enqueue({
50590
50763
  type: "reasoning-delta",
50591
50764
  id: String(blockIndex),
@@ -51098,7 +51271,7 @@ var bedrockImageResponseSchema = exports_external.object({
51098
51271
  details: exports_external.record(exports_external.string(), exports_external.unknown()).optional(),
51099
51272
  preview: exports_external.unknown().optional()
51100
51273
  });
51101
- var VERSION5 = "4.0.85";
51274
+ var VERSION5 = "4.0.96";
51102
51275
  function createSigV4FetchFunction(getCredentials, fetch2 = globalThis.fetch) {
51103
51276
  return async (input, init) => {
51104
51277
  var _a16, _b16;
@@ -51394,7 +51567,7 @@ function createBedrockProvider(config2, providerName) {
51394
51567
  }
51395
51568
 
51396
51569
  // node_modules/@ai-sdk/google/dist/index.mjs
51397
- var VERSION6 = "3.0.54";
51570
+ var VERSION6 = "3.0.64";
51398
51571
  var googleErrorDataSchema = lazySchema(() => zodSchema(exports_external.object({
51399
51572
  error: exports_external.object({
51400
51573
  code: exports_external.number().nullable(),
@@ -51773,7 +51946,7 @@ function appendLegacyToolResultParts(parts, toolName, outputValue) {
51773
51946
  }
51774
51947
  }
51775
51948
  function convertToGoogleGenerativeAIMessages(prompt, options) {
51776
- var _a16, _b16, _c, _d;
51949
+ var _a16, _b16, _c, _d, _e, _f, _g, _h;
51777
51950
  const systemInstructionParts = [];
51778
51951
  const contents = [];
51779
51952
  let systemMessagesAllowed = true;
@@ -51858,6 +52031,18 @@ function convertToGoogleGenerativeAIMessages(prompt, options) {
51858
52031
  };
51859
52032
  }
51860
52033
  case "tool-call": {
52034
+ const serverToolCallId = (providerOpts == null ? undefined : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : undefined;
52035
+ const serverToolType = (providerOpts == null ? undefined : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : undefined;
52036
+ if (serverToolCallId && serverToolType) {
52037
+ return {
52038
+ toolCall: {
52039
+ toolType: serverToolType,
52040
+ args: typeof part.input === "string" ? JSON.parse(part.input) : part.input,
52041
+ id: serverToolCallId
52042
+ },
52043
+ thoughtSignature
52044
+ };
52045
+ }
51861
52046
  return {
51862
52047
  functionCall: {
51863
52048
  name: part.toolName,
@@ -51866,6 +52051,21 @@ function convertToGoogleGenerativeAIMessages(prompt, options) {
51866
52051
  thoughtSignature
51867
52052
  };
51868
52053
  }
52054
+ case "tool-result": {
52055
+ const serverToolCallId = (providerOpts == null ? undefined : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : undefined;
52056
+ const serverToolType = (providerOpts == null ? undefined : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : undefined;
52057
+ if (serverToolCallId && serverToolType) {
52058
+ return {
52059
+ toolResponse: {
52060
+ toolType: serverToolType,
52061
+ response: part.output.type === "json" ? part.output.value : {},
52062
+ id: serverToolCallId
52063
+ },
52064
+ thoughtSignature
52065
+ };
52066
+ }
52067
+ return;
52068
+ }
51869
52069
  }
51870
52070
  }).filter((part) => part !== undefined)
51871
52071
  });
@@ -51878,6 +52078,26 @@ function convertToGoogleGenerativeAIMessages(prompt, options) {
51878
52078
  if (part.type === "tool-approval-response") {
51879
52079
  continue;
51880
52080
  }
52081
+ const partProviderOpts = (_g = (_d = part.providerOptions) == null ? undefined : _d[providerOptionsName]) != null ? _g : providerOptionsName !== "google" ? (_e = part.providerOptions) == null ? undefined : _e.google : (_f = part.providerOptions) == null ? undefined : _f.vertex;
52082
+ const serverToolCallId = (partProviderOpts == null ? undefined : partProviderOpts.serverToolCallId) != null ? String(partProviderOpts.serverToolCallId) : undefined;
52083
+ const serverToolType = (partProviderOpts == null ? undefined : partProviderOpts.serverToolType) != null ? String(partProviderOpts.serverToolType) : undefined;
52084
+ if (serverToolCallId && serverToolType) {
52085
+ const serverThoughtSignature = (partProviderOpts == null ? undefined : partProviderOpts.thoughtSignature) != null ? String(partProviderOpts.thoughtSignature) : undefined;
52086
+ if (contents.length > 0) {
52087
+ const lastContent = contents[contents.length - 1];
52088
+ if (lastContent.role === "model") {
52089
+ lastContent.parts.push({
52090
+ toolResponse: {
52091
+ toolType: serverToolType,
52092
+ response: part.output.type === "json" ? part.output.value : {},
52093
+ id: serverToolCallId
52094
+ },
52095
+ thoughtSignature: serverThoughtSignature
52096
+ });
52097
+ continue;
52098
+ }
52099
+ }
52100
+ }
51881
52101
  const output = part.output;
51882
52102
  if (output.type === "content") {
51883
52103
  if (supportsFunctionResponseParts) {
@@ -51891,7 +52111,7 @@ function convertToGoogleGenerativeAIMessages(prompt, options) {
51891
52111
  name: part.toolName,
51892
52112
  response: {
51893
52113
  name: part.toolName,
51894
- content: output.type === "execution-denied" ? (_d = output.reason) != null ? _d : "Tool execution denied." : output.value
52114
+ content: output.type === "execution-denied" ? (_h = output.reason) != null ? _h : "Tool execution denied." : output.value
51895
52115
  }
51896
52116
  }
51897
52117
  });
@@ -51989,18 +52209,20 @@ var googleLanguageModelOptions = lazySchema(() => zodSchema(exports_external.obj
51989
52209
  longitude: exports_external.number()
51990
52210
  }).optional()
51991
52211
  }).optional(),
51992
- serviceTier: exports_external.enum([
51993
- "SERVICE_TIER_STANDARD",
51994
- "SERVICE_TIER_FLEX",
51995
- "SERVICE_TIER_PRIORITY"
51996
- ]).optional()
52212
+ streamFunctionCallArguments: exports_external.boolean().optional(),
52213
+ serviceTier: exports_external.enum(["standard", "flex", "priority"]).optional()
51997
52214
  })));
52215
+ var VertexServiceTierMap = {
52216
+ standard: "SERVICE_TIER_STANDARD",
52217
+ flex: "SERVICE_TIER_FLEX",
52218
+ priority: "SERVICE_TIER_PRIORITY"
52219
+ };
51998
52220
  function prepareTools4({
51999
52221
  tools,
52000
52222
  toolChoice,
52001
52223
  modelId
52002
52224
  }) {
52003
- var _a16;
52225
+ var _a16, _b16;
52004
52226
  tools = (tools == null ? undefined : tools.length) ? tools : undefined;
52005
52227
  const toolWarnings = [];
52006
52228
  const isLatest = [
@@ -52009,13 +52231,14 @@ function prepareTools4({
52009
52231
  "gemini-pro-latest"
52010
52232
  ].some((id) => id === modelId);
52011
52233
  const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || modelId.includes("nano-banana") || isLatest;
52234
+ const isGemini3orNewer = modelId.includes("gemini-3");
52012
52235
  const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3");
52013
52236
  if (tools == null) {
52014
52237
  return { tools: undefined, toolConfig: undefined, toolWarnings };
52015
52238
  }
52016
52239
  const hasFunctionTools = tools.some((tool2) => tool2.type === "function");
52017
52240
  const hasProviderTools = tools.some((tool2) => tool2.type === "provider");
52018
- if (hasFunctionTools && hasProviderTools) {
52241
+ if (hasFunctionTools && hasProviderTools && !isGemini3orNewer) {
52019
52242
  toolWarnings.push({
52020
52243
  type: "unsupported",
52021
52244
  feature: `combination of function and provider-defined tools`
@@ -52066,7 +52289,7 @@ function prepareTools4({
52066
52289
  toolWarnings.push({
52067
52290
  type: "unsupported",
52068
52291
  feature: `provider-defined tool ${tool2.id}`,
52069
- details: "The code execution tools is not supported with other Gemini models than Gemini 2."
52292
+ details: "The code execution tool is not supported with other Gemini models than Gemini 2."
52070
52293
  });
52071
52294
  }
52072
52295
  break;
@@ -52120,6 +52343,45 @@ function prepareTools4({
52120
52343
  break;
52121
52344
  }
52122
52345
  });
52346
+ if (hasFunctionTools && isGemini3orNewer && googleTools2.length > 0) {
52347
+ const functionDeclarations2 = [];
52348
+ for (const tool2 of tools) {
52349
+ if (tool2.type === "function") {
52350
+ functionDeclarations2.push({
52351
+ name: tool2.name,
52352
+ description: (_a16 = tool2.description) != null ? _a16 : "",
52353
+ parameters: convertJSONSchemaToOpenAPISchema(tool2.inputSchema)
52354
+ });
52355
+ }
52356
+ }
52357
+ const combinedToolConfig = {
52358
+ functionCallingConfig: { mode: "VALIDATED" },
52359
+ includeServerSideToolInvocations: true
52360
+ };
52361
+ if (toolChoice != null) {
52362
+ switch (toolChoice.type) {
52363
+ case "auto":
52364
+ break;
52365
+ case "none":
52366
+ combinedToolConfig.functionCallingConfig = { mode: "NONE" };
52367
+ break;
52368
+ case "required":
52369
+ combinedToolConfig.functionCallingConfig = { mode: "ANY" };
52370
+ break;
52371
+ case "tool":
52372
+ combinedToolConfig.functionCallingConfig = {
52373
+ mode: "ANY",
52374
+ allowedFunctionNames: [toolChoice.toolName]
52375
+ };
52376
+ break;
52377
+ }
52378
+ }
52379
+ return {
52380
+ tools: [...googleTools2, { functionDeclarations: functionDeclarations2 }],
52381
+ toolConfig: combinedToolConfig,
52382
+ toolWarnings
52383
+ };
52384
+ }
52123
52385
  return {
52124
52386
  tools: googleTools2.length > 0 ? googleTools2 : undefined,
52125
52387
  toolConfig: undefined,
@@ -52133,7 +52395,7 @@ function prepareTools4({
52133
52395
  case "function":
52134
52396
  functionDeclarations.push({
52135
52397
  name: tool2.name,
52136
- description: (_a16 = tool2.description) != null ? _a16 : "",
52398
+ description: (_b16 = tool2.description) != null ? _b16 : "",
52137
52399
  parameters: convertJSONSchemaToOpenAPISchema(tool2.inputSchema)
52138
52400
  });
52139
52401
  if (tool2.strict === true) {
@@ -52202,6 +52464,172 @@ function prepareTools4({
52202
52464
  }
52203
52465
  }
52204
52466
  }
52467
+ var GoogleJSONAccumulator = class {
52468
+ constructor() {
52469
+ this.accumulatedArgs = {};
52470
+ this.jsonText = "";
52471
+ this.pathStack = [];
52472
+ this.stringOpen = false;
52473
+ }
52474
+ processPartialArgs(partialArgs) {
52475
+ let delta = "";
52476
+ for (const arg of partialArgs) {
52477
+ const rawPath = arg.jsonPath.replace(/^\$\./, "");
52478
+ if (!rawPath)
52479
+ continue;
52480
+ const segments = parsePath(rawPath);
52481
+ const existingValue = getNestedValue(this.accumulatedArgs, segments);
52482
+ const isStringContinuation = arg.stringValue != null && existingValue !== undefined;
52483
+ if (isStringContinuation) {
52484
+ const escaped = JSON.stringify(arg.stringValue).slice(1, -1);
52485
+ setNestedValue(this.accumulatedArgs, segments, existingValue + arg.stringValue);
52486
+ delta += escaped;
52487
+ continue;
52488
+ }
52489
+ const resolved = resolvePartialArgValue(arg);
52490
+ if (resolved == null)
52491
+ continue;
52492
+ setNestedValue(this.accumulatedArgs, segments, resolved.value);
52493
+ delta += this.emitNavigationTo(segments, arg, resolved.json);
52494
+ }
52495
+ this.jsonText += delta;
52496
+ return {
52497
+ currentJSON: this.accumulatedArgs,
52498
+ textDelta: delta
52499
+ };
52500
+ }
52501
+ finalize() {
52502
+ const finalArgs = JSON.stringify(this.accumulatedArgs);
52503
+ const closingDelta = finalArgs.slice(this.jsonText.length);
52504
+ return { finalJSON: finalArgs, closingDelta };
52505
+ }
52506
+ ensureRoot() {
52507
+ if (this.pathStack.length === 0) {
52508
+ this.pathStack.push({ segment: "", isArray: false, childCount: 0 });
52509
+ return "{";
52510
+ }
52511
+ return "";
52512
+ }
52513
+ emitNavigationTo(targetSegments, arg, valueJson) {
52514
+ let fragment = "";
52515
+ if (this.stringOpen) {
52516
+ fragment += '"';
52517
+ this.stringOpen = false;
52518
+ }
52519
+ fragment += this.ensureRoot();
52520
+ const targetContainerSegments = targetSegments.slice(0, -1);
52521
+ const leafSegment = targetSegments[targetSegments.length - 1];
52522
+ const commonDepth = this.findCommonStackDepth(targetContainerSegments);
52523
+ fragment += this.closeDownTo(commonDepth);
52524
+ fragment += this.openDownTo(targetContainerSegments, leafSegment);
52525
+ fragment += this.emitLeaf(leafSegment, arg, valueJson);
52526
+ return fragment;
52527
+ }
52528
+ findCommonStackDepth(targetContainer) {
52529
+ const maxDepth = Math.min(this.pathStack.length - 1, targetContainer.length);
52530
+ let common = 0;
52531
+ for (let i = 0;i < maxDepth; i++) {
52532
+ if (this.pathStack[i + 1].segment === targetContainer[i]) {
52533
+ common++;
52534
+ } else {
52535
+ break;
52536
+ }
52537
+ }
52538
+ return common + 1;
52539
+ }
52540
+ closeDownTo(targetDepth) {
52541
+ let fragment = "";
52542
+ while (this.pathStack.length > targetDepth) {
52543
+ const entry = this.pathStack.pop();
52544
+ fragment += entry.isArray ? "]" : "}";
52545
+ }
52546
+ return fragment;
52547
+ }
52548
+ openDownTo(targetContainer, leafSegment) {
52549
+ let fragment = "";
52550
+ const startIdx = this.pathStack.length - 1;
52551
+ for (let i = startIdx;i < targetContainer.length; i++) {
52552
+ const seg = targetContainer[i];
52553
+ const parentEntry = this.pathStack[this.pathStack.length - 1];
52554
+ if (parentEntry.childCount > 0) {
52555
+ fragment += ",";
52556
+ }
52557
+ parentEntry.childCount++;
52558
+ if (typeof seg === "string") {
52559
+ fragment += `${JSON.stringify(seg)}:`;
52560
+ }
52561
+ const childSeg = i + 1 < targetContainer.length ? targetContainer[i + 1] : leafSegment;
52562
+ const isArray = typeof childSeg === "number";
52563
+ fragment += isArray ? "[" : "{";
52564
+ this.pathStack.push({ segment: seg, isArray, childCount: 0 });
52565
+ }
52566
+ return fragment;
52567
+ }
52568
+ emitLeaf(leafSegment, arg, valueJson) {
52569
+ let fragment = "";
52570
+ const container = this.pathStack[this.pathStack.length - 1];
52571
+ if (container.childCount > 0) {
52572
+ fragment += ",";
52573
+ }
52574
+ container.childCount++;
52575
+ if (typeof leafSegment === "string") {
52576
+ fragment += `${JSON.stringify(leafSegment)}:`;
52577
+ }
52578
+ if (arg.stringValue != null && arg.willContinue) {
52579
+ fragment += valueJson.slice(0, -1);
52580
+ this.stringOpen = true;
52581
+ } else {
52582
+ fragment += valueJson;
52583
+ }
52584
+ return fragment;
52585
+ }
52586
+ };
52587
+ function parsePath(rawPath) {
52588
+ const segments = [];
52589
+ for (const part of rawPath.split(".")) {
52590
+ const bracketIdx = part.indexOf("[");
52591
+ if (bracketIdx === -1) {
52592
+ segments.push(part);
52593
+ } else {
52594
+ if (bracketIdx > 0)
52595
+ segments.push(part.slice(0, bracketIdx));
52596
+ for (const m of part.matchAll(/\[(\d+)\]/g)) {
52597
+ segments.push(parseInt(m[1], 10));
52598
+ }
52599
+ }
52600
+ }
52601
+ return segments;
52602
+ }
52603
+ function getNestedValue(obj, segments) {
52604
+ let current = obj;
52605
+ for (const seg of segments) {
52606
+ if (current == null || typeof current !== "object")
52607
+ return;
52608
+ current = current[seg];
52609
+ }
52610
+ return current;
52611
+ }
52612
+ function setNestedValue(obj, segments, value) {
52613
+ let current = obj;
52614
+ for (let i = 0;i < segments.length - 1; i++) {
52615
+ const seg = segments[i];
52616
+ const nextSeg = segments[i + 1];
52617
+ if (current[seg] == null) {
52618
+ current[seg] = typeof nextSeg === "number" ? [] : {};
52619
+ }
52620
+ current = current[seg];
52621
+ }
52622
+ current[segments[segments.length - 1]] = value;
52623
+ }
52624
+ function resolvePartialArgValue(arg) {
52625
+ var _a16, _b16;
52626
+ const value = (_b16 = (_a16 = arg.stringValue) != null ? _a16 : arg.numberValue) != null ? _b16 : arg.boolValue;
52627
+ if (value != null)
52628
+ return { value, json: JSON.stringify(value) };
52629
+ if ("nullValue" in arg)
52630
+ return { value: null, json: "null" };
52631
+ return;
52632
+ }
52205
52633
  function mapGoogleGenerativeAIFinishReason({
52206
52634
  finishReason,
52207
52635
  hasToolCalls
@@ -52255,8 +52683,8 @@ var GoogleGenerativeAILanguageModel = class {
52255
52683
  tools,
52256
52684
  toolChoice,
52257
52685
  providerOptions
52258
- }) {
52259
- var _a16;
52686
+ }, { isStreaming = false } = {}) {
52687
+ var _a16, _b16;
52260
52688
  const warnings = [];
52261
52689
  const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google";
52262
52690
  let googleOptions = await parseProviderOptions({
@@ -52271,12 +52699,23 @@ var GoogleGenerativeAILanguageModel = class {
52271
52699
  schema: googleLanguageModelOptions
52272
52700
  });
52273
52701
  }
52274
- if ((tools == null ? undefined : tools.some((tool2) => tool2.type === "provider" && tool2.id === "google.vertex_rag_store")) && !this.config.provider.startsWith("google.vertex.")) {
52702
+ const isVertexProvider = this.config.provider.startsWith("google.vertex.");
52703
+ if ((tools == null ? undefined : tools.some((tool2) => tool2.type === "provider" && tool2.id === "google.vertex_rag_store")) && !isVertexProvider) {
52275
52704
  warnings.push({
52276
52705
  type: "other",
52277
52706
  message: `The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`
52278
52707
  });
52279
52708
  }
52709
+ if ((googleOptions == null ? undefined : googleOptions.streamFunctionCallArguments) && !isVertexProvider) {
52710
+ warnings.push({
52711
+ type: "other",
52712
+ message: `'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`
52713
+ });
52714
+ }
52715
+ let sanitizedServiceTier = googleOptions == null ? undefined : googleOptions.serviceTier;
52716
+ if ((googleOptions == null ? undefined : googleOptions.serviceTier) && isVertexProvider) {
52717
+ sanitizedServiceTier = VertexServiceTierMap[googleOptions.serviceTier];
52718
+ }
52280
52719
  const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
52281
52720
  const supportsFunctionResponseParts = this.modelId.startsWith("gemini-3");
52282
52721
  const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(prompt, {
@@ -52293,6 +52732,19 @@ var GoogleGenerativeAILanguageModel = class {
52293
52732
  toolChoice,
52294
52733
  modelId: this.modelId
52295
52734
  });
52735
+ const streamFunctionCallArguments = isStreaming && isVertexProvider ? (_a16 = googleOptions == null ? undefined : googleOptions.streamFunctionCallArguments) != null ? _a16 : false : undefined;
52736
+ const toolConfig = googleToolConfig || streamFunctionCallArguments || (googleOptions == null ? undefined : googleOptions.retrievalConfig) ? {
52737
+ ...googleToolConfig,
52738
+ ...streamFunctionCallArguments && {
52739
+ functionCallingConfig: {
52740
+ ...googleToolConfig == null ? undefined : googleToolConfig.functionCallingConfig,
52741
+ streamFunctionCallArguments: true
52742
+ }
52743
+ },
52744
+ ...(googleOptions == null ? undefined : googleOptions.retrievalConfig) && {
52745
+ retrievalConfig: googleOptions.retrievalConfig
52746
+ }
52747
+ } : undefined;
52296
52748
  return {
52297
52749
  args: {
52298
52750
  generationConfig: {
@@ -52305,7 +52757,7 @@ var GoogleGenerativeAILanguageModel = class {
52305
52757
  stopSequences,
52306
52758
  seed,
52307
52759
  responseMimeType: (responseFormat == null ? undefined : responseFormat.type) === "json" ? "application/json" : undefined,
52308
- responseSchema: (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null && ((_a16 = googleOptions == null ? undefined : googleOptions.structuredOutputs) != null ? _a16 : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : undefined,
52760
+ responseSchema: (responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null && ((_b16 = googleOptions == null ? undefined : googleOptions.structuredOutputs) != null ? _b16 : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : undefined,
52309
52761
  ...(googleOptions == null ? undefined : googleOptions.audioTimestamp) && {
52310
52762
  audioTimestamp: googleOptions.audioTimestamp
52311
52763
  },
@@ -52322,20 +52774,17 @@ var GoogleGenerativeAILanguageModel = class {
52322
52774
  systemInstruction: isGemmaModel ? undefined : systemInstruction,
52323
52775
  safetySettings: googleOptions == null ? undefined : googleOptions.safetySettings,
52324
52776
  tools: googleTools2,
52325
- toolConfig: (googleOptions == null ? undefined : googleOptions.retrievalConfig) ? {
52326
- ...googleToolConfig,
52327
- retrievalConfig: googleOptions.retrievalConfig
52328
- } : googleToolConfig,
52777
+ toolConfig,
52329
52778
  cachedContent: googleOptions == null ? undefined : googleOptions.cachedContent,
52330
52779
  labels: googleOptions == null ? undefined : googleOptions.labels,
52331
- serviceTier: googleOptions == null ? undefined : googleOptions.serviceTier
52780
+ serviceTier: sanitizedServiceTier
52332
52781
  },
52333
52782
  warnings: [...warnings, ...toolWarnings],
52334
52783
  providerOptionsName
52335
52784
  };
52336
52785
  }
52337
52786
  async doGenerate(options) {
52338
- var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
52787
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
52339
52788
  const { args, warnings, providerOptionsName } = await this.getArgs(options);
52340
52789
  const mergedHeaders = combineHeaders(await resolve(this.config.headers), options.headers);
52341
52790
  const {
@@ -52356,6 +52805,7 @@ var GoogleGenerativeAILanguageModel = class {
52356
52805
  const parts = (_b16 = (_a16 = candidate.content) == null ? undefined : _a16.parts) != null ? _b16 : [];
52357
52806
  const usageMetadata = response.usageMetadata;
52358
52807
  let lastCodeExecutionToolCallId;
52808
+ let lastServerToolCallId;
52359
52809
  for (const part of parts) {
52360
52810
  if ("executableCode" in part && ((_c = part.executableCode) == null ? undefined : _c.code)) {
52361
52811
  const toolCallId = this.config.generateId();
@@ -52396,7 +52846,7 @@ var GoogleGenerativeAILanguageModel = class {
52396
52846
  providerMetadata: thoughtSignatureMetadata
52397
52847
  });
52398
52848
  }
52399
- } else if ("functionCall" in part) {
52849
+ } else if ("functionCall" in part && part.functionCall.name != null && part.functionCall.args != null) {
52400
52850
  content.push({
52401
52851
  type: "tool-call",
52402
52852
  toolCallId: this.config.generateId(),
@@ -52422,12 +52872,56 @@ var GoogleGenerativeAILanguageModel = class {
52422
52872
  }
52423
52873
  } : undefined
52424
52874
  });
52875
+ } else if ("toolCall" in part && part.toolCall) {
52876
+ const toolCallId = (_e = part.toolCall.id) != null ? _e : this.config.generateId();
52877
+ lastServerToolCallId = toolCallId;
52878
+ content.push({
52879
+ type: "tool-call",
52880
+ toolCallId,
52881
+ toolName: `server:${part.toolCall.toolType}`,
52882
+ input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
52883
+ providerExecuted: true,
52884
+ dynamic: true,
52885
+ providerMetadata: part.thoughtSignature ? {
52886
+ [providerOptionsName]: {
52887
+ thoughtSignature: part.thoughtSignature,
52888
+ serverToolCallId: toolCallId,
52889
+ serverToolType: part.toolCall.toolType
52890
+ }
52891
+ } : {
52892
+ [providerOptionsName]: {
52893
+ serverToolCallId: toolCallId,
52894
+ serverToolType: part.toolCall.toolType
52895
+ }
52896
+ }
52897
+ });
52898
+ } else if ("toolResponse" in part && part.toolResponse) {
52899
+ const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : this.config.generateId();
52900
+ content.push({
52901
+ type: "tool-result",
52902
+ toolCallId: responseToolCallId,
52903
+ toolName: `server:${part.toolResponse.toolType}`,
52904
+ result: (_h = part.toolResponse.response) != null ? _h : {},
52905
+ providerMetadata: part.thoughtSignature ? {
52906
+ [providerOptionsName]: {
52907
+ thoughtSignature: part.thoughtSignature,
52908
+ serverToolCallId: responseToolCallId,
52909
+ serverToolType: part.toolResponse.toolType
52910
+ }
52911
+ } : {
52912
+ [providerOptionsName]: {
52913
+ serverToolCallId: responseToolCallId,
52914
+ serverToolType: part.toolResponse.toolType
52915
+ }
52916
+ }
52917
+ });
52918
+ lastServerToolCallId = undefined;
52425
52919
  }
52426
52920
  }
52427
- const sources = (_e = extractSources({
52921
+ const sources = (_i = extractSources({
52428
52922
  groundingMetadata: candidate.groundingMetadata,
52429
52923
  generateId: this.config.generateId
52430
- })) != null ? _e : [];
52924
+ })) != null ? _i : [];
52431
52925
  for (const source of sources) {
52432
52926
  content.push(source);
52433
52927
  }
@@ -52438,19 +52932,19 @@ var GoogleGenerativeAILanguageModel = class {
52438
52932
  finishReason: candidate.finishReason,
52439
52933
  hasToolCalls: content.some((part) => part.type === "tool-call" && !part.providerExecuted)
52440
52934
  }),
52441
- raw: (_f = candidate.finishReason) != null ? _f : undefined
52935
+ raw: (_j = candidate.finishReason) != null ? _j : undefined
52442
52936
  },
52443
52937
  usage: convertGoogleGenerativeAIUsage(usageMetadata),
52444
52938
  warnings,
52445
52939
  providerMetadata: {
52446
52940
  [providerOptionsName]: {
52447
- promptFeedback: (_g = response.promptFeedback) != null ? _g : null,
52448
- groundingMetadata: (_h = candidate.groundingMetadata) != null ? _h : null,
52449
- urlContextMetadata: (_i = candidate.urlContextMetadata) != null ? _i : null,
52450
- safetyRatings: (_j = candidate.safetyRatings) != null ? _j : null,
52941
+ promptFeedback: (_k = response.promptFeedback) != null ? _k : null,
52942
+ groundingMetadata: (_l = candidate.groundingMetadata) != null ? _l : null,
52943
+ urlContextMetadata: (_m = candidate.urlContextMetadata) != null ? _m : null,
52944
+ safetyRatings: (_n = candidate.safetyRatings) != null ? _n : null,
52451
52945
  usageMetadata: usageMetadata != null ? usageMetadata : null,
52452
- finishMessage: (_k = candidate.finishMessage) != null ? _k : null,
52453
- serviceTier: (_l = response.serviceTier) != null ? _l : null
52946
+ finishMessage: (_o = candidate.finishMessage) != null ? _o : null,
52947
+ serviceTier: (_p = response.serviceTier) != null ? _p : null
52454
52948
  }
52455
52949
  },
52456
52950
  request: { body: args },
@@ -52461,7 +52955,7 @@ var GoogleGenerativeAILanguageModel = class {
52461
52955
  };
52462
52956
  }
52463
52957
  async doStream(options) {
52464
- const { args, warnings, providerOptionsName } = await this.getArgs(options);
52958
+ const { args, warnings, providerOptionsName } = await this.getArgs(options, { isStreaming: true });
52465
52959
  const headers = combineHeaders(await resolve(this.config.headers), options.headers);
52466
52960
  const { responseHeaders, value: response } = await postJsonToApi({
52467
52961
  url: `${this.config.baseURL}/${getModelPath(this.modelId)}:streamGenerateContent?alt=sse`,
@@ -52488,13 +52982,15 @@ var GoogleGenerativeAILanguageModel = class {
52488
52982
  let blockCounter = 0;
52489
52983
  const emittedSourceUrls = /* @__PURE__ */ new Set;
52490
52984
  let lastCodeExecutionToolCallId;
52985
+ let lastServerToolCallId;
52986
+ const activeStreamingToolCalls = [];
52491
52987
  return {
52492
52988
  stream: response.pipeThrough(new TransformStream({
52493
52989
  start(controller) {
52494
52990
  controller.enqueue({ type: "stream-start", warnings });
52495
52991
  },
52496
52992
  transform(chunk, controller) {
52497
- var _a16, _b16, _c, _d, _e, _f, _g;
52993
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
52498
52994
  if (options.includeRawChunks) {
52499
52995
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
52500
52996
  }
@@ -52649,38 +53145,145 @@ var GoogleGenerativeAILanguageModel = class {
52649
53145
  data: part.inlineData.data,
52650
53146
  providerMetadata: fileMeta
52651
53147
  });
53148
+ } else if ("toolCall" in part && part.toolCall) {
53149
+ const toolCallId = (_e = part.toolCall.id) != null ? _e : generateId3();
53150
+ lastServerToolCallId = toolCallId;
53151
+ const serverMeta = {
53152
+ [providerOptionsName]: {
53153
+ ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
53154
+ serverToolCallId: toolCallId,
53155
+ serverToolType: part.toolCall.toolType
53156
+ }
53157
+ };
53158
+ controller.enqueue({
53159
+ type: "tool-call",
53160
+ toolCallId,
53161
+ toolName: `server:${part.toolCall.toolType}`,
53162
+ input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
53163
+ providerExecuted: true,
53164
+ dynamic: true,
53165
+ providerMetadata: serverMeta
53166
+ });
53167
+ } else if ("toolResponse" in part && part.toolResponse) {
53168
+ const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : generateId3();
53169
+ const serverMeta = {
53170
+ [providerOptionsName]: {
53171
+ ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
53172
+ serverToolCallId: responseToolCallId,
53173
+ serverToolType: part.toolResponse.toolType
53174
+ }
53175
+ };
53176
+ controller.enqueue({
53177
+ type: "tool-result",
53178
+ toolCallId: responseToolCallId,
53179
+ toolName: `server:${part.toolResponse.toolType}`,
53180
+ result: (_h = part.toolResponse.response) != null ? _h : {},
53181
+ providerMetadata: serverMeta
53182
+ });
53183
+ lastServerToolCallId = undefined;
52652
53184
  }
52653
53185
  }
52654
- const toolCallDeltas = getToolCallsFromParts({
52655
- parts: content.parts,
52656
- generateId: generateId3,
52657
- providerOptionsName
52658
- });
52659
- if (toolCallDeltas != null) {
52660
- for (const toolCall of toolCallDeltas) {
53186
+ for (const part of parts) {
53187
+ if (!("functionCall" in part))
53188
+ continue;
53189
+ const providerMeta = part.thoughtSignature ? {
53190
+ [providerOptionsName]: {
53191
+ thoughtSignature: part.thoughtSignature
53192
+ }
53193
+ } : undefined;
53194
+ const isStreamingChunk = part.functionCall.partialArgs != null || part.functionCall.name != null && part.functionCall.willContinue === true;
53195
+ const isTerminalChunk = part.functionCall.name == null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue == null;
53196
+ const isCompleteCall = part.functionCall.name != null && part.functionCall.args != null && part.functionCall.partialArgs == null;
53197
+ if (isStreamingChunk) {
53198
+ if (part.functionCall.name != null && part.functionCall.willContinue === true) {
53199
+ const toolCallId = generateId3();
53200
+ const accumulator = new GoogleJSONAccumulator;
53201
+ activeStreamingToolCalls.push({
53202
+ toolCallId,
53203
+ toolName: part.functionCall.name,
53204
+ accumulator,
53205
+ providerMetadata: providerMeta
53206
+ });
53207
+ controller.enqueue({
53208
+ type: "tool-input-start",
53209
+ id: toolCallId,
53210
+ toolName: part.functionCall.name,
53211
+ providerMetadata: providerMeta
53212
+ });
53213
+ if (part.functionCall.partialArgs != null) {
53214
+ const { textDelta } = accumulator.processPartialArgs(part.functionCall.partialArgs);
53215
+ if (textDelta.length > 0) {
53216
+ controller.enqueue({
53217
+ type: "tool-input-delta",
53218
+ id: toolCallId,
53219
+ delta: textDelta,
53220
+ providerMetadata: providerMeta
53221
+ });
53222
+ }
53223
+ }
53224
+ } else if (part.functionCall.partialArgs != null && activeStreamingToolCalls.length > 0) {
53225
+ const active = activeStreamingToolCalls[activeStreamingToolCalls.length - 1];
53226
+ const { textDelta } = active.accumulator.processPartialArgs(part.functionCall.partialArgs);
53227
+ if (textDelta.length > 0) {
53228
+ controller.enqueue({
53229
+ type: "tool-input-delta",
53230
+ id: active.toolCallId,
53231
+ delta: textDelta,
53232
+ providerMetadata: providerMeta
53233
+ });
53234
+ }
53235
+ }
53236
+ } else if (isTerminalChunk && activeStreamingToolCalls.length > 0) {
53237
+ const active = activeStreamingToolCalls.pop();
53238
+ const { finalJSON, closingDelta } = active.accumulator.finalize();
53239
+ if (closingDelta.length > 0) {
53240
+ controller.enqueue({
53241
+ type: "tool-input-delta",
53242
+ id: active.toolCallId,
53243
+ delta: closingDelta,
53244
+ providerMetadata: active.providerMetadata
53245
+ });
53246
+ }
53247
+ controller.enqueue({
53248
+ type: "tool-input-end",
53249
+ id: active.toolCallId,
53250
+ providerMetadata: active.providerMetadata
53251
+ });
53252
+ controller.enqueue({
53253
+ type: "tool-call",
53254
+ toolCallId: active.toolCallId,
53255
+ toolName: active.toolName,
53256
+ input: finalJSON,
53257
+ providerMetadata: active.providerMetadata
53258
+ });
53259
+ hasToolCalls = true;
53260
+ } else if (isCompleteCall) {
53261
+ const toolCallId = generateId3();
53262
+ const toolName = part.functionCall.name;
53263
+ const args2 = typeof part.functionCall.args === "string" ? part.functionCall.args : JSON.stringify((_i = part.functionCall.args) != null ? _i : {});
52661
53264
  controller.enqueue({
52662
53265
  type: "tool-input-start",
52663
- id: toolCall.toolCallId,
52664
- toolName: toolCall.toolName,
52665
- providerMetadata: toolCall.providerMetadata
53266
+ id: toolCallId,
53267
+ toolName,
53268
+ providerMetadata: providerMeta
52666
53269
  });
52667
53270
  controller.enqueue({
52668
53271
  type: "tool-input-delta",
52669
- id: toolCall.toolCallId,
52670
- delta: toolCall.args,
52671
- providerMetadata: toolCall.providerMetadata
53272
+ id: toolCallId,
53273
+ delta: args2,
53274
+ providerMetadata: providerMeta
52672
53275
  });
52673
53276
  controller.enqueue({
52674
53277
  type: "tool-input-end",
52675
- id: toolCall.toolCallId,
52676
- providerMetadata: toolCall.providerMetadata
53278
+ id: toolCallId,
53279
+ providerMetadata: providerMeta
52677
53280
  });
52678
53281
  controller.enqueue({
52679
53282
  type: "tool-call",
52680
- toolCallId: toolCall.toolCallId,
52681
- toolName: toolCall.toolName,
52682
- input: toolCall.args,
52683
- providerMetadata: toolCall.providerMetadata
53283
+ toolCallId,
53284
+ toolName,
53285
+ input: args2,
53286
+ providerMetadata: providerMeta
52684
53287
  });
52685
53288
  hasToolCalls = true;
52686
53289
  }
@@ -52696,12 +53299,12 @@ var GoogleGenerativeAILanguageModel = class {
52696
53299
  };
52697
53300
  providerMetadata = {
52698
53301
  [providerOptionsName]: {
52699
- promptFeedback: (_e = value.promptFeedback) != null ? _e : null,
53302
+ promptFeedback: (_j = value.promptFeedback) != null ? _j : null,
52700
53303
  groundingMetadata: lastGroundingMetadata,
52701
53304
  urlContextMetadata: lastUrlContextMetadata,
52702
- safetyRatings: (_f = candidate.safetyRatings) != null ? _f : null,
53305
+ safetyRatings: (_k = candidate.safetyRatings) != null ? _k : null,
52703
53306
  usageMetadata: usageMetadata != null ? usageMetadata : null,
52704
- finishMessage: (_g = candidate.finishMessage) != null ? _g : null,
53307
+ finishMessage: (_l = candidate.finishMessage) != null ? _l : null,
52705
53308
  serviceTier
52706
53309
  }
52707
53310
  };
@@ -52733,24 +53336,6 @@ var GoogleGenerativeAILanguageModel = class {
52733
53336
  };
52734
53337
  }
52735
53338
  };
52736
- function getToolCallsFromParts({
52737
- parts,
52738
- generateId: generateId3,
52739
- providerOptionsName
52740
- }) {
52741
- const functionCallParts = parts == null ? undefined : parts.filter((part) => ("functionCall" in part));
52742
- return functionCallParts == null || functionCallParts.length === 0 ? undefined : functionCallParts.map((part) => ({
52743
- type: "tool-call",
52744
- toolCallId: generateId3(),
52745
- toolName: part.functionCall.name,
52746
- args: JSON.stringify(part.functionCall.args),
52747
- providerMetadata: part.thoughtSignature ? {
52748
- [providerOptionsName]: {
52749
- thoughtSignature: part.thoughtSignature
52750
- }
52751
- } : undefined
52752
- }));
52753
- }
52754
53339
  function extractSources({
52755
53340
  groundingMetadata,
52756
53341
  generateId: generateId3
@@ -52888,12 +53473,22 @@ var getGroundingMetadataSchema = () => exports_external.object({
52888
53473
  exports_external.object({})
52889
53474
  ]).nullish()
52890
53475
  });
53476
+ var partialArgSchema = exports_external.object({
53477
+ jsonPath: exports_external.string(),
53478
+ stringValue: exports_external.string().nullish(),
53479
+ numberValue: exports_external.number().nullish(),
53480
+ boolValue: exports_external.boolean().nullish(),
53481
+ nullValue: exports_external.unknown().nullish(),
53482
+ willContinue: exports_external.boolean().nullish()
53483
+ });
52891
53484
  var getContentSchema = () => exports_external.object({
52892
53485
  parts: exports_external.array(exports_external.union([
52893
53486
  exports_external.object({
52894
53487
  functionCall: exports_external.object({
52895
- name: exports_external.string(),
52896
- args: exports_external.unknown()
53488
+ name: exports_external.string().nullish(),
53489
+ args: exports_external.unknown().nullish(),
53490
+ partialArgs: exports_external.array(partialArgSchema).nullish(),
53491
+ willContinue: exports_external.boolean().nullish()
52897
53492
  }),
52898
53493
  thoughtSignature: exports_external.string().nullish()
52899
53494
  }),
@@ -52905,6 +53500,22 @@ var getContentSchema = () => exports_external.object({
52905
53500
  thought: exports_external.boolean().nullish(),
52906
53501
  thoughtSignature: exports_external.string().nullish()
52907
53502
  }),
53503
+ exports_external.object({
53504
+ toolCall: exports_external.object({
53505
+ toolType: exports_external.string(),
53506
+ args: exports_external.unknown().nullish(),
53507
+ id: exports_external.string()
53508
+ }),
53509
+ thoughtSignature: exports_external.string().nullish()
53510
+ }),
53511
+ exports_external.object({
53512
+ toolResponse: exports_external.object({
53513
+ toolType: exports_external.string(),
53514
+ response: exports_external.unknown().nullish(),
53515
+ id: exports_external.string()
53516
+ }),
53517
+ thoughtSignature: exports_external.string().nullish()
53518
+ }),
52908
53519
  exports_external.object({
52909
53520
  executableCode: exports_external.object({
52910
53521
  language: exports_external.string(),
@@ -52928,13 +53539,19 @@ var getSafetyRatingSchema = () => exports_external.object({
52928
53539
  severityScore: exports_external.number().nullish(),
52929
53540
  blocked: exports_external.boolean().nullish()
52930
53541
  });
53542
+ var tokenDetailsSchema = exports_external.array(exports_external.object({
53543
+ modality: exports_external.string(),
53544
+ tokenCount: exports_external.number()
53545
+ })).nullish();
52931
53546
  var usageSchema = exports_external.object({
52932
53547
  cachedContentTokenCount: exports_external.number().nullish(),
52933
53548
  thoughtsTokenCount: exports_external.number().nullish(),
52934
53549
  promptTokenCount: exports_external.number().nullish(),
52935
53550
  candidatesTokenCount: exports_external.number().nullish(),
52936
53551
  totalTokenCount: exports_external.number().nullish(),
52937
- trafficType: exports_external.string().nullish()
53552
+ trafficType: exports_external.string().nullish(),
53553
+ promptTokensDetails: tokenDetailsSchema,
53554
+ candidatesTokensDetails: tokenDetailsSchema
52938
53555
  });
52939
53556
  var getUrlContextMetadataSchema = () => exports_external.object({
52940
53557
  urlMetadata: exports_external.array(exports_external.object({
@@ -53733,7 +54350,7 @@ var groqLanguageModelOptions = exports_external.object({
53733
54350
  user: exports_external.string().optional(),
53734
54351
  structuredOutputs: exports_external.boolean().optional(),
53735
54352
  strictJsonSchema: exports_external.boolean().optional(),
53736
- serviceTier: exports_external.enum(["on_demand", "flex", "auto"]).optional()
54353
+ serviceTier: exports_external.enum(["on_demand", "performance", "flex", "auto"]).optional()
53737
54354
  });
53738
54355
  var groqErrorDataSchema = exports_external.object({
53739
54356
  error: exports_external.object({
@@ -54293,178 +54910,1750 @@ var GroqTranscriptionModel = class {
54293
54910
  this.config = config2;
54294
54911
  this.specificationVersion = "v3";
54295
54912
  }
54296
- get provider() {
54297
- return this.config.provider;
54913
+ get provider() {
54914
+ return this.config.provider;
54915
+ }
54916
+ async getArgs({
54917
+ audio,
54918
+ mediaType,
54919
+ providerOptions
54920
+ }) {
54921
+ var _a16, _b16, _c, _d, _e;
54922
+ const warnings = [];
54923
+ const groqOptions = await parseProviderOptions({
54924
+ provider: "groq",
54925
+ providerOptions,
54926
+ schema: groqTranscriptionModelOptions
54927
+ });
54928
+ const formData = new FormData;
54929
+ const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]);
54930
+ formData.append("model", this.modelId);
54931
+ const fileExtension = mediaTypeToExtension(mediaType);
54932
+ formData.append("file", new File([blob], "audio", { type: mediaType }), `audio.${fileExtension}`);
54933
+ if (groqOptions) {
54934
+ const transcriptionModelOptions = {
54935
+ language: (_a16 = groqOptions.language) != null ? _a16 : undefined,
54936
+ prompt: (_b16 = groqOptions.prompt) != null ? _b16 : undefined,
54937
+ response_format: (_c = groqOptions.responseFormat) != null ? _c : undefined,
54938
+ temperature: (_d = groqOptions.temperature) != null ? _d : undefined,
54939
+ timestamp_granularities: (_e = groqOptions.timestampGranularities) != null ? _e : undefined
54940
+ };
54941
+ for (const key in transcriptionModelOptions) {
54942
+ const value = transcriptionModelOptions[key];
54943
+ if (value !== undefined) {
54944
+ if (Array.isArray(value)) {
54945
+ for (const item of value) {
54946
+ formData.append(`${key}[]`, String(item));
54947
+ }
54948
+ } else {
54949
+ formData.append(key, String(value));
54950
+ }
54951
+ }
54952
+ }
54953
+ }
54954
+ return {
54955
+ formData,
54956
+ warnings
54957
+ };
54958
+ }
54959
+ async doGenerate(options) {
54960
+ var _a16, _b16, _c, _d, _e, _f, _g;
54961
+ const currentDate = (_c = (_b16 = (_a16 = this.config._internal) == null ? undefined : _a16.currentDate) == null ? undefined : _b16.call(_a16)) != null ? _c : /* @__PURE__ */ new Date;
54962
+ const { formData, warnings } = await this.getArgs(options);
54963
+ const {
54964
+ value: response,
54965
+ responseHeaders,
54966
+ rawValue: rawResponse
54967
+ } = await postFormDataToApi({
54968
+ url: this.config.url({
54969
+ path: "/audio/transcriptions",
54970
+ modelId: this.modelId
54971
+ }),
54972
+ headers: combineHeaders(this.config.headers(), options.headers),
54973
+ formData,
54974
+ failedResponseHandler: groqFailedResponseHandler,
54975
+ successfulResponseHandler: createJsonResponseHandler(groqTranscriptionResponseSchema),
54976
+ abortSignal: options.abortSignal,
54977
+ fetch: this.config.fetch
54978
+ });
54979
+ return {
54980
+ text: response.text,
54981
+ segments: (_e = (_d = response.segments) == null ? undefined : _d.map((segment) => ({
54982
+ text: segment.text,
54983
+ startSecond: segment.start,
54984
+ endSecond: segment.end
54985
+ }))) != null ? _e : [],
54986
+ language: (_f = response.language) != null ? _f : undefined,
54987
+ durationInSeconds: (_g = response.duration) != null ? _g : undefined,
54988
+ warnings,
54989
+ response: {
54990
+ timestamp: currentDate,
54991
+ modelId: this.modelId,
54992
+ headers: responseHeaders,
54993
+ body: rawResponse
54994
+ }
54995
+ };
54996
+ }
54997
+ };
54998
+ var groqTranscriptionResponseSchema = exports_external.object({
54999
+ text: exports_external.string(),
55000
+ x_groq: exports_external.object({
55001
+ id: exports_external.string()
55002
+ }),
55003
+ task: exports_external.string().nullish(),
55004
+ language: exports_external.string().nullish(),
55005
+ duration: exports_external.number().nullish(),
55006
+ segments: exports_external.array(exports_external.object({
55007
+ id: exports_external.number(),
55008
+ seek: exports_external.number(),
55009
+ start: exports_external.number(),
55010
+ end: exports_external.number(),
55011
+ text: exports_external.string(),
55012
+ tokens: exports_external.array(exports_external.number()),
55013
+ temperature: exports_external.number(),
55014
+ avg_logprob: exports_external.number(),
55015
+ compression_ratio: exports_external.number(),
55016
+ no_speech_prob: exports_external.number()
55017
+ })).nullish()
55018
+ });
55019
+ var browserSearch = createProviderToolFactory({
55020
+ id: "groq.browser_search",
55021
+ inputSchema: exports_external.object({})
55022
+ });
55023
+ var groqTools = {
55024
+ browserSearch
55025
+ };
55026
+ var VERSION7 = "3.0.35";
55027
+ function createGroq(options = {}) {
55028
+ var _a16;
55029
+ const baseURL = (_a16 = withoutTrailingSlash(options.baseURL)) != null ? _a16 : "https://api.groq.com/openai/v1";
55030
+ const getHeaders = () => withUserAgentSuffix({
55031
+ Authorization: `Bearer ${loadApiKey({
55032
+ apiKey: options.apiKey,
55033
+ environmentVariableName: "GROQ_API_KEY",
55034
+ description: "Groq"
55035
+ })}`,
55036
+ ...options.headers
55037
+ }, `ai-sdk/groq/${VERSION7}`);
55038
+ const createChatModel = (modelId) => new GroqChatLanguageModel(modelId, {
55039
+ provider: "groq.chat",
55040
+ url: ({ path: path2 }) => `${baseURL}${path2}`,
55041
+ headers: getHeaders,
55042
+ fetch: options.fetch
55043
+ });
55044
+ const createLanguageModel = (modelId) => {
55045
+ if (new.target) {
55046
+ throw new Error("The Groq model function cannot be called with the new keyword.");
55047
+ }
55048
+ return createChatModel(modelId);
55049
+ };
55050
+ const createTranscriptionModel = (modelId) => {
55051
+ return new GroqTranscriptionModel(modelId, {
55052
+ provider: "groq.transcription",
55053
+ url: ({ path: path2 }) => `${baseURL}${path2}`,
55054
+ headers: getHeaders,
55055
+ fetch: options.fetch
55056
+ });
55057
+ };
55058
+ const provider = function(modelId) {
55059
+ return createLanguageModel(modelId);
55060
+ };
55061
+ provider.specificationVersion = "v3";
55062
+ provider.languageModel = createLanguageModel;
55063
+ provider.chat = createChatModel;
55064
+ provider.embeddingModel = (modelId) => {
55065
+ throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
55066
+ };
55067
+ provider.textEmbeddingModel = provider.embeddingModel;
55068
+ provider.imageModel = (modelId) => {
55069
+ throw new NoSuchModelError({ modelId, modelType: "imageModel" });
55070
+ };
55071
+ provider.transcription = createTranscriptionModel;
55072
+ provider.transcriptionModel = createTranscriptionModel;
55073
+ provider.tools = groqTools;
55074
+ return provider;
55075
+ }
55076
+ var groq = createGroq();
55077
+
55078
+ // src/providers/groq.ts
55079
+ function createGroqProvider(config2, providerName) {
55080
+ return createGroq({
55081
+ apiKey: resolveApiKey(config2.api_key_env, providerName),
55082
+ baseURL: config2.base_url,
55083
+ headers: config2.headers
55084
+ });
55085
+ }
55086
+
55087
+ // node_modules/ollama-ai-provider-v2/node_modules/@ai-sdk/provider-utils/dist/index.mjs
55088
+ function combineHeaders2(...headers) {
55089
+ return headers.reduce((combinedHeaders, currentHeaders) => ({
55090
+ ...combinedHeaders,
55091
+ ...currentHeaders != null ? currentHeaders : {}
55092
+ }), {});
55093
+ }
55094
+ function extractResponseHeaders2(response) {
55095
+ return Object.fromEntries([...response.headers]);
55096
+ }
55097
+ var name16 = "AI_DownloadError";
55098
+ var marker17 = `vercel.ai.error.${name16}`;
55099
+ var symbol17 = Symbol.for(marker17);
55100
+ var _a17;
55101
+ var _b17;
55102
+ var DownloadError2 = class extends (_b17 = AISDKError, _a17 = symbol17, _b17) {
55103
+ constructor({
55104
+ url: url2,
55105
+ statusCode,
55106
+ statusText,
55107
+ cause,
55108
+ message = cause == null ? `Failed to download ${url2}: ${statusCode} ${statusText}` : `Failed to download ${url2}: ${cause}`
55109
+ }) {
55110
+ super({ name: name16, message, cause });
55111
+ this[_a17] = true;
55112
+ this.url = url2;
55113
+ this.statusCode = statusCode;
55114
+ this.statusText = statusText;
55115
+ }
55116
+ static isInstance(error48) {
55117
+ return AISDKError.hasMarker(error48, marker17);
55118
+ }
55119
+ };
55120
+ var DEFAULT_MAX_DOWNLOAD_SIZE2 = 2 * 1024 * 1024 * 1024;
55121
+ var createIdGenerator2 = ({
55122
+ prefix,
55123
+ size = 16,
55124
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
55125
+ separator = "-"
55126
+ } = {}) => {
55127
+ const generator = () => {
55128
+ const alphabetLength = alphabet.length;
55129
+ const chars = new Array(size);
55130
+ for (let i = 0;i < size; i++) {
55131
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
55132
+ }
55133
+ return chars.join("");
55134
+ };
55135
+ if (prefix == null) {
55136
+ return generator;
55137
+ }
55138
+ if (alphabet.includes(separator)) {
55139
+ throw new InvalidArgumentError({
55140
+ argument: "separator",
55141
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
55142
+ });
55143
+ }
55144
+ return () => `${prefix}${separator}${generator()}`;
55145
+ };
55146
+ var generateId2 = createIdGenerator2();
55147
+ function isAbortError2(error48) {
55148
+ return (error48 instanceof Error || error48 instanceof DOMException) && (error48.name === "AbortError" || error48.name === "ResponseAborted" || error48.name === "TimeoutError");
55149
+ }
55150
+ var FETCH_FAILED_ERROR_MESSAGES2 = ["fetch failed", "failed to fetch"];
55151
+ var BUN_ERROR_CODES2 = [
55152
+ "ConnectionRefused",
55153
+ "ConnectionClosed",
55154
+ "FailedToOpenSocket",
55155
+ "ECONNRESET",
55156
+ "ECONNREFUSED",
55157
+ "ETIMEDOUT",
55158
+ "EPIPE"
55159
+ ];
55160
+ function isBunNetworkError2(error48) {
55161
+ if (!(error48 instanceof Error)) {
55162
+ return false;
55163
+ }
55164
+ const code = error48.code;
55165
+ if (typeof code === "string" && BUN_ERROR_CODES2.includes(code)) {
55166
+ return true;
55167
+ }
55168
+ return false;
55169
+ }
55170
+ function handleFetchError2({
55171
+ error: error48,
55172
+ url: url2,
55173
+ requestBodyValues
55174
+ }) {
55175
+ if (isAbortError2(error48)) {
55176
+ return error48;
55177
+ }
55178
+ if (error48 instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES2.includes(error48.message.toLowerCase())) {
55179
+ const cause = error48.cause;
55180
+ if (cause != null) {
55181
+ return new APICallError({
55182
+ message: `Cannot connect to API: ${cause.message}`,
55183
+ cause,
55184
+ url: url2,
55185
+ requestBodyValues,
55186
+ isRetryable: true
55187
+ });
55188
+ }
55189
+ }
55190
+ if (isBunNetworkError2(error48)) {
55191
+ return new APICallError({
55192
+ message: `Cannot connect to API: ${error48.message}`,
55193
+ cause: error48,
55194
+ url: url2,
55195
+ requestBodyValues,
55196
+ isRetryable: true
55197
+ });
55198
+ }
55199
+ return error48;
55200
+ }
55201
+ function getRuntimeEnvironmentUserAgent2(globalThisAny = globalThis) {
55202
+ var _a23, _b22, _c;
55203
+ if (globalThisAny.window) {
55204
+ return `runtime/browser`;
55205
+ }
55206
+ if ((_a23 = globalThisAny.navigator) == null ? undefined : _a23.userAgent) {
55207
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
55208
+ }
55209
+ if ((_c = (_b22 = globalThisAny.process) == null ? undefined : _b22.versions) == null ? undefined : _c.node) {
55210
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
55211
+ }
55212
+ if (globalThisAny.EdgeRuntime) {
55213
+ return `runtime/vercel-edge`;
55214
+ }
55215
+ return "runtime/unknown";
55216
+ }
55217
+ function normalizeHeaders2(headers) {
55218
+ if (headers == null) {
55219
+ return {};
55220
+ }
55221
+ const normalized = {};
55222
+ if (headers instanceof Headers) {
55223
+ headers.forEach((value, key) => {
55224
+ normalized[key.toLowerCase()] = value;
55225
+ });
55226
+ } else {
55227
+ if (!Array.isArray(headers)) {
55228
+ headers = Object.entries(headers);
55229
+ }
55230
+ for (const [key, value] of headers) {
55231
+ if (value != null) {
55232
+ normalized[key.toLowerCase()] = value;
55233
+ }
55234
+ }
55235
+ }
55236
+ return normalized;
55237
+ }
55238
+ function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
55239
+ const normalizedHeaders = new Headers(normalizeHeaders2(headers));
55240
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
55241
+ normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
55242
+ return Object.fromEntries(normalizedHeaders.entries());
55243
+ }
55244
+ var VERSION8 = "4.0.21";
55245
+ var suspectProtoRx2 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
55246
+ var suspectConstructorRx2 = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
55247
+ function _parse3(text) {
55248
+ const obj = JSON.parse(text);
55249
+ if (obj === null || typeof obj !== "object") {
55250
+ return obj;
55251
+ }
55252
+ if (suspectProtoRx2.test(text) === false && suspectConstructorRx2.test(text) === false) {
55253
+ return obj;
55254
+ }
55255
+ return filter2(obj);
55256
+ }
55257
+ function filter2(obj) {
55258
+ let next = [obj];
55259
+ while (next.length) {
55260
+ const nodes = next;
55261
+ next = [];
55262
+ for (const node of nodes) {
55263
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
55264
+ throw new SyntaxError("Object contains forbidden prototype property");
55265
+ }
55266
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
55267
+ throw new SyntaxError("Object contains forbidden prototype property");
55268
+ }
55269
+ for (const key in node) {
55270
+ const value = node[key];
55271
+ if (value && typeof value === "object") {
55272
+ next.push(value);
55273
+ }
55274
+ }
55275
+ }
55276
+ }
55277
+ return obj;
55278
+ }
55279
+ function secureJsonParse2(text) {
55280
+ const { stackTraceLimit } = Error;
55281
+ try {
55282
+ Error.stackTraceLimit = 0;
55283
+ } catch (e) {
55284
+ return _parse3(text);
55285
+ }
55286
+ try {
55287
+ return _parse3(text);
55288
+ } finally {
55289
+ Error.stackTraceLimit = stackTraceLimit;
55290
+ }
55291
+ }
55292
+ function addAdditionalPropertiesToJsonSchema2(jsonSchema2) {
55293
+ if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
55294
+ jsonSchema2.additionalProperties = false;
55295
+ const { properties } = jsonSchema2;
55296
+ if (properties != null) {
55297
+ for (const key of Object.keys(properties)) {
55298
+ properties[key] = visit2(properties[key]);
55299
+ }
55300
+ }
55301
+ }
55302
+ if (jsonSchema2.items != null) {
55303
+ jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit2) : visit2(jsonSchema2.items);
55304
+ }
55305
+ if (jsonSchema2.anyOf != null) {
55306
+ jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit2);
55307
+ }
55308
+ if (jsonSchema2.allOf != null) {
55309
+ jsonSchema2.allOf = jsonSchema2.allOf.map(visit2);
55310
+ }
55311
+ if (jsonSchema2.oneOf != null) {
55312
+ jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit2);
55313
+ }
55314
+ const { definitions } = jsonSchema2;
55315
+ if (definitions != null) {
55316
+ for (const key of Object.keys(definitions)) {
55317
+ definitions[key] = visit2(definitions[key]);
55318
+ }
55319
+ }
55320
+ return jsonSchema2;
55321
+ }
55322
+ function visit2(def) {
55323
+ if (typeof def === "boolean")
55324
+ return def;
55325
+ return addAdditionalPropertiesToJsonSchema2(def);
55326
+ }
55327
+ var ignoreOverride2 = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use");
55328
+ var defaultOptions2 = {
55329
+ name: undefined,
55330
+ $refStrategy: "root",
55331
+ basePath: ["#"],
55332
+ effectStrategy: "input",
55333
+ pipeStrategy: "all",
55334
+ dateStrategy: "format:date-time",
55335
+ mapStrategy: "entries",
55336
+ removeAdditionalStrategy: "passthrough",
55337
+ allowedAdditionalProperties: true,
55338
+ rejectedAdditionalProperties: false,
55339
+ definitionPath: "definitions",
55340
+ strictUnions: false,
55341
+ definitions: {},
55342
+ errorMessages: false,
55343
+ patternStrategy: "escape",
55344
+ applyRegexFlags: false,
55345
+ emailStrategy: "format:email",
55346
+ base64Strategy: "contentEncoding:base64",
55347
+ nameStrategy: "ref"
55348
+ };
55349
+ var getDefaultOptions2 = (options) => typeof options === "string" ? {
55350
+ ...defaultOptions2,
55351
+ name: options
55352
+ } : {
55353
+ ...defaultOptions2,
55354
+ ...options
55355
+ };
55356
+ function parseAnyDef2() {
55357
+ return {};
55358
+ }
55359
+ function parseArrayDef2(def, refs) {
55360
+ var _a23, _b22, _c;
55361
+ const res = {
55362
+ type: "array"
55363
+ };
55364
+ if (((_a23 = def.type) == null ? undefined : _a23._def) && ((_c = (_b22 = def.type) == null ? undefined : _b22._def) == null ? undefined : _c.typeName) !== ZodFirstPartyTypeKind2.ZodAny) {
55365
+ res.items = parseDef2(def.type._def, {
55366
+ ...refs,
55367
+ currentPath: [...refs.currentPath, "items"]
55368
+ });
55369
+ }
55370
+ if (def.minLength) {
55371
+ res.minItems = def.minLength.value;
55372
+ }
55373
+ if (def.maxLength) {
55374
+ res.maxItems = def.maxLength.value;
55375
+ }
55376
+ if (def.exactLength) {
55377
+ res.minItems = def.exactLength.value;
55378
+ res.maxItems = def.exactLength.value;
55379
+ }
55380
+ return res;
55381
+ }
55382
+ function parseBigintDef2(def) {
55383
+ const res = {
55384
+ type: "integer",
55385
+ format: "int64"
55386
+ };
55387
+ if (!def.checks)
55388
+ return res;
55389
+ for (const check2 of def.checks) {
55390
+ switch (check2.kind) {
55391
+ case "min":
55392
+ if (check2.inclusive) {
55393
+ res.minimum = check2.value;
55394
+ } else {
55395
+ res.exclusiveMinimum = check2.value;
55396
+ }
55397
+ break;
55398
+ case "max":
55399
+ if (check2.inclusive) {
55400
+ res.maximum = check2.value;
55401
+ } else {
55402
+ res.exclusiveMaximum = check2.value;
55403
+ }
55404
+ break;
55405
+ case "multipleOf":
55406
+ res.multipleOf = check2.value;
55407
+ break;
55408
+ }
55409
+ }
55410
+ return res;
55411
+ }
55412
+ function parseBooleanDef2() {
55413
+ return { type: "boolean" };
55414
+ }
55415
+ function parseBrandedDef2(_def, refs) {
55416
+ return parseDef2(_def.type._def, refs);
55417
+ }
55418
+ var parseCatchDef2 = (def, refs) => {
55419
+ return parseDef2(def.innerType._def, refs);
55420
+ };
55421
+ function parseDateDef2(def, refs, overrideDateStrategy) {
55422
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
55423
+ if (Array.isArray(strategy)) {
55424
+ return {
55425
+ anyOf: strategy.map((item, i) => parseDateDef2(def, refs, item))
55426
+ };
55427
+ }
55428
+ switch (strategy) {
55429
+ case "string":
55430
+ case "format:date-time":
55431
+ return {
55432
+ type: "string",
55433
+ format: "date-time"
55434
+ };
55435
+ case "format:date":
55436
+ return {
55437
+ type: "string",
55438
+ format: "date"
55439
+ };
55440
+ case "integer":
55441
+ return integerDateParser2(def);
55442
+ }
55443
+ }
55444
+ var integerDateParser2 = (def) => {
55445
+ const res = {
55446
+ type: "integer",
55447
+ format: "unix-time"
55448
+ };
55449
+ for (const check2 of def.checks) {
55450
+ switch (check2.kind) {
55451
+ case "min":
55452
+ res.minimum = check2.value;
55453
+ break;
55454
+ case "max":
55455
+ res.maximum = check2.value;
55456
+ break;
55457
+ }
55458
+ }
55459
+ return res;
55460
+ };
55461
+ function parseDefaultDef2(_def, refs) {
55462
+ return {
55463
+ ...parseDef2(_def.innerType._def, refs),
55464
+ default: _def.defaultValue()
55465
+ };
55466
+ }
55467
+ function parseEffectsDef2(_def, refs) {
55468
+ return refs.effectStrategy === "input" ? parseDef2(_def.schema._def, refs) : parseAnyDef2();
55469
+ }
55470
+ function parseEnumDef2(def) {
55471
+ return {
55472
+ type: "string",
55473
+ enum: Array.from(def.values)
55474
+ };
55475
+ }
55476
+ var isJsonSchema7AllOfType2 = (type) => {
55477
+ if ("type" in type && type.type === "string")
55478
+ return false;
55479
+ return "allOf" in type;
55480
+ };
55481
+ function parseIntersectionDef2(def, refs) {
55482
+ const allOf = [
55483
+ parseDef2(def.left._def, {
55484
+ ...refs,
55485
+ currentPath: [...refs.currentPath, "allOf", "0"]
55486
+ }),
55487
+ parseDef2(def.right._def, {
55488
+ ...refs,
55489
+ currentPath: [...refs.currentPath, "allOf", "1"]
55490
+ })
55491
+ ].filter((x) => !!x);
55492
+ const mergedAllOf = [];
55493
+ allOf.forEach((schema) => {
55494
+ if (isJsonSchema7AllOfType2(schema)) {
55495
+ mergedAllOf.push(...schema.allOf);
55496
+ } else {
55497
+ let nestedSchema = schema;
55498
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
55499
+ const { additionalProperties, ...rest } = schema;
55500
+ nestedSchema = rest;
55501
+ }
55502
+ mergedAllOf.push(nestedSchema);
55503
+ }
55504
+ });
55505
+ return mergedAllOf.length ? { allOf: mergedAllOf } : undefined;
55506
+ }
55507
+ function parseLiteralDef2(def) {
55508
+ const parsedType2 = typeof def.value;
55509
+ if (parsedType2 !== "bigint" && parsedType2 !== "number" && parsedType2 !== "boolean" && parsedType2 !== "string") {
55510
+ return {
55511
+ type: Array.isArray(def.value) ? "array" : "object"
55512
+ };
55513
+ }
55514
+ return {
55515
+ type: parsedType2 === "bigint" ? "integer" : parsedType2,
55516
+ const: def.value
55517
+ };
55518
+ }
55519
+ var emojiRegex3 = undefined;
55520
+ var zodPatterns2 = {
55521
+ cuid: /^[cC][^\s-]{8,}$/,
55522
+ cuid2: /^[0-9a-z]+$/,
55523
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
55524
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
55525
+ emoji: () => {
55526
+ if (emojiRegex3 === undefined) {
55527
+ emojiRegex3 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
55528
+ }
55529
+ return emojiRegex3;
55530
+ },
55531
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
55532
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
55533
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
55534
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
55535
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
55536
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
55537
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
55538
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
55539
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
55540
+ };
55541
+ function parseStringDef2(def, refs) {
55542
+ const res = {
55543
+ type: "string"
55544
+ };
55545
+ if (def.checks) {
55546
+ for (const check2 of def.checks) {
55547
+ switch (check2.kind) {
55548
+ case "min":
55549
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value;
55550
+ break;
55551
+ case "max":
55552
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value;
55553
+ break;
55554
+ case "email":
55555
+ switch (refs.emailStrategy) {
55556
+ case "format:email":
55557
+ addFormat2(res, "email", check2.message, refs);
55558
+ break;
55559
+ case "format:idn-email":
55560
+ addFormat2(res, "idn-email", check2.message, refs);
55561
+ break;
55562
+ case "pattern:zod":
55563
+ addPattern2(res, zodPatterns2.email, check2.message, refs);
55564
+ break;
55565
+ }
55566
+ break;
55567
+ case "url":
55568
+ addFormat2(res, "uri", check2.message, refs);
55569
+ break;
55570
+ case "uuid":
55571
+ addFormat2(res, "uuid", check2.message, refs);
55572
+ break;
55573
+ case "regex":
55574
+ addPattern2(res, check2.regex, check2.message, refs);
55575
+ break;
55576
+ case "cuid":
55577
+ addPattern2(res, zodPatterns2.cuid, check2.message, refs);
55578
+ break;
55579
+ case "cuid2":
55580
+ addPattern2(res, zodPatterns2.cuid2, check2.message, refs);
55581
+ break;
55582
+ case "startsWith":
55583
+ addPattern2(res, RegExp(`^${escapeLiteralCheckValue2(check2.value, refs)}`), check2.message, refs);
55584
+ break;
55585
+ case "endsWith":
55586
+ addPattern2(res, RegExp(`${escapeLiteralCheckValue2(check2.value, refs)}$`), check2.message, refs);
55587
+ break;
55588
+ case "datetime":
55589
+ addFormat2(res, "date-time", check2.message, refs);
55590
+ break;
55591
+ case "date":
55592
+ addFormat2(res, "date", check2.message, refs);
55593
+ break;
55594
+ case "time":
55595
+ addFormat2(res, "time", check2.message, refs);
55596
+ break;
55597
+ case "duration":
55598
+ addFormat2(res, "duration", check2.message, refs);
55599
+ break;
55600
+ case "length":
55601
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value;
55602
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value;
55603
+ break;
55604
+ case "includes": {
55605
+ addPattern2(res, RegExp(escapeLiteralCheckValue2(check2.value, refs)), check2.message, refs);
55606
+ break;
55607
+ }
55608
+ case "ip": {
55609
+ if (check2.version !== "v6") {
55610
+ addFormat2(res, "ipv4", check2.message, refs);
55611
+ }
55612
+ if (check2.version !== "v4") {
55613
+ addFormat2(res, "ipv6", check2.message, refs);
55614
+ }
55615
+ break;
55616
+ }
55617
+ case "base64url":
55618
+ addPattern2(res, zodPatterns2.base64url, check2.message, refs);
55619
+ break;
55620
+ case "jwt":
55621
+ addPattern2(res, zodPatterns2.jwt, check2.message, refs);
55622
+ break;
55623
+ case "cidr": {
55624
+ if (check2.version !== "v6") {
55625
+ addPattern2(res, zodPatterns2.ipv4Cidr, check2.message, refs);
55626
+ }
55627
+ if (check2.version !== "v4") {
55628
+ addPattern2(res, zodPatterns2.ipv6Cidr, check2.message, refs);
55629
+ }
55630
+ break;
55631
+ }
55632
+ case "emoji":
55633
+ addPattern2(res, zodPatterns2.emoji(), check2.message, refs);
55634
+ break;
55635
+ case "ulid": {
55636
+ addPattern2(res, zodPatterns2.ulid, check2.message, refs);
55637
+ break;
55638
+ }
55639
+ case "base64": {
55640
+ switch (refs.base64Strategy) {
55641
+ case "format:binary": {
55642
+ addFormat2(res, "binary", check2.message, refs);
55643
+ break;
55644
+ }
55645
+ case "contentEncoding:base64": {
55646
+ res.contentEncoding = "base64";
55647
+ break;
55648
+ }
55649
+ case "pattern:zod": {
55650
+ addPattern2(res, zodPatterns2.base64, check2.message, refs);
55651
+ break;
55652
+ }
55653
+ }
55654
+ break;
55655
+ }
55656
+ case "nanoid": {
55657
+ addPattern2(res, zodPatterns2.nanoid, check2.message, refs);
55658
+ }
55659
+ case "toLowerCase":
55660
+ case "toUpperCase":
55661
+ case "trim":
55662
+ break;
55663
+ default:
55664
+ }
55665
+ }
55666
+ }
55667
+ return res;
55668
+ }
55669
+ function escapeLiteralCheckValue2(literal2, refs) {
55670
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric2(literal2) : literal2;
55671
+ }
55672
+ var ALPHA_NUMERIC2 = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
55673
+ function escapeNonAlphaNumeric2(source) {
55674
+ let result = "";
55675
+ for (let i = 0;i < source.length; i++) {
55676
+ if (!ALPHA_NUMERIC2.has(source[i])) {
55677
+ result += "\\";
55678
+ }
55679
+ result += source[i];
55680
+ }
55681
+ return result;
55682
+ }
55683
+ function addFormat2(schema, value, message, refs) {
55684
+ var _a23;
55685
+ if (schema.format || ((_a23 = schema.anyOf) == null ? undefined : _a23.some((x) => x.format))) {
55686
+ if (!schema.anyOf) {
55687
+ schema.anyOf = [];
55688
+ }
55689
+ if (schema.format) {
55690
+ schema.anyOf.push({
55691
+ format: schema.format
55692
+ });
55693
+ delete schema.format;
55694
+ }
55695
+ schema.anyOf.push({
55696
+ format: value,
55697
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
55698
+ });
55699
+ } else {
55700
+ schema.format = value;
55701
+ }
55702
+ }
55703
+ function addPattern2(schema, regex, message, refs) {
55704
+ var _a23;
55705
+ if (schema.pattern || ((_a23 = schema.allOf) == null ? undefined : _a23.some((x) => x.pattern))) {
55706
+ if (!schema.allOf) {
55707
+ schema.allOf = [];
55708
+ }
55709
+ if (schema.pattern) {
55710
+ schema.allOf.push({
55711
+ pattern: schema.pattern
55712
+ });
55713
+ delete schema.pattern;
55714
+ }
55715
+ schema.allOf.push({
55716
+ pattern: stringifyRegExpWithFlags2(regex, refs),
55717
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
55718
+ });
55719
+ } else {
55720
+ schema.pattern = stringifyRegExpWithFlags2(regex, refs);
55721
+ }
55722
+ }
55723
+ function stringifyRegExpWithFlags2(regex, refs) {
55724
+ var _a23;
55725
+ if (!refs.applyRegexFlags || !regex.flags) {
55726
+ return regex.source;
55727
+ }
55728
+ const flags = {
55729
+ i: regex.flags.includes("i"),
55730
+ m: regex.flags.includes("m"),
55731
+ s: regex.flags.includes("s")
55732
+ };
55733
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
55734
+ let pattern = "";
55735
+ let isEscaped = false;
55736
+ let inCharGroup = false;
55737
+ let inCharRange = false;
55738
+ for (let i = 0;i < source.length; i++) {
55739
+ if (isEscaped) {
55740
+ pattern += source[i];
55741
+ isEscaped = false;
55742
+ continue;
55743
+ }
55744
+ if (flags.i) {
55745
+ if (inCharGroup) {
55746
+ if (source[i].match(/[a-z]/)) {
55747
+ if (inCharRange) {
55748
+ pattern += source[i];
55749
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
55750
+ inCharRange = false;
55751
+ } else if (source[i + 1] === "-" && ((_a23 = source[i + 2]) == null ? undefined : _a23.match(/[a-z]/))) {
55752
+ pattern += source[i];
55753
+ inCharRange = true;
55754
+ } else {
55755
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
55756
+ }
55757
+ continue;
55758
+ }
55759
+ } else if (source[i].match(/[a-z]/)) {
55760
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
55761
+ continue;
55762
+ }
55763
+ }
55764
+ if (flags.m) {
55765
+ if (source[i] === "^") {
55766
+ pattern += `(^|(?<=[\r
55767
+ ]))`;
55768
+ continue;
55769
+ } else if (source[i] === "$") {
55770
+ pattern += `($|(?=[\r
55771
+ ]))`;
55772
+ continue;
55773
+ }
55774
+ }
55775
+ if (flags.s && source[i] === ".") {
55776
+ pattern += inCharGroup ? `${source[i]}\r
55777
+ ` : `[${source[i]}\r
55778
+ ]`;
55779
+ continue;
55780
+ }
55781
+ pattern += source[i];
55782
+ if (source[i] === "\\") {
55783
+ isEscaped = true;
55784
+ } else if (inCharGroup && source[i] === "]") {
55785
+ inCharGroup = false;
55786
+ } else if (!inCharGroup && source[i] === "[") {
55787
+ inCharGroup = true;
55788
+ }
55789
+ }
55790
+ try {
55791
+ new RegExp(pattern);
55792
+ } catch (e) {
55793
+ console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
55794
+ return regex.source;
55795
+ }
55796
+ return pattern;
55797
+ }
55798
+ function parseRecordDef2(def, refs) {
55799
+ var _a23, _b22, _c, _d, _e, _f;
55800
+ const schema = {
55801
+ type: "object",
55802
+ additionalProperties: (_a23 = parseDef2(def.valueType._def, {
55803
+ ...refs,
55804
+ currentPath: [...refs.currentPath, "additionalProperties"]
55805
+ })) != null ? _a23 : refs.allowedAdditionalProperties
55806
+ };
55807
+ if (((_b22 = def.keyType) == null ? undefined : _b22._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? undefined : _c.length)) {
55808
+ const { type, ...keyType } = parseStringDef2(def.keyType._def, refs);
55809
+ return {
55810
+ ...schema,
55811
+ propertyNames: keyType
55812
+ };
55813
+ } else if (((_d = def.keyType) == null ? undefined : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
55814
+ return {
55815
+ ...schema,
55816
+ propertyNames: {
55817
+ enum: def.keyType._def.values
55818
+ }
55819
+ };
55820
+ } else if (((_e = def.keyType) == null ? undefined : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? undefined : _f.length)) {
55821
+ const { type, ...keyType } = parseBrandedDef2(def.keyType._def, refs);
55822
+ return {
55823
+ ...schema,
55824
+ propertyNames: keyType
55825
+ };
55826
+ }
55827
+ return schema;
55828
+ }
55829
+ function parseMapDef2(def, refs) {
55830
+ if (refs.mapStrategy === "record") {
55831
+ return parseRecordDef2(def, refs);
55832
+ }
55833
+ const keys = parseDef2(def.keyType._def, {
55834
+ ...refs,
55835
+ currentPath: [...refs.currentPath, "items", "items", "0"]
55836
+ }) || parseAnyDef2();
55837
+ const values = parseDef2(def.valueType._def, {
55838
+ ...refs,
55839
+ currentPath: [...refs.currentPath, "items", "items", "1"]
55840
+ }) || parseAnyDef2();
55841
+ return {
55842
+ type: "array",
55843
+ maxItems: 125,
55844
+ items: {
55845
+ type: "array",
55846
+ items: [keys, values],
55847
+ minItems: 2,
55848
+ maxItems: 2
55849
+ }
55850
+ };
55851
+ }
55852
+ function parseNativeEnumDef2(def) {
55853
+ const object2 = def.values;
55854
+ const actualKeys = Object.keys(def.values).filter((key) => {
55855
+ return typeof object2[object2[key]] !== "number";
55856
+ });
55857
+ const actualValues = actualKeys.map((key) => object2[key]);
55858
+ const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
55859
+ return {
55860
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
55861
+ enum: actualValues
55862
+ };
55863
+ }
55864
+ function parseNeverDef2() {
55865
+ return { not: parseAnyDef2() };
55866
+ }
55867
+ function parseNullDef2() {
55868
+ return {
55869
+ type: "null"
55870
+ };
55871
+ }
55872
+ var primitiveMappings2 = {
55873
+ ZodString: "string",
55874
+ ZodNumber: "number",
55875
+ ZodBigInt: "integer",
55876
+ ZodBoolean: "boolean",
55877
+ ZodNull: "null"
55878
+ };
55879
+ function parseUnionDef2(def, refs) {
55880
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
55881
+ if (options.every((x) => (x._def.typeName in primitiveMappings2) && (!x._def.checks || !x._def.checks.length))) {
55882
+ const types = options.reduce((types2, x) => {
55883
+ const type = primitiveMappings2[x._def.typeName];
55884
+ return type && !types2.includes(type) ? [...types2, type] : types2;
55885
+ }, []);
55886
+ return {
55887
+ type: types.length > 1 ? types : types[0]
55888
+ };
55889
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
55890
+ const types = options.reduce((acc, x) => {
55891
+ const type = typeof x._def.value;
55892
+ switch (type) {
55893
+ case "string":
55894
+ case "number":
55895
+ case "boolean":
55896
+ return [...acc, type];
55897
+ case "bigint":
55898
+ return [...acc, "integer"];
55899
+ case "object":
55900
+ if (x._def.value === null)
55901
+ return [...acc, "null"];
55902
+ case "symbol":
55903
+ case "undefined":
55904
+ case "function":
55905
+ default:
55906
+ return acc;
55907
+ }
55908
+ }, []);
55909
+ if (types.length === options.length) {
55910
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
55911
+ return {
55912
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
55913
+ enum: options.reduce((acc, x) => {
55914
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
55915
+ }, [])
55916
+ };
55917
+ }
55918
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
55919
+ return {
55920
+ type: "string",
55921
+ enum: options.reduce((acc, x) => [
55922
+ ...acc,
55923
+ ...x._def.values.filter((x2) => !acc.includes(x2))
55924
+ ], [])
55925
+ };
55926
+ }
55927
+ return asAnyOf2(def, refs);
55928
+ }
55929
+ var asAnyOf2 = (def, refs) => {
55930
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef2(x._def, {
55931
+ ...refs,
55932
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
55933
+ })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
55934
+ return anyOf.length ? { anyOf } : undefined;
55935
+ };
55936
+ function parseNullableDef2(def, refs) {
55937
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
55938
+ return {
55939
+ type: [
55940
+ primitiveMappings2[def.innerType._def.typeName],
55941
+ "null"
55942
+ ]
55943
+ };
55944
+ }
55945
+ const base = parseDef2(def.innerType._def, {
55946
+ ...refs,
55947
+ currentPath: [...refs.currentPath, "anyOf", "0"]
55948
+ });
55949
+ return base && { anyOf: [base, { type: "null" }] };
55950
+ }
55951
+ function parseNumberDef2(def) {
55952
+ const res = {
55953
+ type: "number"
55954
+ };
55955
+ if (!def.checks)
55956
+ return res;
55957
+ for (const check2 of def.checks) {
55958
+ switch (check2.kind) {
55959
+ case "int":
55960
+ res.type = "integer";
55961
+ break;
55962
+ case "min":
55963
+ if (check2.inclusive) {
55964
+ res.minimum = check2.value;
55965
+ } else {
55966
+ res.exclusiveMinimum = check2.value;
55967
+ }
55968
+ break;
55969
+ case "max":
55970
+ if (check2.inclusive) {
55971
+ res.maximum = check2.value;
55972
+ } else {
55973
+ res.exclusiveMaximum = check2.value;
55974
+ }
55975
+ break;
55976
+ case "multipleOf":
55977
+ res.multipleOf = check2.value;
55978
+ break;
55979
+ }
55980
+ }
55981
+ return res;
55982
+ }
55983
+ function parseObjectDef2(def, refs) {
55984
+ const result = {
55985
+ type: "object",
55986
+ properties: {}
55987
+ };
55988
+ const required2 = [];
55989
+ const shape = def.shape();
55990
+ for (const propName in shape) {
55991
+ let propDef = shape[propName];
55992
+ if (propDef === undefined || propDef._def === undefined) {
55993
+ continue;
55994
+ }
55995
+ const propOptional = safeIsOptional2(propDef);
55996
+ const parsedDef = parseDef2(propDef._def, {
55997
+ ...refs,
55998
+ currentPath: [...refs.currentPath, "properties", propName],
55999
+ propertyPath: [...refs.currentPath, "properties", propName]
56000
+ });
56001
+ if (parsedDef === undefined) {
56002
+ continue;
56003
+ }
56004
+ result.properties[propName] = parsedDef;
56005
+ if (!propOptional) {
56006
+ required2.push(propName);
56007
+ }
56008
+ }
56009
+ if (required2.length) {
56010
+ result.required = required2;
56011
+ }
56012
+ const additionalProperties = decideAdditionalProperties2(def, refs);
56013
+ if (additionalProperties !== undefined) {
56014
+ result.additionalProperties = additionalProperties;
56015
+ }
56016
+ return result;
56017
+ }
56018
+ function decideAdditionalProperties2(def, refs) {
56019
+ if (def.catchall._def.typeName !== "ZodNever") {
56020
+ return parseDef2(def.catchall._def, {
56021
+ ...refs,
56022
+ currentPath: [...refs.currentPath, "additionalProperties"]
56023
+ });
56024
+ }
56025
+ switch (def.unknownKeys) {
56026
+ case "passthrough":
56027
+ return refs.allowedAdditionalProperties;
56028
+ case "strict":
56029
+ return refs.rejectedAdditionalProperties;
56030
+ case "strip":
56031
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
56032
+ }
56033
+ }
56034
+ function safeIsOptional2(schema) {
56035
+ try {
56036
+ return schema.isOptional();
56037
+ } catch (e) {
56038
+ return true;
56039
+ }
56040
+ }
56041
+ var parseOptionalDef2 = (def, refs) => {
56042
+ var _a23;
56043
+ if (refs.currentPath.toString() === ((_a23 = refs.propertyPath) == null ? undefined : _a23.toString())) {
56044
+ return parseDef2(def.innerType._def, refs);
56045
+ }
56046
+ const innerSchema = parseDef2(def.innerType._def, {
56047
+ ...refs,
56048
+ currentPath: [...refs.currentPath, "anyOf", "1"]
56049
+ });
56050
+ return innerSchema ? { anyOf: [{ not: parseAnyDef2() }, innerSchema] } : parseAnyDef2();
56051
+ };
56052
+ var parsePipelineDef2 = (def, refs) => {
56053
+ if (refs.pipeStrategy === "input") {
56054
+ return parseDef2(def.in._def, refs);
56055
+ } else if (refs.pipeStrategy === "output") {
56056
+ return parseDef2(def.out._def, refs);
56057
+ }
56058
+ const a = parseDef2(def.in._def, {
56059
+ ...refs,
56060
+ currentPath: [...refs.currentPath, "allOf", "0"]
56061
+ });
56062
+ const b = parseDef2(def.out._def, {
56063
+ ...refs,
56064
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
56065
+ });
56066
+ return {
56067
+ allOf: [a, b].filter((x) => x !== undefined)
56068
+ };
56069
+ };
56070
+ function parsePromiseDef2(def, refs) {
56071
+ return parseDef2(def.type._def, refs);
56072
+ }
56073
+ function parseSetDef2(def, refs) {
56074
+ const items = parseDef2(def.valueType._def, {
56075
+ ...refs,
56076
+ currentPath: [...refs.currentPath, "items"]
56077
+ });
56078
+ const schema = {
56079
+ type: "array",
56080
+ uniqueItems: true,
56081
+ items
56082
+ };
56083
+ if (def.minSize) {
56084
+ schema.minItems = def.minSize.value;
56085
+ }
56086
+ if (def.maxSize) {
56087
+ schema.maxItems = def.maxSize.value;
56088
+ }
56089
+ return schema;
56090
+ }
56091
+ function parseTupleDef2(def, refs) {
56092
+ if (def.rest) {
56093
+ return {
56094
+ type: "array",
56095
+ minItems: def.items.length,
56096
+ items: def.items.map((x, i) => parseDef2(x._def, {
56097
+ ...refs,
56098
+ currentPath: [...refs.currentPath, "items", `${i}`]
56099
+ })).reduce((acc, x) => x === undefined ? acc : [...acc, x], []),
56100
+ additionalItems: parseDef2(def.rest._def, {
56101
+ ...refs,
56102
+ currentPath: [...refs.currentPath, "additionalItems"]
56103
+ })
56104
+ };
56105
+ } else {
56106
+ return {
56107
+ type: "array",
56108
+ minItems: def.items.length,
56109
+ maxItems: def.items.length,
56110
+ items: def.items.map((x, i) => parseDef2(x._def, {
56111
+ ...refs,
56112
+ currentPath: [...refs.currentPath, "items", `${i}`]
56113
+ })).reduce((acc, x) => x === undefined ? acc : [...acc, x], [])
56114
+ };
56115
+ }
56116
+ }
56117
+ function parseUndefinedDef2() {
56118
+ return {
56119
+ not: parseAnyDef2()
56120
+ };
56121
+ }
56122
+ function parseUnknownDef2() {
56123
+ return parseAnyDef2();
56124
+ }
56125
+ var parseReadonlyDef2 = (def, refs) => {
56126
+ return parseDef2(def.innerType._def, refs);
56127
+ };
56128
+ var selectParser2 = (def, typeName, refs) => {
56129
+ switch (typeName) {
56130
+ case ZodFirstPartyTypeKind2.ZodString:
56131
+ return parseStringDef2(def, refs);
56132
+ case ZodFirstPartyTypeKind2.ZodNumber:
56133
+ return parseNumberDef2(def);
56134
+ case ZodFirstPartyTypeKind2.ZodObject:
56135
+ return parseObjectDef2(def, refs);
56136
+ case ZodFirstPartyTypeKind2.ZodBigInt:
56137
+ return parseBigintDef2(def);
56138
+ case ZodFirstPartyTypeKind2.ZodBoolean:
56139
+ return parseBooleanDef2();
56140
+ case ZodFirstPartyTypeKind2.ZodDate:
56141
+ return parseDateDef2(def, refs);
56142
+ case ZodFirstPartyTypeKind2.ZodUndefined:
56143
+ return parseUndefinedDef2();
56144
+ case ZodFirstPartyTypeKind2.ZodNull:
56145
+ return parseNullDef2();
56146
+ case ZodFirstPartyTypeKind2.ZodArray:
56147
+ return parseArrayDef2(def, refs);
56148
+ case ZodFirstPartyTypeKind2.ZodUnion:
56149
+ case ZodFirstPartyTypeKind2.ZodDiscriminatedUnion:
56150
+ return parseUnionDef2(def, refs);
56151
+ case ZodFirstPartyTypeKind2.ZodIntersection:
56152
+ return parseIntersectionDef2(def, refs);
56153
+ case ZodFirstPartyTypeKind2.ZodTuple:
56154
+ return parseTupleDef2(def, refs);
56155
+ case ZodFirstPartyTypeKind2.ZodRecord:
56156
+ return parseRecordDef2(def, refs);
56157
+ case ZodFirstPartyTypeKind2.ZodLiteral:
56158
+ return parseLiteralDef2(def);
56159
+ case ZodFirstPartyTypeKind2.ZodEnum:
56160
+ return parseEnumDef2(def);
56161
+ case ZodFirstPartyTypeKind2.ZodNativeEnum:
56162
+ return parseNativeEnumDef2(def);
56163
+ case ZodFirstPartyTypeKind2.ZodNullable:
56164
+ return parseNullableDef2(def, refs);
56165
+ case ZodFirstPartyTypeKind2.ZodOptional:
56166
+ return parseOptionalDef2(def, refs);
56167
+ case ZodFirstPartyTypeKind2.ZodMap:
56168
+ return parseMapDef2(def, refs);
56169
+ case ZodFirstPartyTypeKind2.ZodSet:
56170
+ return parseSetDef2(def, refs);
56171
+ case ZodFirstPartyTypeKind2.ZodLazy:
56172
+ return () => def.getter()._def;
56173
+ case ZodFirstPartyTypeKind2.ZodPromise:
56174
+ return parsePromiseDef2(def, refs);
56175
+ case ZodFirstPartyTypeKind2.ZodNaN:
56176
+ case ZodFirstPartyTypeKind2.ZodNever:
56177
+ return parseNeverDef2();
56178
+ case ZodFirstPartyTypeKind2.ZodEffects:
56179
+ return parseEffectsDef2(def, refs);
56180
+ case ZodFirstPartyTypeKind2.ZodAny:
56181
+ return parseAnyDef2();
56182
+ case ZodFirstPartyTypeKind2.ZodUnknown:
56183
+ return parseUnknownDef2();
56184
+ case ZodFirstPartyTypeKind2.ZodDefault:
56185
+ return parseDefaultDef2(def, refs);
56186
+ case ZodFirstPartyTypeKind2.ZodBranded:
56187
+ return parseBrandedDef2(def, refs);
56188
+ case ZodFirstPartyTypeKind2.ZodReadonly:
56189
+ return parseReadonlyDef2(def, refs);
56190
+ case ZodFirstPartyTypeKind2.ZodCatch:
56191
+ return parseCatchDef2(def, refs);
56192
+ case ZodFirstPartyTypeKind2.ZodPipeline:
56193
+ return parsePipelineDef2(def, refs);
56194
+ case ZodFirstPartyTypeKind2.ZodFunction:
56195
+ case ZodFirstPartyTypeKind2.ZodVoid:
56196
+ case ZodFirstPartyTypeKind2.ZodSymbol:
56197
+ return;
56198
+ default:
56199
+ return /* @__PURE__ */ ((_) => {
56200
+ return;
56201
+ })(typeName);
56202
+ }
56203
+ };
56204
+ var getRelativePath2 = (pathA, pathB) => {
56205
+ let i = 0;
56206
+ for (;i < pathA.length && i < pathB.length; i++) {
56207
+ if (pathA[i] !== pathB[i])
56208
+ break;
56209
+ }
56210
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
56211
+ };
56212
+ function parseDef2(def, refs, forceResolution = false) {
56213
+ var _a23;
56214
+ const seenItem = refs.seen.get(def);
56215
+ if (refs.override) {
56216
+ const overrideResult = (_a23 = refs.override) == null ? undefined : _a23.call(refs, def, refs, seenItem, forceResolution);
56217
+ if (overrideResult !== ignoreOverride2) {
56218
+ return overrideResult;
56219
+ }
56220
+ }
56221
+ if (seenItem && !forceResolution) {
56222
+ const seenSchema = get$ref2(seenItem, refs);
56223
+ if (seenSchema !== undefined) {
56224
+ return seenSchema;
56225
+ }
56226
+ }
56227
+ const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
56228
+ refs.seen.set(def, newItem);
56229
+ const jsonSchemaOrGetter = selectParser2(def, def.typeName, refs);
56230
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef2(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
56231
+ if (jsonSchema2) {
56232
+ addMeta2(def, refs, jsonSchema2);
56233
+ }
56234
+ if (refs.postProcess) {
56235
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
56236
+ newItem.jsonSchema = jsonSchema2;
56237
+ return postProcessResult;
56238
+ }
56239
+ newItem.jsonSchema = jsonSchema2;
56240
+ return jsonSchema2;
56241
+ }
56242
+ var get$ref2 = (item, refs) => {
56243
+ switch (refs.$refStrategy) {
56244
+ case "root":
56245
+ return { $ref: item.path.join("/") };
56246
+ case "relative":
56247
+ return { $ref: getRelativePath2(refs.currentPath, item.path) };
56248
+ case "none":
56249
+ case "seen": {
56250
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
56251
+ console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
56252
+ return parseAnyDef2();
56253
+ }
56254
+ return refs.$refStrategy === "seen" ? parseAnyDef2() : undefined;
56255
+ }
56256
+ }
56257
+ };
56258
+ var addMeta2 = (def, refs, jsonSchema2) => {
56259
+ if (def.description) {
56260
+ jsonSchema2.description = def.description;
56261
+ }
56262
+ return jsonSchema2;
56263
+ };
56264
+ var getRefs2 = (options) => {
56265
+ const _options = getDefaultOptions2(options);
56266
+ const currentPath = _options.name !== undefined ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
56267
+ return {
56268
+ ..._options,
56269
+ currentPath,
56270
+ propertyPath: undefined,
56271
+ seen: new Map(Object.entries(_options.definitions).map(([name22, def]) => [
56272
+ def._def,
56273
+ {
56274
+ def: def._def,
56275
+ path: [..._options.basePath, _options.definitionPath, name22],
56276
+ jsonSchema: undefined
56277
+ }
56278
+ ]))
56279
+ };
56280
+ };
56281
+ var zod3ToJsonSchema2 = (schema, options) => {
56282
+ var _a23;
56283
+ const refs = getRefs2(options);
56284
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name32, schema2]) => {
56285
+ var _a32;
56286
+ return {
56287
+ ...acc,
56288
+ [name32]: (_a32 = parseDef2(schema2._def, {
56289
+ ...refs,
56290
+ currentPath: [...refs.basePath, refs.definitionPath, name32]
56291
+ }, true)) != null ? _a32 : parseAnyDef2()
56292
+ };
56293
+ }, {}) : undefined;
56294
+ const name22 = typeof options === "string" ? options : (options == null ? undefined : options.nameStrategy) === "title" ? undefined : options == null ? undefined : options.name;
56295
+ const main = (_a23 = parseDef2(schema._def, name22 === undefined ? refs : {
56296
+ ...refs,
56297
+ currentPath: [...refs.basePath, refs.definitionPath, name22]
56298
+ }, false)) != null ? _a23 : parseAnyDef2();
56299
+ const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined;
56300
+ if (title !== undefined) {
56301
+ main.title = title;
56302
+ }
56303
+ const combined = name22 === undefined ? definitions ? {
56304
+ ...main,
56305
+ [refs.definitionPath]: definitions
56306
+ } : main : {
56307
+ $ref: [
56308
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
56309
+ refs.definitionPath,
56310
+ name22
56311
+ ].join("/"),
56312
+ [refs.definitionPath]: {
56313
+ ...definitions,
56314
+ [name22]: main
56315
+ }
56316
+ };
56317
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
56318
+ return combined;
56319
+ };
56320
+ var schemaSymbol2 = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
56321
+ function jsonSchema2(jsonSchema22, {
56322
+ validate
56323
+ } = {}) {
56324
+ return {
56325
+ [schemaSymbol2]: true,
56326
+ _type: undefined,
56327
+ get jsonSchema() {
56328
+ if (typeof jsonSchema22 === "function") {
56329
+ jsonSchema22 = jsonSchema22();
56330
+ }
56331
+ return jsonSchema22;
56332
+ },
56333
+ validate
56334
+ };
56335
+ }
56336
+ function isSchema2(value) {
56337
+ return typeof value === "object" && value !== null && schemaSymbol2 in value && value[schemaSymbol2] === true && "jsonSchema" in value && "validate" in value;
56338
+ }
56339
+ function asSchema2(schema) {
56340
+ return schema == null ? jsonSchema2({ properties: {}, additionalProperties: false }) : isSchema2(schema) ? schema : ("~standard" in schema) ? schema["~standard"].vendor === "zod" ? zodSchema2(schema) : standardSchema2(schema) : schema();
56341
+ }
56342
+ function standardSchema2(standardSchema22) {
56343
+ return jsonSchema2(() => addAdditionalPropertiesToJsonSchema2(standardSchema22["~standard"].jsonSchema.input({
56344
+ target: "draft-07"
56345
+ })), {
56346
+ validate: async (value) => {
56347
+ const result = await standardSchema22["~standard"].validate(value);
56348
+ return "value" in result ? { success: true, value: result.value } : {
56349
+ success: false,
56350
+ error: new TypeValidationError({
56351
+ value,
56352
+ cause: result.issues
56353
+ })
56354
+ };
56355
+ }
56356
+ });
56357
+ }
56358
+ function zod3Schema2(zodSchema2, options) {
56359
+ var _a23;
56360
+ const useReferences = (_a23 = options == null ? undefined : options.useReferences) != null ? _a23 : false;
56361
+ return jsonSchema2(() => zod3ToJsonSchema2(zodSchema2, {
56362
+ $refStrategy: useReferences ? "root" : "none"
56363
+ }), {
56364
+ validate: async (value) => {
56365
+ const result = await zodSchema2.safeParseAsync(value);
56366
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
56367
+ }
56368
+ });
56369
+ }
56370
+ function zod4Schema2(zodSchema2, options) {
56371
+ var _a23;
56372
+ const useReferences = (_a23 = options == null ? undefined : options.useReferences) != null ? _a23 : false;
56373
+ return jsonSchema2(() => addAdditionalPropertiesToJsonSchema2(toJSONSchema(zodSchema2, {
56374
+ target: "draft-7",
56375
+ io: "input",
56376
+ reused: useReferences ? "ref" : "inline"
56377
+ })), {
56378
+ validate: async (value) => {
56379
+ const result = await safeParseAsync2(zodSchema2, value);
56380
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
56381
+ }
56382
+ });
56383
+ }
56384
+ function isZod4Schema2(zodSchema2) {
56385
+ return "_zod" in zodSchema2;
56386
+ }
56387
+ function zodSchema2(zodSchema22, options) {
56388
+ if (isZod4Schema2(zodSchema22)) {
56389
+ return zod4Schema2(zodSchema22, options);
56390
+ } else {
56391
+ return zod3Schema2(zodSchema22, options);
56392
+ }
56393
+ }
56394
+ async function validateTypes2({
56395
+ value,
56396
+ schema,
56397
+ context
56398
+ }) {
56399
+ const result = await safeValidateTypes2({ value, schema, context });
56400
+ if (!result.success) {
56401
+ throw TypeValidationError.wrap({ value, cause: result.error, context });
56402
+ }
56403
+ return result.value;
56404
+ }
56405
+ async function safeValidateTypes2({
56406
+ value,
56407
+ schema,
56408
+ context
56409
+ }) {
56410
+ const actualSchema = asSchema2(schema);
56411
+ try {
56412
+ if (actualSchema.validate == null) {
56413
+ return { success: true, value, rawValue: value };
56414
+ }
56415
+ const result = await actualSchema.validate(value);
56416
+ if (result.success) {
56417
+ return { success: true, value: result.value, rawValue: value };
56418
+ }
56419
+ return {
56420
+ success: false,
56421
+ error: TypeValidationError.wrap({ value, cause: result.error, context }),
56422
+ rawValue: value
56423
+ };
56424
+ } catch (error48) {
56425
+ return {
56426
+ success: false,
56427
+ error: TypeValidationError.wrap({ value, cause: error48, context }),
56428
+ rawValue: value
56429
+ };
56430
+ }
56431
+ }
56432
+ async function parseJSON2({
56433
+ text,
56434
+ schema
56435
+ }) {
56436
+ try {
56437
+ const value = secureJsonParse2(text);
56438
+ if (schema == null) {
56439
+ return value;
56440
+ }
56441
+ return validateTypes2({ value, schema });
56442
+ } catch (error48) {
56443
+ if (JSONParseError.isInstance(error48) || TypeValidationError.isInstance(error48)) {
56444
+ throw error48;
56445
+ }
56446
+ throw new JSONParseError({ text, cause: error48 });
54298
56447
  }
54299
- async getArgs({
54300
- audio,
54301
- mediaType,
54302
- providerOptions
54303
- }) {
54304
- var _a16, _b16, _c, _d, _e;
54305
- const warnings = [];
54306
- const groqOptions = await parseProviderOptions({
54307
- provider: "groq",
54308
- providerOptions,
54309
- schema: groqTranscriptionModelOptions
56448
+ }
56449
+ async function safeParseJSON2({
56450
+ text,
56451
+ schema
56452
+ }) {
56453
+ try {
56454
+ const value = secureJsonParse2(text);
56455
+ if (schema == null) {
56456
+ return { success: true, value, rawValue: value };
56457
+ }
56458
+ return await safeValidateTypes2({ value, schema });
56459
+ } catch (error48) {
56460
+ return {
56461
+ success: false,
56462
+ error: JSONParseError.isInstance(error48) ? error48 : new JSONParseError({ text, cause: error48 }),
56463
+ rawValue: undefined
56464
+ };
56465
+ }
56466
+ }
56467
+ async function parseProviderOptions2({
56468
+ provider,
56469
+ providerOptions,
56470
+ schema
56471
+ }) {
56472
+ if ((providerOptions == null ? undefined : providerOptions[provider]) == null) {
56473
+ return;
56474
+ }
56475
+ const parsedProviderOptions = await safeValidateTypes2({
56476
+ value: providerOptions[provider],
56477
+ schema
56478
+ });
56479
+ if (!parsedProviderOptions.success) {
56480
+ throw new InvalidArgumentError({
56481
+ argument: "providerOptions",
56482
+ message: `invalid ${provider} provider options`,
56483
+ cause: parsedProviderOptions.error
54310
56484
  });
54311
- const formData = new FormData;
54312
- const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]);
54313
- formData.append("model", this.modelId);
54314
- const fileExtension = mediaTypeToExtension(mediaType);
54315
- formData.append("file", new File([blob], "audio", { type: mediaType }), `audio.${fileExtension}`);
54316
- if (groqOptions) {
54317
- const transcriptionModelOptions = {
54318
- language: (_a16 = groqOptions.language) != null ? _a16 : undefined,
54319
- prompt: (_b16 = groqOptions.prompt) != null ? _b16 : undefined,
54320
- response_format: (_c = groqOptions.responseFormat) != null ? _c : undefined,
54321
- temperature: (_d = groqOptions.temperature) != null ? _d : undefined,
54322
- timestamp_granularities: (_e = groqOptions.timestampGranularities) != null ? _e : undefined
54323
- };
54324
- for (const key in transcriptionModelOptions) {
54325
- const value = transcriptionModelOptions[key];
54326
- if (value !== undefined) {
54327
- if (Array.isArray(value)) {
54328
- for (const item of value) {
54329
- formData.append(`${key}[]`, String(item));
54330
- }
54331
- } else {
54332
- formData.append(key, String(value));
54333
- }
56485
+ }
56486
+ return parsedProviderOptions.value;
56487
+ }
56488
+ var getOriginalFetch22 = () => globalThis.fetch;
56489
+ var postJsonToApi2 = async ({
56490
+ url: url2,
56491
+ headers,
56492
+ body,
56493
+ failedResponseHandler,
56494
+ successfulResponseHandler,
56495
+ abortSignal,
56496
+ fetch: fetch2
56497
+ }) => postToApi2({
56498
+ url: url2,
56499
+ headers: {
56500
+ "Content-Type": "application/json",
56501
+ ...headers
56502
+ },
56503
+ body: {
56504
+ content: JSON.stringify(body),
56505
+ values: body
56506
+ },
56507
+ failedResponseHandler,
56508
+ successfulResponseHandler,
56509
+ abortSignal,
56510
+ fetch: fetch2
56511
+ });
56512
+ var postToApi2 = async ({
56513
+ url: url2,
56514
+ headers = {},
56515
+ body,
56516
+ successfulResponseHandler,
56517
+ failedResponseHandler,
56518
+ abortSignal,
56519
+ fetch: fetch2 = getOriginalFetch22()
56520
+ }) => {
56521
+ try {
56522
+ const response = await fetch2(url2, {
56523
+ method: "POST",
56524
+ headers: withUserAgentSuffix2(headers, `ai-sdk/provider-utils/${VERSION8}`, getRuntimeEnvironmentUserAgent2()),
56525
+ body: body.content,
56526
+ signal: abortSignal
56527
+ });
56528
+ const responseHeaders = extractResponseHeaders2(response);
56529
+ if (!response.ok) {
56530
+ let errorInformation;
56531
+ try {
56532
+ errorInformation = await failedResponseHandler({
56533
+ response,
56534
+ url: url2,
56535
+ requestBodyValues: body.values
56536
+ });
56537
+ } catch (error48) {
56538
+ if (isAbortError2(error48) || APICallError.isInstance(error48)) {
56539
+ throw error48;
56540
+ }
56541
+ throw new APICallError({
56542
+ message: "Failed to process error response",
56543
+ cause: error48,
56544
+ statusCode: response.status,
56545
+ url: url2,
56546
+ responseHeaders,
56547
+ requestBodyValues: body.values
56548
+ });
56549
+ }
56550
+ throw errorInformation.value;
56551
+ }
56552
+ try {
56553
+ return await successfulResponseHandler({
56554
+ response,
56555
+ url: url2,
56556
+ requestBodyValues: body.values
56557
+ });
56558
+ } catch (error48) {
56559
+ if (error48 instanceof Error) {
56560
+ if (isAbortError2(error48) || APICallError.isInstance(error48)) {
56561
+ throw error48;
54334
56562
  }
54335
56563
  }
56564
+ throw new APICallError({
56565
+ message: "Failed to process successful response",
56566
+ cause: error48,
56567
+ statusCode: response.status,
56568
+ url: url2,
56569
+ responseHeaders,
56570
+ requestBodyValues: body.values
56571
+ });
54336
56572
  }
56573
+ } catch (error48) {
56574
+ throw handleFetchError2({ error: error48, url: url2, requestBodyValues: body.values });
56575
+ }
56576
+ };
56577
+ var createJsonErrorResponseHandler2 = ({
56578
+ errorSchema,
56579
+ errorToMessage,
56580
+ isRetryable
56581
+ }) => async ({ response, url: url2, requestBodyValues }) => {
56582
+ const responseBody = await response.text();
56583
+ const responseHeaders = extractResponseHeaders2(response);
56584
+ if (responseBody.trim() === "") {
54337
56585
  return {
54338
- formData,
54339
- warnings
56586
+ responseHeaders,
56587
+ value: new APICallError({
56588
+ message: response.statusText,
56589
+ url: url2,
56590
+ requestBodyValues,
56591
+ statusCode: response.status,
56592
+ responseHeaders,
56593
+ responseBody,
56594
+ isRetryable: isRetryable == null ? undefined : isRetryable(response)
56595
+ })
54340
56596
  };
54341
56597
  }
54342
- async doGenerate(options) {
54343
- var _a16, _b16, _c, _d, _e, _f, _g;
54344
- const currentDate = (_c = (_b16 = (_a16 = this.config._internal) == null ? undefined : _a16.currentDate) == null ? undefined : _b16.call(_a16)) != null ? _c : /* @__PURE__ */ new Date;
54345
- const { formData, warnings } = await this.getArgs(options);
54346
- const {
54347
- value: response,
54348
- responseHeaders,
54349
- rawValue: rawResponse
54350
- } = await postFormDataToApi({
54351
- url: this.config.url({
54352
- path: "/audio/transcriptions",
54353
- modelId: this.modelId
54354
- }),
54355
- headers: combineHeaders(this.config.headers(), options.headers),
54356
- formData,
54357
- failedResponseHandler: groqFailedResponseHandler,
54358
- successfulResponseHandler: createJsonResponseHandler(groqTranscriptionResponseSchema),
54359
- abortSignal: options.abortSignal,
54360
- fetch: this.config.fetch
56598
+ try {
56599
+ const parsedError = await parseJSON2({
56600
+ text: responseBody,
56601
+ schema: errorSchema
54361
56602
  });
54362
56603
  return {
54363
- text: response.text,
54364
- segments: (_e = (_d = response.segments) == null ? undefined : _d.map((segment) => ({
54365
- text: segment.text,
54366
- startSecond: segment.start,
54367
- endSecond: segment.end
54368
- }))) != null ? _e : [],
54369
- language: (_f = response.language) != null ? _f : undefined,
54370
- durationInSeconds: (_g = response.duration) != null ? _g : undefined,
54371
- warnings,
54372
- response: {
54373
- timestamp: currentDate,
54374
- modelId: this.modelId,
54375
- headers: responseHeaders,
54376
- body: rawResponse
54377
- }
56604
+ responseHeaders,
56605
+ value: new APICallError({
56606
+ message: errorToMessage(parsedError),
56607
+ url: url2,
56608
+ requestBodyValues,
56609
+ statusCode: response.status,
56610
+ responseHeaders,
56611
+ responseBody,
56612
+ data: parsedError,
56613
+ isRetryable: isRetryable == null ? undefined : isRetryable(response, parsedError)
56614
+ })
56615
+ };
56616
+ } catch (parseError) {
56617
+ return {
56618
+ responseHeaders,
56619
+ value: new APICallError({
56620
+ message: response.statusText,
56621
+ url: url2,
56622
+ requestBodyValues,
56623
+ statusCode: response.status,
56624
+ responseHeaders,
56625
+ responseBody,
56626
+ isRetryable: isRetryable == null ? undefined : isRetryable(response)
56627
+ })
54378
56628
  };
54379
56629
  }
54380
56630
  };
54381
- var groqTranscriptionResponseSchema = exports_external.object({
54382
- text: exports_external.string(),
54383
- x_groq: exports_external.object({
54384
- id: exports_external.string()
54385
- }),
54386
- task: exports_external.string().nullish(),
54387
- language: exports_external.string().nullish(),
54388
- duration: exports_external.number().nullish(),
54389
- segments: exports_external.array(exports_external.object({
54390
- id: exports_external.number(),
54391
- seek: exports_external.number(),
54392
- start: exports_external.number(),
54393
- end: exports_external.number(),
54394
- text: exports_external.string(),
54395
- tokens: exports_external.array(exports_external.number()),
54396
- temperature: exports_external.number(),
54397
- avg_logprob: exports_external.number(),
54398
- compression_ratio: exports_external.number(),
54399
- no_speech_prob: exports_external.number()
54400
- })).nullish()
54401
- });
54402
- var browserSearch = createProviderToolFactory({
54403
- id: "groq.browser_search",
54404
- inputSchema: exports_external.object({})
54405
- });
54406
- var groqTools = {
54407
- browserSearch
54408
- };
54409
- var VERSION7 = "3.0.31";
54410
- function createGroq(options = {}) {
54411
- var _a16;
54412
- const baseURL = (_a16 = withoutTrailingSlash(options.baseURL)) != null ? _a16 : "https://api.groq.com/openai/v1";
54413
- const getHeaders = () => withUserAgentSuffix({
54414
- Authorization: `Bearer ${loadApiKey({
54415
- apiKey: options.apiKey,
54416
- environmentVariableName: "GROQ_API_KEY",
54417
- description: "Groq"
54418
- })}`,
54419
- ...options.headers
54420
- }, `ai-sdk/groq/${VERSION7}`);
54421
- const createChatModel = (modelId) => new GroqChatLanguageModel(modelId, {
54422
- provider: "groq.chat",
54423
- url: ({ path: path2 }) => `${baseURL}${path2}`,
54424
- headers: getHeaders,
54425
- fetch: options.fetch
56631
+ var createJsonResponseHandler2 = (responseSchema2) => async ({ response, url: url2, requestBodyValues }) => {
56632
+ const responseBody = await response.text();
56633
+ const parsedResult = await safeParseJSON2({
56634
+ text: responseBody,
56635
+ schema: responseSchema2
54426
56636
  });
54427
- const createLanguageModel = (modelId) => {
54428
- if (new.target) {
54429
- throw new Error("The Groq model function cannot be called with the new keyword.");
54430
- }
54431
- return createChatModel(modelId);
54432
- };
54433
- const createTranscriptionModel = (modelId) => {
54434
- return new GroqTranscriptionModel(modelId, {
54435
- provider: "groq.transcription",
54436
- url: ({ path: path2 }) => `${baseURL}${path2}`,
54437
- headers: getHeaders,
54438
- fetch: options.fetch
56637
+ const responseHeaders = extractResponseHeaders2(response);
56638
+ if (!parsedResult.success) {
56639
+ throw new APICallError({
56640
+ message: "Invalid JSON response",
56641
+ cause: parsedResult.error,
56642
+ statusCode: response.status,
56643
+ responseHeaders,
56644
+ responseBody,
56645
+ url: url2,
56646
+ requestBodyValues
54439
56647
  });
56648
+ }
56649
+ return {
56650
+ responseHeaders,
56651
+ value: parsedResult.value,
56652
+ rawValue: parsedResult.rawValue
54440
56653
  };
54441
- const provider = function(modelId) {
54442
- return createLanguageModel(modelId);
54443
- };
54444
- provider.specificationVersion = "v3";
54445
- provider.languageModel = createLanguageModel;
54446
- provider.chat = createChatModel;
54447
- provider.embeddingModel = (modelId) => {
54448
- throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
54449
- };
54450
- provider.textEmbeddingModel = provider.embeddingModel;
54451
- provider.imageModel = (modelId) => {
54452
- throw new NoSuchModelError({ modelId, modelType: "imageModel" });
54453
- };
54454
- provider.transcription = createTranscriptionModel;
54455
- provider.transcriptionModel = createTranscriptionModel;
54456
- provider.tools = groqTools;
54457
- return provider;
54458
- }
54459
- var groq = createGroq();
54460
-
54461
- // src/providers/groq.ts
54462
- function createGroqProvider(config2, providerName) {
54463
- return createGroq({
54464
- apiKey: resolveApiKey(config2.api_key_env, providerName),
54465
- baseURL: config2.base_url,
54466
- headers: config2.headers
54467
- });
56654
+ };
56655
+ function withoutTrailingSlash2(url2) {
56656
+ return url2 == null ? undefined : url2.replace(/\/$/, "");
54468
56657
  }
54469
56658
 
54470
56659
  // node_modules/ollama-ai-provider-v2/dist/index.mjs
@@ -54582,7 +56771,7 @@ function getResponseMetadata5({
54582
56771
  }
54583
56772
  function createNdjsonStreamResponseHandler(schema) {
54584
56773
  return async ({ response }) => {
54585
- const responseHeaders = extractResponseHeaders(response);
56774
+ const responseHeaders = extractResponseHeaders2(response);
54586
56775
  if (response.body == null) {
54587
56776
  throw new Error("Response body is null");
54588
56777
  }
@@ -54640,7 +56829,7 @@ var ollamaErrorDataSchema = exports_external.object({
54640
56829
  code: exports_external.union([exports_external.string(), exports_external.number()]).nullish()
54641
56830
  })
54642
56831
  });
54643
- var ollamaFailedResponseHandler = createJsonErrorResponseHandler({
56832
+ var ollamaFailedResponseHandler = createJsonErrorResponseHandler2({
54644
56833
  errorSchema: ollamaErrorDataSchema,
54645
56834
  errorToMessage: (data) => data.error.message
54646
56835
  });
@@ -54722,15 +56911,15 @@ var OllamaCompletionLanguageModel = class {
54722
56911
  responseHeaders,
54723
56912
  value: response,
54724
56913
  rawValue: rawResponse
54725
- } = await postJsonToApi({
56914
+ } = await postJsonToApi2({
54726
56915
  url: this.config.url({
54727
56916
  path: "/generate",
54728
56917
  modelId: this.modelId
54729
56918
  }),
54730
- headers: combineHeaders(this.config.headers(), options.headers),
56919
+ headers: combineHeaders2(this.config.headers(), options.headers),
54731
56920
  body: { ...body, stream: false },
54732
56921
  failedResponseHandler: ollamaFailedResponseHandler,
54733
- successfulResponseHandler: createJsonResponseHandler(baseOllamaResponseSchema),
56922
+ successfulResponseHandler: createJsonResponseHandler2(baseOllamaResponseSchema),
54734
56923
  abortSignal: options.abortSignal,
54735
56924
  fetch: this.config.fetch
54736
56925
  });
@@ -54772,12 +56961,12 @@ var OllamaCompletionLanguageModel = class {
54772
56961
  ...args,
54773
56962
  stream: true
54774
56963
  };
54775
- const { responseHeaders, value: response } = await postJsonToApi({
56964
+ const { responseHeaders, value: response } = await postJsonToApi2({
54776
56965
  url: this.config.url({
54777
56966
  path: "/generate",
54778
56967
  modelId: this.modelId
54779
56968
  }),
54780
- headers: combineHeaders(this.config.headers(), options.headers),
56969
+ headers: combineHeaders2(this.config.headers(), options.headers),
54781
56970
  body,
54782
56971
  failedResponseHandler: ollamaFailedResponseHandler,
54783
56972
  successfulResponseHandler: createNdjsonStreamResponseHandler(baseOllamaResponseSchema),
@@ -54801,7 +56990,7 @@ var OllamaCompletionLanguageModel = class {
54801
56990
  };
54802
56991
  let isFirstChunk = true;
54803
56992
  let textStarted = false;
54804
- const textId = generateId();
56993
+ const textId = generateId2();
54805
56994
  return {
54806
56995
  stream: response.pipeThrough(new TransformStream({
54807
56996
  transform(chunk, controller) {
@@ -54915,7 +57104,7 @@ var OllamaEmbeddingModel = class {
54915
57104
  values
54916
57105
  });
54917
57106
  }
54918
- const ollamaOptions = await parseProviderOptions({
57107
+ const ollamaOptions = await parseProviderOptions2({
54919
57108
  provider: "ollama",
54920
57109
  providerOptions,
54921
57110
  schema: ollamaEmbeddingProviderOptions
@@ -54937,15 +57126,15 @@ var OllamaEmbeddingModel = class {
54937
57126
  responseHeaders,
54938
57127
  value: response,
54939
57128
  rawValue
54940
- } = await postJsonToApi({
57129
+ } = await postJsonToApi2({
54941
57130
  url: this.config.url({
54942
57131
  path: "/embed",
54943
57132
  modelId: this.modelId
54944
57133
  }),
54945
- headers: combineHeaders(this.config.headers(), headers),
57134
+ headers: combineHeaders2(this.config.headers(), headers),
54946
57135
  body: { ...body },
54947
57136
  failedResponseHandler: ollamaFailedResponseHandler,
54948
- successfulResponseHandler: createJsonResponseHandler(ollamaTextEmbeddingResponseSchema),
57137
+ successfulResponseHandler: createJsonResponseHandler2(ollamaTextEmbeddingResponseSchema),
54949
57138
  abortSignal,
54950
57139
  fetch: this.config.fetch
54951
57140
  });
@@ -55027,7 +57216,7 @@ var OllamaResponseProcessor = class {
55027
57216
  for (const toolCall of (_a16 = response.message.tool_calls) != null ? _a16 : []) {
55028
57217
  content.push({
55029
57218
  type: "tool-call",
55030
- toolCallId: (_e = toolCall.id) != null ? _e : (_d = (_c = (_b16 = this.config).generateId) == null ? undefined : _c.call(_b16)) != null ? _d : generateId(),
57219
+ toolCallId: (_e = toolCall.id) != null ? _e : (_d = (_c = (_b16 = this.config).generateId) == null ? undefined : _c.call(_b16)) != null ? _d : generateId2(),
55031
57220
  toolName: toolCall.function.name,
55032
57221
  input: JSON.stringify(toolCall.function.arguments)
55033
57222
  });
@@ -55476,7 +57665,7 @@ var OllamaRequestBuilder = class {
55476
57665
  return warnings;
55477
57666
  }
55478
57667
  async parseProviderOptions(providerOptions) {
55479
- const result = await parseProviderOptions({
57668
+ const result = await parseProviderOptions2({
55480
57669
  provider: "ollama",
55481
57670
  providerOptions,
55482
57671
  schema: ollamaProviderOptions
@@ -55552,8 +57741,8 @@ var OllamaStreamProcessor = class {
55552
57741
  hasReasoningStarted: false,
55553
57742
  textEnded: false,
55554
57743
  reasoningEnded: false,
55555
- textId: generateId(),
55556
- reasoningId: generateId()
57744
+ textId: generateId2(),
57745
+ reasoningId: generateId2()
55557
57746
  };
55558
57747
  }
55559
57748
  processChunk(chunk, controller, options) {
@@ -55664,7 +57853,7 @@ var OllamaStreamProcessor = class {
55664
57853
  }
55665
57854
  emitToolCall(toolCall, controller) {
55666
57855
  var _a16, _b16, _c, _d;
55667
- const id = (_d = toolCall.id) != null ? _d : (_c = (_b16 = (_a16 = this.config).generateId) == null ? undefined : _b16.call(_a16)) != null ? _c : generateId();
57856
+ const id = (_d = toolCall.id) != null ? _d : (_c = (_b16 = (_a16 = this.config).generateId) == null ? undefined : _b16.call(_a16)) != null ? _c : generateId2();
55668
57857
  controller.enqueue({
55669
57858
  type: "tool-input-start",
55670
57859
  id,
@@ -55729,15 +57918,15 @@ var OllamaResponsesLanguageModel = class {
55729
57918
  responseHeaders,
55730
57919
  value: response,
55731
57920
  rawValue: rawResponse
55732
- } = await postJsonToApi({
57921
+ } = await postJsonToApi2({
55733
57922
  url: this.config.url({
55734
57923
  path: "/chat",
55735
57924
  modelId: this.modelId
55736
57925
  }),
55737
- headers: combineHeaders(this.config.headers(), options.headers),
57926
+ headers: combineHeaders2(this.config.headers(), options.headers),
55738
57927
  body: { ...body, stream: false },
55739
57928
  failedResponseHandler: ollamaFailedResponseHandler,
55740
- successfulResponseHandler: createJsonResponseHandler(baseOllamaResponseSchema2),
57929
+ successfulResponseHandler: createJsonResponseHandler2(baseOllamaResponseSchema2),
55741
57930
  abortSignal: options.abortSignal,
55742
57931
  fetch: this.config.fetch
55743
57932
  });
@@ -55756,12 +57945,12 @@ var OllamaResponsesLanguageModel = class {
55756
57945
  }
55757
57946
  async doStream(options) {
55758
57947
  const { args: body, warnings } = await this.prepareRequest(options);
55759
- const { responseHeaders, value: response } = await postJsonToApi({
57948
+ const { responseHeaders, value: response } = await postJsonToApi2({
55760
57949
  url: this.config.url({
55761
57950
  path: "/chat",
55762
57951
  modelId: this.modelId
55763
57952
  }),
55764
- headers: combineHeaders(this.config.headers(), options.headers),
57953
+ headers: combineHeaders2(this.config.headers(), options.headers),
55765
57954
  body: { ...body, stream: true },
55766
57955
  failedResponseHandler: ollamaFailedResponseHandler,
55767
57956
  successfulResponseHandler: createNdjsonStreamResponseHandler(baseOllamaResponseSchema2),
@@ -55785,7 +57974,7 @@ var OllamaResponsesLanguageModel = class {
55785
57974
  };
55786
57975
  function createOllama(options = {}) {
55787
57976
  var _a16, _b16;
55788
- const baseURL = (_a16 = withoutTrailingSlash(options.baseURL)) != null ? _a16 : "http://127.0.0.1:11434/api";
57977
+ const baseURL = (_a16 = withoutTrailingSlash2(options.baseURL)) != null ? _a16 : "http://127.0.0.1:11434/api";
55789
57978
  const providerName = (_b16 = options.name) != null ? _b16 : "ollama";
55790
57979
  const getHeaders = () => ({
55791
57980
  "Ollama-Organization": options.organization,
@@ -55918,6 +58107,9 @@ function convertOpenAIChatUsage2(usage) {
55918
58107
  raw: usage
55919
58108
  };
55920
58109
  }
58110
+ function serializeToolCallArguments3(input) {
58111
+ return JSON.stringify(input === undefined ? {} : input);
58112
+ }
55921
58113
  function convertToOpenAIChatMessages2({
55922
58114
  prompt,
55923
58115
  systemMessageMode = "system"
@@ -56045,7 +58237,7 @@ function convertToOpenAIChatMessages2({
56045
58237
  type: "function",
56046
58238
  function: {
56047
58239
  name: part.toolName,
56048
- arguments: JSON.stringify(part.input)
58240
+ arguments: serializeToolCallArguments3(part.input)
56049
58241
  }
56050
58242
  });
56051
58243
  break;
@@ -57863,6 +60055,9 @@ function convertOpenAIResponsesUsage2(usage) {
57863
60055
  raw: usage
57864
60056
  };
57865
60057
  }
60058
+ function serializeToolCallArguments22(input) {
60059
+ return JSON.stringify(input === undefined ? {} : input);
60060
+ }
57866
60061
  function isFileId2(data, prefixes) {
57867
60062
  if (!prefixes)
57868
60063
  return false;
@@ -58083,7 +60278,7 @@ async function convertToOpenAIResponsesInput2({
58083
60278
  type: "function_call",
58084
60279
  call_id: part.toolCallId,
58085
60280
  name: resolvedToolName,
58086
- arguments: JSON.stringify(part.input),
60281
+ arguments: serializeToolCallArguments22(part.input),
58087
60282
  id
58088
60283
  });
58089
60284
  break;
@@ -59484,8 +61679,8 @@ async function prepareResponsesTools3({
59484
61679
  value: tool2.args,
59485
61680
  schema: mcpArgsSchema2
59486
61681
  });
59487
- const mapApprovalFilter = (filter2) => ({
59488
- tool_names: filter2.toolNames
61682
+ const mapApprovalFilter = (filter3) => ({
61683
+ tool_names: filter3.toolNames
59489
61684
  });
59490
61685
  const requireApproval = args.requireApproval;
59491
61686
  const requireApprovalParam = requireApproval == null ? undefined : typeof requireApproval === "string" ? requireApproval : requireApproval.never != null ? { never: mapApprovalFilter(requireApproval.never) } : undefined;
@@ -61546,7 +63741,7 @@ var OpenAITranscriptionModel2 = class {
61546
63741
  };
61547
63742
  }
61548
63743
  };
61549
- var VERSION8 = "3.0.49";
63744
+ var VERSION9 = "3.0.53";
61550
63745
  function createOpenAI(options = {}) {
61551
63746
  var _a16, _b16;
61552
63747
  const baseURL = (_a16 = withoutTrailingSlash(loadOptionalSetting({
@@ -61563,7 +63758,7 @@ function createOpenAI(options = {}) {
61563
63758
  "OpenAI-Organization": options.organization,
61564
63759
  "OpenAI-Project": options.project,
61565
63760
  ...options.headers
61566
- }, `ai-sdk/openai/${VERSION8}`);
63761
+ }, `ai-sdk/openai/${VERSION9}`);
61567
63762
  const createChatModel = (modelId) => new OpenAIChatLanguageModel2(modelId, {
61568
63763
  provider: `${providerName}.chat`,
61569
63764
  url: ({ path: path2 }) => `${baseURL}${path2}`,
@@ -61648,6 +63843,16 @@ function createOpenAIProvider(config2, providerName) {
61648
63843
  }
61649
63844
 
61650
63845
  // node_modules/@ai-sdk/openai-compatible/dist/index.mjs
63846
+ function toCamelCase(str) {
63847
+ return str.replace(/[_-]([a-z])/g, (g) => g[1].toUpperCase());
63848
+ }
63849
+ function resolveProviderOptionsKey(rawName, providerOptions) {
63850
+ const camelName = toCamelCase(rawName);
63851
+ if (camelName !== rawName && (providerOptions == null ? undefined : providerOptions[camelName]) != null) {
63852
+ return camelName;
63853
+ }
63854
+ return rawName;
63855
+ }
61651
63856
  var openaiCompatibleErrorDataSchema = exports_external.object({
61652
63857
  error: exports_external.object({
61653
63858
  message: exports_external.string(),
@@ -62037,8 +64242,12 @@ var OpenAICompatibleChatLanguageModel = class {
62037
64242
  provider: this.providerOptionsName,
62038
64243
  providerOptions,
62039
64244
  schema: openaiCompatibleLanguageModelChatOptions
62040
- })) != null ? _b16 : {});
62041
- const strictJsonSchema = (_c = compatibleOptions == null ? undefined : compatibleOptions.strictJsonSchema) != null ? _c : true;
64245
+ })) != null ? _b16 : {}, (_c = await parseProviderOptions({
64246
+ provider: toCamelCase(this.providerOptionsName),
64247
+ providerOptions,
64248
+ schema: openaiCompatibleLanguageModelChatOptions
64249
+ })) != null ? _c : {});
64250
+ const strictJsonSchema = (_d = compatibleOptions == null ? undefined : compatibleOptions.strictJsonSchema) != null ? _d : true;
62042
64251
  if (topK != null) {
62043
64252
  warnings.push({ type: "unsupported", feature: "topK" });
62044
64253
  }
@@ -62057,7 +64266,9 @@ var OpenAICompatibleChatLanguageModel = class {
62057
64266
  tools,
62058
64267
  toolChoice
62059
64268
  });
64269
+ const metadataKey = resolveProviderOptionsKey(this.providerOptionsName, providerOptions);
62060
64270
  return {
64271
+ metadataKey,
62061
64272
  args: {
62062
64273
  model: this.modelId,
62063
64274
  user: compatibleOptions.user,
@@ -62071,13 +64282,16 @@ var OpenAICompatibleChatLanguageModel = class {
62071
64282
  json_schema: {
62072
64283
  schema: responseFormat.schema,
62073
64284
  strict: strictJsonSchema,
62074
- name: (_d = responseFormat.name) != null ? _d : "response",
64285
+ name: (_e = responseFormat.name) != null ? _e : "response",
62075
64286
  description: responseFormat.description
62076
64287
  }
62077
64288
  } : { type: "json_object" } : undefined,
62078
64289
  stop: stopSequences,
62079
64290
  seed,
62080
- ...Object.fromEntries(Object.entries((_e = providerOptions == null ? undefined : providerOptions[this.providerOptionsName]) != null ? _e : {}).filter(([key]) => !Object.keys(openaiCompatibleLanguageModelChatOptions.shape).includes(key))),
64291
+ ...Object.fromEntries(Object.entries({
64292
+ ...providerOptions == null ? undefined : providerOptions[this.providerOptionsName],
64293
+ ...providerOptions == null ? undefined : providerOptions[toCamelCase(this.providerOptionsName)]
64294
+ }).filter(([key]) => !Object.keys(openaiCompatibleLanguageModelChatOptions.shape).includes(key))),
62081
64295
  reasoning_effort: compatibleOptions.reasoningEffort,
62082
64296
  verbosity: compatibleOptions.textVerbosity,
62083
64297
  messages: convertToOpenAICompatibleChatMessages(prompt),
@@ -62089,7 +64303,7 @@ var OpenAICompatibleChatLanguageModel = class {
62089
64303
  }
62090
64304
  async doGenerate(options) {
62091
64305
  var _a16, _b16, _c, _d, _e, _f, _g, _h;
62092
- const { args, warnings } = await this.getArgs({ ...options });
64306
+ const { args, warnings, metadataKey } = await this.getArgs({ ...options });
62093
64307
  const transformedBody = this.transformRequestBody(args);
62094
64308
  const body = JSON.stringify(transformedBody);
62095
64309
  const {
@@ -62131,24 +64345,24 @@ var OpenAICompatibleChatLanguageModel = class {
62131
64345
  input: toolCall.function.arguments,
62132
64346
  ...thoughtSignature ? {
62133
64347
  providerMetadata: {
62134
- [this.providerOptionsName]: { thoughtSignature }
64348
+ [metadataKey]: { thoughtSignature }
62135
64349
  }
62136
64350
  } : {}
62137
64351
  });
62138
64352
  }
62139
64353
  }
62140
64354
  const providerMetadata = {
62141
- [this.providerOptionsName]: {},
64355
+ [metadataKey]: {},
62142
64356
  ...await ((_f = (_e = this.config.metadataExtractor) == null ? undefined : _e.extractMetadata) == null ? undefined : _f.call(_e, {
62143
64357
  parsedBody: rawResponse
62144
64358
  }))
62145
64359
  };
62146
64360
  const completionTokenDetails = (_g = responseBody.usage) == null ? undefined : _g.completion_tokens_details;
62147
64361
  if ((completionTokenDetails == null ? undefined : completionTokenDetails.accepted_prediction_tokens) != null) {
62148
- providerMetadata[this.providerOptionsName].acceptedPredictionTokens = completionTokenDetails == null ? undefined : completionTokenDetails.accepted_prediction_tokens;
64362
+ providerMetadata[metadataKey].acceptedPredictionTokens = completionTokenDetails == null ? undefined : completionTokenDetails.accepted_prediction_tokens;
62149
64363
  }
62150
64364
  if ((completionTokenDetails == null ? undefined : completionTokenDetails.rejected_prediction_tokens) != null) {
62151
- providerMetadata[this.providerOptionsName].rejectedPredictionTokens = completionTokenDetails == null ? undefined : completionTokenDetails.rejected_prediction_tokens;
64365
+ providerMetadata[metadataKey].rejectedPredictionTokens = completionTokenDetails == null ? undefined : completionTokenDetails.rejected_prediction_tokens;
62152
64366
  }
62153
64367
  return {
62154
64368
  content,
@@ -62169,7 +64383,7 @@ var OpenAICompatibleChatLanguageModel = class {
62169
64383
  }
62170
64384
  async doStream(options) {
62171
64385
  var _a16;
62172
- const { args, warnings } = await this.getArgs({ ...options });
64386
+ const { args, warnings, metadataKey } = await this.getArgs({ ...options });
62173
64387
  const body = this.transformRequestBody({
62174
64388
  ...args,
62175
64389
  stream: true,
@@ -62195,7 +64409,7 @@ var OpenAICompatibleChatLanguageModel = class {
62195
64409
  };
62196
64410
  let usage = undefined;
62197
64411
  let isFirstChunk = true;
62198
- const providerOptionsName = this.providerOptionsName;
64412
+ const providerOptionsName = metadataKey;
62199
64413
  let isActiveReasoning = false;
62200
64414
  let isActiveText = false;
62201
64415
  return {
@@ -62675,13 +64889,17 @@ var OpenAICompatibleCompletionLanguageModel = class {
62675
64889
  tools,
62676
64890
  toolChoice
62677
64891
  }) {
62678
- var _a16;
64892
+ var _a16, _b16;
62679
64893
  const warnings = [];
62680
- const completionOptions = (_a16 = await parseProviderOptions({
64894
+ const completionOptions = Object.assign((_a16 = await parseProviderOptions({
62681
64895
  provider: this.providerOptionsName,
62682
64896
  providerOptions,
62683
64897
  schema: openaiCompatibleLanguageModelCompletionOptions
62684
- })) != null ? _a16 : {};
64898
+ })) != null ? _a16 : {}, (_b16 = await parseProviderOptions({
64899
+ provider: toCamelCase(this.providerOptionsName),
64900
+ providerOptions,
64901
+ schema: openaiCompatibleLanguageModelCompletionOptions
64902
+ })) != null ? _b16 : {});
62685
64903
  if (topK != null) {
62686
64904
  warnings.push({ type: "unsupported", feature: "topK" });
62687
64905
  }
@@ -62714,6 +64932,7 @@ var OpenAICompatibleCompletionLanguageModel = class {
62714
64932
  presence_penalty: presencePenalty,
62715
64933
  seed,
62716
64934
  ...providerOptions == null ? undefined : providerOptions[this.providerOptionsName],
64935
+ ...providerOptions == null ? undefined : providerOptions[toCamelCase(this.providerOptionsName)],
62717
64936
  prompt: completionPrompt,
62718
64937
  stop: stop.length > 0 ? stop : undefined
62719
64938
  },
@@ -63091,10 +65310,7 @@ async function fileToBlob3(file2) {
63091
65310
  const data = file2.data instanceof Uint8Array ? file2.data : convertBase64ToUint8Array(file2.data);
63092
65311
  return new Blob([data], { type: file2.mediaType });
63093
65312
  }
63094
- function toCamelCase(str) {
63095
- return str.replace(/[_-]([a-z])/g, (g) => g[1].toUpperCase());
63096
- }
63097
- var VERSION9 = "2.0.37";
65313
+ var VERSION10 = "2.0.41";
63098
65314
  function createOpenAICompatible(options) {
63099
65315
  const baseURL = withoutTrailingSlash(options.baseURL);
63100
65316
  const providerName = options.name;
@@ -63102,7 +65318,7 @@ function createOpenAICompatible(options) {
63102
65318
  ...options.apiKey && { Authorization: `Bearer ${options.apiKey}` },
63103
65319
  ...options.headers
63104
65320
  };
63105
- const getHeaders = () => withUserAgentSuffix(headers, `ai-sdk/openai-compatible/${VERSION9}`);
65321
+ const getHeaders = () => withUserAgentSuffix(headers, `ai-sdk/openai-compatible/${VERSION10}`);
63106
65322
  const getCommonModelConfig = (modelType) => ({
63107
65323
  provider: `${providerName}.${modelType}`,
63108
65324
  url: ({ path: path2 }) => {
@@ -63330,11 +65546,11 @@ function listProviders(config2) {
63330
65546
  // node_modules/@ai-sdk/gateway/dist/index.mjs
63331
65547
  var import_oidc = __toESM(require_dist(), 1);
63332
65548
  var import_oidc2 = __toESM(require_dist(), 1);
63333
- var marker17 = "vercel.ai.gateway.error";
63334
- var symbol17 = Symbol.for(marker17);
63335
- var _a17;
63336
- var _b17;
63337
- var GatewayError = class _GatewayError extends (_b17 = Error, _a17 = symbol17, _b17) {
65549
+ var marker18 = "vercel.ai.gateway.error";
65550
+ var symbol18 = Symbol.for(marker18);
65551
+ var _a18;
65552
+ var _b18;
65553
+ var GatewayError = class _GatewayError extends (_b18 = Error, _a18 = symbol18, _b18) {
63338
65554
  constructor({
63339
65555
  message,
63340
65556
  statusCode = 500,
@@ -63342,7 +65558,7 @@ var GatewayError = class _GatewayError extends (_b17 = Error, _a17 = symbol17, _
63342
65558
  generationId
63343
65559
  }) {
63344
65560
  super(generationId ? `${message} [${generationId}]` : message);
63345
- this[_a17] = true;
65561
+ this[_a18] = true;
63346
65562
  this.statusCode = statusCode;
63347
65563
  this.cause = cause;
63348
65564
  this.generationId = generationId;
@@ -63351,11 +65567,11 @@ var GatewayError = class _GatewayError extends (_b17 = Error, _a17 = symbol17, _
63351
65567
  return _GatewayError.hasMarker(error48);
63352
65568
  }
63353
65569
  static hasMarker(error48) {
63354
- return typeof error48 === "object" && error48 !== null && symbol17 in error48 && error48[symbol17] === true;
65570
+ return typeof error48 === "object" && error48 !== null && symbol18 in error48 && error48[symbol18] === true;
63355
65571
  }
63356
65572
  };
63357
- var name16 = "GatewayAuthenticationError";
63358
- var marker22 = `vercel.ai.gateway.error.${name16}`;
65573
+ var name17 = "GatewayAuthenticationError";
65574
+ var marker22 = `vercel.ai.gateway.error.${name17}`;
63359
65575
  var symbol23 = Symbol.for(marker22);
63360
65576
  var _a23;
63361
65577
  var _b22;
@@ -63368,7 +65584,7 @@ var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b22
63368
65584
  } = {}) {
63369
65585
  super({ message, statusCode, cause, generationId });
63370
65586
  this[_a23] = true;
63371
- this.name = name16;
65587
+ this.name = name17;
63372
65588
  this.type = "authentication_error";
63373
65589
  }
63374
65590
  static isInstance(error48) {
@@ -63723,6 +65939,13 @@ async function parseAuthMethod(headers) {
63723
65939
  return result.success ? result.value : undefined;
63724
65940
  }
63725
65941
  var gatewayAuthMethodSchema = lazySchema(() => zodSchema(exports_external.union([exports_external.literal("api-key"), exports_external.literal("oidc")])));
65942
+ var KNOWN_MODEL_TYPES = [
65943
+ "embedding",
65944
+ "image",
65945
+ "language",
65946
+ "reranking",
65947
+ "video"
65948
+ ];
63726
65949
  var GatewayFetchMetadata = class {
63727
65950
  constructor(config2) {
63728
65951
  this.config = config2;
@@ -63784,8 +66007,8 @@ var gatewayAvailableModelsResponseSchema = lazySchema(() => zodSchema(exports_ex
63784
66007
  provider: exports_external.string(),
63785
66008
  modelId: exports_external.string()
63786
66009
  }),
63787
- modelType: exports_external.enum(["embedding", "image", "language", "video"]).nullish()
63788
- }))
66010
+ modelType: exports_external.string().nullish()
66011
+ })).transform((models) => models.filter((m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType)))
63789
66012
  })));
63790
66013
  var gatewayCreditsResponseSchema = lazySchema(() => zodSchema(exports_external.object({
63791
66014
  balance: exports_external.string(),
@@ -64457,6 +66680,73 @@ var gatewayVideoEventSchema = exports_external.discriminatedUnion("type", [
64457
66680
  param: exports_external.unknown().nullable()
64458
66681
  })
64459
66682
  ]);
66683
+ var GatewayRerankingModel = class {
66684
+ constructor(modelId, config2) {
66685
+ this.modelId = modelId;
66686
+ this.config = config2;
66687
+ this.specificationVersion = "v3";
66688
+ }
66689
+ get provider() {
66690
+ return this.config.provider;
66691
+ }
66692
+ async doRerank({
66693
+ documents,
66694
+ query,
66695
+ topN,
66696
+ headers,
66697
+ abortSignal,
66698
+ providerOptions
66699
+ }) {
66700
+ const resolvedHeaders = await resolve(this.config.headers());
66701
+ try {
66702
+ const {
66703
+ responseHeaders,
66704
+ value: responseBody,
66705
+ rawValue
66706
+ } = await postJsonToApi({
66707
+ url: this.getUrl(),
66708
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
66709
+ body: {
66710
+ documents,
66711
+ query,
66712
+ ...topN != null ? { topN } : {},
66713
+ ...providerOptions ? { providerOptions } : {}
66714
+ },
66715
+ successfulResponseHandler: createJsonResponseHandler(gatewayRerankingResponseSchema),
66716
+ failedResponseHandler: createJsonErrorResponseHandler({
66717
+ errorSchema: exports_external.any(),
66718
+ errorToMessage: (data) => data
66719
+ }),
66720
+ ...abortSignal && { abortSignal },
66721
+ fetch: this.config.fetch
66722
+ });
66723
+ return {
66724
+ ranking: responseBody.ranking,
66725
+ providerMetadata: responseBody.providerMetadata,
66726
+ response: { headers: responseHeaders, body: rawValue },
66727
+ warnings: []
66728
+ };
66729
+ } catch (error48) {
66730
+ throw await asGatewayError(error48, await parseAuthMethod(resolvedHeaders));
66731
+ }
66732
+ }
66733
+ getUrl() {
66734
+ return `${this.config.baseURL}/reranking-model`;
66735
+ }
66736
+ getModelConfigHeaders() {
66737
+ return {
66738
+ "ai-reranking-model-specification-version": "3",
66739
+ "ai-model-id": this.modelId
66740
+ };
66741
+ }
66742
+ };
66743
+ var gatewayRerankingResponseSchema = lazySchema(() => zodSchema(exports_external.object({
66744
+ ranking: exports_external.array(exports_external.object({
66745
+ index: exports_external.number(),
66746
+ relevanceScore: exports_external.number()
66747
+ })),
66748
+ providerMetadata: exports_external.record(exports_external.string(), exports_external.record(exports_external.string(), exports_external.unknown())).optional()
66749
+ })));
64460
66750
  var parallelSearchInputSchema = lazySchema(() => zodSchema(exports_external.object({
64461
66751
  objective: exports_external.string().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),
64462
66752
  search_queries: exports_external.array(exports_external.string()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),
@@ -64556,7 +66846,7 @@ async function getVercelRequestId() {
64556
66846
  var _a92;
64557
66847
  return (_a92 = import_oidc.getContext().headers) == null ? undefined : _a92["x-vercel-id"];
64558
66848
  }
64559
- var VERSION10 = "3.0.84";
66849
+ var VERSION11 = "3.0.104";
64560
66850
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
64561
66851
  function createGatewayProvider(options = {}) {
64562
66852
  var _a92, _b92;
@@ -64573,7 +66863,7 @@ function createGatewayProvider(options = {}) {
64573
66863
  "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION,
64574
66864
  [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,
64575
66865
  ...options.headers
64576
- }, `ai-sdk/gateway/${VERSION10}`);
66866
+ }, `ai-sdk/gateway/${VERSION11}`);
64577
66867
  } catch (error48) {
64578
66868
  throw GatewayAuthenticationError.createContextualError({
64579
66869
  apiKeyProvided: false,
@@ -64706,6 +66996,17 @@ function createGatewayProvider(options = {}) {
64706
66996
  o11yHeaders: createO11yHeaders()
64707
66997
  });
64708
66998
  };
66999
+ const createRerankingModel = (modelId) => {
67000
+ return new GatewayRerankingModel(modelId, {
67001
+ provider: "gateway",
67002
+ baseURL,
67003
+ headers: getHeaders,
67004
+ fetch: options.fetch,
67005
+ o11yHeaders: createO11yHeaders()
67006
+ });
67007
+ };
67008
+ provider.rerankingModel = createRerankingModel;
67009
+ provider.reranking = createRerankingModel;
64709
67010
  provider.chat = provider.languageModel;
64710
67011
  provider.embedding = provider.embeddingModel;
64711
67012
  provider.image = provider.imageModel;
@@ -64740,10 +67041,10 @@ var __export2 = (target, all) => {
64740
67041
  for (var name21 in all)
64741
67042
  __defProp2(target, name21, { get: all[name21], enumerable: true });
64742
67043
  };
64743
- var name17 = "AI_InvalidArgumentError";
64744
- var marker18 = `vercel.ai.error.${name17}`;
64745
- var symbol18 = Symbol.for(marker18);
64746
- var _a18;
67044
+ var name18 = "AI_InvalidArgumentError";
67045
+ var marker19 = `vercel.ai.error.${name18}`;
67046
+ var symbol19 = Symbol.for(marker19);
67047
+ var _a19;
64747
67048
  var InvalidArgumentError2 = class extends AISDKError {
64748
67049
  constructor({
64749
67050
  parameter,
@@ -64751,18 +67052,18 @@ var InvalidArgumentError2 = class extends AISDKError {
64751
67052
  message
64752
67053
  }) {
64753
67054
  super({
64754
- name: name17,
67055
+ name: name18,
64755
67056
  message: `Invalid argument for parameter ${parameter}: ${message}`
64756
67057
  });
64757
- this[_a18] = true;
67058
+ this[_a19] = true;
64758
67059
  this.parameter = parameter;
64759
67060
  this.value = value;
64760
67061
  }
64761
67062
  static isInstance(error48) {
64762
- return AISDKError.hasMarker(error48, marker18);
67063
+ return AISDKError.hasMarker(error48, marker19);
64763
67064
  }
64764
67065
  };
64765
- _a18 = symbol18;
67066
+ _a19 = symbol19;
64766
67067
  var name23 = "AI_InvalidStreamPartError";
64767
67068
  var marker23 = `vercel.ai.error.${name23}`;
64768
67069
  var symbol24 = Symbol.for(marker23);
@@ -65002,15 +67303,15 @@ var InvalidMessageRoleError = class extends AISDKError {
65002
67303
  }
65003
67304
  };
65004
67305
  _a172 = symbol172;
65005
- var name18 = "AI_MessageConversionError";
65006
- var marker182 = `vercel.ai.error.${name18}`;
67306
+ var name182 = "AI_MessageConversionError";
67307
+ var marker182 = `vercel.ai.error.${name182}`;
65007
67308
  var symbol182 = Symbol.for(marker182);
65008
67309
  var _a182;
65009
67310
  _a182 = symbol182;
65010
67311
  var name19 = "AI_RetryError";
65011
- var marker19 = `vercel.ai.error.${name19}`;
65012
- var symbol19 = Symbol.for(marker19);
65013
- var _a19;
67312
+ var marker192 = `vercel.ai.error.${name19}`;
67313
+ var symbol192 = Symbol.for(marker192);
67314
+ var _a192;
65014
67315
  var RetryError = class extends AISDKError {
65015
67316
  constructor({
65016
67317
  message,
@@ -65018,16 +67319,16 @@ var RetryError = class extends AISDKError {
65018
67319
  errors: errors3
65019
67320
  }) {
65020
67321
  super({ name: name19, message });
65021
- this[_a19] = true;
67322
+ this[_a192] = true;
65022
67323
  this.reason = reason;
65023
67324
  this.errors = errors3;
65024
67325
  this.lastError = errors3[errors3.length - 1];
65025
67326
  }
65026
67327
  static isInstance(error48) {
65027
- return AISDKError.hasMarker(error48, marker19);
67328
+ return AISDKError.hasMarker(error48, marker192);
65028
67329
  }
65029
67330
  };
65030
- _a19 = symbol19;
67331
+ _a192 = symbol192;
65031
67332
  function asArray(value) {
65032
67333
  return value === undefined ? [] : Array.isArray(value) ? value : [value];
65033
67334
  }
@@ -65324,7 +67625,7 @@ function detectMediaType({
65324
67625
  }
65325
67626
  return;
65326
67627
  }
65327
- var VERSION11 = "6.0.142";
67628
+ var VERSION12 = "6.0.168";
65328
67629
  var download = async ({
65329
67630
  url: url2,
65330
67631
  maxBytes,
@@ -65335,7 +67636,7 @@ var download = async ({
65335
67636
  validateDownloadUrl(urlText);
65336
67637
  try {
65337
67638
  const response = await fetch(urlText, {
65338
- headers: withUserAgentSuffix({}, `ai-sdk/${VERSION11}`, getRuntimeEnvironmentUserAgent()),
67639
+ headers: withUserAgentSuffix({}, `ai-sdk/${VERSION12}`, getRuntimeEnvironmentUserAgent()),
65339
67640
  signal: abortSignal
65340
67641
  });
65341
67642
  if (response.redirected) {
@@ -67189,9 +69490,9 @@ var object2 = ({
67189
69490
  const schema = asSchema(inputSchema);
67190
69491
  return {
67191
69492
  name: "object",
67192
- responseFormat: resolve(schema.jsonSchema).then((jsonSchema2) => ({
69493
+ responseFormat: resolve(schema.jsonSchema).then((jsonSchema22) => ({
67193
69494
  type: "json",
67194
- schema: jsonSchema2,
69495
+ schema: jsonSchema22,
67195
69496
  ...name21 != null && { name: name21 },
67196
69497
  ...description != null && { description }
67197
69498
  })),
@@ -67251,8 +69552,8 @@ var array2 = ({
67251
69552
  const elementSchema = asSchema(inputElementSchema);
67252
69553
  return {
67253
69554
  name: "array",
67254
- responseFormat: resolve(elementSchema.jsonSchema).then((jsonSchema2) => {
67255
- const { $schema, ...itemSchema } = jsonSchema2;
69555
+ responseFormat: resolve(elementSchema.jsonSchema).then((jsonSchema22) => {
69556
+ const { $schema, ...itemSchema } = jsonSchema22;
67256
69557
  return {
67257
69558
  type: "json",
67258
69559
  schema: {
@@ -67714,7 +70015,7 @@ async function toResponseMessages({
67714
70015
  type: "tool-call",
67715
70016
  toolCallId: part.toolCallId,
67716
70017
  toolName: part.toolName,
67717
- input: part.input,
70018
+ input: part.invalid && typeof part.input !== "object" ? {} : part.input,
67718
70019
  providerExecuted: part.providerExecuted,
67719
70020
  providerOptions: part.providerMetadata
67720
70021
  });
@@ -68918,7 +71219,7 @@ function runToolsTransformation({
68918
71219
  abortSignal,
68919
71220
  repairToolCall,
68920
71221
  experimental_context,
68921
- generateId: generateId2,
71222
+ generateId: generateId22,
68922
71223
  stepNumber,
68923
71224
  model,
68924
71225
  onToolCallStart,
@@ -69048,14 +71349,14 @@ function runToolsTransformation({
69048
71349
  })) {
69049
71350
  toolResultsStreamController.enqueue({
69050
71351
  type: "tool-approval-request",
69051
- approvalId: generateId2(),
71352
+ approvalId: generateId22(),
69052
71353
  toolCall
69053
71354
  });
69054
71355
  break;
69055
71356
  }
69056
71357
  toolInputs.set(toolCall.toolCallId, toolCall.input);
69057
71358
  if (tool2.execute != null && toolCall.providerExecuted !== true) {
69058
- const toolExecutionId = generateId2();
71359
+ const toolExecutionId = generateId22();
69059
71360
  outstandingToolResults.add(toolExecutionId);
69060
71361
  executeToolCall({
69061
71362
  toolCall,
@@ -69188,7 +71489,7 @@ function streamText({
69188
71489
  experimental_onToolCallFinish: onToolCallFinish,
69189
71490
  experimental_context,
69190
71491
  experimental_include: include,
69191
- _internal: { now: now2 = now, generateId: generateId2 = originalGenerateId2 } = {},
71492
+ _internal: { now: now2 = now, generateId: generateId22 = originalGenerateId2 } = {},
69192
71493
  ...settings
69193
71494
  }) {
69194
71495
  const totalTimeoutMs = getTotalTimeoutMs(timeout);
@@ -69233,7 +71534,7 @@ function streamText({
69233
71534
  onToolCallStart,
69234
71535
  onToolCallFinish,
69235
71536
  now: now2,
69236
- generateId: generateId2,
71537
+ generateId: generateId22,
69237
71538
  experimental_context,
69238
71539
  download: download2,
69239
71540
  include
@@ -69244,7 +71545,7 @@ function createOutputTransformStream(output) {
69244
71545
  let text2 = "";
69245
71546
  let textChunk = "";
69246
71547
  let textProviderMetadata = undefined;
69247
- let lastPublishedJson = "";
71548
+ let lastPublishedValue = "";
69248
71549
  function publishTextChunk({
69249
71550
  controller,
69250
71551
  partialOutput = undefined
@@ -69292,10 +71593,10 @@ function createOutputTransformStream(output) {
69292
71593
  textProviderMetadata = (_a21 = chunk.providerMetadata) != null ? _a21 : textProviderMetadata;
69293
71594
  const result = await output.parsePartialOutput({ text: text2 });
69294
71595
  if (result !== undefined) {
69295
- const currentJson = JSON.stringify(result.partial);
69296
- if (currentJson !== lastPublishedJson) {
71596
+ const currentValue = typeof result.partial === "string" ? result.partial : JSON.stringify(result.partial);
71597
+ if (currentValue !== lastPublishedValue) {
69297
71598
  publishTextChunk({ controller, partialOutput: result.partial });
69298
- lastPublishedJson = currentJson;
71599
+ lastPublishedValue = currentValue;
69299
71600
  }
69300
71601
  }
69301
71602
  }
@@ -69327,7 +71628,7 @@ var DefaultStreamTextResult = class {
69327
71628
  prepareStep,
69328
71629
  includeRawChunks,
69329
71630
  now: now2,
69330
- generateId: generateId2,
71631
+ generateId: generateId22,
69331
71632
  timeout,
69332
71633
  stopWhen,
69333
71634
  originalAbortSignal,
@@ -69736,10 +72037,6 @@ var DefaultStreamTextResult = class {
69736
72037
  const initialResponseMessages = [];
69737
72038
  const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovals({ messages: initialMessages });
69738
72039
  if (deniedToolApprovals.length > 0 || approvedToolApprovals.length > 0) {
69739
- const providerExecutedToolApprovals = [
69740
- ...approvedToolApprovals,
69741
- ...deniedToolApprovals
69742
- ].filter((toolApproval) => toolApproval.toolCall.providerExecuted);
69743
72040
  const localApprovedToolApprovals = approvedToolApprovals.filter((toolApproval) => !toolApproval.toolCall.providerExecuted);
69744
72041
  const localDeniedToolApprovals = deniedToolApprovals.filter((toolApproval) => !toolApproval.toolCall.providerExecuted);
69745
72042
  const deniedProviderExecutedToolApprovals = deniedToolApprovals.filter((toolApproval) => toolApproval.toolCall.providerExecuted);
@@ -69790,18 +72087,6 @@ var DefaultStreamTextResult = class {
69790
72087
  toolOutputs.push(result);
69791
72088
  }
69792
72089
  }));
69793
- if (providerExecutedToolApprovals.length > 0) {
69794
- initialResponseMessages.push({
69795
- role: "tool",
69796
- content: providerExecutedToolApprovals.map((toolApproval) => ({
69797
- type: "tool-approval-response",
69798
- approvalId: toolApproval.approvalResponse.approvalId,
69799
- approved: toolApproval.approvalResponse.approved,
69800
- reason: toolApproval.approvalResponse.reason,
69801
- providerExecuted: true
69802
- }))
69803
- });
69804
- }
69805
72090
  if (toolOutputs.length > 0 || localDeniedToolApprovals.length > 0) {
69806
72091
  const localToolContent = [];
69807
72092
  for (const output2 of toolOutputs) {
@@ -69989,7 +72274,7 @@ var DefaultStreamTextResult = class {
69989
72274
  repairToolCall,
69990
72275
  abortSignal,
69991
72276
  experimental_context,
69992
- generateId: generateId2,
72277
+ generateId: generateId22,
69993
72278
  stepNumber: recordedSteps.length,
69994
72279
  model: stepModelInfo,
69995
72280
  onToolCallStart: [
@@ -70012,7 +72297,7 @@ var DefaultStreamTextResult = class {
70012
72297
  let stepProviderMetadata;
70013
72298
  let stepFirstChunk = true;
70014
72299
  let stepResponse = {
70015
- id: generateId2(),
72300
+ id: generateId22(),
70016
72301
  timestamp: /* @__PURE__ */ new Date,
70017
72302
  modelId: modelInfo.modelId
70018
72303
  };
@@ -70502,12 +72787,15 @@ var DefaultStreamTextResult = class {
70502
72787
  });
70503
72788
  break;
70504
72789
  }
70505
- case "reasoning-start": {
70506
- controller.enqueue({
70507
- type: "reasoning-start",
70508
- id: part.id,
70509
- ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
70510
- });
72790
+ case "reasoning-start":
72791
+ case "reasoning-end": {
72792
+ if (sendReasoning) {
72793
+ controller.enqueue({
72794
+ type: partType,
72795
+ id: part.id,
72796
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
72797
+ });
72798
+ }
70511
72799
  break;
70512
72800
  }
70513
72801
  case "reasoning-delta": {
@@ -70521,14 +72809,6 @@ var DefaultStreamTextResult = class {
70521
72809
  }
70522
72810
  break;
70523
72811
  }
70524
- case "reasoning-end": {
70525
- controller.enqueue({
70526
- type: "reasoning-end",
70527
- id: part.id,
70528
- ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
70529
- });
70530
- break;
70531
- }
70532
72812
  case "file": {
70533
72813
  controller.enqueue({
70534
72814
  type: "file",