@mastra/agent-builder 1.0.0-beta.0 → 1.0.0-beta.10

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.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { Agent, tryGenerateWithJsonFallback, tryStreamWithJsonFallback } from '@mastra/core/agent';
1
+ import { __commonJS, require_token_error, __toESM } from './chunk-E53QBCQN.js';
2
+ import { Agent, isSupportedLanguageModel, tryGenerateWithJsonFallback, tryStreamWithJsonFallback } from '@mastra/core/agent';
2
3
  import { Memory } from '@mastra/memory';
3
- import { TokenLimiter } from '@mastra/memory/processors';
4
4
  import { exec as exec$1, execFile as execFile$1, spawn as spawn$1 } from 'child_process';
5
5
  import { mkdtemp, rm, readFile, writeFile, readdir, mkdir, copyFile, stat } from 'fs/promises';
6
6
  import { join, resolve, basename, extname, dirname, isAbsolute, relative } from 'path';
@@ -11,13 +11,13 @@ import { existsSync, readFileSync } from 'fs';
11
11
  import { createRequire } from 'module';
12
12
  import { promisify } from 'util';
13
13
  import { ModelRouterLanguageModel } from '@mastra/core/llm';
14
- import { MemoryProcessor } from '@mastra/core/memory';
15
14
  import { tmpdir } from 'os';
16
15
  import { openai } from '@ai-sdk/openai';
17
16
  import { createStep, createWorkflow } from '@mastra/core/workflows';
18
- import { stepCountIs } from 'ai';
17
+ import * as z4 from 'zod/v4';
18
+ import { z as z$1 } from 'zod/v4';
19
+ import { ZodFirstPartyTypeKind } from 'zod/v3';
19
20
 
20
- // src/agent/index.ts
21
21
  var UNIT_KINDS = ["mcp-server", "tool", "workflow", "agent", "integration", "network", "other"];
22
22
  var TemplateUnitSchema = z.object({
23
23
  kind: z.enum(UNIT_KINDS),
@@ -189,7 +189,7 @@ var PackageMergeResultSchema = z.object({
189
189
  error: z.string().optional()
190
190
  });
191
191
  var InstallInputSchema = z.object({
192
- targetPath: z.string().describe("Path to the project to install packages in")
192
+ targetPath: z.string().optional().describe("Path to the project to install packages in")
193
193
  });
194
194
  var InstallResultSchema = z.object({
195
195
  success: z.boolean(),
@@ -249,7 +249,7 @@ function isInWorkspaceSubfolder(cwd) {
249
249
  }
250
250
  }
251
251
  function spawn(command, args, options) {
252
- return new Promise((resolve4, reject) => {
252
+ return new Promise((resolve5, reject) => {
253
253
  const childProcess = spawn$1(command, args, {
254
254
  stdio: "inherit",
255
255
  // Enable proper stdio handling
@@ -260,7 +260,7 @@ function spawn(command, args, options) {
260
260
  });
261
261
  childProcess.on("close", (code) => {
262
262
  if (code === 0) {
263
- resolve4(void 0);
263
+ resolve5(void 0);
264
264
  } else {
265
265
  reject(new Error(`Command failed with exit code ${code}`));
266
266
  }
@@ -1124,7 +1124,7 @@ export const mastra = new Mastra({
1124
1124
  encoding: z.string(),
1125
1125
  lastModified: z.string()
1126
1126
  }).optional(),
1127
- error: z.string().optional()
1127
+ errorMessage: z.string().optional()
1128
1128
  }),
1129
1129
  execute: async (inputData) => {
1130
1130
  return await _AgentBuilderDefaults.readFile({ ...inputData, projectPath });
@@ -1144,7 +1144,7 @@ export const mastra = new Mastra({
1144
1144
  filePath: z.string(),
1145
1145
  bytesWritten: z.number().optional(),
1146
1146
  message: z.string(),
1147
- error: z.string().optional()
1147
+ errorMessage: z.string().optional()
1148
1148
  }),
1149
1149
  execute: async (inputData) => {
1150
1150
  return await _AgentBuilderDefaults.writeFile({ ...inputData, projectPath });
@@ -1176,7 +1176,7 @@ export const mastra = new Mastra({
1176
1176
  totalItems: z.number(),
1177
1177
  path: z.string(),
1178
1178
  message: z.string(),
1179
- error: z.string().optional()
1179
+ errorMessage: z.string().optional()
1180
1180
  }),
1181
1181
  execute: async (inputData) => {
1182
1182
  return await _AgentBuilderDefaults.listDirectory({ ...inputData, projectPath });
@@ -1201,7 +1201,7 @@ export const mastra = new Mastra({
1201
1201
  command: z.string(),
1202
1202
  workingDirectory: z.string().optional(),
1203
1203
  executionTime: z.number().optional(),
1204
- error: z.string().optional()
1204
+ errorMessage: z.string().optional()
1205
1205
  }),
1206
1206
  execute: async (inputData) => {
1207
1207
  return await _AgentBuilderDefaults.executeCommand({
@@ -1302,7 +1302,7 @@ export const mastra = new Mastra({
1302
1302
  message: z.string(),
1303
1303
  linesReplaced: z.number().optional(),
1304
1304
  backup: z.string().optional(),
1305
- error: z.string().optional()
1305
+ errorMessage: z.string().optional()
1306
1306
  }),
1307
1307
  execute: async (inputData) => {
1308
1308
  return await _AgentBuilderDefaults.replaceLines({ ...inputData, projectPath });
@@ -1331,7 +1331,7 @@ export const mastra = new Mastra({
1331
1331
  ),
1332
1332
  totalLines: z.number(),
1333
1333
  message: z.string(),
1334
- error: z.string().optional()
1334
+ errorMessage: z.string().optional()
1335
1335
  }),
1336
1336
  execute: async (inputData) => {
1337
1337
  return await _AgentBuilderDefaults.showFileLines({ ...inputData, projectPath });
@@ -1449,7 +1449,7 @@ export const mastra = new Mastra({
1449
1449
  totalResults: z.number(),
1450
1450
  searchTime: z.number(),
1451
1451
  suggestions: z.array(z.string()).optional(),
1452
- error: z.string().optional()
1452
+ errorMessage: z.string().optional()
1453
1453
  }),
1454
1454
  execute: async (inputData) => {
1455
1455
  return await _AgentBuilderDefaults.webSearch(inputData);
@@ -1505,7 +1505,7 @@ export const mastra = new Mastra({
1505
1505
  warnings: z.array(z.string()).optional(),
1506
1506
  message: z.string().optional(),
1507
1507
  details: z.string().optional(),
1508
- error: z.string().optional()
1508
+ errorMessage: z.string().optional()
1509
1509
  }),
1510
1510
  execute: async (inputData) => {
1511
1511
  const { action, features, packages } = inputData;
@@ -1567,7 +1567,7 @@ export const mastra = new Mastra({
1567
1567
  url: z.string().optional(),
1568
1568
  message: z.string().optional(),
1569
1569
  stdout: z.array(z.string()).optional().describe("Server output lines captured during startup"),
1570
- error: z.string().optional()
1570
+ errorMessage: z.string().optional()
1571
1571
  }),
1572
1572
  execute: async (inputData) => {
1573
1573
  const { action, port } = inputData;
@@ -1593,10 +1593,10 @@ export const mastra = new Mastra({
1593
1593
  success: false,
1594
1594
  status: "unknown",
1595
1595
  message: `Failed to restart: could not stop server on port ${port}`,
1596
- error: stopResult.error || "Unknown stop error"
1596
+ errorMessage: stopResult.errorMessage || "Unknown stop error"
1597
1597
  };
1598
1598
  }
1599
- await new Promise((resolve4) => setTimeout(resolve4, 500));
1599
+ await new Promise((resolve5) => setTimeout(resolve5, 500));
1600
1600
  const startResult = await _AgentBuilderDefaults.startMastraServer({
1601
1601
  port,
1602
1602
  projectPath
@@ -1606,7 +1606,7 @@ export const mastra = new Mastra({
1606
1606
  success: false,
1607
1607
  status: "stopped",
1608
1608
  message: `Failed to restart: server stopped successfully but failed to start on port ${port}`,
1609
- error: startResult.error || "Unknown start error"
1609
+ errorMessage: startResult.errorMessage || "Unknown start error"
1610
1610
  };
1611
1611
  }
1612
1612
  return {
@@ -1651,7 +1651,7 @@ export const mastra = new Mastra({
1651
1651
  statusText: z.string().optional(),
1652
1652
  headers: z.record(z.string()).optional(),
1653
1653
  data: z.any().optional(),
1654
- error: z.string().optional(),
1654
+ errorMessage: z.string().optional(),
1655
1655
  url: z.string(),
1656
1656
  method: z.string()
1657
1657
  }),
@@ -1671,7 +1671,7 @@ export const mastra = new Mastra({
1671
1671
  success: false,
1672
1672
  url: baseUrl ? `${baseUrl}${url}` : url,
1673
1673
  method,
1674
- error: error instanceof Error ? error.message : String(error)
1674
+ errorMessage: error instanceof Error ? error.message : String(error)
1675
1675
  };
1676
1676
  }
1677
1677
  }
@@ -1735,7 +1735,7 @@ export const mastra = new Mastra({
1735
1735
  projectPath: `./${projectName}`,
1736
1736
  message: `Successfully created Mastra project: ${projectName}.`,
1737
1737
  details: stdout,
1738
- error: stderr
1738
+ errorMessage: stderr
1739
1739
  };
1740
1740
  } catch (error) {
1741
1741
  console.error(error);
@@ -1816,7 +1816,7 @@ export const mastra = new Mastra({
1816
1816
  stdio: "pipe"
1817
1817
  });
1818
1818
  const stdoutLines = [];
1819
- const serverStarted = new Promise((resolve4, reject) => {
1819
+ const serverStarted = new Promise((resolve5, reject) => {
1820
1820
  const timeout = setTimeout(() => {
1821
1821
  reject(new Error(`Server startup timeout after 30 seconds. Output: ${stdoutLines.join("\n")}`));
1822
1822
  }, 3e4);
@@ -1824,9 +1824,9 @@ export const mastra = new Mastra({
1824
1824
  const output = data.toString();
1825
1825
  const lines = output.split("\n").filter((line) => line.trim());
1826
1826
  stdoutLines.push(...lines);
1827
- if (output.includes("Mastra API running on port")) {
1827
+ if (output.includes("Mastra API running on ")) {
1828
1828
  clearTimeout(timeout);
1829
- resolve4({
1829
+ resolve5({
1830
1830
  success: true,
1831
1831
  status: "running",
1832
1832
  pid: serverProcess.pid,
@@ -1863,7 +1863,7 @@ export const mastra = new Mastra({
1863
1863
  return {
1864
1864
  success: false,
1865
1865
  status: "stopped",
1866
- error: error instanceof Error ? error.message : String(error)
1866
+ errorMessage: error instanceof Error ? error.message : String(error)
1867
1867
  };
1868
1868
  }
1869
1869
  }
@@ -1875,7 +1875,7 @@ export const mastra = new Mastra({
1875
1875
  return {
1876
1876
  success: false,
1877
1877
  status: "error",
1878
- error: `Invalid port value: ${String(port)}`
1878
+ errorMessage: `Invalid port value: ${String(port)}`
1879
1879
  };
1880
1880
  }
1881
1881
  try {
@@ -1907,7 +1907,7 @@ export const mastra = new Mastra({
1907
1907
  success: false,
1908
1908
  status: "unknown",
1909
1909
  message: `Failed to stop any processes on port ${port}`,
1910
- error: `Could not kill PIDs: ${failedPids.join(", ")}`
1910
+ errorMessage: `Could not kill PIDs: ${failedPids.join(", ")}`
1911
1911
  };
1912
1912
  }
1913
1913
  if (failedPids.length > 0) {
@@ -1915,7 +1915,7 @@ export const mastra = new Mastra({
1915
1915
  `Killed ${killedPids.length} processes but failed to kill ${failedPids.length} processes: ${failedPids.join(", ")}`
1916
1916
  );
1917
1917
  }
1918
- await new Promise((resolve4) => setTimeout(resolve4, 2e3));
1918
+ await new Promise((resolve5) => setTimeout(resolve5, 2e3));
1919
1919
  try {
1920
1920
  const { stdout: checkStdoutRaw } = await execFile("lsof", ["-ti", String(port)]);
1921
1921
  const checkStdout = checkStdoutRaw.trim() ? checkStdoutRaw : "No process found";
@@ -1930,7 +1930,7 @@ export const mastra = new Mastra({
1930
1930
  }
1931
1931
  }
1932
1932
  }
1933
- await new Promise((resolve4) => setTimeout(resolve4, 1e3));
1933
+ await new Promise((resolve5) => setTimeout(resolve5, 1e3));
1934
1934
  const { stdout: finalCheckRaw } = await execFile("lsof", ["-ti", String(port)]);
1935
1935
  const finalCheck = finalCheckRaw.trim() ? finalCheckRaw : "No process found";
1936
1936
  if (finalCheck && finalCheck !== "No process found") {
@@ -1938,7 +1938,7 @@ export const mastra = new Mastra({
1938
1938
  success: false,
1939
1939
  status: "unknown",
1940
1940
  message: `Server processes still running on port ${port} after stop attempts`,
1941
- error: `Remaining PIDs: ${finalCheck.trim()}`
1941
+ errorMessage: `Remaining PIDs: ${finalCheck.trim()}`
1942
1942
  };
1943
1943
  }
1944
1944
  }
@@ -1954,7 +1954,7 @@ export const mastra = new Mastra({
1954
1954
  return {
1955
1955
  success: false,
1956
1956
  status: "unknown",
1957
- error: error instanceof Error ? error.message : String(error)
1957
+ errorMessage: error instanceof Error ? error.message : String(error)
1958
1958
  };
1959
1959
  }
1960
1960
  }
@@ -2215,14 +2215,14 @@ export const mastra = new Mastra({
2215
2215
  noEmit: true
2216
2216
  };
2217
2217
  const host = {
2218
- getSourceFile: (name) => name === fileName ? sourceFile : void 0,
2218
+ getSourceFile: (name16) => name16 === fileName ? sourceFile : void 0,
2219
2219
  writeFile: () => {
2220
2220
  },
2221
2221
  getCurrentDirectory: () => "",
2222
2222
  getDirectories: () => [],
2223
- fileExists: (name) => name === fileName,
2224
- readFile: (name) => name === fileName ? fileContent : void 0,
2225
- getCanonicalFileName: (name) => name,
2223
+ fileExists: (name16) => name16 === fileName,
2224
+ readFile: (name16) => name16 === fileName ? fileContent : void 0,
2225
+ getCanonicalFileName: (name16) => name16,
2226
2226
  useCaseSensitiveFileNames: () => true,
2227
2227
  getNewLine: () => "\n",
2228
2228
  getDefaultLibFileName: () => "lib.d.ts"
@@ -2437,7 +2437,7 @@ export const mastra = new Mastra({
2437
2437
  success: false,
2438
2438
  url: baseUrl ? `${baseUrl}${url}` : url,
2439
2439
  method,
2440
- error: error instanceof Error ? error.message : String(error)
2440
+ errorMessage: error instanceof Error ? error.message : String(error)
2441
2441
  };
2442
2442
  }
2443
2443
  }
@@ -2620,21 +2620,21 @@ export const mastra = new Mastra({
2620
2620
  return {
2621
2621
  success: false,
2622
2622
  message: `Line numbers must be 1 or greater. Got startLine: ${startLine}, endLine: ${endLine}`,
2623
- error: "Invalid line range"
2623
+ errorMessage: "Invalid line range"
2624
2624
  };
2625
2625
  }
2626
2626
  if (startLine > lines.length || endLine > lines.length) {
2627
2627
  return {
2628
2628
  success: false,
2629
2629
  message: `Line range ${startLine}-${endLine} is out of bounds. File has ${lines.length} lines. Remember: lines are 1-indexed, so valid range is 1-${lines.length}.`,
2630
- error: "Invalid line range"
2630
+ errorMessage: "Invalid line range"
2631
2631
  };
2632
2632
  }
2633
2633
  if (startLine > endLine) {
2634
2634
  return {
2635
2635
  success: false,
2636
2636
  message: `Start line (${startLine}) cannot be greater than end line (${endLine}).`,
2637
- error: "Invalid line range"
2637
+ errorMessage: "Invalid line range"
2638
2638
  };
2639
2639
  }
2640
2640
  let backup;
@@ -2661,7 +2661,7 @@ export const mastra = new Mastra({
2661
2661
  return {
2662
2662
  success: false,
2663
2663
  message: `Failed to replace lines: ${error instanceof Error ? error.message : String(error)}`,
2664
- error: error instanceof Error ? error.message : String(error)
2664
+ errorMessage: error instanceof Error ? error.message : String(error)
2665
2665
  };
2666
2666
  }
2667
2667
  }
@@ -2706,7 +2706,7 @@ export const mastra = new Mastra({
2706
2706
  lines: [],
2707
2707
  totalLines: 0,
2708
2708
  message: `Failed to read file: ${error instanceof Error ? error.message : String(error)}`,
2709
- error: error instanceof Error ? error.message : String(error)
2709
+ errorMessage: error instanceof Error ? error.message : String(error)
2710
2710
  };
2711
2711
  }
2712
2712
  }
@@ -2856,7 +2856,7 @@ export const mastra = new Mastra({
2856
2856
  } catch (error) {
2857
2857
  return {
2858
2858
  success: false,
2859
- error: error instanceof Error ? error.message : String(error)
2859
+ errorMessage: error instanceof Error ? error.message : String(error)
2860
2860
  };
2861
2861
  }
2862
2862
  }
@@ -2883,7 +2883,7 @@ export const mastra = new Mastra({
2883
2883
  success: false,
2884
2884
  filePath: context.filePath,
2885
2885
  message: `Failed to write file: ${error instanceof Error ? error.message : String(error)}`,
2886
- error: error instanceof Error ? error.message : String(error)
2886
+ errorMessage: error instanceof Error ? error.message : String(error)
2887
2887
  };
2888
2888
  }
2889
2889
  }
@@ -2974,7 +2974,7 @@ export const mastra = new Mastra({
2974
2974
  totalItems: 0,
2975
2975
  path: context.path,
2976
2976
  message: `Failed to list directory: ${error instanceof Error ? error.message : String(error)}`,
2977
- error: error instanceof Error ? error.message : String(error)
2977
+ errorMessage: error instanceof Error ? error.message : String(error)
2978
2978
  };
2979
2979
  }
2980
2980
  }
@@ -3016,7 +3016,7 @@ export const mastra = new Mastra({
3016
3016
  command: context.command,
3017
3017
  workingDirectory: context.workingDirectory,
3018
3018
  executionTime,
3019
- error: error instanceof Error ? error.message : String(error)
3019
+ errorMessage: error instanceof Error ? error.message : String(error)
3020
3020
  };
3021
3021
  }
3022
3022
  }
@@ -3079,16 +3079,17 @@ export const mastra = new Mastra({
3079
3079
  results: [],
3080
3080
  totalResults: 0,
3081
3081
  searchTime: 0,
3082
- error: error instanceof Error ? error.message : String(error)
3082
+ errorMessage: error instanceof Error ? error.message : String(error)
3083
3083
  };
3084
3084
  }
3085
3085
  }
3086
3086
  };
3087
- var ToolSummaryProcessor = class extends MemoryProcessor {
3087
+ var ToolSummaryProcessor = class {
3088
+ id = "tool-summary-processor";
3089
+ name = "ToolSummaryProcessor";
3088
3090
  summaryAgent;
3089
3091
  summaryCache = /* @__PURE__ */ new Map();
3090
3092
  constructor({ summaryModel }) {
3091
- super({ name: "ToolSummaryProcessor" });
3092
3093
  this.summaryAgent = new Agent({
3093
3094
  id: "tool-summary-agent",
3094
3095
  name: "Tool Summary Agent",
@@ -3125,30 +3126,37 @@ var ToolSummaryProcessor = class extends MemoryProcessor {
3125
3126
  keys: Array.from(this.summaryCache.keys())
3126
3127
  };
3127
3128
  }
3128
- async process(messages) {
3129
+ async processInput({
3130
+ messages,
3131
+ messageList: _messageList
3132
+ }) {
3129
3133
  const summaryTasks = [];
3130
3134
  for (const message of messages) {
3131
- if (message.role === "tool" && Array.isArray(message.content) && message.content.length > 0 && message.content?.some((content) => content.type === "tool-result")) {
3132
- for (const content of message.content) {
3133
- if (content.type === "tool-result") {
3134
- const assistantMessageWithToolCall = messages.find(
3135
- (message2) => message2.role === "assistant" && Array.isArray(message2.content) && message2.content.length > 0 && message2.content?.some(
3136
- (assistantContent) => assistantContent.type === "tool-call" && assistantContent.toolCallId === content.toolCallId
3137
- )
3138
- );
3139
- const toolCall = Array.isArray(assistantMessageWithToolCall?.content) ? assistantMessageWithToolCall?.content.find(
3140
- (assistantContent) => assistantContent.type === "tool-call" && assistantContent.toolCallId === content.toolCallId
3141
- ) : null;
3142
- const cacheKey = this.createCacheKey(toolCall);
3135
+ if (message.content.format === 2 && message.content.parts) {
3136
+ for (let partIndex = 0; partIndex < message.content.parts.length; partIndex++) {
3137
+ const part = message.content.parts[partIndex];
3138
+ if (part && part.type === "tool-invocation" && part.toolInvocation?.state === "result") {
3139
+ const cacheKey = this.createCacheKey(part.toolInvocation);
3143
3140
  const cachedSummary = this.summaryCache.get(cacheKey);
3144
3141
  if (cachedSummary) {
3145
- content.result = `Tool call summary: ${cachedSummary}`;
3142
+ message.content.parts[partIndex] = {
3143
+ type: "tool-invocation",
3144
+ toolInvocation: {
3145
+ state: "result",
3146
+ step: part.toolInvocation.step,
3147
+ toolCallId: part.toolInvocation.toolCallId,
3148
+ toolName: part.toolInvocation.toolName,
3149
+ args: part.toolInvocation.args,
3150
+ result: `Tool call summary: ${cachedSummary}`
3151
+ }
3152
+ };
3146
3153
  } else {
3147
3154
  const summaryPromise = this.summaryAgent.generate(
3148
- `Summarize the following tool call: ${JSON.stringify(toolCall)} and result: ${JSON.stringify(content)}`
3155
+ `Summarize the following tool call: ${JSON.stringify(part.toolInvocation)}`
3149
3156
  );
3150
3157
  summaryTasks.push({
3151
- content,
3158
+ message,
3159
+ partIndex,
3152
3160
  promise: summaryPromise,
3153
3161
  cacheKey
3154
3162
  });
@@ -3166,10 +3174,24 @@ var ToolSummaryProcessor = class extends MemoryProcessor {
3166
3174
  const summaryResult = result.value;
3167
3175
  const summaryText = summaryResult.text;
3168
3176
  this.summaryCache.set(task.cacheKey, summaryText);
3169
- task.content.result = `Tool call summary: ${summaryText}`;
3177
+ if (task.message.content.format === 2 && task.message.content.parts) {
3178
+ const part = task.message.content.parts[task.partIndex];
3179
+ if (part && part.type === "tool-invocation" && part.toolInvocation?.state === "result") {
3180
+ task.message.content.parts[task.partIndex] = {
3181
+ type: "tool-invocation",
3182
+ toolInvocation: {
3183
+ state: "result",
3184
+ step: part.toolInvocation.step,
3185
+ toolCallId: part.toolInvocation.toolCallId,
3186
+ toolName: part.toolInvocation.toolName,
3187
+ args: part.toolInvocation.args,
3188
+ result: `Tool call summary: ${summaryText}`
3189
+ }
3190
+ };
3191
+ }
3192
+ }
3170
3193
  } else if (result.status === "rejected") {
3171
3194
  console.warn(`Failed to generate summary for tool call:`, result.reason);
3172
- task.content.result = `Tool call summary: [Summary generation failed]`;
3173
3195
  }
3174
3196
  });
3175
3197
  }
@@ -3189,6 +3211,7 @@ var AgentBuilder = class extends Agent {
3189
3211
  ${config.instructions}` : "";
3190
3212
  const combinedInstructions = additionalInstructions + AgentBuilderDefaults.DEFAULT_INSTRUCTIONS(config.projectPath);
3191
3213
  const agentConfig = {
3214
+ id: "agent-builder",
3192
3215
  name: "agent-builder",
3193
3216
  description: "An AI agent specialized in generating Mastra agents, tools, and workflows from natural language requirements.",
3194
3217
  instructions: combinedInstructions,
@@ -3200,15 +3223,14 @@ ${config.instructions}` : "";
3200
3223
  };
3201
3224
  },
3202
3225
  memory: new Memory({
3203
- options: AgentBuilderDefaults.DEFAULT_MEMORY_CONFIG,
3204
- processors: [
3205
- // use the write to disk processor to debug the agent's context
3206
- // new WriteToDiskProcessor({ prefix: 'before-filter' }),
3207
- new ToolSummaryProcessor({ summaryModel: config.summaryModel || config.model }),
3208
- new TokenLimiter(1e5)
3209
- // new WriteToDiskProcessor({ prefix: 'after-filter' }),
3210
- ]
3211
- })
3226
+ options: AgentBuilderDefaults.DEFAULT_MEMORY_CONFIG
3227
+ }),
3228
+ inputProcessors: [
3229
+ // use the write to disk processor to debug the agent's context
3230
+ // new WriteToDiskProcessor({ prefix: 'before-filter' }),
3231
+ new ToolSummaryProcessor({ summaryModel: config.summaryModel || config.model })
3232
+ // new WriteToDiskProcessor({ prefix: 'after-filter' }),
3233
+ ]
3212
3234
  };
3213
3235
  super(agentConfig);
3214
3236
  this.builderConfig = config;
@@ -3456,7 +3478,8 @@ Return the actual exported names of the units, as well as the file names.`,
3456
3478
  listDirectory: tools.listDirectory
3457
3479
  }
3458
3480
  });
3459
- const isV2 = model.specificationVersion === "v2";
3481
+ const resolvedModel = await agent.getModel();
3482
+ const isSupported = isSupportedLanguageModel(resolvedModel);
3460
3483
  const prompt = `Analyze the Mastra project directory structure at "${templateDir}".
3461
3484
 
3462
3485
  List directory contents using listDirectory tool, and then analyze each file with readFile tool.
@@ -3475,7 +3498,7 @@ Return the actual exported names of the units, as well as the file names.`,
3475
3498
  networks: z.array(z.object({ name: z.string(), file: z.string() })).optional(),
3476
3499
  other: z.array(z.object({ name: z.string(), file: z.string() })).optional()
3477
3500
  });
3478
- const result = isV2 ? await tryGenerateWithJsonFallback(agent, prompt, {
3501
+ const result = isSupported ? await tryGenerateWithJsonFallback(agent, prompt, {
3479
3502
  structuredOutput: {
3480
3503
  schema: output
3481
3504
  },
@@ -3608,25 +3631,25 @@ var packageMergeStep = createStep({
3608
3631
  const tplDevDeps = ensureObj(packageInfo.devDependencies);
3609
3632
  const tplPeerDeps = ensureObj(packageInfo.peerDependencies);
3610
3633
  const tplScripts = ensureObj(packageInfo.scripts);
3611
- const existsAnywhere = (name) => name in targetPkg.dependencies || name in targetPkg.devDependencies || name in targetPkg.peerDependencies;
3612
- for (const [name, ver] of Object.entries(tplDeps)) {
3613
- if (!existsAnywhere(name)) {
3614
- targetPkg.dependencies[name] = String(ver);
3634
+ const existsAnywhere = (name16) => name16 in targetPkg.dependencies || name16 in targetPkg.devDependencies || name16 in targetPkg.peerDependencies;
3635
+ for (const [name16, ver] of Object.entries(tplDeps)) {
3636
+ if (!existsAnywhere(name16)) {
3637
+ targetPkg.dependencies[name16] = String(ver);
3615
3638
  }
3616
3639
  }
3617
- for (const [name, ver] of Object.entries(tplDevDeps)) {
3618
- if (!existsAnywhere(name)) {
3619
- targetPkg.devDependencies[name] = String(ver);
3640
+ for (const [name16, ver] of Object.entries(tplDevDeps)) {
3641
+ if (!existsAnywhere(name16)) {
3642
+ targetPkg.devDependencies[name16] = String(ver);
3620
3643
  }
3621
3644
  }
3622
- for (const [name, ver] of Object.entries(tplPeerDeps)) {
3623
- if (!(name in targetPkg.peerDependencies)) {
3624
- targetPkg.peerDependencies[name] = String(ver);
3645
+ for (const [name16, ver] of Object.entries(tplPeerDeps)) {
3646
+ if (!(name16 in targetPkg.peerDependencies)) {
3647
+ targetPkg.peerDependencies[name16] = String(ver);
3625
3648
  }
3626
3649
  }
3627
3650
  const prefix = `template:${slug}:`;
3628
- for (const [name, cmd] of Object.entries(tplScripts)) {
3629
- const newKey = `${prefix}${name}`;
3651
+ for (const [name16, cmd] of Object.entries(tplScripts)) {
3652
+ const newKey = `${prefix}${name16}`;
3630
3653
  if (!(newKey in targetPkg.scripts)) {
3631
3654
  targetPkg.scripts[newKey] = String(cmd);
3632
3655
  }
@@ -3711,9 +3734,9 @@ var programmaticFileCopyStep = createStep({
3711
3734
  return "unknown";
3712
3735
  }
3713
3736
  };
3714
- const convertNaming = (name, convention) => {
3715
- const baseName = basename(name, extname(name));
3716
- const ext = extname(name);
3737
+ const convertNaming = (name16, convention) => {
3738
+ const baseName = basename(name16, extname(name16));
3739
+ const ext = extname(name16);
3717
3740
  switch (convention) {
3718
3741
  case "camelCase":
3719
3742
  return baseName.replace(/[-_]/g, "").replace(/([A-Z])/g, (match, p1, offset) => offset === 0 ? p1.toLowerCase() : p1) + ext;
@@ -3724,7 +3747,7 @@ var programmaticFileCopyStep = createStep({
3724
3747
  case "PascalCase":
3725
3748
  return baseName.replace(/[-_]/g, "").replace(/^[a-z]/, (match) => match.toUpperCase()) + ext;
3726
3749
  default:
3727
- return name;
3750
+ return name16;
3728
3751
  }
3729
3752
  };
3730
3753
  for (const unit of orderedUnits) {
@@ -4052,7 +4075,7 @@ var intelligentMergeStep = createStep({
4052
4075
  outputSchema: z.object({
4053
4076
  success: z.boolean(),
4054
4077
  message: z.string(),
4055
- error: z.string().optional()
4078
+ errorMessage: z.string().optional()
4056
4079
  }),
4057
4080
  execute: async (input) => {
4058
4081
  try {
@@ -4067,11 +4090,11 @@ var intelligentMergeStep = createStep({
4067
4090
  success: true,
4068
4091
  message: `Successfully copied file from ${sourcePath} to ${destinationPath}`
4069
4092
  };
4070
- } catch (error) {
4093
+ } catch (err) {
4071
4094
  return {
4072
4095
  success: false,
4073
- message: `Failed to copy file: ${error instanceof Error ? error.message : String(error)}`,
4074
- error: error instanceof Error ? error.message : String(error)
4096
+ message: `Failed to copy file: ${err instanceof Error ? err.message : String(err)}`,
4097
+ errorMessage: err instanceof Error ? err.message : String(err)
4075
4098
  };
4076
4099
  }
4077
4100
  }
@@ -4225,8 +4248,9 @@ For each task:
4225
4248
 
4226
4249
  Start by listing your tasks and work through them systematically!
4227
4250
  `;
4228
- const isV2 = model.specificationVersion === "v2";
4229
- const result = isV2 ? await agentBuilder.stream(prompt) : await agentBuilder.streamLegacy(prompt);
4251
+ const resolvedModel = await agentBuilder.getModel();
4252
+ const isSupported = isSupportedLanguageModel(resolvedModel);
4253
+ const result = isSupported ? await agentBuilder.stream(prompt) : await agentBuilder.streamLegacy(prompt);
4230
4254
  const actualResolutions = [];
4231
4255
  for await (const chunk of result.fullStream) {
4232
4256
  if (chunk.type === "step-finish" || chunk.type === "step-start") {
@@ -4467,9 +4491,10 @@ Be thorough and methodical. Always use listDirectory to verify actual file exist
4467
4491
  Start by running validateCode with all validation types to get a complete picture of any issues, then systematically fix them.` : `Continue validation and fixing for the template integration at ${targetPath}. This is iteration ${currentIteration} of validation.
4468
4492
 
4469
4493
  Previous iterations may have fixed some issues, so start by re-running validateCode to see the current state, then fix any remaining issues.`;
4470
- const isV2 = model.specificationVersion === "v2";
4494
+ const resolvedModel = await validationAgent.getModel();
4495
+ const isSupported = isSupportedLanguageModel(resolvedModel);
4471
4496
  const output = z.object({ success: z.boolean() });
4472
- const result = isV2 ? await tryStreamWithJsonFallback(validationAgent, iterationPrompt, {
4497
+ const result = isSupported ? await tryStreamWithJsonFallback(validationAgent, iterationPrompt, {
4473
4498
  structuredOutput: {
4474
4499
  schema: output
4475
4500
  }
@@ -4749,6 +4774,4304 @@ var determineConflictStrategy = (_unit, _targetFile) => {
4749
4774
  var shouldAbortWorkflow = (stepResult) => {
4750
4775
  return stepResult?.success === false || stepResult?.error;
4751
4776
  };
4777
+ var marker = "vercel.ai.error";
4778
+ var symbol = Symbol.for(marker);
4779
+ var _a;
4780
+ var _AISDKError = class _AISDKError2 extends Error {
4781
+ /**
4782
+ * Creates an AI SDK Error.
4783
+ *
4784
+ * @param {Object} params - The parameters for creating the error.
4785
+ * @param {string} params.name - The name of the error.
4786
+ * @param {string} params.message - The error message.
4787
+ * @param {unknown} [params.cause] - The underlying cause of the error.
4788
+ */
4789
+ constructor({
4790
+ name: name143,
4791
+ message,
4792
+ cause
4793
+ }) {
4794
+ super(message);
4795
+ this[_a] = true;
4796
+ this.name = name143;
4797
+ this.cause = cause;
4798
+ }
4799
+ /**
4800
+ * Checks if the given error is an AI SDK Error.
4801
+ * @param {unknown} error - The error to check.
4802
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
4803
+ */
4804
+ static isInstance(error) {
4805
+ return _AISDKError2.hasMarker(error, marker);
4806
+ }
4807
+ static hasMarker(error, marker153) {
4808
+ const markerSymbol = Symbol.for(marker153);
4809
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
4810
+ }
4811
+ };
4812
+ _a = symbol;
4813
+ var AISDKError = _AISDKError;
4814
+ var name = "AI_APICallError";
4815
+ var marker2 = `vercel.ai.error.${name}`;
4816
+ var symbol2 = Symbol.for(marker2);
4817
+ var _a2;
4818
+ var APICallError = class extends AISDKError {
4819
+ constructor({
4820
+ message,
4821
+ url,
4822
+ requestBodyValues,
4823
+ statusCode,
4824
+ responseHeaders,
4825
+ responseBody,
4826
+ cause,
4827
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
4828
+ statusCode === 409 || // conflict
4829
+ statusCode === 429 || // too many requests
4830
+ statusCode >= 500),
4831
+ // server error
4832
+ data
4833
+ }) {
4834
+ super({ name, message, cause });
4835
+ this[_a2] = true;
4836
+ this.url = url;
4837
+ this.requestBodyValues = requestBodyValues;
4838
+ this.statusCode = statusCode;
4839
+ this.responseHeaders = responseHeaders;
4840
+ this.responseBody = responseBody;
4841
+ this.isRetryable = isRetryable;
4842
+ this.data = data;
4843
+ }
4844
+ static isInstance(error) {
4845
+ return AISDKError.hasMarker(error, marker2);
4846
+ }
4847
+ };
4848
+ _a2 = symbol2;
4849
+ var name2 = "AI_EmptyResponseBodyError";
4850
+ var marker3 = `vercel.ai.error.${name2}`;
4851
+ var symbol3 = Symbol.for(marker3);
4852
+ var _a3;
4853
+ var EmptyResponseBodyError = class extends AISDKError {
4854
+ // used in isInstance
4855
+ constructor({ message = "Empty response body" } = {}) {
4856
+ super({ name: name2, message });
4857
+ this[_a3] = true;
4858
+ }
4859
+ static isInstance(error) {
4860
+ return AISDKError.hasMarker(error, marker3);
4861
+ }
4862
+ };
4863
+ _a3 = symbol3;
4864
+ function getErrorMessage(error) {
4865
+ if (error == null) {
4866
+ return "unknown error";
4867
+ }
4868
+ if (typeof error === "string") {
4869
+ return error;
4870
+ }
4871
+ if (error instanceof Error) {
4872
+ return error.message;
4873
+ }
4874
+ return JSON.stringify(error);
4875
+ }
4876
+ var name3 = "AI_InvalidArgumentError";
4877
+ var marker4 = `vercel.ai.error.${name3}`;
4878
+ var symbol4 = Symbol.for(marker4);
4879
+ var _a4;
4880
+ var InvalidArgumentError = class extends AISDKError {
4881
+ constructor({
4882
+ message,
4883
+ cause,
4884
+ argument
4885
+ }) {
4886
+ super({ name: name3, message, cause });
4887
+ this[_a4] = true;
4888
+ this.argument = argument;
4889
+ }
4890
+ static isInstance(error) {
4891
+ return AISDKError.hasMarker(error, marker4);
4892
+ }
4893
+ };
4894
+ _a4 = symbol4;
4895
+ var name6 = "AI_JSONParseError";
4896
+ var marker7 = `vercel.ai.error.${name6}`;
4897
+ var symbol7 = Symbol.for(marker7);
4898
+ var _a7;
4899
+ var JSONParseError = class extends AISDKError {
4900
+ constructor({ text: text2, cause }) {
4901
+ super({
4902
+ name: name6,
4903
+ message: `JSON parsing failed: Text: ${text2}.
4904
+ Error message: ${getErrorMessage(cause)}`,
4905
+ cause
4906
+ });
4907
+ this[_a7] = true;
4908
+ this.text = text2;
4909
+ }
4910
+ static isInstance(error) {
4911
+ return AISDKError.hasMarker(error, marker7);
4912
+ }
4913
+ };
4914
+ _a7 = symbol7;
4915
+ var name12 = "AI_TypeValidationError";
4916
+ var marker13 = `vercel.ai.error.${name12}`;
4917
+ var symbol13 = Symbol.for(marker13);
4918
+ var _a13;
4919
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
4920
+ constructor({ value, cause }) {
4921
+ super({
4922
+ name: name12,
4923
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
4924
+ Error message: ${getErrorMessage(cause)}`,
4925
+ cause
4926
+ });
4927
+ this[_a13] = true;
4928
+ this.value = value;
4929
+ }
4930
+ static isInstance(error) {
4931
+ return AISDKError.hasMarker(error, marker13);
4932
+ }
4933
+ /**
4934
+ * Wraps an error into a TypeValidationError.
4935
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
4936
+ * Otherwise, it creates a new TypeValidationError.
4937
+ *
4938
+ * @param {Object} params - The parameters for wrapping the error.
4939
+ * @param {unknown} params.value - The value that failed validation.
4940
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
4941
+ * @returns {TypeValidationError} A TypeValidationError instance.
4942
+ */
4943
+ static wrap({
4944
+ value,
4945
+ cause
4946
+ }) {
4947
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
4948
+ }
4949
+ };
4950
+ _a13 = symbol13;
4951
+ var TypeValidationError = _TypeValidationError;
4952
+ var ParseError = class extends Error {
4953
+ constructor(message, options) {
4954
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
4955
+ }
4956
+ };
4957
+ function noop(_arg) {
4958
+ }
4959
+ function createParser(callbacks) {
4960
+ if (typeof callbacks == "function")
4961
+ throw new TypeError(
4962
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
4963
+ );
4964
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
4965
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
4966
+ function feed(newChunk) {
4967
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
4968
+ for (const line of complete)
4969
+ parseLine(line);
4970
+ incompleteLine = incomplete, isFirstChunk = false;
4971
+ }
4972
+ function parseLine(line) {
4973
+ if (line === "") {
4974
+ dispatchEvent();
4975
+ return;
4976
+ }
4977
+ if (line.startsWith(":")) {
4978
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
4979
+ return;
4980
+ }
4981
+ const fieldSeparatorIndex = line.indexOf(":");
4982
+ if (fieldSeparatorIndex !== -1) {
4983
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
4984
+ processField(field, value, line);
4985
+ return;
4986
+ }
4987
+ processField(line, "", line);
4988
+ }
4989
+ function processField(field, value, line) {
4990
+ switch (field) {
4991
+ case "event":
4992
+ eventType = value;
4993
+ break;
4994
+ case "data":
4995
+ data = `${data}${value}
4996
+ `;
4997
+ break;
4998
+ case "id":
4999
+ id = value.includes("\0") ? void 0 : value;
5000
+ break;
5001
+ case "retry":
5002
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
5003
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
5004
+ type: "invalid-retry",
5005
+ value,
5006
+ line
5007
+ })
5008
+ );
5009
+ break;
5010
+ default:
5011
+ onError(
5012
+ new ParseError(
5013
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
5014
+ { type: "unknown-field", field, value, line }
5015
+ )
5016
+ );
5017
+ break;
5018
+ }
5019
+ }
5020
+ function dispatchEvent() {
5021
+ data.length > 0 && onEvent({
5022
+ id,
5023
+ event: eventType || void 0,
5024
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
5025
+ // then remove the last character from the data buffer.
5026
+ data: data.endsWith(`
5027
+ `) ? data.slice(0, -1) : data
5028
+ }), id = void 0, data = "", eventType = "";
5029
+ }
5030
+ function reset(options = {}) {
5031
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
5032
+ }
5033
+ return { feed, reset };
5034
+ }
5035
+ function splitLines(chunk) {
5036
+ const lines = [];
5037
+ let incompleteLine = "", searchIndex = 0;
5038
+ for (; searchIndex < chunk.length; ) {
5039
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
5040
+ `, searchIndex);
5041
+ let lineEnd = -1;
5042
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
5043
+ incompleteLine = chunk.slice(searchIndex);
5044
+ break;
5045
+ } else {
5046
+ const line = chunk.slice(searchIndex, lineEnd);
5047
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
5048
+ ` && searchIndex++;
5049
+ }
5050
+ }
5051
+ return [lines, incompleteLine];
5052
+ }
5053
+ var EventSourceParserStream = class extends TransformStream {
5054
+ constructor({ onError, onRetry, onComment } = {}) {
5055
+ let parser;
5056
+ super({
5057
+ start(controller) {
5058
+ parser = createParser({
5059
+ onEvent: (event) => {
5060
+ controller.enqueue(event);
5061
+ },
5062
+ onError(error) {
5063
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
5064
+ },
5065
+ onRetry,
5066
+ onComment
5067
+ });
5068
+ },
5069
+ transform(chunk) {
5070
+ parser.feed(chunk);
5071
+ }
5072
+ });
5073
+ }
5074
+ };
5075
+ function combineHeaders(...headers) {
5076
+ return headers.reduce(
5077
+ (combinedHeaders, currentHeaders) => ({
5078
+ ...combinedHeaders,
5079
+ ...currentHeaders != null ? currentHeaders : {}
5080
+ }),
5081
+ {}
5082
+ );
5083
+ }
5084
+ function extractResponseHeaders(response) {
5085
+ return Object.fromEntries([...response.headers]);
5086
+ }
5087
+ var createIdGenerator = ({
5088
+ prefix,
5089
+ size = 16,
5090
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
5091
+ separator = "-"
5092
+ } = {}) => {
5093
+ const generator = () => {
5094
+ const alphabetLength = alphabet.length;
5095
+ const chars = new Array(size);
5096
+ for (let i = 0; i < size; i++) {
5097
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
5098
+ }
5099
+ return chars.join("");
5100
+ };
5101
+ if (prefix == null) {
5102
+ return generator;
5103
+ }
5104
+ if (alphabet.includes(separator)) {
5105
+ throw new InvalidArgumentError({
5106
+ argument: "separator",
5107
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
5108
+ });
5109
+ }
5110
+ return () => `${prefix}${separator}${generator()}`;
5111
+ };
5112
+ createIdGenerator();
5113
+ function isAbortError(error) {
5114
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
5115
+ error.name === "TimeoutError");
5116
+ }
5117
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
5118
+ function handleFetchError({
5119
+ error,
5120
+ url,
5121
+ requestBodyValues
5122
+ }) {
5123
+ if (isAbortError(error)) {
5124
+ return error;
5125
+ }
5126
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
5127
+ const cause = error.cause;
5128
+ if (cause != null) {
5129
+ return new APICallError({
5130
+ message: `Cannot connect to API: ${cause.message}`,
5131
+ cause,
5132
+ url,
5133
+ requestBodyValues,
5134
+ isRetryable: true
5135
+ // retry when network error
5136
+ });
5137
+ }
5138
+ }
5139
+ return error;
5140
+ }
5141
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
5142
+ var _a153, _b8, _c;
5143
+ if (globalThisAny.window) {
5144
+ return `runtime/browser`;
5145
+ }
5146
+ if ((_a153 = globalThisAny.navigator) == null ? void 0 : _a153.userAgent) {
5147
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
5148
+ }
5149
+ if ((_c = (_b8 = globalThisAny.process) == null ? void 0 : _b8.versions) == null ? void 0 : _c.node) {
5150
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
5151
+ }
5152
+ if (globalThisAny.EdgeRuntime) {
5153
+ return `runtime/vercel-edge`;
5154
+ }
5155
+ return "runtime/unknown";
5156
+ }
5157
+ function normalizeHeaders(headers) {
5158
+ if (headers == null) {
5159
+ return {};
5160
+ }
5161
+ const normalized = {};
5162
+ if (headers instanceof Headers) {
5163
+ headers.forEach((value, key) => {
5164
+ normalized[key.toLowerCase()] = value;
5165
+ });
5166
+ } else {
5167
+ if (!Array.isArray(headers)) {
5168
+ headers = Object.entries(headers);
5169
+ }
5170
+ for (const [key, value] of headers) {
5171
+ if (value != null) {
5172
+ normalized[key.toLowerCase()] = value;
5173
+ }
5174
+ }
5175
+ }
5176
+ return normalized;
5177
+ }
5178
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
5179
+ const normalizedHeaders = new Headers(normalizeHeaders(headers));
5180
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
5181
+ normalizedHeaders.set(
5182
+ "user-agent",
5183
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
5184
+ );
5185
+ return Object.fromEntries(normalizedHeaders.entries());
5186
+ }
5187
+ var VERSION = "3.0.17";
5188
+ var getOriginalFetch = () => globalThis.fetch;
5189
+ var getFromApi = async ({
5190
+ url,
5191
+ headers = {},
5192
+ successfulResponseHandler,
5193
+ failedResponseHandler,
5194
+ abortSignal,
5195
+ fetch: fetch2 = getOriginalFetch()
5196
+ }) => {
5197
+ try {
5198
+ const response = await fetch2(url, {
5199
+ method: "GET",
5200
+ headers: withUserAgentSuffix(
5201
+ headers,
5202
+ `ai-sdk/provider-utils/${VERSION}`,
5203
+ getRuntimeEnvironmentUserAgent()
5204
+ ),
5205
+ signal: abortSignal
5206
+ });
5207
+ const responseHeaders = extractResponseHeaders(response);
5208
+ if (!response.ok) {
5209
+ let errorInformation;
5210
+ try {
5211
+ errorInformation = await failedResponseHandler({
5212
+ response,
5213
+ url,
5214
+ requestBodyValues: {}
5215
+ });
5216
+ } catch (error) {
5217
+ if (isAbortError(error) || APICallError.isInstance(error)) {
5218
+ throw error;
5219
+ }
5220
+ throw new APICallError({
5221
+ message: "Failed to process error response",
5222
+ cause: error,
5223
+ statusCode: response.status,
5224
+ url,
5225
+ responseHeaders,
5226
+ requestBodyValues: {}
5227
+ });
5228
+ }
5229
+ throw errorInformation.value;
5230
+ }
5231
+ try {
5232
+ return await successfulResponseHandler({
5233
+ response,
5234
+ url,
5235
+ requestBodyValues: {}
5236
+ });
5237
+ } catch (error) {
5238
+ if (error instanceof Error) {
5239
+ if (isAbortError(error) || APICallError.isInstance(error)) {
5240
+ throw error;
5241
+ }
5242
+ }
5243
+ throw new APICallError({
5244
+ message: "Failed to process successful response",
5245
+ cause: error,
5246
+ statusCode: response.status,
5247
+ url,
5248
+ responseHeaders,
5249
+ requestBodyValues: {}
5250
+ });
5251
+ }
5252
+ } catch (error) {
5253
+ throw handleFetchError({ error, url, requestBodyValues: {} });
5254
+ }
5255
+ };
5256
+ function loadOptionalSetting({
5257
+ settingValue,
5258
+ environmentVariableName
5259
+ }) {
5260
+ if (typeof settingValue === "string") {
5261
+ return settingValue;
5262
+ }
5263
+ if (settingValue != null || typeof process === "undefined") {
5264
+ return void 0;
5265
+ }
5266
+ settingValue = process.env[environmentVariableName];
5267
+ if (settingValue == null || typeof settingValue !== "string") {
5268
+ return void 0;
5269
+ }
5270
+ return settingValue;
5271
+ }
5272
+ var suspectProtoRx = /"__proto__"\s*:/;
5273
+ var suspectConstructorRx = /"constructor"\s*:/;
5274
+ function _parse(text2) {
5275
+ const obj = JSON.parse(text2);
5276
+ if (obj === null || typeof obj !== "object") {
5277
+ return obj;
5278
+ }
5279
+ if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
5280
+ return obj;
5281
+ }
5282
+ return filter(obj);
5283
+ }
5284
+ function filter(obj) {
5285
+ let next = [obj];
5286
+ while (next.length) {
5287
+ const nodes = next;
5288
+ next = [];
5289
+ for (const node of nodes) {
5290
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
5291
+ throw new SyntaxError("Object contains forbidden prototype property");
5292
+ }
5293
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
5294
+ throw new SyntaxError("Object contains forbidden prototype property");
5295
+ }
5296
+ for (const key in node) {
5297
+ const value = node[key];
5298
+ if (value && typeof value === "object") {
5299
+ next.push(value);
5300
+ }
5301
+ }
5302
+ }
5303
+ }
5304
+ return obj;
5305
+ }
5306
+ function secureJsonParse(text2) {
5307
+ const { stackTraceLimit } = Error;
5308
+ try {
5309
+ Error.stackTraceLimit = 0;
5310
+ } catch (e) {
5311
+ return _parse(text2);
5312
+ }
5313
+ try {
5314
+ return _parse(text2);
5315
+ } finally {
5316
+ Error.stackTraceLimit = stackTraceLimit;
5317
+ }
5318
+ }
5319
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
5320
+ function validator(validate) {
5321
+ return { [validatorSymbol]: true, validate };
5322
+ }
5323
+ function isValidator(value) {
5324
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
5325
+ }
5326
+ function lazyValidator(createValidator) {
5327
+ let validator2;
5328
+ return () => {
5329
+ if (validator2 == null) {
5330
+ validator2 = createValidator();
5331
+ }
5332
+ return validator2;
5333
+ };
5334
+ }
5335
+ function asValidator(value) {
5336
+ return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
5337
+ }
5338
+ function standardSchemaValidator(standardSchema) {
5339
+ return validator(async (value) => {
5340
+ const result = await standardSchema["~standard"].validate(value);
5341
+ return result.issues == null ? { success: true, value: result.value } : {
5342
+ success: false,
5343
+ error: new TypeValidationError({
5344
+ value,
5345
+ cause: result.issues
5346
+ })
5347
+ };
5348
+ });
5349
+ }
5350
+ async function validateTypes({
5351
+ value,
5352
+ schema
5353
+ }) {
5354
+ const result = await safeValidateTypes({ value, schema });
5355
+ if (!result.success) {
5356
+ throw TypeValidationError.wrap({ value, cause: result.error });
5357
+ }
5358
+ return result.value;
5359
+ }
5360
+ async function safeValidateTypes({
5361
+ value,
5362
+ schema
5363
+ }) {
5364
+ const validator2 = asValidator(schema);
5365
+ try {
5366
+ if (validator2.validate == null) {
5367
+ return { success: true, value, rawValue: value };
5368
+ }
5369
+ const result = await validator2.validate(value);
5370
+ if (result.success) {
5371
+ return { success: true, value: result.value, rawValue: value };
5372
+ }
5373
+ return {
5374
+ success: false,
5375
+ error: TypeValidationError.wrap({ value, cause: result.error }),
5376
+ rawValue: value
5377
+ };
5378
+ } catch (error) {
5379
+ return {
5380
+ success: false,
5381
+ error: TypeValidationError.wrap({ value, cause: error }),
5382
+ rawValue: value
5383
+ };
5384
+ }
5385
+ }
5386
+ async function parseJSON({
5387
+ text: text2,
5388
+ schema
5389
+ }) {
5390
+ try {
5391
+ const value = secureJsonParse(text2);
5392
+ if (schema == null) {
5393
+ return value;
5394
+ }
5395
+ return validateTypes({ value, schema });
5396
+ } catch (error) {
5397
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
5398
+ throw error;
5399
+ }
5400
+ throw new JSONParseError({ text: text2, cause: error });
5401
+ }
5402
+ }
5403
+ async function safeParseJSON({
5404
+ text: text2,
5405
+ schema
5406
+ }) {
5407
+ try {
5408
+ const value = secureJsonParse(text2);
5409
+ if (schema == null) {
5410
+ return { success: true, value, rawValue: value };
5411
+ }
5412
+ return await safeValidateTypes({ value, schema });
5413
+ } catch (error) {
5414
+ return {
5415
+ success: false,
5416
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text: text2, cause: error }),
5417
+ rawValue: void 0
5418
+ };
5419
+ }
5420
+ }
5421
+ function parseJsonEventStream({
5422
+ stream,
5423
+ schema
5424
+ }) {
5425
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
5426
+ new TransformStream({
5427
+ async transform({ data }, controller) {
5428
+ if (data === "[DONE]") {
5429
+ return;
5430
+ }
5431
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
5432
+ }
5433
+ })
5434
+ );
5435
+ }
5436
+ var getOriginalFetch2 = () => globalThis.fetch;
5437
+ var postJsonToApi = async ({
5438
+ url,
5439
+ headers,
5440
+ body,
5441
+ failedResponseHandler,
5442
+ successfulResponseHandler,
5443
+ abortSignal,
5444
+ fetch: fetch2
5445
+ }) => postToApi({
5446
+ url,
5447
+ headers: {
5448
+ "Content-Type": "application/json",
5449
+ ...headers
5450
+ },
5451
+ body: {
5452
+ content: JSON.stringify(body),
5453
+ values: body
5454
+ },
5455
+ failedResponseHandler,
5456
+ successfulResponseHandler,
5457
+ abortSignal,
5458
+ fetch: fetch2
5459
+ });
5460
+ var postToApi = async ({
5461
+ url,
5462
+ headers = {},
5463
+ body,
5464
+ successfulResponseHandler,
5465
+ failedResponseHandler,
5466
+ abortSignal,
5467
+ fetch: fetch2 = getOriginalFetch2()
5468
+ }) => {
5469
+ try {
5470
+ const response = await fetch2(url, {
5471
+ method: "POST",
5472
+ headers: withUserAgentSuffix(
5473
+ headers,
5474
+ `ai-sdk/provider-utils/${VERSION}`,
5475
+ getRuntimeEnvironmentUserAgent()
5476
+ ),
5477
+ body: body.content,
5478
+ signal: abortSignal
5479
+ });
5480
+ const responseHeaders = extractResponseHeaders(response);
5481
+ if (!response.ok) {
5482
+ let errorInformation;
5483
+ try {
5484
+ errorInformation = await failedResponseHandler({
5485
+ response,
5486
+ url,
5487
+ requestBodyValues: body.values
5488
+ });
5489
+ } catch (error) {
5490
+ if (isAbortError(error) || APICallError.isInstance(error)) {
5491
+ throw error;
5492
+ }
5493
+ throw new APICallError({
5494
+ message: "Failed to process error response",
5495
+ cause: error,
5496
+ statusCode: response.status,
5497
+ url,
5498
+ responseHeaders,
5499
+ requestBodyValues: body.values
5500
+ });
5501
+ }
5502
+ throw errorInformation.value;
5503
+ }
5504
+ try {
5505
+ return await successfulResponseHandler({
5506
+ response,
5507
+ url,
5508
+ requestBodyValues: body.values
5509
+ });
5510
+ } catch (error) {
5511
+ if (error instanceof Error) {
5512
+ if (isAbortError(error) || APICallError.isInstance(error)) {
5513
+ throw error;
5514
+ }
5515
+ }
5516
+ throw new APICallError({
5517
+ message: "Failed to process successful response",
5518
+ cause: error,
5519
+ statusCode: response.status,
5520
+ url,
5521
+ responseHeaders,
5522
+ requestBodyValues: body.values
5523
+ });
5524
+ }
5525
+ } catch (error) {
5526
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
5527
+ }
5528
+ };
5529
+ async function resolve4(value) {
5530
+ if (typeof value === "function") {
5531
+ value = value();
5532
+ }
5533
+ return Promise.resolve(value);
5534
+ }
5535
+ var createJsonErrorResponseHandler = ({
5536
+ errorSchema,
5537
+ errorToMessage,
5538
+ isRetryable
5539
+ }) => async ({ response, url, requestBodyValues }) => {
5540
+ const responseBody = await response.text();
5541
+ const responseHeaders = extractResponseHeaders(response);
5542
+ if (responseBody.trim() === "") {
5543
+ return {
5544
+ responseHeaders,
5545
+ value: new APICallError({
5546
+ message: response.statusText,
5547
+ url,
5548
+ requestBodyValues,
5549
+ statusCode: response.status,
5550
+ responseHeaders,
5551
+ responseBody,
5552
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
5553
+ })
5554
+ };
5555
+ }
5556
+ try {
5557
+ const parsedError = await parseJSON({
5558
+ text: responseBody,
5559
+ schema: errorSchema
5560
+ });
5561
+ return {
5562
+ responseHeaders,
5563
+ value: new APICallError({
5564
+ message: errorToMessage(parsedError),
5565
+ url,
5566
+ requestBodyValues,
5567
+ statusCode: response.status,
5568
+ responseHeaders,
5569
+ responseBody,
5570
+ data: parsedError,
5571
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
5572
+ })
5573
+ };
5574
+ } catch (parseError) {
5575
+ return {
5576
+ responseHeaders,
5577
+ value: new APICallError({
5578
+ message: response.statusText,
5579
+ url,
5580
+ requestBodyValues,
5581
+ statusCode: response.status,
5582
+ responseHeaders,
5583
+ responseBody,
5584
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
5585
+ })
5586
+ };
5587
+ }
5588
+ };
5589
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
5590
+ const responseHeaders = extractResponseHeaders(response);
5591
+ if (response.body == null) {
5592
+ throw new EmptyResponseBodyError({});
5593
+ }
5594
+ return {
5595
+ responseHeaders,
5596
+ value: parseJsonEventStream({
5597
+ stream: response.body,
5598
+ schema: chunkSchema
5599
+ })
5600
+ };
5601
+ };
5602
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
5603
+ const responseBody = await response.text();
5604
+ const parsedResult = await safeParseJSON({
5605
+ text: responseBody,
5606
+ schema: responseSchema
5607
+ });
5608
+ const responseHeaders = extractResponseHeaders(response);
5609
+ if (!parsedResult.success) {
5610
+ throw new APICallError({
5611
+ message: "Invalid JSON response",
5612
+ cause: parsedResult.error,
5613
+ statusCode: response.status,
5614
+ responseHeaders,
5615
+ responseBody,
5616
+ url,
5617
+ requestBodyValues
5618
+ });
5619
+ }
5620
+ return {
5621
+ responseHeaders,
5622
+ value: parsedResult.value,
5623
+ rawValue: parsedResult.rawValue
5624
+ };
5625
+ };
5626
+ var getRelativePath = (pathA, pathB) => {
5627
+ let i = 0;
5628
+ for (; i < pathA.length && i < pathB.length; i++) {
5629
+ if (pathA[i] !== pathB[i]) break;
5630
+ }
5631
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
5632
+ };
5633
+ var ignoreOverride = Symbol(
5634
+ "Let zodToJsonSchema decide on which parser to use"
5635
+ );
5636
+ var defaultOptions = {
5637
+ name: void 0,
5638
+ $refStrategy: "root",
5639
+ basePath: ["#"],
5640
+ effectStrategy: "input",
5641
+ pipeStrategy: "all",
5642
+ dateStrategy: "format:date-time",
5643
+ mapStrategy: "entries",
5644
+ removeAdditionalStrategy: "passthrough",
5645
+ allowedAdditionalProperties: true,
5646
+ rejectedAdditionalProperties: false,
5647
+ definitionPath: "definitions",
5648
+ strictUnions: false,
5649
+ definitions: {},
5650
+ errorMessages: false,
5651
+ patternStrategy: "escape",
5652
+ applyRegexFlags: false,
5653
+ emailStrategy: "format:email",
5654
+ base64Strategy: "contentEncoding:base64",
5655
+ nameStrategy: "ref"
5656
+ };
5657
+ var getDefaultOptions = (options) => typeof options === "string" ? {
5658
+ ...defaultOptions,
5659
+ name: options
5660
+ } : {
5661
+ ...defaultOptions,
5662
+ ...options
5663
+ };
5664
+ function parseAnyDef() {
5665
+ return {};
5666
+ }
5667
+ function parseArrayDef(def, refs) {
5668
+ var _a153, _b8, _c;
5669
+ const res = {
5670
+ type: "array"
5671
+ };
5672
+ if (((_a153 = def.type) == null ? void 0 : _a153._def) && ((_c = (_b8 = def.type) == null ? void 0 : _b8._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
5673
+ res.items = parseDef(def.type._def, {
5674
+ ...refs,
5675
+ currentPath: [...refs.currentPath, "items"]
5676
+ });
5677
+ }
5678
+ if (def.minLength) {
5679
+ res.minItems = def.minLength.value;
5680
+ }
5681
+ if (def.maxLength) {
5682
+ res.maxItems = def.maxLength.value;
5683
+ }
5684
+ if (def.exactLength) {
5685
+ res.minItems = def.exactLength.value;
5686
+ res.maxItems = def.exactLength.value;
5687
+ }
5688
+ return res;
5689
+ }
5690
+ function parseBigintDef(def) {
5691
+ const res = {
5692
+ type: "integer",
5693
+ format: "int64"
5694
+ };
5695
+ if (!def.checks) return res;
5696
+ for (const check of def.checks) {
5697
+ switch (check.kind) {
5698
+ case "min":
5699
+ if (check.inclusive) {
5700
+ res.minimum = check.value;
5701
+ } else {
5702
+ res.exclusiveMinimum = check.value;
5703
+ }
5704
+ break;
5705
+ case "max":
5706
+ if (check.inclusive) {
5707
+ res.maximum = check.value;
5708
+ } else {
5709
+ res.exclusiveMaximum = check.value;
5710
+ }
5711
+ break;
5712
+ case "multipleOf":
5713
+ res.multipleOf = check.value;
5714
+ break;
5715
+ }
5716
+ }
5717
+ return res;
5718
+ }
5719
+ function parseBooleanDef() {
5720
+ return { type: "boolean" };
5721
+ }
5722
+ function parseBrandedDef(_def, refs) {
5723
+ return parseDef(_def.type._def, refs);
5724
+ }
5725
+ var parseCatchDef = (def, refs) => {
5726
+ return parseDef(def.innerType._def, refs);
5727
+ };
5728
+ function parseDateDef(def, refs, overrideDateStrategy) {
5729
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
5730
+ if (Array.isArray(strategy)) {
5731
+ return {
5732
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
5733
+ };
5734
+ }
5735
+ switch (strategy) {
5736
+ case "string":
5737
+ case "format:date-time":
5738
+ return {
5739
+ type: "string",
5740
+ format: "date-time"
5741
+ };
5742
+ case "format:date":
5743
+ return {
5744
+ type: "string",
5745
+ format: "date"
5746
+ };
5747
+ case "integer":
5748
+ return integerDateParser(def);
5749
+ }
5750
+ }
5751
+ var integerDateParser = (def) => {
5752
+ const res = {
5753
+ type: "integer",
5754
+ format: "unix-time"
5755
+ };
5756
+ for (const check of def.checks) {
5757
+ switch (check.kind) {
5758
+ case "min":
5759
+ res.minimum = check.value;
5760
+ break;
5761
+ case "max":
5762
+ res.maximum = check.value;
5763
+ break;
5764
+ }
5765
+ }
5766
+ return res;
5767
+ };
5768
+ function parseDefaultDef(_def, refs) {
5769
+ return {
5770
+ ...parseDef(_def.innerType._def, refs),
5771
+ default: _def.defaultValue()
5772
+ };
5773
+ }
5774
+ function parseEffectsDef(_def, refs) {
5775
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
5776
+ }
5777
+ function parseEnumDef(def) {
5778
+ return {
5779
+ type: "string",
5780
+ enum: Array.from(def.values)
5781
+ };
5782
+ }
5783
+ var isJsonSchema7AllOfType = (type) => {
5784
+ if ("type" in type && type.type === "string") return false;
5785
+ return "allOf" in type;
5786
+ };
5787
+ function parseIntersectionDef(def, refs) {
5788
+ const allOf = [
5789
+ parseDef(def.left._def, {
5790
+ ...refs,
5791
+ currentPath: [...refs.currentPath, "allOf", "0"]
5792
+ }),
5793
+ parseDef(def.right._def, {
5794
+ ...refs,
5795
+ currentPath: [...refs.currentPath, "allOf", "1"]
5796
+ })
5797
+ ].filter((x) => !!x);
5798
+ const mergedAllOf = [];
5799
+ allOf.forEach((schema) => {
5800
+ if (isJsonSchema7AllOfType(schema)) {
5801
+ mergedAllOf.push(...schema.allOf);
5802
+ } else {
5803
+ let nestedSchema = schema;
5804
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
5805
+ const { additionalProperties, ...rest } = schema;
5806
+ nestedSchema = rest;
5807
+ }
5808
+ mergedAllOf.push(nestedSchema);
5809
+ }
5810
+ });
5811
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
5812
+ }
5813
+ function parseLiteralDef(def) {
5814
+ const parsedType = typeof def.value;
5815
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
5816
+ return {
5817
+ type: Array.isArray(def.value) ? "array" : "object"
5818
+ };
5819
+ }
5820
+ return {
5821
+ type: parsedType === "bigint" ? "integer" : parsedType,
5822
+ const: def.value
5823
+ };
5824
+ }
5825
+ var emojiRegex = void 0;
5826
+ var zodPatterns = {
5827
+ /**
5828
+ * `c` was changed to `[cC]` to replicate /i flag
5829
+ */
5830
+ cuid: /^[cC][^\s-]{8,}$/,
5831
+ cuid2: /^[0-9a-z]+$/,
5832
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
5833
+ /**
5834
+ * `a-z` was added to replicate /i flag
5835
+ */
5836
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
5837
+ /**
5838
+ * Constructed a valid Unicode RegExp
5839
+ *
5840
+ * Lazily instantiate since this type of regex isn't supported
5841
+ * in all envs (e.g. React Native).
5842
+ *
5843
+ * See:
5844
+ * https://github.com/colinhacks/zod/issues/2433
5845
+ * Fix in Zod:
5846
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
5847
+ */
5848
+ emoji: () => {
5849
+ if (emojiRegex === void 0) {
5850
+ emojiRegex = RegExp(
5851
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
5852
+ "u"
5853
+ );
5854
+ }
5855
+ return emojiRegex;
5856
+ },
5857
+ /**
5858
+ * Unused
5859
+ */
5860
+ 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}$/,
5861
+ /**
5862
+ * Unused
5863
+ */
5864
+ 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])$/,
5865
+ 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])$/,
5866
+ /**
5867
+ * Unused
5868
+ */
5869
+ 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})))$/,
5870
+ 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])$/,
5871
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
5872
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
5873
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
5874
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
5875
+ };
5876
+ function parseStringDef(def, refs) {
5877
+ const res = {
5878
+ type: "string"
5879
+ };
5880
+ if (def.checks) {
5881
+ for (const check of def.checks) {
5882
+ switch (check.kind) {
5883
+ case "min":
5884
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
5885
+ break;
5886
+ case "max":
5887
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
5888
+ break;
5889
+ case "email":
5890
+ switch (refs.emailStrategy) {
5891
+ case "format:email":
5892
+ addFormat(res, "email", check.message, refs);
5893
+ break;
5894
+ case "format:idn-email":
5895
+ addFormat(res, "idn-email", check.message, refs);
5896
+ break;
5897
+ case "pattern:zod":
5898
+ addPattern(res, zodPatterns.email, check.message, refs);
5899
+ break;
5900
+ }
5901
+ break;
5902
+ case "url":
5903
+ addFormat(res, "uri", check.message, refs);
5904
+ break;
5905
+ case "uuid":
5906
+ addFormat(res, "uuid", check.message, refs);
5907
+ break;
5908
+ case "regex":
5909
+ addPattern(res, check.regex, check.message, refs);
5910
+ break;
5911
+ case "cuid":
5912
+ addPattern(res, zodPatterns.cuid, check.message, refs);
5913
+ break;
5914
+ case "cuid2":
5915
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
5916
+ break;
5917
+ case "startsWith":
5918
+ addPattern(
5919
+ res,
5920
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
5921
+ check.message,
5922
+ refs
5923
+ );
5924
+ break;
5925
+ case "endsWith":
5926
+ addPattern(
5927
+ res,
5928
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
5929
+ check.message,
5930
+ refs
5931
+ );
5932
+ break;
5933
+ case "datetime":
5934
+ addFormat(res, "date-time", check.message, refs);
5935
+ break;
5936
+ case "date":
5937
+ addFormat(res, "date", check.message, refs);
5938
+ break;
5939
+ case "time":
5940
+ addFormat(res, "time", check.message, refs);
5941
+ break;
5942
+ case "duration":
5943
+ addFormat(res, "duration", check.message, refs);
5944
+ break;
5945
+ case "length":
5946
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
5947
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
5948
+ break;
5949
+ case "includes": {
5950
+ addPattern(
5951
+ res,
5952
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
5953
+ check.message,
5954
+ refs
5955
+ );
5956
+ break;
5957
+ }
5958
+ case "ip": {
5959
+ if (check.version !== "v6") {
5960
+ addFormat(res, "ipv4", check.message, refs);
5961
+ }
5962
+ if (check.version !== "v4") {
5963
+ addFormat(res, "ipv6", check.message, refs);
5964
+ }
5965
+ break;
5966
+ }
5967
+ case "base64url":
5968
+ addPattern(res, zodPatterns.base64url, check.message, refs);
5969
+ break;
5970
+ case "jwt":
5971
+ addPattern(res, zodPatterns.jwt, check.message, refs);
5972
+ break;
5973
+ case "cidr": {
5974
+ if (check.version !== "v6") {
5975
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
5976
+ }
5977
+ if (check.version !== "v4") {
5978
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
5979
+ }
5980
+ break;
5981
+ }
5982
+ case "emoji":
5983
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
5984
+ break;
5985
+ case "ulid": {
5986
+ addPattern(res, zodPatterns.ulid, check.message, refs);
5987
+ break;
5988
+ }
5989
+ case "base64": {
5990
+ switch (refs.base64Strategy) {
5991
+ case "format:binary": {
5992
+ addFormat(res, "binary", check.message, refs);
5993
+ break;
5994
+ }
5995
+ case "contentEncoding:base64": {
5996
+ res.contentEncoding = "base64";
5997
+ break;
5998
+ }
5999
+ case "pattern:zod": {
6000
+ addPattern(res, zodPatterns.base64, check.message, refs);
6001
+ break;
6002
+ }
6003
+ }
6004
+ break;
6005
+ }
6006
+ case "nanoid": {
6007
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
6008
+ }
6009
+ }
6010
+ }
6011
+ }
6012
+ return res;
6013
+ }
6014
+ function escapeLiteralCheckValue(literal, refs) {
6015
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
6016
+ }
6017
+ var ALPHA_NUMERIC = new Set(
6018
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
6019
+ );
6020
+ function escapeNonAlphaNumeric(source) {
6021
+ let result = "";
6022
+ for (let i = 0; i < source.length; i++) {
6023
+ if (!ALPHA_NUMERIC.has(source[i])) {
6024
+ result += "\\";
6025
+ }
6026
+ result += source[i];
6027
+ }
6028
+ return result;
6029
+ }
6030
+ function addFormat(schema, value, message, refs) {
6031
+ var _a153;
6032
+ if (schema.format || ((_a153 = schema.anyOf) == null ? void 0 : _a153.some((x) => x.format))) {
6033
+ if (!schema.anyOf) {
6034
+ schema.anyOf = [];
6035
+ }
6036
+ if (schema.format) {
6037
+ schema.anyOf.push({
6038
+ format: schema.format
6039
+ });
6040
+ delete schema.format;
6041
+ }
6042
+ schema.anyOf.push({
6043
+ format: value,
6044
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
6045
+ });
6046
+ } else {
6047
+ schema.format = value;
6048
+ }
6049
+ }
6050
+ function addPattern(schema, regex, message, refs) {
6051
+ var _a153;
6052
+ if (schema.pattern || ((_a153 = schema.allOf) == null ? void 0 : _a153.some((x) => x.pattern))) {
6053
+ if (!schema.allOf) {
6054
+ schema.allOf = [];
6055
+ }
6056
+ if (schema.pattern) {
6057
+ schema.allOf.push({
6058
+ pattern: schema.pattern
6059
+ });
6060
+ delete schema.pattern;
6061
+ }
6062
+ schema.allOf.push({
6063
+ pattern: stringifyRegExpWithFlags(regex, refs),
6064
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
6065
+ });
6066
+ } else {
6067
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
6068
+ }
6069
+ }
6070
+ function stringifyRegExpWithFlags(regex, refs) {
6071
+ var _a153;
6072
+ if (!refs.applyRegexFlags || !regex.flags) {
6073
+ return regex.source;
6074
+ }
6075
+ const flags = {
6076
+ i: regex.flags.includes("i"),
6077
+ // Case-insensitive
6078
+ m: regex.flags.includes("m"),
6079
+ // `^` and `$` matches adjacent to newline characters
6080
+ s: regex.flags.includes("s")
6081
+ // `.` matches newlines
6082
+ };
6083
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
6084
+ let pattern = "";
6085
+ let isEscaped = false;
6086
+ let inCharGroup = false;
6087
+ let inCharRange = false;
6088
+ for (let i = 0; i < source.length; i++) {
6089
+ if (isEscaped) {
6090
+ pattern += source[i];
6091
+ isEscaped = false;
6092
+ continue;
6093
+ }
6094
+ if (flags.i) {
6095
+ if (inCharGroup) {
6096
+ if (source[i].match(/[a-z]/)) {
6097
+ if (inCharRange) {
6098
+ pattern += source[i];
6099
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
6100
+ inCharRange = false;
6101
+ } else if (source[i + 1] === "-" && ((_a153 = source[i + 2]) == null ? void 0 : _a153.match(/[a-z]/))) {
6102
+ pattern += source[i];
6103
+ inCharRange = true;
6104
+ } else {
6105
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
6106
+ }
6107
+ continue;
6108
+ }
6109
+ } else if (source[i].match(/[a-z]/)) {
6110
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
6111
+ continue;
6112
+ }
6113
+ }
6114
+ if (flags.m) {
6115
+ if (source[i] === "^") {
6116
+ pattern += `(^|(?<=[\r
6117
+ ]))`;
6118
+ continue;
6119
+ } else if (source[i] === "$") {
6120
+ pattern += `($|(?=[\r
6121
+ ]))`;
6122
+ continue;
6123
+ }
6124
+ }
6125
+ if (flags.s && source[i] === ".") {
6126
+ pattern += inCharGroup ? `${source[i]}\r
6127
+ ` : `[${source[i]}\r
6128
+ ]`;
6129
+ continue;
6130
+ }
6131
+ pattern += source[i];
6132
+ if (source[i] === "\\") {
6133
+ isEscaped = true;
6134
+ } else if (inCharGroup && source[i] === "]") {
6135
+ inCharGroup = false;
6136
+ } else if (!inCharGroup && source[i] === "[") {
6137
+ inCharGroup = true;
6138
+ }
6139
+ }
6140
+ return pattern;
6141
+ }
6142
+ function parseRecordDef(def, refs) {
6143
+ var _a153, _b8, _c, _d, _e, _f;
6144
+ const schema = {
6145
+ type: "object",
6146
+ additionalProperties: (_a153 = parseDef(def.valueType._def, {
6147
+ ...refs,
6148
+ currentPath: [...refs.currentPath, "additionalProperties"]
6149
+ })) != null ? _a153 : refs.allowedAdditionalProperties
6150
+ };
6151
+ if (((_b8 = def.keyType) == null ? void 0 : _b8._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
6152
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
6153
+ return {
6154
+ ...schema,
6155
+ propertyNames: keyType
6156
+ };
6157
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) {
6158
+ return {
6159
+ ...schema,
6160
+ propertyNames: {
6161
+ enum: def.keyType._def.values
6162
+ }
6163
+ };
6164
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
6165
+ const { type, ...keyType } = parseBrandedDef(
6166
+ def.keyType._def,
6167
+ refs
6168
+ );
6169
+ return {
6170
+ ...schema,
6171
+ propertyNames: keyType
6172
+ };
6173
+ }
6174
+ return schema;
6175
+ }
6176
+ function parseMapDef(def, refs) {
6177
+ if (refs.mapStrategy === "record") {
6178
+ return parseRecordDef(def, refs);
6179
+ }
6180
+ const keys = parseDef(def.keyType._def, {
6181
+ ...refs,
6182
+ currentPath: [...refs.currentPath, "items", "items", "0"]
6183
+ }) || parseAnyDef();
6184
+ const values = parseDef(def.valueType._def, {
6185
+ ...refs,
6186
+ currentPath: [...refs.currentPath, "items", "items", "1"]
6187
+ }) || parseAnyDef();
6188
+ return {
6189
+ type: "array",
6190
+ maxItems: 125,
6191
+ items: {
6192
+ type: "array",
6193
+ items: [keys, values],
6194
+ minItems: 2,
6195
+ maxItems: 2
6196
+ }
6197
+ };
6198
+ }
6199
+ function parseNativeEnumDef(def) {
6200
+ const object2 = def.values;
6201
+ const actualKeys = Object.keys(def.values).filter((key) => {
6202
+ return typeof object2[object2[key]] !== "number";
6203
+ });
6204
+ const actualValues = actualKeys.map((key) => object2[key]);
6205
+ const parsedTypes = Array.from(
6206
+ new Set(actualValues.map((values) => typeof values))
6207
+ );
6208
+ return {
6209
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
6210
+ enum: actualValues
6211
+ };
6212
+ }
6213
+ function parseNeverDef() {
6214
+ return { not: parseAnyDef() };
6215
+ }
6216
+ function parseNullDef() {
6217
+ return {
6218
+ type: "null"
6219
+ };
6220
+ }
6221
+ var primitiveMappings = {
6222
+ ZodString: "string",
6223
+ ZodNumber: "number",
6224
+ ZodBigInt: "integer",
6225
+ ZodBoolean: "boolean",
6226
+ ZodNull: "null"
6227
+ };
6228
+ function parseUnionDef(def, refs) {
6229
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
6230
+ if (options.every(
6231
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
6232
+ )) {
6233
+ const types = options.reduce((types2, x) => {
6234
+ const type = primitiveMappings[x._def.typeName];
6235
+ return type && !types2.includes(type) ? [...types2, type] : types2;
6236
+ }, []);
6237
+ return {
6238
+ type: types.length > 1 ? types : types[0]
6239
+ };
6240
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
6241
+ const types = options.reduce(
6242
+ (acc, x) => {
6243
+ const type = typeof x._def.value;
6244
+ switch (type) {
6245
+ case "string":
6246
+ case "number":
6247
+ case "boolean":
6248
+ return [...acc, type];
6249
+ case "bigint":
6250
+ return [...acc, "integer"];
6251
+ case "object":
6252
+ if (x._def.value === null) return [...acc, "null"];
6253
+ case "symbol":
6254
+ case "undefined":
6255
+ case "function":
6256
+ default:
6257
+ return acc;
6258
+ }
6259
+ },
6260
+ []
6261
+ );
6262
+ if (types.length === options.length) {
6263
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
6264
+ return {
6265
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
6266
+ enum: options.reduce(
6267
+ (acc, x) => {
6268
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
6269
+ },
6270
+ []
6271
+ )
6272
+ };
6273
+ }
6274
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
6275
+ return {
6276
+ type: "string",
6277
+ enum: options.reduce(
6278
+ (acc, x) => [
6279
+ ...acc,
6280
+ ...x._def.values.filter((x2) => !acc.includes(x2))
6281
+ ],
6282
+ []
6283
+ )
6284
+ };
6285
+ }
6286
+ return asAnyOf(def, refs);
6287
+ }
6288
+ var asAnyOf = (def, refs) => {
6289
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
6290
+ (x, i) => parseDef(x._def, {
6291
+ ...refs,
6292
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
6293
+ })
6294
+ ).filter(
6295
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
6296
+ );
6297
+ return anyOf.length ? { anyOf } : void 0;
6298
+ };
6299
+ function parseNullableDef(def, refs) {
6300
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
6301
+ def.innerType._def.typeName
6302
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
6303
+ return {
6304
+ type: [
6305
+ primitiveMappings[def.innerType._def.typeName],
6306
+ "null"
6307
+ ]
6308
+ };
6309
+ }
6310
+ const base = parseDef(def.innerType._def, {
6311
+ ...refs,
6312
+ currentPath: [...refs.currentPath, "anyOf", "0"]
6313
+ });
6314
+ return base && { anyOf: [base, { type: "null" }] };
6315
+ }
6316
+ function parseNumberDef(def) {
6317
+ const res = {
6318
+ type: "number"
6319
+ };
6320
+ if (!def.checks) return res;
6321
+ for (const check of def.checks) {
6322
+ switch (check.kind) {
6323
+ case "int":
6324
+ res.type = "integer";
6325
+ break;
6326
+ case "min":
6327
+ if (check.inclusive) {
6328
+ res.minimum = check.value;
6329
+ } else {
6330
+ res.exclusiveMinimum = check.value;
6331
+ }
6332
+ break;
6333
+ case "max":
6334
+ if (check.inclusive) {
6335
+ res.maximum = check.value;
6336
+ } else {
6337
+ res.exclusiveMaximum = check.value;
6338
+ }
6339
+ break;
6340
+ case "multipleOf":
6341
+ res.multipleOf = check.value;
6342
+ break;
6343
+ }
6344
+ }
6345
+ return res;
6346
+ }
6347
+ function parseObjectDef(def, refs) {
6348
+ const result = {
6349
+ type: "object",
6350
+ properties: {}
6351
+ };
6352
+ const required = [];
6353
+ const shape = def.shape();
6354
+ for (const propName in shape) {
6355
+ let propDef = shape[propName];
6356
+ if (propDef === void 0 || propDef._def === void 0) {
6357
+ continue;
6358
+ }
6359
+ const propOptional = safeIsOptional(propDef);
6360
+ const parsedDef = parseDef(propDef._def, {
6361
+ ...refs,
6362
+ currentPath: [...refs.currentPath, "properties", propName],
6363
+ propertyPath: [...refs.currentPath, "properties", propName]
6364
+ });
6365
+ if (parsedDef === void 0) {
6366
+ continue;
6367
+ }
6368
+ result.properties[propName] = parsedDef;
6369
+ if (!propOptional) {
6370
+ required.push(propName);
6371
+ }
6372
+ }
6373
+ if (required.length) {
6374
+ result.required = required;
6375
+ }
6376
+ const additionalProperties = decideAdditionalProperties(def, refs);
6377
+ if (additionalProperties !== void 0) {
6378
+ result.additionalProperties = additionalProperties;
6379
+ }
6380
+ return result;
6381
+ }
6382
+ function decideAdditionalProperties(def, refs) {
6383
+ if (def.catchall._def.typeName !== "ZodNever") {
6384
+ return parseDef(def.catchall._def, {
6385
+ ...refs,
6386
+ currentPath: [...refs.currentPath, "additionalProperties"]
6387
+ });
6388
+ }
6389
+ switch (def.unknownKeys) {
6390
+ case "passthrough":
6391
+ return refs.allowedAdditionalProperties;
6392
+ case "strict":
6393
+ return refs.rejectedAdditionalProperties;
6394
+ case "strip":
6395
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
6396
+ }
6397
+ }
6398
+ function safeIsOptional(schema) {
6399
+ try {
6400
+ return schema.isOptional();
6401
+ } catch (e) {
6402
+ return true;
6403
+ }
6404
+ }
6405
+ var parseOptionalDef = (def, refs) => {
6406
+ var _a153;
6407
+ if (refs.currentPath.toString() === ((_a153 = refs.propertyPath) == null ? void 0 : _a153.toString())) {
6408
+ return parseDef(def.innerType._def, refs);
6409
+ }
6410
+ const innerSchema = parseDef(def.innerType._def, {
6411
+ ...refs,
6412
+ currentPath: [...refs.currentPath, "anyOf", "1"]
6413
+ });
6414
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
6415
+ };
6416
+ var parsePipelineDef = (def, refs) => {
6417
+ if (refs.pipeStrategy === "input") {
6418
+ return parseDef(def.in._def, refs);
6419
+ } else if (refs.pipeStrategy === "output") {
6420
+ return parseDef(def.out._def, refs);
6421
+ }
6422
+ const a = parseDef(def.in._def, {
6423
+ ...refs,
6424
+ currentPath: [...refs.currentPath, "allOf", "0"]
6425
+ });
6426
+ const b = parseDef(def.out._def, {
6427
+ ...refs,
6428
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
6429
+ });
6430
+ return {
6431
+ allOf: [a, b].filter((x) => x !== void 0)
6432
+ };
6433
+ };
6434
+ function parsePromiseDef(def, refs) {
6435
+ return parseDef(def.type._def, refs);
6436
+ }
6437
+ function parseSetDef(def, refs) {
6438
+ const items = parseDef(def.valueType._def, {
6439
+ ...refs,
6440
+ currentPath: [...refs.currentPath, "items"]
6441
+ });
6442
+ const schema = {
6443
+ type: "array",
6444
+ uniqueItems: true,
6445
+ items
6446
+ };
6447
+ if (def.minSize) {
6448
+ schema.minItems = def.minSize.value;
6449
+ }
6450
+ if (def.maxSize) {
6451
+ schema.maxItems = def.maxSize.value;
6452
+ }
6453
+ return schema;
6454
+ }
6455
+ function parseTupleDef(def, refs) {
6456
+ if (def.rest) {
6457
+ return {
6458
+ type: "array",
6459
+ minItems: def.items.length,
6460
+ items: def.items.map(
6461
+ (x, i) => parseDef(x._def, {
6462
+ ...refs,
6463
+ currentPath: [...refs.currentPath, "items", `${i}`]
6464
+ })
6465
+ ).reduce(
6466
+ (acc, x) => x === void 0 ? acc : [...acc, x],
6467
+ []
6468
+ ),
6469
+ additionalItems: parseDef(def.rest._def, {
6470
+ ...refs,
6471
+ currentPath: [...refs.currentPath, "additionalItems"]
6472
+ })
6473
+ };
6474
+ } else {
6475
+ return {
6476
+ type: "array",
6477
+ minItems: def.items.length,
6478
+ maxItems: def.items.length,
6479
+ items: def.items.map(
6480
+ (x, i) => parseDef(x._def, {
6481
+ ...refs,
6482
+ currentPath: [...refs.currentPath, "items", `${i}`]
6483
+ })
6484
+ ).reduce(
6485
+ (acc, x) => x === void 0 ? acc : [...acc, x],
6486
+ []
6487
+ )
6488
+ };
6489
+ }
6490
+ }
6491
+ function parseUndefinedDef() {
6492
+ return {
6493
+ not: parseAnyDef()
6494
+ };
6495
+ }
6496
+ function parseUnknownDef() {
6497
+ return parseAnyDef();
6498
+ }
6499
+ var parseReadonlyDef = (def, refs) => {
6500
+ return parseDef(def.innerType._def, refs);
6501
+ };
6502
+ var selectParser = (def, typeName, refs) => {
6503
+ switch (typeName) {
6504
+ case ZodFirstPartyTypeKind.ZodString:
6505
+ return parseStringDef(def, refs);
6506
+ case ZodFirstPartyTypeKind.ZodNumber:
6507
+ return parseNumberDef(def);
6508
+ case ZodFirstPartyTypeKind.ZodObject:
6509
+ return parseObjectDef(def, refs);
6510
+ case ZodFirstPartyTypeKind.ZodBigInt:
6511
+ return parseBigintDef(def);
6512
+ case ZodFirstPartyTypeKind.ZodBoolean:
6513
+ return parseBooleanDef();
6514
+ case ZodFirstPartyTypeKind.ZodDate:
6515
+ return parseDateDef(def, refs);
6516
+ case ZodFirstPartyTypeKind.ZodUndefined:
6517
+ return parseUndefinedDef();
6518
+ case ZodFirstPartyTypeKind.ZodNull:
6519
+ return parseNullDef();
6520
+ case ZodFirstPartyTypeKind.ZodArray:
6521
+ return parseArrayDef(def, refs);
6522
+ case ZodFirstPartyTypeKind.ZodUnion:
6523
+ case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
6524
+ return parseUnionDef(def, refs);
6525
+ case ZodFirstPartyTypeKind.ZodIntersection:
6526
+ return parseIntersectionDef(def, refs);
6527
+ case ZodFirstPartyTypeKind.ZodTuple:
6528
+ return parseTupleDef(def, refs);
6529
+ case ZodFirstPartyTypeKind.ZodRecord:
6530
+ return parseRecordDef(def, refs);
6531
+ case ZodFirstPartyTypeKind.ZodLiteral:
6532
+ return parseLiteralDef(def);
6533
+ case ZodFirstPartyTypeKind.ZodEnum:
6534
+ return parseEnumDef(def);
6535
+ case ZodFirstPartyTypeKind.ZodNativeEnum:
6536
+ return parseNativeEnumDef(def);
6537
+ case ZodFirstPartyTypeKind.ZodNullable:
6538
+ return parseNullableDef(def, refs);
6539
+ case ZodFirstPartyTypeKind.ZodOptional:
6540
+ return parseOptionalDef(def, refs);
6541
+ case ZodFirstPartyTypeKind.ZodMap:
6542
+ return parseMapDef(def, refs);
6543
+ case ZodFirstPartyTypeKind.ZodSet:
6544
+ return parseSetDef(def, refs);
6545
+ case ZodFirstPartyTypeKind.ZodLazy:
6546
+ return () => def.getter()._def;
6547
+ case ZodFirstPartyTypeKind.ZodPromise:
6548
+ return parsePromiseDef(def, refs);
6549
+ case ZodFirstPartyTypeKind.ZodNaN:
6550
+ case ZodFirstPartyTypeKind.ZodNever:
6551
+ return parseNeverDef();
6552
+ case ZodFirstPartyTypeKind.ZodEffects:
6553
+ return parseEffectsDef(def, refs);
6554
+ case ZodFirstPartyTypeKind.ZodAny:
6555
+ return parseAnyDef();
6556
+ case ZodFirstPartyTypeKind.ZodUnknown:
6557
+ return parseUnknownDef();
6558
+ case ZodFirstPartyTypeKind.ZodDefault:
6559
+ return parseDefaultDef(def, refs);
6560
+ case ZodFirstPartyTypeKind.ZodBranded:
6561
+ return parseBrandedDef(def, refs);
6562
+ case ZodFirstPartyTypeKind.ZodReadonly:
6563
+ return parseReadonlyDef(def, refs);
6564
+ case ZodFirstPartyTypeKind.ZodCatch:
6565
+ return parseCatchDef(def, refs);
6566
+ case ZodFirstPartyTypeKind.ZodPipeline:
6567
+ return parsePipelineDef(def, refs);
6568
+ case ZodFirstPartyTypeKind.ZodFunction:
6569
+ case ZodFirstPartyTypeKind.ZodVoid:
6570
+ case ZodFirstPartyTypeKind.ZodSymbol:
6571
+ return void 0;
6572
+ default:
6573
+ return /* @__PURE__ */ ((_) => void 0)();
6574
+ }
6575
+ };
6576
+ function parseDef(def, refs, forceResolution = false) {
6577
+ var _a153;
6578
+ const seenItem = refs.seen.get(def);
6579
+ if (refs.override) {
6580
+ const overrideResult = (_a153 = refs.override) == null ? void 0 : _a153.call(
6581
+ refs,
6582
+ def,
6583
+ refs,
6584
+ seenItem,
6585
+ forceResolution
6586
+ );
6587
+ if (overrideResult !== ignoreOverride) {
6588
+ return overrideResult;
6589
+ }
6590
+ }
6591
+ if (seenItem && !forceResolution) {
6592
+ const seenSchema = get$ref(seenItem, refs);
6593
+ if (seenSchema !== void 0) {
6594
+ return seenSchema;
6595
+ }
6596
+ }
6597
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
6598
+ refs.seen.set(def, newItem);
6599
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
6600
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
6601
+ if (jsonSchema2) {
6602
+ addMeta(def, refs, jsonSchema2);
6603
+ }
6604
+ if (refs.postProcess) {
6605
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
6606
+ newItem.jsonSchema = jsonSchema2;
6607
+ return postProcessResult;
6608
+ }
6609
+ newItem.jsonSchema = jsonSchema2;
6610
+ return jsonSchema2;
6611
+ }
6612
+ var get$ref = (item, refs) => {
6613
+ switch (refs.$refStrategy) {
6614
+ case "root":
6615
+ return { $ref: item.path.join("/") };
6616
+ case "relative":
6617
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
6618
+ case "none":
6619
+ case "seen": {
6620
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
6621
+ console.warn(
6622
+ `Recursive reference detected at ${refs.currentPath.join(
6623
+ "/"
6624
+ )}! Defaulting to any`
6625
+ );
6626
+ return parseAnyDef();
6627
+ }
6628
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
6629
+ }
6630
+ }
6631
+ };
6632
+ var addMeta = (def, refs, jsonSchema2) => {
6633
+ if (def.description) {
6634
+ jsonSchema2.description = def.description;
6635
+ }
6636
+ return jsonSchema2;
6637
+ };
6638
+ var getRefs = (options) => {
6639
+ const _options = getDefaultOptions(options);
6640
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
6641
+ return {
6642
+ ..._options,
6643
+ currentPath,
6644
+ propertyPath: void 0,
6645
+ seen: new Map(
6646
+ Object.entries(_options.definitions).map(([name143, def]) => [
6647
+ def._def,
6648
+ {
6649
+ def: def._def,
6650
+ path: [..._options.basePath, _options.definitionPath, name143],
6651
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
6652
+ jsonSchema: void 0
6653
+ }
6654
+ ])
6655
+ )
6656
+ };
6657
+ };
6658
+ var zodToJsonSchema = (schema, options) => {
6659
+ var _a153;
6660
+ const refs = getRefs(options);
6661
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
6662
+ (acc, [name223, schema2]) => {
6663
+ var _a223;
6664
+ return {
6665
+ ...acc,
6666
+ [name223]: (_a223 = parseDef(
6667
+ schema2._def,
6668
+ {
6669
+ ...refs,
6670
+ currentPath: [...refs.basePath, refs.definitionPath, name223]
6671
+ },
6672
+ true
6673
+ )) != null ? _a223 : parseAnyDef()
6674
+ };
6675
+ },
6676
+ {}
6677
+ ) : void 0;
6678
+ const name143 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
6679
+ const main = (_a153 = parseDef(
6680
+ schema._def,
6681
+ name143 === void 0 ? refs : {
6682
+ ...refs,
6683
+ currentPath: [...refs.basePath, refs.definitionPath, name143]
6684
+ },
6685
+ false
6686
+ )) != null ? _a153 : parseAnyDef();
6687
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
6688
+ if (title !== void 0) {
6689
+ main.title = title;
6690
+ }
6691
+ const combined = name143 === void 0 ? definitions ? {
6692
+ ...main,
6693
+ [refs.definitionPath]: definitions
6694
+ } : main : {
6695
+ $ref: [
6696
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
6697
+ refs.definitionPath,
6698
+ name143
6699
+ ].join("/"),
6700
+ [refs.definitionPath]: {
6701
+ ...definitions,
6702
+ [name143]: main
6703
+ }
6704
+ };
6705
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
6706
+ return combined;
6707
+ };
6708
+ var zod_to_json_schema_default = zodToJsonSchema;
6709
+ function zod3Schema(zodSchema2, options) {
6710
+ var _a153;
6711
+ const useReferences = (_a153 = void 0 ) != null ? _a153 : false;
6712
+ return jsonSchema(
6713
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
6714
+ () => zod_to_json_schema_default(zodSchema2, {
6715
+ $refStrategy: useReferences ? "root" : "none"
6716
+ }),
6717
+ {
6718
+ validate: async (value) => {
6719
+ const result = await zodSchema2.safeParseAsync(value);
6720
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
6721
+ }
6722
+ }
6723
+ );
6724
+ }
6725
+ function zod4Schema(zodSchema2, options) {
6726
+ var _a153;
6727
+ const useReferences = (_a153 = void 0 ) != null ? _a153 : false;
6728
+ return jsonSchema(
6729
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
6730
+ () => z4.toJSONSchema(zodSchema2, {
6731
+ target: "draft-7",
6732
+ io: "output",
6733
+ reused: useReferences ? "ref" : "inline"
6734
+ }),
6735
+ {
6736
+ validate: async (value) => {
6737
+ const result = await z4.safeParseAsync(zodSchema2, value);
6738
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
6739
+ }
6740
+ }
6741
+ );
6742
+ }
6743
+ function isZod4Schema(zodSchema2) {
6744
+ return "_zod" in zodSchema2;
6745
+ }
6746
+ function zodSchema(zodSchema2, options) {
6747
+ if (isZod4Schema(zodSchema2)) {
6748
+ return zod4Schema(zodSchema2);
6749
+ } else {
6750
+ return zod3Schema(zodSchema2);
6751
+ }
6752
+ }
6753
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
6754
+ function jsonSchema(jsonSchema2, {
6755
+ validate
6756
+ } = {}) {
6757
+ return {
6758
+ [schemaSymbol]: true,
6759
+ _type: void 0,
6760
+ // should never be used directly
6761
+ [validatorSymbol]: true,
6762
+ get jsonSchema() {
6763
+ if (typeof jsonSchema2 === "function") {
6764
+ jsonSchema2 = jsonSchema2();
6765
+ }
6766
+ return jsonSchema2;
6767
+ },
6768
+ validate
6769
+ };
6770
+ }
6771
+ function isSchema(value) {
6772
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
6773
+ }
6774
+ function asSchema(schema) {
6775
+ return schema == null ? jsonSchema({
6776
+ properties: {},
6777
+ additionalProperties: false
6778
+ }) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema);
6779
+ }
6780
+ function withoutTrailingSlash(url) {
6781
+ return url == null ? void 0 : url.replace(/\/$/, "");
6782
+ }
6783
+ var require_get_context = __commonJS({
6784
+ "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-context.js"(exports, module) {
6785
+ var __defProp2 = Object.defineProperty;
6786
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6787
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6788
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6789
+ var __export2 = (target, all) => {
6790
+ for (var name16 in all)
6791
+ __defProp2(target, name16, { get: all[name16], enumerable: true });
6792
+ };
6793
+ var __copyProps = (to, from, except, desc) => {
6794
+ if (from && typeof from === "object" || typeof from === "function") {
6795
+ for (let key of __getOwnPropNames(from))
6796
+ if (!__hasOwnProp.call(to, key) && key !== except)
6797
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
6798
+ }
6799
+ return to;
6800
+ };
6801
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
6802
+ var get_context_exports = {};
6803
+ __export2(get_context_exports, {
6804
+ SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
6805
+ getContext: () => getContext3
6806
+ });
6807
+ module.exports = __toCommonJS(get_context_exports);
6808
+ var SYMBOL_FOR_REQ_CONTEXT = Symbol.for("@vercel/request-context");
6809
+ function getContext3() {
6810
+ const fromSymbol = globalThis;
6811
+ return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
6812
+ }
6813
+ }
6814
+ });
6815
+ var require_get_vercel_oidc_token = __commonJS({
6816
+ "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports, module) {
6817
+ var __defProp2 = Object.defineProperty;
6818
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6819
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6820
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6821
+ var __export2 = (target, all) => {
6822
+ for (var name16 in all)
6823
+ __defProp2(target, name16, { get: all[name16], enumerable: true });
6824
+ };
6825
+ var __copyProps = (to, from, except, desc) => {
6826
+ if (from && typeof from === "object" || typeof from === "function") {
6827
+ for (let key of __getOwnPropNames(from))
6828
+ if (!__hasOwnProp.call(to, key) && key !== except)
6829
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
6830
+ }
6831
+ return to;
6832
+ };
6833
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
6834
+ var get_vercel_oidc_token_exports = {};
6835
+ __export2(get_vercel_oidc_token_exports, {
6836
+ getVercelOidcToken: () => getVercelOidcToken3,
6837
+ getVercelOidcTokenSync: () => getVercelOidcTokenSync2
6838
+ });
6839
+ module.exports = __toCommonJS(get_vercel_oidc_token_exports);
6840
+ var import_get_context = require_get_context();
6841
+ var import_token_error = require_token_error();
6842
+ async function getVercelOidcToken3() {
6843
+ let token = "";
6844
+ let err;
6845
+ try {
6846
+ token = getVercelOidcTokenSync2();
6847
+ } catch (error) {
6848
+ err = error;
6849
+ }
6850
+ try {
6851
+ const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
6852
+ await import('./token-util-NEHG7TUY-DJYRKLRD.js'),
6853
+ await import('./token-6GSAFR2W-KVDFAJ2M.js')
6854
+ ]);
6855
+ if (!token || isExpired(getTokenPayload(token))) {
6856
+ await refreshToken();
6857
+ token = getVercelOidcTokenSync2();
6858
+ }
6859
+ } catch (error) {
6860
+ if (err?.message && error instanceof Error) {
6861
+ error.message = `${err.message}
6862
+ ${error.message}`;
6863
+ }
6864
+ throw new import_token_error.VercelOidcTokenError(`Failed to refresh OIDC token`, error);
6865
+ }
6866
+ return token;
6867
+ }
6868
+ function getVercelOidcTokenSync2() {
6869
+ const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
6870
+ if (!token) {
6871
+ throw new Error(
6872
+ `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
6873
+ );
6874
+ }
6875
+ return token;
6876
+ }
6877
+ }
6878
+ });
6879
+ var require_dist = __commonJS({
6880
+ "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/index.js"(exports, module) {
6881
+ var __defProp2 = Object.defineProperty;
6882
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6883
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6884
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6885
+ var __export2 = (target, all) => {
6886
+ for (var name16 in all)
6887
+ __defProp2(target, name16, { get: all[name16], enumerable: true });
6888
+ };
6889
+ var __copyProps = (to, from, except, desc) => {
6890
+ if (from && typeof from === "object" || typeof from === "function") {
6891
+ for (let key of __getOwnPropNames(from))
6892
+ if (!__hasOwnProp.call(to, key) && key !== except)
6893
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
6894
+ }
6895
+ return to;
6896
+ };
6897
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
6898
+ var src_exports = {};
6899
+ __export2(src_exports, {
6900
+ getContext: () => import_get_context.getContext,
6901
+ getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
6902
+ getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
6903
+ });
6904
+ module.exports = __toCommonJS(src_exports);
6905
+ var import_get_vercel_oidc_token = require_get_vercel_oidc_token();
6906
+ var import_get_context = require_get_context();
6907
+ }
6908
+ });
6909
+ var import_oidc = __toESM(require_dist(), 1);
6910
+ var import_oidc2 = __toESM(require_dist(), 1);
6911
+ var marker15 = "vercel.ai.gateway.error";
6912
+ var symbol15 = Symbol.for(marker15);
6913
+ var _a15;
6914
+ var _b;
6915
+ var GatewayError = class _GatewayError extends (_b = Error, _a15 = symbol15, _b) {
6916
+ constructor({
6917
+ message,
6918
+ statusCode = 500,
6919
+ cause
6920
+ }) {
6921
+ super(message);
6922
+ this[_a15] = true;
6923
+ this.statusCode = statusCode;
6924
+ this.cause = cause;
6925
+ }
6926
+ /**
6927
+ * Checks if the given error is a Gateway Error.
6928
+ * @param {unknown} error - The error to check.
6929
+ * @returns {boolean} True if the error is a Gateway Error, false otherwise.
6930
+ */
6931
+ static isInstance(error) {
6932
+ return _GatewayError.hasMarker(error);
6933
+ }
6934
+ static hasMarker(error) {
6935
+ return typeof error === "object" && error !== null && symbol15 in error && error[symbol15] === true;
6936
+ }
6937
+ };
6938
+ var name14 = "GatewayAuthenticationError";
6939
+ var marker22 = `vercel.ai.gateway.error.${name14}`;
6940
+ var symbol22 = Symbol.for(marker22);
6941
+ var _a22;
6942
+ var _b2;
6943
+ var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a22 = symbol22, _b2) {
6944
+ constructor({
6945
+ message = "Authentication failed",
6946
+ statusCode = 401,
6947
+ cause
6948
+ } = {}) {
6949
+ super({ message, statusCode, cause });
6950
+ this[_a22] = true;
6951
+ this.name = name14;
6952
+ this.type = "authentication_error";
6953
+ }
6954
+ static isInstance(error) {
6955
+ return GatewayError.hasMarker(error) && symbol22 in error;
6956
+ }
6957
+ /**
6958
+ * Creates a contextual error message when authentication fails
6959
+ */
6960
+ static createContextualError({
6961
+ apiKeyProvided,
6962
+ oidcTokenProvided,
6963
+ message = "Authentication failed",
6964
+ statusCode = 401,
6965
+ cause
6966
+ }) {
6967
+ let contextualMessage;
6968
+ if (apiKeyProvided) {
6969
+ contextualMessage = `AI Gateway authentication failed: Invalid API key.
6970
+
6971
+ Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
6972
+
6973
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;
6974
+ } else if (oidcTokenProvided) {
6975
+ contextualMessage = `AI Gateway authentication failed: Invalid OIDC token.
6976
+
6977
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
6978
+
6979
+ Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`;
6980
+ } else {
6981
+ contextualMessage = `AI Gateway authentication failed: No authentication provided.
6982
+
6983
+ Option 1 - API key:
6984
+ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
6985
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
6986
+
6987
+ Option 2 - OIDC token:
6988
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;
6989
+ }
6990
+ return new _GatewayAuthenticationError({
6991
+ message: contextualMessage,
6992
+ statusCode,
6993
+ cause
6994
+ });
6995
+ }
6996
+ };
6997
+ var name22 = "GatewayInvalidRequestError";
6998
+ var marker32 = `vercel.ai.gateway.error.${name22}`;
6999
+ var symbol32 = Symbol.for(marker32);
7000
+ var _a32;
7001
+ var _b3;
7002
+ var GatewayInvalidRequestError = class extends (_b3 = GatewayError, _a32 = symbol32, _b3) {
7003
+ constructor({
7004
+ message = "Invalid request",
7005
+ statusCode = 400,
7006
+ cause
7007
+ } = {}) {
7008
+ super({ message, statusCode, cause });
7009
+ this[_a32] = true;
7010
+ this.name = name22;
7011
+ this.type = "invalid_request_error";
7012
+ }
7013
+ static isInstance(error) {
7014
+ return GatewayError.hasMarker(error) && symbol32 in error;
7015
+ }
7016
+ };
7017
+ var name32 = "GatewayRateLimitError";
7018
+ var marker42 = `vercel.ai.gateway.error.${name32}`;
7019
+ var symbol42 = Symbol.for(marker42);
7020
+ var _a42;
7021
+ var _b4;
7022
+ var GatewayRateLimitError = class extends (_b4 = GatewayError, _a42 = symbol42, _b4) {
7023
+ constructor({
7024
+ message = "Rate limit exceeded",
7025
+ statusCode = 429,
7026
+ cause
7027
+ } = {}) {
7028
+ super({ message, statusCode, cause });
7029
+ this[_a42] = true;
7030
+ this.name = name32;
7031
+ this.type = "rate_limit_exceeded";
7032
+ }
7033
+ static isInstance(error) {
7034
+ return GatewayError.hasMarker(error) && symbol42 in error;
7035
+ }
7036
+ };
7037
+ var name42 = "GatewayModelNotFoundError";
7038
+ var marker52 = `vercel.ai.gateway.error.${name42}`;
7039
+ var symbol52 = Symbol.for(marker52);
7040
+ var modelNotFoundParamSchema = lazyValidator(
7041
+ () => zodSchema(
7042
+ z$1.object({
7043
+ modelId: z$1.string()
7044
+ })
7045
+ )
7046
+ );
7047
+ var _a52;
7048
+ var _b5;
7049
+ var GatewayModelNotFoundError = class extends (_b5 = GatewayError, _a52 = symbol52, _b5) {
7050
+ constructor({
7051
+ message = "Model not found",
7052
+ statusCode = 404,
7053
+ modelId,
7054
+ cause
7055
+ } = {}) {
7056
+ super({ message, statusCode, cause });
7057
+ this[_a52] = true;
7058
+ this.name = name42;
7059
+ this.type = "model_not_found";
7060
+ this.modelId = modelId;
7061
+ }
7062
+ static isInstance(error) {
7063
+ return GatewayError.hasMarker(error) && symbol52 in error;
7064
+ }
7065
+ };
7066
+ var name52 = "GatewayInternalServerError";
7067
+ var marker62 = `vercel.ai.gateway.error.${name52}`;
7068
+ var symbol62 = Symbol.for(marker62);
7069
+ var _a62;
7070
+ var _b6;
7071
+ var GatewayInternalServerError = class extends (_b6 = GatewayError, _a62 = symbol62, _b6) {
7072
+ constructor({
7073
+ message = "Internal server error",
7074
+ statusCode = 500,
7075
+ cause
7076
+ } = {}) {
7077
+ super({ message, statusCode, cause });
7078
+ this[_a62] = true;
7079
+ this.name = name52;
7080
+ this.type = "internal_server_error";
7081
+ }
7082
+ static isInstance(error) {
7083
+ return GatewayError.hasMarker(error) && symbol62 in error;
7084
+ }
7085
+ };
7086
+ var name62 = "GatewayResponseError";
7087
+ var marker72 = `vercel.ai.gateway.error.${name62}`;
7088
+ var symbol72 = Symbol.for(marker72);
7089
+ var _a72;
7090
+ var _b7;
7091
+ var GatewayResponseError = class extends (_b7 = GatewayError, _a72 = symbol72, _b7) {
7092
+ constructor({
7093
+ message = "Invalid response from Gateway",
7094
+ statusCode = 502,
7095
+ response,
7096
+ validationError,
7097
+ cause
7098
+ } = {}) {
7099
+ super({ message, statusCode, cause });
7100
+ this[_a72] = true;
7101
+ this.name = name62;
7102
+ this.type = "response_error";
7103
+ this.response = response;
7104
+ this.validationError = validationError;
7105
+ }
7106
+ static isInstance(error) {
7107
+ return GatewayError.hasMarker(error) && symbol72 in error;
7108
+ }
7109
+ };
7110
+ async function createGatewayErrorFromResponse({
7111
+ response,
7112
+ statusCode,
7113
+ defaultMessage = "Gateway request failed",
7114
+ cause,
7115
+ authMethod
7116
+ }) {
7117
+ const parseResult = await safeValidateTypes({
7118
+ value: response,
7119
+ schema: gatewayErrorResponseSchema
7120
+ });
7121
+ if (!parseResult.success) {
7122
+ return new GatewayResponseError({
7123
+ message: `Invalid error response format: ${defaultMessage}`,
7124
+ statusCode,
7125
+ response,
7126
+ validationError: parseResult.error,
7127
+ cause
7128
+ });
7129
+ }
7130
+ const validatedResponse = parseResult.value;
7131
+ const errorType = validatedResponse.error.type;
7132
+ const message = validatedResponse.error.message;
7133
+ switch (errorType) {
7134
+ case "authentication_error":
7135
+ return GatewayAuthenticationError.createContextualError({
7136
+ apiKeyProvided: authMethod === "api-key",
7137
+ oidcTokenProvided: authMethod === "oidc",
7138
+ statusCode,
7139
+ cause
7140
+ });
7141
+ case "invalid_request_error":
7142
+ return new GatewayInvalidRequestError({ message, statusCode, cause });
7143
+ case "rate_limit_exceeded":
7144
+ return new GatewayRateLimitError({ message, statusCode, cause });
7145
+ case "model_not_found": {
7146
+ const modelResult = await safeValidateTypes({
7147
+ value: validatedResponse.error.param,
7148
+ schema: modelNotFoundParamSchema
7149
+ });
7150
+ return new GatewayModelNotFoundError({
7151
+ message,
7152
+ statusCode,
7153
+ modelId: modelResult.success ? modelResult.value.modelId : void 0,
7154
+ cause
7155
+ });
7156
+ }
7157
+ case "internal_server_error":
7158
+ return new GatewayInternalServerError({ message, statusCode, cause });
7159
+ default:
7160
+ return new GatewayInternalServerError({ message, statusCode, cause });
7161
+ }
7162
+ }
7163
+ var gatewayErrorResponseSchema = lazyValidator(
7164
+ () => zodSchema(
7165
+ z$1.object({
7166
+ error: z$1.object({
7167
+ message: z$1.string(),
7168
+ type: z$1.string().nullish(),
7169
+ param: z$1.unknown().nullish(),
7170
+ code: z$1.union([z$1.string(), z$1.number()]).nullish()
7171
+ })
7172
+ })
7173
+ )
7174
+ );
7175
+ function asGatewayError(error, authMethod) {
7176
+ var _a83;
7177
+ if (GatewayError.isInstance(error)) {
7178
+ return error;
7179
+ }
7180
+ if (APICallError.isInstance(error)) {
7181
+ return createGatewayErrorFromResponse({
7182
+ response: extractApiCallResponse(error),
7183
+ statusCode: (_a83 = error.statusCode) != null ? _a83 : 500,
7184
+ defaultMessage: "Gateway request failed",
7185
+ cause: error,
7186
+ authMethod
7187
+ });
7188
+ }
7189
+ return createGatewayErrorFromResponse({
7190
+ response: {},
7191
+ statusCode: 500,
7192
+ defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
7193
+ cause: error,
7194
+ authMethod
7195
+ });
7196
+ }
7197
+ function extractApiCallResponse(error) {
7198
+ if (error.data !== void 0) {
7199
+ return error.data;
7200
+ }
7201
+ if (error.responseBody != null) {
7202
+ try {
7203
+ return JSON.parse(error.responseBody);
7204
+ } catch (e) {
7205
+ return error.responseBody;
7206
+ }
7207
+ }
7208
+ return {};
7209
+ }
7210
+ var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
7211
+ async function parseAuthMethod(headers) {
7212
+ const result = await safeValidateTypes({
7213
+ value: headers[GATEWAY_AUTH_METHOD_HEADER],
7214
+ schema: gatewayAuthMethodSchema
7215
+ });
7216
+ return result.success ? result.value : void 0;
7217
+ }
7218
+ var gatewayAuthMethodSchema = lazyValidator(
7219
+ () => zodSchema(z$1.union([z$1.literal("api-key"), z$1.literal("oidc")]))
7220
+ );
7221
+ var GatewayFetchMetadata = class {
7222
+ constructor(config) {
7223
+ this.config = config;
7224
+ }
7225
+ async getAvailableModels() {
7226
+ try {
7227
+ const { value } = await getFromApi({
7228
+ url: `${this.config.baseURL}/config`,
7229
+ headers: await resolve4(this.config.headers()),
7230
+ successfulResponseHandler: createJsonResponseHandler(
7231
+ gatewayAvailableModelsResponseSchema
7232
+ ),
7233
+ failedResponseHandler: createJsonErrorResponseHandler({
7234
+ errorSchema: z$1.any(),
7235
+ errorToMessage: (data) => data
7236
+ }),
7237
+ fetch: this.config.fetch
7238
+ });
7239
+ return value;
7240
+ } catch (error) {
7241
+ throw await asGatewayError(error);
7242
+ }
7243
+ }
7244
+ async getCredits() {
7245
+ try {
7246
+ const baseUrl = new URL(this.config.baseURL);
7247
+ const { value } = await getFromApi({
7248
+ url: `${baseUrl.origin}/v1/credits`,
7249
+ headers: await resolve4(this.config.headers()),
7250
+ successfulResponseHandler: createJsonResponseHandler(
7251
+ gatewayCreditsResponseSchema
7252
+ ),
7253
+ failedResponseHandler: createJsonErrorResponseHandler({
7254
+ errorSchema: z$1.any(),
7255
+ errorToMessage: (data) => data
7256
+ }),
7257
+ fetch: this.config.fetch
7258
+ });
7259
+ return value;
7260
+ } catch (error) {
7261
+ throw await asGatewayError(error);
7262
+ }
7263
+ }
7264
+ };
7265
+ var gatewayAvailableModelsResponseSchema = lazyValidator(
7266
+ () => zodSchema(
7267
+ z$1.object({
7268
+ models: z$1.array(
7269
+ z$1.object({
7270
+ id: z$1.string(),
7271
+ name: z$1.string(),
7272
+ description: z$1.string().nullish(),
7273
+ pricing: z$1.object({
7274
+ input: z$1.string(),
7275
+ output: z$1.string(),
7276
+ input_cache_read: z$1.string().nullish(),
7277
+ input_cache_write: z$1.string().nullish()
7278
+ }).transform(
7279
+ ({ input, output, input_cache_read, input_cache_write }) => ({
7280
+ input,
7281
+ output,
7282
+ ...input_cache_read ? { cachedInputTokens: input_cache_read } : {},
7283
+ ...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}
7284
+ })
7285
+ ).nullish(),
7286
+ specification: z$1.object({
7287
+ specificationVersion: z$1.literal("v2"),
7288
+ provider: z$1.string(),
7289
+ modelId: z$1.string()
7290
+ }),
7291
+ modelType: z$1.enum(["language", "embedding", "image"]).nullish()
7292
+ })
7293
+ )
7294
+ })
7295
+ )
7296
+ );
7297
+ var gatewayCreditsResponseSchema = lazyValidator(
7298
+ () => zodSchema(
7299
+ z$1.object({
7300
+ balance: z$1.string(),
7301
+ total_used: z$1.string()
7302
+ }).transform(({ balance, total_used }) => ({
7303
+ balance,
7304
+ totalUsed: total_used
7305
+ }))
7306
+ )
7307
+ );
7308
+ var GatewayLanguageModel = class {
7309
+ constructor(modelId, config) {
7310
+ this.modelId = modelId;
7311
+ this.config = config;
7312
+ this.specificationVersion = "v2";
7313
+ this.supportedUrls = { "*/*": [/.*/] };
7314
+ }
7315
+ get provider() {
7316
+ return this.config.provider;
7317
+ }
7318
+ async getArgs(options) {
7319
+ const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;
7320
+ return {
7321
+ args: this.maybeEncodeFileParts(optionsWithoutSignal),
7322
+ warnings: []
7323
+ };
7324
+ }
7325
+ async doGenerate(options) {
7326
+ const { args, warnings } = await this.getArgs(options);
7327
+ const { abortSignal } = options;
7328
+ const resolvedHeaders = await resolve4(this.config.headers());
7329
+ try {
7330
+ const {
7331
+ responseHeaders,
7332
+ value: responseBody,
7333
+ rawValue: rawResponse
7334
+ } = await postJsonToApi({
7335
+ url: this.getUrl(),
7336
+ headers: combineHeaders(
7337
+ resolvedHeaders,
7338
+ options.headers,
7339
+ this.getModelConfigHeaders(this.modelId, false),
7340
+ await resolve4(this.config.o11yHeaders)
7341
+ ),
7342
+ body: args,
7343
+ successfulResponseHandler: createJsonResponseHandler(z$1.any()),
7344
+ failedResponseHandler: createJsonErrorResponseHandler({
7345
+ errorSchema: z$1.any(),
7346
+ errorToMessage: (data) => data
7347
+ }),
7348
+ ...abortSignal && { abortSignal },
7349
+ fetch: this.config.fetch
7350
+ });
7351
+ return {
7352
+ ...responseBody,
7353
+ request: { body: args },
7354
+ response: { headers: responseHeaders, body: rawResponse },
7355
+ warnings
7356
+ };
7357
+ } catch (error) {
7358
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7359
+ }
7360
+ }
7361
+ async doStream(options) {
7362
+ const { args, warnings } = await this.getArgs(options);
7363
+ const { abortSignal } = options;
7364
+ const resolvedHeaders = await resolve4(this.config.headers());
7365
+ try {
7366
+ const { value: response, responseHeaders } = await postJsonToApi({
7367
+ url: this.getUrl(),
7368
+ headers: combineHeaders(
7369
+ resolvedHeaders,
7370
+ options.headers,
7371
+ this.getModelConfigHeaders(this.modelId, true),
7372
+ await resolve4(this.config.o11yHeaders)
7373
+ ),
7374
+ body: args,
7375
+ successfulResponseHandler: createEventSourceResponseHandler(z$1.any()),
7376
+ failedResponseHandler: createJsonErrorResponseHandler({
7377
+ errorSchema: z$1.any(),
7378
+ errorToMessage: (data) => data
7379
+ }),
7380
+ ...abortSignal && { abortSignal },
7381
+ fetch: this.config.fetch
7382
+ });
7383
+ return {
7384
+ stream: response.pipeThrough(
7385
+ new TransformStream({
7386
+ start(controller) {
7387
+ if (warnings.length > 0) {
7388
+ controller.enqueue({ type: "stream-start", warnings });
7389
+ }
7390
+ },
7391
+ transform(chunk, controller) {
7392
+ if (chunk.success) {
7393
+ const streamPart = chunk.value;
7394
+ if (streamPart.type === "raw" && !options.includeRawChunks) {
7395
+ return;
7396
+ }
7397
+ if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string") {
7398
+ streamPart.timestamp = new Date(streamPart.timestamp);
7399
+ }
7400
+ controller.enqueue(streamPart);
7401
+ } else {
7402
+ controller.error(
7403
+ chunk.error
7404
+ );
7405
+ }
7406
+ }
7407
+ })
7408
+ ),
7409
+ request: { body: args },
7410
+ response: { headers: responseHeaders }
7411
+ };
7412
+ } catch (error) {
7413
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7414
+ }
7415
+ }
7416
+ isFilePart(part) {
7417
+ return part && typeof part === "object" && "type" in part && part.type === "file";
7418
+ }
7419
+ /**
7420
+ * Encodes file parts in the prompt to base64. Mutates the passed options
7421
+ * instance directly to avoid copying the file data.
7422
+ * @param options - The options to encode.
7423
+ * @returns The options with the file parts encoded.
7424
+ */
7425
+ maybeEncodeFileParts(options) {
7426
+ for (const message of options.prompt) {
7427
+ for (const part of message.content) {
7428
+ if (this.isFilePart(part)) {
7429
+ const filePart = part;
7430
+ if (filePart.data instanceof Uint8Array) {
7431
+ const buffer = Uint8Array.from(filePart.data);
7432
+ const base64Data = Buffer.from(buffer).toString("base64");
7433
+ filePart.data = new URL(
7434
+ `data:${filePart.mediaType || "application/octet-stream"};base64,${base64Data}`
7435
+ );
7436
+ }
7437
+ }
7438
+ }
7439
+ }
7440
+ return options;
7441
+ }
7442
+ getUrl() {
7443
+ return `${this.config.baseURL}/language-model`;
7444
+ }
7445
+ getModelConfigHeaders(modelId, streaming) {
7446
+ return {
7447
+ "ai-language-model-specification-version": "2",
7448
+ "ai-language-model-id": modelId,
7449
+ "ai-language-model-streaming": String(streaming)
7450
+ };
7451
+ }
7452
+ };
7453
+ var GatewayEmbeddingModel = class {
7454
+ constructor(modelId, config) {
7455
+ this.modelId = modelId;
7456
+ this.config = config;
7457
+ this.specificationVersion = "v2";
7458
+ this.maxEmbeddingsPerCall = 2048;
7459
+ this.supportsParallelCalls = true;
7460
+ }
7461
+ get provider() {
7462
+ return this.config.provider;
7463
+ }
7464
+ async doEmbed({
7465
+ values,
7466
+ headers,
7467
+ abortSignal,
7468
+ providerOptions
7469
+ }) {
7470
+ var _a83;
7471
+ const resolvedHeaders = await resolve4(this.config.headers());
7472
+ try {
7473
+ const {
7474
+ responseHeaders,
7475
+ value: responseBody,
7476
+ rawValue
7477
+ } = await postJsonToApi({
7478
+ url: this.getUrl(),
7479
+ headers: combineHeaders(
7480
+ resolvedHeaders,
7481
+ headers != null ? headers : {},
7482
+ this.getModelConfigHeaders(),
7483
+ await resolve4(this.config.o11yHeaders)
7484
+ ),
7485
+ body: {
7486
+ input: values.length === 1 ? values[0] : values,
7487
+ ...providerOptions ? { providerOptions } : {}
7488
+ },
7489
+ successfulResponseHandler: createJsonResponseHandler(
7490
+ gatewayEmbeddingResponseSchema
7491
+ ),
7492
+ failedResponseHandler: createJsonErrorResponseHandler({
7493
+ errorSchema: z$1.any(),
7494
+ errorToMessage: (data) => data
7495
+ }),
7496
+ ...abortSignal && { abortSignal },
7497
+ fetch: this.config.fetch
7498
+ });
7499
+ return {
7500
+ embeddings: responseBody.embeddings,
7501
+ usage: (_a83 = responseBody.usage) != null ? _a83 : void 0,
7502
+ providerMetadata: responseBody.providerMetadata,
7503
+ response: { headers: responseHeaders, body: rawValue }
7504
+ };
7505
+ } catch (error) {
7506
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7507
+ }
7508
+ }
7509
+ getUrl() {
7510
+ return `${this.config.baseURL}/embedding-model`;
7511
+ }
7512
+ getModelConfigHeaders() {
7513
+ return {
7514
+ "ai-embedding-model-specification-version": "2",
7515
+ "ai-model-id": this.modelId
7516
+ };
7517
+ }
7518
+ };
7519
+ var gatewayEmbeddingResponseSchema = lazyValidator(
7520
+ () => zodSchema(
7521
+ z$1.object({
7522
+ embeddings: z$1.array(z$1.array(z$1.number())),
7523
+ usage: z$1.object({ tokens: z$1.number() }).nullish(),
7524
+ providerMetadata: z$1.record(z$1.string(), z$1.record(z$1.string(), z$1.unknown())).optional()
7525
+ })
7526
+ )
7527
+ );
7528
+ var GatewayImageModel = class {
7529
+ constructor(modelId, config) {
7530
+ this.modelId = modelId;
7531
+ this.config = config;
7532
+ this.specificationVersion = "v2";
7533
+ this.maxImagesPerCall = Number.MAX_SAFE_INTEGER;
7534
+ }
7535
+ get provider() {
7536
+ return this.config.provider;
7537
+ }
7538
+ async doGenerate({
7539
+ prompt,
7540
+ n,
7541
+ size,
7542
+ aspectRatio,
7543
+ seed,
7544
+ providerOptions,
7545
+ headers,
7546
+ abortSignal
7547
+ }) {
7548
+ var _a83;
7549
+ const resolvedHeaders = await resolve4(this.config.headers());
7550
+ try {
7551
+ const {
7552
+ responseHeaders,
7553
+ value: responseBody
7554
+ } = await postJsonToApi({
7555
+ url: this.getUrl(),
7556
+ headers: combineHeaders(
7557
+ resolvedHeaders,
7558
+ headers != null ? headers : {},
7559
+ this.getModelConfigHeaders(),
7560
+ await resolve4(this.config.o11yHeaders)
7561
+ ),
7562
+ body: {
7563
+ prompt,
7564
+ n,
7565
+ ...size && { size },
7566
+ ...aspectRatio && { aspectRatio },
7567
+ ...seed && { seed },
7568
+ ...providerOptions && { providerOptions }
7569
+ },
7570
+ successfulResponseHandler: createJsonResponseHandler(
7571
+ gatewayImageResponseSchema
7572
+ ),
7573
+ failedResponseHandler: createJsonErrorResponseHandler({
7574
+ errorSchema: z$1.any(),
7575
+ errorToMessage: (data) => data
7576
+ }),
7577
+ ...abortSignal && { abortSignal },
7578
+ fetch: this.config.fetch
7579
+ });
7580
+ return {
7581
+ images: responseBody.images,
7582
+ // Always base64 strings from server
7583
+ warnings: (_a83 = responseBody.warnings) != null ? _a83 : [],
7584
+ providerMetadata: responseBody.providerMetadata,
7585
+ response: {
7586
+ timestamp: /* @__PURE__ */ new Date(),
7587
+ modelId: this.modelId,
7588
+ headers: responseHeaders
7589
+ }
7590
+ };
7591
+ } catch (error) {
7592
+ throw asGatewayError(error, await parseAuthMethod(resolvedHeaders));
7593
+ }
7594
+ }
7595
+ getUrl() {
7596
+ return `${this.config.baseURL}/image-model`;
7597
+ }
7598
+ getModelConfigHeaders() {
7599
+ return {
7600
+ "ai-image-model-specification-version": "2",
7601
+ "ai-model-id": this.modelId
7602
+ };
7603
+ }
7604
+ };
7605
+ var providerMetadataEntrySchema = z$1.object({
7606
+ images: z$1.array(z$1.unknown()).optional()
7607
+ }).catchall(z$1.unknown());
7608
+ var gatewayImageResponseSchema = z$1.object({
7609
+ images: z$1.array(z$1.string()),
7610
+ // Always base64 strings over the wire
7611
+ warnings: z$1.array(
7612
+ z$1.object({
7613
+ type: z$1.literal("other"),
7614
+ message: z$1.string()
7615
+ })
7616
+ ).optional(),
7617
+ providerMetadata: z$1.record(z$1.string(), providerMetadataEntrySchema).optional()
7618
+ });
7619
+ async function getVercelRequestId() {
7620
+ var _a83;
7621
+ return (_a83 = (0, import_oidc.getContext)().headers) == null ? void 0 : _a83["x-vercel-id"];
7622
+ }
7623
+ var VERSION2 = "2.0.15";
7624
+ var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
7625
+ function createGatewayProvider(options = {}) {
7626
+ var _a83, _b8;
7627
+ let pendingMetadata = null;
7628
+ let metadataCache = null;
7629
+ const cacheRefreshMillis = (_a83 = options.metadataCacheRefreshMillis) != null ? _a83 : 1e3 * 60 * 5;
7630
+ let lastFetchTime = 0;
7631
+ const baseURL = (_b8 = withoutTrailingSlash(options.baseURL)) != null ? _b8 : "https://ai-gateway.vercel.sh/v1/ai";
7632
+ const getHeaders = async () => {
7633
+ const auth = await getGatewayAuthToken(options);
7634
+ if (auth) {
7635
+ return withUserAgentSuffix(
7636
+ {
7637
+ Authorization: `Bearer ${auth.token}`,
7638
+ "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION,
7639
+ [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,
7640
+ ...options.headers
7641
+ },
7642
+ `ai-sdk/gateway/${VERSION2}`
7643
+ );
7644
+ }
7645
+ throw GatewayAuthenticationError.createContextualError({
7646
+ apiKeyProvided: false,
7647
+ oidcTokenProvided: false,
7648
+ statusCode: 401
7649
+ });
7650
+ };
7651
+ const createO11yHeaders = () => {
7652
+ const deploymentId = loadOptionalSetting({
7653
+ settingValue: void 0,
7654
+ environmentVariableName: "VERCEL_DEPLOYMENT_ID"
7655
+ });
7656
+ const environment = loadOptionalSetting({
7657
+ settingValue: void 0,
7658
+ environmentVariableName: "VERCEL_ENV"
7659
+ });
7660
+ const region = loadOptionalSetting({
7661
+ settingValue: void 0,
7662
+ environmentVariableName: "VERCEL_REGION"
7663
+ });
7664
+ return async () => {
7665
+ const requestId = await getVercelRequestId();
7666
+ return {
7667
+ ...deploymentId && { "ai-o11y-deployment-id": deploymentId },
7668
+ ...environment && { "ai-o11y-environment": environment },
7669
+ ...region && { "ai-o11y-region": region },
7670
+ ...requestId && { "ai-o11y-request-id": requestId }
7671
+ };
7672
+ };
7673
+ };
7674
+ const createLanguageModel = (modelId) => {
7675
+ return new GatewayLanguageModel(modelId, {
7676
+ provider: "gateway",
7677
+ baseURL,
7678
+ headers: getHeaders,
7679
+ fetch: options.fetch,
7680
+ o11yHeaders: createO11yHeaders()
7681
+ });
7682
+ };
7683
+ const getAvailableModels = async () => {
7684
+ var _a922, _b9, _c;
7685
+ const now2 = (_c = (_b9 = (_a922 = options._internal) == null ? void 0 : _a922.currentDate) == null ? void 0 : _b9.call(_a922).getTime()) != null ? _c : Date.now();
7686
+ if (!pendingMetadata || now2 - lastFetchTime > cacheRefreshMillis) {
7687
+ lastFetchTime = now2;
7688
+ pendingMetadata = new GatewayFetchMetadata({
7689
+ baseURL,
7690
+ headers: getHeaders,
7691
+ fetch: options.fetch
7692
+ }).getAvailableModels().then((metadata) => {
7693
+ metadataCache = metadata;
7694
+ return metadata;
7695
+ }).catch(async (error) => {
7696
+ throw await asGatewayError(
7697
+ error,
7698
+ await parseAuthMethod(await getHeaders())
7699
+ );
7700
+ });
7701
+ }
7702
+ return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;
7703
+ };
7704
+ const getCredits = async () => {
7705
+ return new GatewayFetchMetadata({
7706
+ baseURL,
7707
+ headers: getHeaders,
7708
+ fetch: options.fetch
7709
+ }).getCredits().catch(async (error) => {
7710
+ throw await asGatewayError(
7711
+ error,
7712
+ await parseAuthMethod(await getHeaders())
7713
+ );
7714
+ });
7715
+ };
7716
+ const provider = function(modelId) {
7717
+ if (new.target) {
7718
+ throw new Error(
7719
+ "The Gateway Provider model function cannot be called with the new keyword."
7720
+ );
7721
+ }
7722
+ return createLanguageModel(modelId);
7723
+ };
7724
+ provider.getAvailableModels = getAvailableModels;
7725
+ provider.getCredits = getCredits;
7726
+ provider.imageModel = (modelId) => {
7727
+ return new GatewayImageModel(modelId, {
7728
+ provider: "gateway",
7729
+ baseURL,
7730
+ headers: getHeaders,
7731
+ fetch: options.fetch,
7732
+ o11yHeaders: createO11yHeaders()
7733
+ });
7734
+ };
7735
+ provider.languageModel = createLanguageModel;
7736
+ provider.textEmbeddingModel = (modelId) => {
7737
+ return new GatewayEmbeddingModel(modelId, {
7738
+ provider: "gateway",
7739
+ baseURL,
7740
+ headers: getHeaders,
7741
+ fetch: options.fetch,
7742
+ o11yHeaders: createO11yHeaders()
7743
+ });
7744
+ };
7745
+ return provider;
7746
+ }
7747
+ createGatewayProvider();
7748
+ async function getGatewayAuthToken(options) {
7749
+ const apiKey = loadOptionalSetting({
7750
+ settingValue: options.apiKey,
7751
+ environmentVariableName: "AI_GATEWAY_API_KEY"
7752
+ });
7753
+ if (apiKey) {
7754
+ return {
7755
+ token: apiKey,
7756
+ authMethod: "api-key"
7757
+ };
7758
+ }
7759
+ try {
7760
+ const oidcToken = await (0, import_oidc2.getVercelOidcToken)();
7761
+ return {
7762
+ token: oidcToken,
7763
+ authMethod: "oidc"
7764
+ };
7765
+ } catch (e) {
7766
+ return null;
7767
+ }
7768
+ }
7769
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
7770
+ var VERSION22 = "1.9.0";
7771
+ var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
7772
+ function _makeCompatibilityCheck(ownVersion) {
7773
+ var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
7774
+ var rejectedVersions = /* @__PURE__ */ new Set();
7775
+ var myVersionMatch = ownVersion.match(re);
7776
+ if (!myVersionMatch) {
7777
+ return function() {
7778
+ return false;
7779
+ };
7780
+ }
7781
+ var ownVersionParsed = {
7782
+ major: +myVersionMatch[1],
7783
+ minor: +myVersionMatch[2],
7784
+ patch: +myVersionMatch[3],
7785
+ prerelease: myVersionMatch[4]
7786
+ };
7787
+ if (ownVersionParsed.prerelease != null) {
7788
+ return function isExactmatch(globalVersion) {
7789
+ return globalVersion === ownVersion;
7790
+ };
7791
+ }
7792
+ function _reject(v) {
7793
+ rejectedVersions.add(v);
7794
+ return false;
7795
+ }
7796
+ function _accept(v) {
7797
+ acceptedVersions.add(v);
7798
+ return true;
7799
+ }
7800
+ return function isCompatible2(globalVersion) {
7801
+ if (acceptedVersions.has(globalVersion)) {
7802
+ return true;
7803
+ }
7804
+ if (rejectedVersions.has(globalVersion)) {
7805
+ return false;
7806
+ }
7807
+ var globalVersionMatch = globalVersion.match(re);
7808
+ if (!globalVersionMatch) {
7809
+ return _reject(globalVersion);
7810
+ }
7811
+ var globalVersionParsed = {
7812
+ major: +globalVersionMatch[1],
7813
+ minor: +globalVersionMatch[2],
7814
+ patch: +globalVersionMatch[3],
7815
+ prerelease: globalVersionMatch[4]
7816
+ };
7817
+ if (globalVersionParsed.prerelease != null) {
7818
+ return _reject(globalVersion);
7819
+ }
7820
+ if (ownVersionParsed.major !== globalVersionParsed.major) {
7821
+ return _reject(globalVersion);
7822
+ }
7823
+ if (ownVersionParsed.major === 0) {
7824
+ if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
7825
+ return _accept(globalVersion);
7826
+ }
7827
+ return _reject(globalVersion);
7828
+ }
7829
+ if (ownVersionParsed.minor <= globalVersionParsed.minor) {
7830
+ return _accept(globalVersion);
7831
+ }
7832
+ return _reject(globalVersion);
7833
+ };
7834
+ }
7835
+ var isCompatible = _makeCompatibilityCheck(VERSION22);
7836
+ var major = VERSION22.split(".")[0];
7837
+ var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
7838
+ var _global = _globalThis;
7839
+ function registerGlobal(type, instance, diag, allowOverride) {
7840
+ var _a16;
7841
+ if (allowOverride === void 0) {
7842
+ allowOverride = false;
7843
+ }
7844
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a16 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a16 !== void 0 ? _a16 : {
7845
+ version: VERSION22
7846
+ };
7847
+ if (!allowOverride && api[type]) {
7848
+ var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
7849
+ diag.error(err.stack || err.message);
7850
+ return false;
7851
+ }
7852
+ if (api.version !== VERSION22) {
7853
+ var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION22);
7854
+ diag.error(err.stack || err.message);
7855
+ return false;
7856
+ }
7857
+ api[type] = instance;
7858
+ diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION22 + ".");
7859
+ return true;
7860
+ }
7861
+ function getGlobal(type) {
7862
+ var _a16, _b8;
7863
+ var globalVersion = (_a16 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a16 === void 0 ? void 0 : _a16.version;
7864
+ if (!globalVersion || !isCompatible(globalVersion)) {
7865
+ return;
7866
+ }
7867
+ return (_b8 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b8 === void 0 ? void 0 : _b8[type];
7868
+ }
7869
+ function unregisterGlobal(type, diag) {
7870
+ diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION22 + ".");
7871
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
7872
+ if (api) {
7873
+ delete api[type];
7874
+ }
7875
+ }
7876
+ var __read = function(o, n) {
7877
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
7878
+ if (!m) return o;
7879
+ var i = m.call(o), r, ar = [], e;
7880
+ try {
7881
+ while (!(r = i.next()).done) ar.push(r.value);
7882
+ } catch (error) {
7883
+ e = { error };
7884
+ } finally {
7885
+ try {
7886
+ if (r && !r.done && (m = i["return"])) m.call(i);
7887
+ } finally {
7888
+ if (e) throw e.error;
7889
+ }
7890
+ }
7891
+ return ar;
7892
+ };
7893
+ var __spreadArray = function(to, from, pack) {
7894
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
7895
+ if (ar || !(i in from)) {
7896
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
7897
+ ar[i] = from[i];
7898
+ }
7899
+ }
7900
+ return to.concat(ar || Array.prototype.slice.call(from));
7901
+ };
7902
+ var DiagComponentLogger = (
7903
+ /** @class */
7904
+ (function() {
7905
+ function DiagComponentLogger2(props) {
7906
+ this._namespace = props.namespace || "DiagComponentLogger";
7907
+ }
7908
+ DiagComponentLogger2.prototype.debug = function() {
7909
+ var args = [];
7910
+ for (var _i = 0; _i < arguments.length; _i++) {
7911
+ args[_i] = arguments[_i];
7912
+ }
7913
+ return logProxy("debug", this._namespace, args);
7914
+ };
7915
+ DiagComponentLogger2.prototype.error = function() {
7916
+ var args = [];
7917
+ for (var _i = 0; _i < arguments.length; _i++) {
7918
+ args[_i] = arguments[_i];
7919
+ }
7920
+ return logProxy("error", this._namespace, args);
7921
+ };
7922
+ DiagComponentLogger2.prototype.info = function() {
7923
+ var args = [];
7924
+ for (var _i = 0; _i < arguments.length; _i++) {
7925
+ args[_i] = arguments[_i];
7926
+ }
7927
+ return logProxy("info", this._namespace, args);
7928
+ };
7929
+ DiagComponentLogger2.prototype.warn = function() {
7930
+ var args = [];
7931
+ for (var _i = 0; _i < arguments.length; _i++) {
7932
+ args[_i] = arguments[_i];
7933
+ }
7934
+ return logProxy("warn", this._namespace, args);
7935
+ };
7936
+ DiagComponentLogger2.prototype.verbose = function() {
7937
+ var args = [];
7938
+ for (var _i = 0; _i < arguments.length; _i++) {
7939
+ args[_i] = arguments[_i];
7940
+ }
7941
+ return logProxy("verbose", this._namespace, args);
7942
+ };
7943
+ return DiagComponentLogger2;
7944
+ })()
7945
+ );
7946
+ function logProxy(funcName, namespace, args) {
7947
+ var logger = getGlobal("diag");
7948
+ if (!logger) {
7949
+ return;
7950
+ }
7951
+ args.unshift(namespace);
7952
+ return logger[funcName].apply(logger, __spreadArray([], __read(args), false));
7953
+ }
7954
+ var DiagLogLevel;
7955
+ (function(DiagLogLevel2) {
7956
+ DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
7957
+ DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
7958
+ DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
7959
+ DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
7960
+ DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
7961
+ DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
7962
+ DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
7963
+ })(DiagLogLevel || (DiagLogLevel = {}));
7964
+ function createLogLevelDiagLogger(maxLevel, logger) {
7965
+ if (maxLevel < DiagLogLevel.NONE) {
7966
+ maxLevel = DiagLogLevel.NONE;
7967
+ } else if (maxLevel > DiagLogLevel.ALL) {
7968
+ maxLevel = DiagLogLevel.ALL;
7969
+ }
7970
+ logger = logger || {};
7971
+ function _filterFunc(funcName, theLevel) {
7972
+ var theFunc = logger[funcName];
7973
+ if (typeof theFunc === "function" && maxLevel >= theLevel) {
7974
+ return theFunc.bind(logger);
7975
+ }
7976
+ return function() {
7977
+ };
7978
+ }
7979
+ return {
7980
+ error: _filterFunc("error", DiagLogLevel.ERROR),
7981
+ warn: _filterFunc("warn", DiagLogLevel.WARN),
7982
+ info: _filterFunc("info", DiagLogLevel.INFO),
7983
+ debug: _filterFunc("debug", DiagLogLevel.DEBUG),
7984
+ verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
7985
+ };
7986
+ }
7987
+ var __read2 = function(o, n) {
7988
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
7989
+ if (!m) return o;
7990
+ var i = m.call(o), r, ar = [], e;
7991
+ try {
7992
+ while (!(r = i.next()).done) ar.push(r.value);
7993
+ } catch (error) {
7994
+ e = { error };
7995
+ } finally {
7996
+ try {
7997
+ if (r && !r.done && (m = i["return"])) m.call(i);
7998
+ } finally {
7999
+ if (e) throw e.error;
8000
+ }
8001
+ }
8002
+ return ar;
8003
+ };
8004
+ var __spreadArray2 = function(to, from, pack) {
8005
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
8006
+ if (ar || !(i in from)) {
8007
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
8008
+ ar[i] = from[i];
8009
+ }
8010
+ }
8011
+ return to.concat(ar || Array.prototype.slice.call(from));
8012
+ };
8013
+ var API_NAME = "diag";
8014
+ var DiagAPI = (
8015
+ /** @class */
8016
+ (function() {
8017
+ function DiagAPI2() {
8018
+ function _logProxy(funcName) {
8019
+ return function() {
8020
+ var args = [];
8021
+ for (var _i = 0; _i < arguments.length; _i++) {
8022
+ args[_i] = arguments[_i];
8023
+ }
8024
+ var logger = getGlobal("diag");
8025
+ if (!logger)
8026
+ return;
8027
+ return logger[funcName].apply(logger, __spreadArray2([], __read2(args), false));
8028
+ };
8029
+ }
8030
+ var self = this;
8031
+ var setLogger = function(logger, optionsOrLogLevel) {
8032
+ var _a16, _b8, _c;
8033
+ if (optionsOrLogLevel === void 0) {
8034
+ optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
8035
+ }
8036
+ if (logger === self) {
8037
+ var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
8038
+ self.error((_a16 = err.stack) !== null && _a16 !== void 0 ? _a16 : err.message);
8039
+ return false;
8040
+ }
8041
+ if (typeof optionsOrLogLevel === "number") {
8042
+ optionsOrLogLevel = {
8043
+ logLevel: optionsOrLogLevel
8044
+ };
8045
+ }
8046
+ var oldLogger = getGlobal("diag");
8047
+ var newLogger = createLogLevelDiagLogger((_b8 = optionsOrLogLevel.logLevel) !== null && _b8 !== void 0 ? _b8 : DiagLogLevel.INFO, logger);
8048
+ if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
8049
+ var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
8050
+ oldLogger.warn("Current logger will be overwritten from " + stack);
8051
+ newLogger.warn("Current logger will overwrite one already registered from " + stack);
8052
+ }
8053
+ return registerGlobal("diag", newLogger, self, true);
8054
+ };
8055
+ self.setLogger = setLogger;
8056
+ self.disable = function() {
8057
+ unregisterGlobal(API_NAME, self);
8058
+ };
8059
+ self.createComponentLogger = function(options) {
8060
+ return new DiagComponentLogger(options);
8061
+ };
8062
+ self.verbose = _logProxy("verbose");
8063
+ self.debug = _logProxy("debug");
8064
+ self.info = _logProxy("info");
8065
+ self.warn = _logProxy("warn");
8066
+ self.error = _logProxy("error");
8067
+ }
8068
+ DiagAPI2.instance = function() {
8069
+ if (!this._instance) {
8070
+ this._instance = new DiagAPI2();
8071
+ }
8072
+ return this._instance;
8073
+ };
8074
+ return DiagAPI2;
8075
+ })()
8076
+ );
8077
+ function createContextKey(description) {
8078
+ return Symbol.for(description);
8079
+ }
8080
+ var BaseContext = (
8081
+ /** @class */
8082
+ /* @__PURE__ */ (function() {
8083
+ function BaseContext2(parentContext) {
8084
+ var self = this;
8085
+ self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
8086
+ self.getValue = function(key) {
8087
+ return self._currentContext.get(key);
8088
+ };
8089
+ self.setValue = function(key, value) {
8090
+ var context = new BaseContext2(self._currentContext);
8091
+ context._currentContext.set(key, value);
8092
+ return context;
8093
+ };
8094
+ self.deleteValue = function(key) {
8095
+ var context = new BaseContext2(self._currentContext);
8096
+ context._currentContext.delete(key);
8097
+ return context;
8098
+ };
8099
+ }
8100
+ return BaseContext2;
8101
+ })()
8102
+ );
8103
+ var ROOT_CONTEXT = new BaseContext();
8104
+ var __read3 = function(o, n) {
8105
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
8106
+ if (!m) return o;
8107
+ var i = m.call(o), r, ar = [], e;
8108
+ try {
8109
+ while (!(r = i.next()).done) ar.push(r.value);
8110
+ } catch (error) {
8111
+ e = { error };
8112
+ } finally {
8113
+ try {
8114
+ if (r && !r.done && (m = i["return"])) m.call(i);
8115
+ } finally {
8116
+ if (e) throw e.error;
8117
+ }
8118
+ }
8119
+ return ar;
8120
+ };
8121
+ var __spreadArray3 = function(to, from, pack) {
8122
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
8123
+ if (ar || !(i in from)) {
8124
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
8125
+ ar[i] = from[i];
8126
+ }
8127
+ }
8128
+ return to.concat(ar || Array.prototype.slice.call(from));
8129
+ };
8130
+ var NoopContextManager = (
8131
+ /** @class */
8132
+ (function() {
8133
+ function NoopContextManager2() {
8134
+ }
8135
+ NoopContextManager2.prototype.active = function() {
8136
+ return ROOT_CONTEXT;
8137
+ };
8138
+ NoopContextManager2.prototype.with = function(_context, fn, thisArg) {
8139
+ var args = [];
8140
+ for (var _i = 3; _i < arguments.length; _i++) {
8141
+ args[_i - 3] = arguments[_i];
8142
+ }
8143
+ return fn.call.apply(fn, __spreadArray3([thisArg], __read3(args), false));
8144
+ };
8145
+ NoopContextManager2.prototype.bind = function(_context, target) {
8146
+ return target;
8147
+ };
8148
+ NoopContextManager2.prototype.enable = function() {
8149
+ return this;
8150
+ };
8151
+ NoopContextManager2.prototype.disable = function() {
8152
+ return this;
8153
+ };
8154
+ return NoopContextManager2;
8155
+ })()
8156
+ );
8157
+ var __read4 = function(o, n) {
8158
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
8159
+ if (!m) return o;
8160
+ var i = m.call(o), r, ar = [], e;
8161
+ try {
8162
+ while (!(r = i.next()).done) ar.push(r.value);
8163
+ } catch (error) {
8164
+ e = { error };
8165
+ } finally {
8166
+ try {
8167
+ if (r && !r.done && (m = i["return"])) m.call(i);
8168
+ } finally {
8169
+ if (e) throw e.error;
8170
+ }
8171
+ }
8172
+ return ar;
8173
+ };
8174
+ var __spreadArray4 = function(to, from, pack) {
8175
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
8176
+ if (ar || !(i in from)) {
8177
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
8178
+ ar[i] = from[i];
8179
+ }
8180
+ }
8181
+ return to.concat(ar || Array.prototype.slice.call(from));
8182
+ };
8183
+ var API_NAME2 = "context";
8184
+ var NOOP_CONTEXT_MANAGER = new NoopContextManager();
8185
+ var ContextAPI = (
8186
+ /** @class */
8187
+ (function() {
8188
+ function ContextAPI2() {
8189
+ }
8190
+ ContextAPI2.getInstance = function() {
8191
+ if (!this._instance) {
8192
+ this._instance = new ContextAPI2();
8193
+ }
8194
+ return this._instance;
8195
+ };
8196
+ ContextAPI2.prototype.setGlobalContextManager = function(contextManager) {
8197
+ return registerGlobal(API_NAME2, contextManager, DiagAPI.instance());
8198
+ };
8199
+ ContextAPI2.prototype.active = function() {
8200
+ return this._getContextManager().active();
8201
+ };
8202
+ ContextAPI2.prototype.with = function(context, fn, thisArg) {
8203
+ var _a16;
8204
+ var args = [];
8205
+ for (var _i = 3; _i < arguments.length; _i++) {
8206
+ args[_i - 3] = arguments[_i];
8207
+ }
8208
+ return (_a16 = this._getContextManager()).with.apply(_a16, __spreadArray4([context, fn, thisArg], __read4(args), false));
8209
+ };
8210
+ ContextAPI2.prototype.bind = function(context, target) {
8211
+ return this._getContextManager().bind(context, target);
8212
+ };
8213
+ ContextAPI2.prototype._getContextManager = function() {
8214
+ return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER;
8215
+ };
8216
+ ContextAPI2.prototype.disable = function() {
8217
+ this._getContextManager().disable();
8218
+ unregisterGlobal(API_NAME2, DiagAPI.instance());
8219
+ };
8220
+ return ContextAPI2;
8221
+ })()
8222
+ );
8223
+ var TraceFlags;
8224
+ (function(TraceFlags2) {
8225
+ TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
8226
+ TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
8227
+ })(TraceFlags || (TraceFlags = {}));
8228
+ var INVALID_SPANID = "0000000000000000";
8229
+ var INVALID_TRACEID = "00000000000000000000000000000000";
8230
+ var INVALID_SPAN_CONTEXT = {
8231
+ traceId: INVALID_TRACEID,
8232
+ spanId: INVALID_SPANID,
8233
+ traceFlags: TraceFlags.NONE
8234
+ };
8235
+ var NonRecordingSpan = (
8236
+ /** @class */
8237
+ (function() {
8238
+ function NonRecordingSpan2(_spanContext) {
8239
+ if (_spanContext === void 0) {
8240
+ _spanContext = INVALID_SPAN_CONTEXT;
8241
+ }
8242
+ this._spanContext = _spanContext;
8243
+ }
8244
+ NonRecordingSpan2.prototype.spanContext = function() {
8245
+ return this._spanContext;
8246
+ };
8247
+ NonRecordingSpan2.prototype.setAttribute = function(_key, _value) {
8248
+ return this;
8249
+ };
8250
+ NonRecordingSpan2.prototype.setAttributes = function(_attributes) {
8251
+ return this;
8252
+ };
8253
+ NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) {
8254
+ return this;
8255
+ };
8256
+ NonRecordingSpan2.prototype.addLink = function(_link) {
8257
+ return this;
8258
+ };
8259
+ NonRecordingSpan2.prototype.addLinks = function(_links) {
8260
+ return this;
8261
+ };
8262
+ NonRecordingSpan2.prototype.setStatus = function(_status) {
8263
+ return this;
8264
+ };
8265
+ NonRecordingSpan2.prototype.updateName = function(_name) {
8266
+ return this;
8267
+ };
8268
+ NonRecordingSpan2.prototype.end = function(_endTime) {
8269
+ };
8270
+ NonRecordingSpan2.prototype.isRecording = function() {
8271
+ return false;
8272
+ };
8273
+ NonRecordingSpan2.prototype.recordException = function(_exception, _time) {
8274
+ };
8275
+ return NonRecordingSpan2;
8276
+ })()
8277
+ );
8278
+ var SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
8279
+ function getSpan(context) {
8280
+ return context.getValue(SPAN_KEY) || void 0;
8281
+ }
8282
+ function getActiveSpan() {
8283
+ return getSpan(ContextAPI.getInstance().active());
8284
+ }
8285
+ function setSpan(context, span) {
8286
+ return context.setValue(SPAN_KEY, span);
8287
+ }
8288
+ function deleteSpan(context) {
8289
+ return context.deleteValue(SPAN_KEY);
8290
+ }
8291
+ function setSpanContext(context, spanContext) {
8292
+ return setSpan(context, new NonRecordingSpan(spanContext));
8293
+ }
8294
+ function getSpanContext(context) {
8295
+ var _a16;
8296
+ return (_a16 = getSpan(context)) === null || _a16 === void 0 ? void 0 : _a16.spanContext();
8297
+ }
8298
+ var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
8299
+ var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
8300
+ function isValidTraceId(traceId) {
8301
+ return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;
8302
+ }
8303
+ function isValidSpanId(spanId) {
8304
+ return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;
8305
+ }
8306
+ function isSpanContextValid(spanContext) {
8307
+ return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
8308
+ }
8309
+ function wrapSpanContext(spanContext) {
8310
+ return new NonRecordingSpan(spanContext);
8311
+ }
8312
+ var contextApi = ContextAPI.getInstance();
8313
+ var NoopTracer = (
8314
+ /** @class */
8315
+ (function() {
8316
+ function NoopTracer2() {
8317
+ }
8318
+ NoopTracer2.prototype.startSpan = function(name16, options, context) {
8319
+ if (context === void 0) {
8320
+ context = contextApi.active();
8321
+ }
8322
+ var root = Boolean(options === null || options === void 0 ? void 0 : options.root);
8323
+ if (root) {
8324
+ return new NonRecordingSpan();
8325
+ }
8326
+ var parentFromContext = context && getSpanContext(context);
8327
+ if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
8328
+ return new NonRecordingSpan(parentFromContext);
8329
+ } else {
8330
+ return new NonRecordingSpan();
8331
+ }
8332
+ };
8333
+ NoopTracer2.prototype.startActiveSpan = function(name16, arg2, arg3, arg4) {
8334
+ var opts;
8335
+ var ctx;
8336
+ var fn;
8337
+ if (arguments.length < 2) {
8338
+ return;
8339
+ } else if (arguments.length === 2) {
8340
+ fn = arg2;
8341
+ } else if (arguments.length === 3) {
8342
+ opts = arg2;
8343
+ fn = arg3;
8344
+ } else {
8345
+ opts = arg2;
8346
+ ctx = arg3;
8347
+ fn = arg4;
8348
+ }
8349
+ var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
8350
+ var span = this.startSpan(name16, opts, parentContext);
8351
+ var contextWithSpanSet = setSpan(parentContext, span);
8352
+ return contextApi.with(contextWithSpanSet, fn, void 0, span);
8353
+ };
8354
+ return NoopTracer2;
8355
+ })()
8356
+ );
8357
+ function isSpanContext(spanContext) {
8358
+ return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
8359
+ }
8360
+ var NOOP_TRACER = new NoopTracer();
8361
+ var ProxyTracer = (
8362
+ /** @class */
8363
+ (function() {
8364
+ function ProxyTracer2(_provider, name16, version, options) {
8365
+ this._provider = _provider;
8366
+ this.name = name16;
8367
+ this.version = version;
8368
+ this.options = options;
8369
+ }
8370
+ ProxyTracer2.prototype.startSpan = function(name16, options, context) {
8371
+ return this._getTracer().startSpan(name16, options, context);
8372
+ };
8373
+ ProxyTracer2.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
8374
+ var tracer = this._getTracer();
8375
+ return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
8376
+ };
8377
+ ProxyTracer2.prototype._getTracer = function() {
8378
+ if (this._delegate) {
8379
+ return this._delegate;
8380
+ }
8381
+ var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
8382
+ if (!tracer) {
8383
+ return NOOP_TRACER;
8384
+ }
8385
+ this._delegate = tracer;
8386
+ return this._delegate;
8387
+ };
8388
+ return ProxyTracer2;
8389
+ })()
8390
+ );
8391
+ var NoopTracerProvider = (
8392
+ /** @class */
8393
+ (function() {
8394
+ function NoopTracerProvider2() {
8395
+ }
8396
+ NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options) {
8397
+ return new NoopTracer();
8398
+ };
8399
+ return NoopTracerProvider2;
8400
+ })()
8401
+ );
8402
+ var NOOP_TRACER_PROVIDER = new NoopTracerProvider();
8403
+ var ProxyTracerProvider = (
8404
+ /** @class */
8405
+ (function() {
8406
+ function ProxyTracerProvider2() {
8407
+ }
8408
+ ProxyTracerProvider2.prototype.getTracer = function(name16, version, options) {
8409
+ var _a16;
8410
+ return (_a16 = this.getDelegateTracer(name16, version, options)) !== null && _a16 !== void 0 ? _a16 : new ProxyTracer(this, name16, version, options);
8411
+ };
8412
+ ProxyTracerProvider2.prototype.getDelegate = function() {
8413
+ var _a16;
8414
+ return (_a16 = this._delegate) !== null && _a16 !== void 0 ? _a16 : NOOP_TRACER_PROVIDER;
8415
+ };
8416
+ ProxyTracerProvider2.prototype.setDelegate = function(delegate) {
8417
+ this._delegate = delegate;
8418
+ };
8419
+ ProxyTracerProvider2.prototype.getDelegateTracer = function(name16, version, options) {
8420
+ var _a16;
8421
+ return (_a16 = this._delegate) === null || _a16 === void 0 ? void 0 : _a16.getTracer(name16, version, options);
8422
+ };
8423
+ return ProxyTracerProvider2;
8424
+ })()
8425
+ );
8426
+ var SpanStatusCode;
8427
+ (function(SpanStatusCode2) {
8428
+ SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
8429
+ SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
8430
+ SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
8431
+ })(SpanStatusCode || (SpanStatusCode = {}));
8432
+ var API_NAME3 = "trace";
8433
+ var TraceAPI = (
8434
+ /** @class */
8435
+ (function() {
8436
+ function TraceAPI2() {
8437
+ this._proxyTracerProvider = new ProxyTracerProvider();
8438
+ this.wrapSpanContext = wrapSpanContext;
8439
+ this.isSpanContextValid = isSpanContextValid;
8440
+ this.deleteSpan = deleteSpan;
8441
+ this.getSpan = getSpan;
8442
+ this.getActiveSpan = getActiveSpan;
8443
+ this.getSpanContext = getSpanContext;
8444
+ this.setSpan = setSpan;
8445
+ this.setSpanContext = setSpanContext;
8446
+ }
8447
+ TraceAPI2.getInstance = function() {
8448
+ if (!this._instance) {
8449
+ this._instance = new TraceAPI2();
8450
+ }
8451
+ return this._instance;
8452
+ };
8453
+ TraceAPI2.prototype.setGlobalTracerProvider = function(provider) {
8454
+ var success = registerGlobal(API_NAME3, this._proxyTracerProvider, DiagAPI.instance());
8455
+ if (success) {
8456
+ this._proxyTracerProvider.setDelegate(provider);
8457
+ }
8458
+ return success;
8459
+ };
8460
+ TraceAPI2.prototype.getTracerProvider = function() {
8461
+ return getGlobal(API_NAME3) || this._proxyTracerProvider;
8462
+ };
8463
+ TraceAPI2.prototype.getTracer = function(name16, version) {
8464
+ return this.getTracerProvider().getTracer(name16, version);
8465
+ };
8466
+ TraceAPI2.prototype.disable = function() {
8467
+ unregisterGlobal(API_NAME3, DiagAPI.instance());
8468
+ this._proxyTracerProvider = new ProxyTracerProvider();
8469
+ };
8470
+ return TraceAPI2;
8471
+ })()
8472
+ );
8473
+ TraceAPI.getInstance();
8474
+ var __defProp = Object.defineProperty;
8475
+ var __export = (target, all) => {
8476
+ for (var name16 in all)
8477
+ __defProp(target, name16, { get: all[name16], enumerable: true });
8478
+ };
8479
+ var name622 = "AI_NoObjectGeneratedError";
8480
+ var marker622 = `vercel.ai.error.${name622}`;
8481
+ var symbol622 = Symbol.for(marker622);
8482
+ var _a622;
8483
+ var NoObjectGeneratedError = class extends AISDKError {
8484
+ constructor({
8485
+ message = "No object generated.",
8486
+ cause,
8487
+ text: text2,
8488
+ response,
8489
+ usage,
8490
+ finishReason
8491
+ }) {
8492
+ super({ name: name622, message, cause });
8493
+ this[_a622] = true;
8494
+ this.text = text2;
8495
+ this.response = response;
8496
+ this.usage = usage;
8497
+ this.finishReason = finishReason;
8498
+ }
8499
+ static isInstance(error) {
8500
+ return AISDKError.hasMarker(error, marker622);
8501
+ }
8502
+ };
8503
+ _a622 = symbol622;
8504
+ var dataContentSchema = z$1.union([
8505
+ z$1.string(),
8506
+ z$1.instanceof(Uint8Array),
8507
+ z$1.instanceof(ArrayBuffer),
8508
+ z$1.custom(
8509
+ // Buffer might not be available in some environments such as CloudFlare:
8510
+ (value) => {
8511
+ var _a16, _b8;
8512
+ return (_b8 = (_a16 = globalThis.Buffer) == null ? void 0 : _a16.isBuffer(value)) != null ? _b8 : false;
8513
+ },
8514
+ { message: "Must be a Buffer" }
8515
+ )
8516
+ ]);
8517
+ var jsonValueSchema = z$1.lazy(
8518
+ () => z$1.union([
8519
+ z$1.null(),
8520
+ z$1.string(),
8521
+ z$1.number(),
8522
+ z$1.boolean(),
8523
+ z$1.record(z$1.string(), jsonValueSchema),
8524
+ z$1.array(jsonValueSchema)
8525
+ ])
8526
+ );
8527
+ var providerMetadataSchema = z$1.record(
8528
+ z$1.string(),
8529
+ z$1.record(z$1.string(), jsonValueSchema)
8530
+ );
8531
+ var textPartSchema = z$1.object({
8532
+ type: z$1.literal("text"),
8533
+ text: z$1.string(),
8534
+ providerOptions: providerMetadataSchema.optional()
8535
+ });
8536
+ var imagePartSchema = z$1.object({
8537
+ type: z$1.literal("image"),
8538
+ image: z$1.union([dataContentSchema, z$1.instanceof(URL)]),
8539
+ mediaType: z$1.string().optional(),
8540
+ providerOptions: providerMetadataSchema.optional()
8541
+ });
8542
+ var filePartSchema = z$1.object({
8543
+ type: z$1.literal("file"),
8544
+ data: z$1.union([dataContentSchema, z$1.instanceof(URL)]),
8545
+ filename: z$1.string().optional(),
8546
+ mediaType: z$1.string(),
8547
+ providerOptions: providerMetadataSchema.optional()
8548
+ });
8549
+ var reasoningPartSchema = z$1.object({
8550
+ type: z$1.literal("reasoning"),
8551
+ text: z$1.string(),
8552
+ providerOptions: providerMetadataSchema.optional()
8553
+ });
8554
+ var toolCallPartSchema = z$1.object({
8555
+ type: z$1.literal("tool-call"),
8556
+ toolCallId: z$1.string(),
8557
+ toolName: z$1.string(),
8558
+ input: z$1.unknown(),
8559
+ providerOptions: providerMetadataSchema.optional(),
8560
+ providerExecuted: z$1.boolean().optional()
8561
+ });
8562
+ var outputSchema = z$1.discriminatedUnion("type", [
8563
+ z$1.object({
8564
+ type: z$1.literal("text"),
8565
+ value: z$1.string()
8566
+ }),
8567
+ z$1.object({
8568
+ type: z$1.literal("json"),
8569
+ value: jsonValueSchema
8570
+ }),
8571
+ z$1.object({
8572
+ type: z$1.literal("error-text"),
8573
+ value: z$1.string()
8574
+ }),
8575
+ z$1.object({
8576
+ type: z$1.literal("error-json"),
8577
+ value: jsonValueSchema
8578
+ }),
8579
+ z$1.object({
8580
+ type: z$1.literal("content"),
8581
+ value: z$1.array(
8582
+ z$1.union([
8583
+ z$1.object({
8584
+ type: z$1.literal("text"),
8585
+ text: z$1.string()
8586
+ }),
8587
+ z$1.object({
8588
+ type: z$1.literal("media"),
8589
+ data: z$1.string(),
8590
+ mediaType: z$1.string()
8591
+ })
8592
+ ])
8593
+ )
8594
+ })
8595
+ ]);
8596
+ var toolResultPartSchema = z$1.object({
8597
+ type: z$1.literal("tool-result"),
8598
+ toolCallId: z$1.string(),
8599
+ toolName: z$1.string(),
8600
+ output: outputSchema,
8601
+ providerOptions: providerMetadataSchema.optional()
8602
+ });
8603
+ var systemModelMessageSchema = z$1.object(
8604
+ {
8605
+ role: z$1.literal("system"),
8606
+ content: z$1.string(),
8607
+ providerOptions: providerMetadataSchema.optional()
8608
+ }
8609
+ );
8610
+ var userModelMessageSchema = z$1.object({
8611
+ role: z$1.literal("user"),
8612
+ content: z$1.union([
8613
+ z$1.string(),
8614
+ z$1.array(z$1.union([textPartSchema, imagePartSchema, filePartSchema]))
8615
+ ]),
8616
+ providerOptions: providerMetadataSchema.optional()
8617
+ });
8618
+ var assistantModelMessageSchema = z$1.object({
8619
+ role: z$1.literal("assistant"),
8620
+ content: z$1.union([
8621
+ z$1.string(),
8622
+ z$1.array(
8623
+ z$1.union([
8624
+ textPartSchema,
8625
+ filePartSchema,
8626
+ reasoningPartSchema,
8627
+ toolCallPartSchema,
8628
+ toolResultPartSchema
8629
+ ])
8630
+ )
8631
+ ]),
8632
+ providerOptions: providerMetadataSchema.optional()
8633
+ });
8634
+ var toolModelMessageSchema = z$1.object({
8635
+ role: z$1.literal("tool"),
8636
+ content: z$1.array(toolResultPartSchema),
8637
+ providerOptions: providerMetadataSchema.optional()
8638
+ });
8639
+ z$1.union([
8640
+ systemModelMessageSchema,
8641
+ userModelMessageSchema,
8642
+ assistantModelMessageSchema,
8643
+ toolModelMessageSchema
8644
+ ]);
8645
+ function stepCountIs(stepCount) {
8646
+ return ({ steps }) => steps.length === stepCount;
8647
+ }
8648
+ createIdGenerator({
8649
+ prefix: "aitxt",
8650
+ size: 24
8651
+ });
8652
+ (class extends TransformStream {
8653
+ constructor() {
8654
+ super({
8655
+ transform(part, controller) {
8656
+ controller.enqueue(`data: ${JSON.stringify(part)}
8657
+
8658
+ `);
8659
+ },
8660
+ flush(controller) {
8661
+ controller.enqueue("data: [DONE]\n\n");
8662
+ }
8663
+ });
8664
+ }
8665
+ });
8666
+ function fixJson(input) {
8667
+ const stack = ["ROOT"];
8668
+ let lastValidIndex = -1;
8669
+ let literalStart = null;
8670
+ function processValueStart(char, i, swapState) {
8671
+ {
8672
+ switch (char) {
8673
+ case '"': {
8674
+ lastValidIndex = i;
8675
+ stack.pop();
8676
+ stack.push(swapState);
8677
+ stack.push("INSIDE_STRING");
8678
+ break;
8679
+ }
8680
+ case "f":
8681
+ case "t":
8682
+ case "n": {
8683
+ lastValidIndex = i;
8684
+ literalStart = i;
8685
+ stack.pop();
8686
+ stack.push(swapState);
8687
+ stack.push("INSIDE_LITERAL");
8688
+ break;
8689
+ }
8690
+ case "-": {
8691
+ stack.pop();
8692
+ stack.push(swapState);
8693
+ stack.push("INSIDE_NUMBER");
8694
+ break;
8695
+ }
8696
+ case "0":
8697
+ case "1":
8698
+ case "2":
8699
+ case "3":
8700
+ case "4":
8701
+ case "5":
8702
+ case "6":
8703
+ case "7":
8704
+ case "8":
8705
+ case "9": {
8706
+ lastValidIndex = i;
8707
+ stack.pop();
8708
+ stack.push(swapState);
8709
+ stack.push("INSIDE_NUMBER");
8710
+ break;
8711
+ }
8712
+ case "{": {
8713
+ lastValidIndex = i;
8714
+ stack.pop();
8715
+ stack.push(swapState);
8716
+ stack.push("INSIDE_OBJECT_START");
8717
+ break;
8718
+ }
8719
+ case "[": {
8720
+ lastValidIndex = i;
8721
+ stack.pop();
8722
+ stack.push(swapState);
8723
+ stack.push("INSIDE_ARRAY_START");
8724
+ break;
8725
+ }
8726
+ }
8727
+ }
8728
+ }
8729
+ function processAfterObjectValue(char, i) {
8730
+ switch (char) {
8731
+ case ",": {
8732
+ stack.pop();
8733
+ stack.push("INSIDE_OBJECT_AFTER_COMMA");
8734
+ break;
8735
+ }
8736
+ case "}": {
8737
+ lastValidIndex = i;
8738
+ stack.pop();
8739
+ break;
8740
+ }
8741
+ }
8742
+ }
8743
+ function processAfterArrayValue(char, i) {
8744
+ switch (char) {
8745
+ case ",": {
8746
+ stack.pop();
8747
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
8748
+ break;
8749
+ }
8750
+ case "]": {
8751
+ lastValidIndex = i;
8752
+ stack.pop();
8753
+ break;
8754
+ }
8755
+ }
8756
+ }
8757
+ for (let i = 0; i < input.length; i++) {
8758
+ const char = input[i];
8759
+ const currentState = stack[stack.length - 1];
8760
+ switch (currentState) {
8761
+ case "ROOT":
8762
+ processValueStart(char, i, "FINISH");
8763
+ break;
8764
+ case "INSIDE_OBJECT_START": {
8765
+ switch (char) {
8766
+ case '"': {
8767
+ stack.pop();
8768
+ stack.push("INSIDE_OBJECT_KEY");
8769
+ break;
8770
+ }
8771
+ case "}": {
8772
+ lastValidIndex = i;
8773
+ stack.pop();
8774
+ break;
8775
+ }
8776
+ }
8777
+ break;
8778
+ }
8779
+ case "INSIDE_OBJECT_AFTER_COMMA": {
8780
+ switch (char) {
8781
+ case '"': {
8782
+ stack.pop();
8783
+ stack.push("INSIDE_OBJECT_KEY");
8784
+ break;
8785
+ }
8786
+ }
8787
+ break;
8788
+ }
8789
+ case "INSIDE_OBJECT_KEY": {
8790
+ switch (char) {
8791
+ case '"': {
8792
+ stack.pop();
8793
+ stack.push("INSIDE_OBJECT_AFTER_KEY");
8794
+ break;
8795
+ }
8796
+ }
8797
+ break;
8798
+ }
8799
+ case "INSIDE_OBJECT_AFTER_KEY": {
8800
+ switch (char) {
8801
+ case ":": {
8802
+ stack.pop();
8803
+ stack.push("INSIDE_OBJECT_BEFORE_VALUE");
8804
+ break;
8805
+ }
8806
+ }
8807
+ break;
8808
+ }
8809
+ case "INSIDE_OBJECT_BEFORE_VALUE": {
8810
+ processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
8811
+ break;
8812
+ }
8813
+ case "INSIDE_OBJECT_AFTER_VALUE": {
8814
+ processAfterObjectValue(char, i);
8815
+ break;
8816
+ }
8817
+ case "INSIDE_STRING": {
8818
+ switch (char) {
8819
+ case '"': {
8820
+ stack.pop();
8821
+ lastValidIndex = i;
8822
+ break;
8823
+ }
8824
+ case "\\": {
8825
+ stack.push("INSIDE_STRING_ESCAPE");
8826
+ break;
8827
+ }
8828
+ default: {
8829
+ lastValidIndex = i;
8830
+ }
8831
+ }
8832
+ break;
8833
+ }
8834
+ case "INSIDE_ARRAY_START": {
8835
+ switch (char) {
8836
+ case "]": {
8837
+ lastValidIndex = i;
8838
+ stack.pop();
8839
+ break;
8840
+ }
8841
+ default: {
8842
+ lastValidIndex = i;
8843
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
8844
+ break;
8845
+ }
8846
+ }
8847
+ break;
8848
+ }
8849
+ case "INSIDE_ARRAY_AFTER_VALUE": {
8850
+ switch (char) {
8851
+ case ",": {
8852
+ stack.pop();
8853
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
8854
+ break;
8855
+ }
8856
+ case "]": {
8857
+ lastValidIndex = i;
8858
+ stack.pop();
8859
+ break;
8860
+ }
8861
+ default: {
8862
+ lastValidIndex = i;
8863
+ break;
8864
+ }
8865
+ }
8866
+ break;
8867
+ }
8868
+ case "INSIDE_ARRAY_AFTER_COMMA": {
8869
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
8870
+ break;
8871
+ }
8872
+ case "INSIDE_STRING_ESCAPE": {
8873
+ stack.pop();
8874
+ lastValidIndex = i;
8875
+ break;
8876
+ }
8877
+ case "INSIDE_NUMBER": {
8878
+ switch (char) {
8879
+ case "0":
8880
+ case "1":
8881
+ case "2":
8882
+ case "3":
8883
+ case "4":
8884
+ case "5":
8885
+ case "6":
8886
+ case "7":
8887
+ case "8":
8888
+ case "9": {
8889
+ lastValidIndex = i;
8890
+ break;
8891
+ }
8892
+ case "e":
8893
+ case "E":
8894
+ case "-":
8895
+ case ".": {
8896
+ break;
8897
+ }
8898
+ case ",": {
8899
+ stack.pop();
8900
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
8901
+ processAfterArrayValue(char, i);
8902
+ }
8903
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
8904
+ processAfterObjectValue(char, i);
8905
+ }
8906
+ break;
8907
+ }
8908
+ case "}": {
8909
+ stack.pop();
8910
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
8911
+ processAfterObjectValue(char, i);
8912
+ }
8913
+ break;
8914
+ }
8915
+ case "]": {
8916
+ stack.pop();
8917
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
8918
+ processAfterArrayValue(char, i);
8919
+ }
8920
+ break;
8921
+ }
8922
+ default: {
8923
+ stack.pop();
8924
+ break;
8925
+ }
8926
+ }
8927
+ break;
8928
+ }
8929
+ case "INSIDE_LITERAL": {
8930
+ const partialLiteral = input.substring(literalStart, i + 1);
8931
+ if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
8932
+ stack.pop();
8933
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
8934
+ processAfterObjectValue(char, i);
8935
+ } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
8936
+ processAfterArrayValue(char, i);
8937
+ }
8938
+ } else {
8939
+ lastValidIndex = i;
8940
+ }
8941
+ break;
8942
+ }
8943
+ }
8944
+ }
8945
+ let result = input.slice(0, lastValidIndex + 1);
8946
+ for (let i = stack.length - 1; i >= 0; i--) {
8947
+ const state = stack[i];
8948
+ switch (state) {
8949
+ case "INSIDE_STRING": {
8950
+ result += '"';
8951
+ break;
8952
+ }
8953
+ case "INSIDE_OBJECT_KEY":
8954
+ case "INSIDE_OBJECT_AFTER_KEY":
8955
+ case "INSIDE_OBJECT_AFTER_COMMA":
8956
+ case "INSIDE_OBJECT_START":
8957
+ case "INSIDE_OBJECT_BEFORE_VALUE":
8958
+ case "INSIDE_OBJECT_AFTER_VALUE": {
8959
+ result += "}";
8960
+ break;
8961
+ }
8962
+ case "INSIDE_ARRAY_START":
8963
+ case "INSIDE_ARRAY_AFTER_COMMA":
8964
+ case "INSIDE_ARRAY_AFTER_VALUE": {
8965
+ result += "]";
8966
+ break;
8967
+ }
8968
+ case "INSIDE_LITERAL": {
8969
+ const partialLiteral = input.substring(literalStart, input.length);
8970
+ if ("true".startsWith(partialLiteral)) {
8971
+ result += "true".slice(partialLiteral.length);
8972
+ } else if ("false".startsWith(partialLiteral)) {
8973
+ result += "false".slice(partialLiteral.length);
8974
+ } else if ("null".startsWith(partialLiteral)) {
8975
+ result += "null".slice(partialLiteral.length);
8976
+ }
8977
+ }
8978
+ }
8979
+ }
8980
+ return result;
8981
+ }
8982
+ async function parsePartialJson(jsonText) {
8983
+ if (jsonText === void 0) {
8984
+ return { value: void 0, state: "undefined-input" };
8985
+ }
8986
+ let result = await safeParseJSON({ text: jsonText });
8987
+ if (result.success) {
8988
+ return { value: result.value, state: "successful-parse" };
8989
+ }
8990
+ result = await safeParseJSON({ text: fixJson(jsonText) });
8991
+ if (result.success) {
8992
+ return { value: result.value, state: "repaired-parse" };
8993
+ }
8994
+ return { value: void 0, state: "failed-parse" };
8995
+ }
8996
+ createIdGenerator({
8997
+ prefix: "aitxt",
8998
+ size: 24
8999
+ });
9000
+ createIdGenerator({ prefix: "aiobj", size: 24 });
9001
+ createIdGenerator({ prefix: "aiobj", size: 24 });
9002
+ var output_exports = {};
9003
+ __export(output_exports, {
9004
+ object: () => object,
9005
+ text: () => text
9006
+ });
9007
+ var text = () => ({
9008
+ type: "text",
9009
+ responseFormat: { type: "text" },
9010
+ async parsePartial({ text: text2 }) {
9011
+ return { partial: text2 };
9012
+ },
9013
+ async parseOutput({ text: text2 }) {
9014
+ return text2;
9015
+ }
9016
+ });
9017
+ var object = ({
9018
+ schema: inputSchema
9019
+ }) => {
9020
+ const schema = asSchema(inputSchema);
9021
+ return {
9022
+ type: "object",
9023
+ responseFormat: {
9024
+ type: "json",
9025
+ schema: schema.jsonSchema
9026
+ },
9027
+ async parsePartial({ text: text2 }) {
9028
+ const result = await parsePartialJson(text2);
9029
+ switch (result.state) {
9030
+ case "failed-parse":
9031
+ case "undefined-input":
9032
+ return void 0;
9033
+ case "repaired-parse":
9034
+ case "successful-parse":
9035
+ return {
9036
+ // Note: currently no validation of partial results:
9037
+ partial: result.value
9038
+ };
9039
+ default: {
9040
+ const _exhaustiveCheck = result.state;
9041
+ throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
9042
+ }
9043
+ }
9044
+ },
9045
+ async parseOutput({ text: text2 }, context) {
9046
+ const parseResult = await safeParseJSON({ text: text2 });
9047
+ if (!parseResult.success) {
9048
+ throw new NoObjectGeneratedError({
9049
+ message: "No object generated: could not parse the response.",
9050
+ cause: parseResult.error,
9051
+ text: text2,
9052
+ response: context.response,
9053
+ usage: context.usage,
9054
+ finishReason: context.finishReason
9055
+ });
9056
+ }
9057
+ const validationResult = await safeValidateTypes({
9058
+ value: parseResult.value,
9059
+ schema
9060
+ });
9061
+ if (!validationResult.success) {
9062
+ throw new NoObjectGeneratedError({
9063
+ message: "No object generated: response did not match schema.",
9064
+ cause: validationResult.error,
9065
+ text: text2,
9066
+ response: context.response,
9067
+ usage: context.usage,
9068
+ finishReason: context.finishReason
9069
+ });
9070
+ }
9071
+ return validationResult.value;
9072
+ }
9073
+ };
9074
+ };
4752
9075
  var TaskSchema = z.array(
4753
9076
  z.object({
4754
9077
  id: z.string().describe("Unique task ID using kebab-case"),
@@ -5072,6 +9395,7 @@ var planningIterationStep = createStep({
5072
9395
  try {
5073
9396
  const model = await resolveModel({ requestContext });
5074
9397
  const planningAgent = new Agent({
9398
+ id: "workflow-planning-agent",
5075
9399
  model,
5076
9400
  instructions: taskPlanningPrompts.planningAgent.instructions({
5077
9401
  storedQAPairs
@@ -5802,6 +10126,7 @@ var workflowResearchStep = createStep({
5802
10126
  try {
5803
10127
  const model = await resolveModel({ requestContext });
5804
10128
  const researchAgent = new Agent({
10129
+ id: "workflow-research-agent",
5805
10130
  model,
5806
10131
  instructions: workflowBuilderPrompts.researchAgent.instructions,
5807
10132
  name: "Workflow Research Agent"